How to set RingCentral hold music? - ringcentral

RingCentral has the ability to upload custom Hold Music via the UI. Can this be done via the API, as user and as an admin for other users? Searching the API Reference for hold music didn't turn up an API.
Here's some info on this functionality:
User: https://support.ringcentral.com/s/article/1798
Admin: https://support.ringcentral.com/s/article/8360
Here's what the UI looks like:

Try ringcentral API for creating custom user greeting and set greeting type as HoldMusic
https://developers.ringcentral.com/api-reference/Rule-Management/createCustomUserGreeting
Create custom user greeting API

There are two steps to this:
Get the Answering Rule ID of the rule you want to change. This can be a standard rule such as business-hours-rule, or it can be a custom rule that you have created. You can call the Get Call Handling Rules API to get a list of current standard and custom rules.
Call the Update Greeting API with type set to HoldMusic and answeringRuleId set to the id you wish to update, e.g. business-hours-rule
There are actually several ways to call the Update Greeting API:
multipart/form-data with individual string parts. In this approach, separate parts are sent with names type, answeringRuleId, and binary
multipart/form-data with JSON metadata part. In this approach, a JSON MIME part named json is sent with a payload like: {"type": "HoldMusic", "answeringRule": { "id": "12345678" }}
multipart/mixed
I tend to prefer the first approach (multipart/form-data with individual string parts) because it's easy to use with tools like cURL and many HTTP clients.
Here's an example using Go:
package main
import(
"log"
"net/http"
"net/url"
"os"
"github.com/grokify/gotilla/mime/multipartutil"
"github.com/grokify/oauth2more/ringcentral"
)
func main() {
// Get the Client (*http.Client):
client, err = ringcentral.NewClientPassword(
ringcentral.ApplicationCredentials{
ClientID: os.Getenv("RINGCENTRAL_CLIENT_ID"),
ClientSecret: os.Getenv("RINGCENTRAL_CLIENT_SECRET"),
ServerURL: os.Getenv("RINGCENTRAL_SERVER_URL")},
ringcentral.PasswordCredentials{
Username: os.Getenv("RINGCENTRAL_USERNAME"),
Extension: os.Getenv("RINGCENTRAL_EXTENSION"),
Password: os.Getenv("RINGCENTRAL_PASSWORD")})
if err!=nil {
log.Fatal(err)
}
// Create the HTTP Request (*http.Request)
params := url.Values{}
params.Set("type", "HoldMusic")
params.Set("answeringRuleId", "business-hours-rule")
req, err := multipartutil.NewRequest(
http.MethodPost,
"https://platform.ringcenral.com/restapi/v1.0/account/~/extension/~/greeting",
params,
[]multipartutil.FileInfo{
{
MIMEPartName: "binary",
Filepath: "mygreeting.wav",
},
},
)
// Send the request
resp, err = client.Do(req)
if err != nil {
log.Fatal(err)
}
fmt.Printf("STATUS: %v\n", resp.StatusCode)
}

Related

How do I test my handler which require tokens to call data services

This is the code written in the handler, which gets the token required to call the data service.
m2m, err := h.getM2MToken(ctx)
if err != nil {
return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
StatusCode: http.StatusInternalServerError,
Body: "Internal Server Error (m2m)",
})
}
//Get the bearer token
userToken, err := h.getBearer(req.Headers)
if err != nil {
xray.AddError(ctx, err)
return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
StatusCode: http.StatusInternalServerError,
Body: "Internal Server Error (bearer)",
})
}
My suggestion is to first try abstracting the inputs that you sent to a method
Like instead of this
userToken, err := h.getBearer(req.Headers)
You can pass specify interfaces like
type userTokenInput struct {}
uti := userTokenInput{}
userToken, err := h.getBearer(uti)
The above helps you to have control over input which makes testing easier
For network calls try using some mock HTTP client which can return expected
data you can follow this for mock HTTP client https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/
If the service does not work without a token, you will have to provide one.
If the calls you will be doing should not be seen on the real target system for whatever reason, you will need a different target system for testing.
Ask the provider if they have a test installation you can use.
Consider testing against a mock.

API Gateway HTTP client request with IAM auth with Go

Hello StackOverflow AWS Gophers,
I'm implementing a CLI with the excellent cobra/viper packages from spf13. We have an Athena database fronted by an API Gateway endpoint, which authenticates with IAM.
That is, in order to interact with its endpoints by using Postman, I have to define AWS Signature as Authorization method, define the corresponding AWS id/secret and then in the Headers there will be X-Amz-Security-Token and others. Nothing unusual, works as expected.
Since I'm new to Go, I was a bit shocked to see that there are no examples to do this simple HTTP GET request with the aws-sdk-go itself... I'm trying to use the shared credentials provider (~/.aws/credentials), as demonstrated for the S3 client Go code snippets from re:Invent 2015:
req := request.New(nil)
How can I accomplish this seemingly easy feat in 2019 without having to resort to self-cooked net/http and therefore having to manually read ~/.aws/credentials or worse, go with os.Getenv and other ugly hacks?
Any Go code samples interacting as client would be super helpful. No Golang Lambda/server examples, please, there's plenty of those out there.
Unfortunately, it seems that the library has been updated since the accepted answer was written and the solution no longer is the same. After some trial and error, this appears to be the more current method of handling the signing (using https://pkg.go.dev/github.com/aws/aws-sdk-go-v2):
import (
"context"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
func main() {
// Context is not being used in this example.
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
// Handle error.
}
credentials, err := cfg.Credentials.Retrieve(context.TODO())
if err != nil {
// Handle error.
}
// The signer requires a payload hash. This hash is for an empty payload.
hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
req, _ := http.NewRequest(http.MethodGet, "api-gw-url", nil)
signer := v4.NewSigner()
err = signer.SignHTTP(context.TODO(), credentials, req, hash, "execute-api", cfg.Region, time.Now())
if err != nil {
// Handle error.
}
// Use `req`
}
The solution below uses aws-sdk-go-v2
https://github.com/aws/aws-sdk-go-v2
// A AWS SDK session is created because the HTTP API is secured using a
// IAM authorizer. As such, we need AWS client credentials and a
// session to properly sign the request.
cfg, err := external.LoadDefaultAWSConfig(
external.WithSharedConfigProfile(profile),
)
if err != nil {
fmt.Println("unable to create an AWS session for the provided profile")
return
}
req, _ := http.NewRequest(http.MethodGet, "", nil)
req = req.WithContext(ctx)
signer := v4.NewSigner(cfg.Credentials)
_, err = signer.Sign(req, nil, "execute-api", cfg.Region, time.Now())
if err != nil {
fmt.Printf("failed to sign request: (%v)\n", err)
return
}
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("failed to call remote service: (%v)\n", err)
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
fmt.Printf("service returned a status not 200: (%d)\n", res.StatusCode)
return
}
The first argument to request.New is aws.Config, where you can send credentials.
https://github.com/aws/aws-sdk-go/blob/master/aws/request/request.go#L99
https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
There are multiple ways to create credentials object: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
For example using static values:
creds:= credentials.NewStaticCredentials("AKID", "SECRET_KEY", "TOKEN")
req := request.New(aws.Config{Credentials: creds}, ...)
I'm pretty new to go myself (3rd day learning go) but from watching the video you posted with the S3 example and reading through the source code (for the s3 service and request module) here is my understanding (which I'm hoping helps).
If you look at the code for the s3.New() function aws-sdk-go/service/s3/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *S3 {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, .SigningName) }
As opposed to request.New() function aws-sdk-go/aws/request/request.go
func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { ...
As you can see in the s3 scenario the *aws.Config struct is a pointer, and so is probably initialized / populated elsewhere. As opposed to the request function where the aws.Config is a parameter. So I am guessing the request module is probably a very low level module which doesn't get the shared credentials automatically.
Now, seeing as you will be interacting with API gateway I had a look at that service specifically to see if there was something similar. I looked at aws-sdk-go/service/apigateway/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *APIGateway {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) }...
Which looks pretty much the same as the s3 client, so perhaps try using that and see how you go?

Calling AppSync Mutation from Lambda with Golang

I'm trying to invoke a mutation from lambda (specifically using golang). I used AWS_IAM as the authentication method of my AppSync API. I also give appsync:GraphQL permission to my lambda.
However, after looking at the docs here: https://docs.aws.amazon.com/sdk-for-go/api/service/appsync/
I can't find any documentation on how to invoke the appsync from the library. Can anyone point me to the right direction here?
P.S. I don't want to query or subscribe or anything else from lambda. It's just a mutation
Thanks!
------UPDATE-------
Thanks to #thomasmichaelwallace for informing me to use https://godoc.org/github.com/machinebox/graphql
Now the problem is how can I sign the request from that package using aws v4?
I found a way of using plain http.Request and AWS v4 signing. (Thanks to #thomasmichaelwallace for pointing this method out)
client := new(http.Client)
// construct the query
query := AppSyncPublish{
Query: `
mutation ($userid: ID!) {
publishMessage(
userid: $userid
){
userid
}
}
`,
Variables: PublishInput{
UserID: "wow",
},
}
b, err := json.Marshal(&query)
if err != nil {
fmt.Println(err)
}
// construct the request object
req, err := http.NewRequest("POST", os.Getenv("APPSYNC_URL"), bytes.NewReader(b))
if err != nil {
fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json")
// get aws credential
config := aws.Config{
Region: aws.String(os.Getenv("AWS_REGION")),
}
sess := session.Must(session.NewSession(&config))
//sign the request
signer := v4.NewSigner(sess.Config.Credentials)
signer.Sign(req, bytes.NewReader(b), "appsync", "ap-southeast-1", time.Now())
//FIRE!!
response, _ := client.Do(req)
//print the response
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
newStr := buf.String()
fmt.Printf(newStr)
The problem is that that API/library is designed to help you create/update app-sync instances.
If you want to actually invoke them then you need to POST to the GraphQL endpoint.
The easiest way for testing is to sign-in to the AWS AppSync Console, press the 'Queries' button in the sidebar and then enter and run your mutation.
I'm not great with go, but from what I can see there are client libraries for GraphQL in golang (e.g. https://godoc.org/github.com/machinebox/graphql).
If you are using IAM then you'll need to sign your request with a v4 signature (see this article for details: https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html)

Mocking remote api calls in golang

I'm trying to get better at writing mocked golang tests that call a remote api
I can similate a single call pretty easily with the httptest library but am a
bit stuck handling other functions that call single endpoint calls multiple times.
For example given a simple create function
func createItem(url string, product Product) (int, error) {
// make request
return createdId, nil
}
I can write some tests that look like this
func TestCreateItem(t *testing.T) {
mock_ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`37`))
}))
prod := Product{...}
_, err := createItem(mock_ts.URL, 1, prod)
if err != nil {
t.Errorf("Error saving item: %v", err)
}
}
Now if I have this other wrapper function I won't be able to pass in the
mock test server url.
func someFunctionThatMakesManyItems(...) {
url = "http://www.realapiendpoint.com" // or some func that gets api url
// this function might generate a list of items
for _, item := range items {
createItem(url, item)
}
}
I could need to pass in the url to the someFunctionThatMakesManyItems and any
functions that rely on api functions and that just seems like the wrong approach.
Any advice on how to model this better to help with my tests?
Make the endpoint URL configurable instead of hard-coding it - make it a function parameter, or a field of some configuration struct, or returned from an internal configuration service, something like that. Designing for testability is all about avoiding hard-coded configuration and dependencies: code should receive its configuration values and its dependencies from the caller rather than setting or creating them itself.

How to mock while sending http request to API

I have implemented a ReST API in Go using go-gin and I am trying to test a handler function which looks like the following
func editNameHandler(c *gin.Context) {
// make a ReST call to another server
callToAnotherServer()
c.Status(200)
}
I want to to mock callToAnotherServer method so that my test case doesn't call the 3rd party server at all.
My test case looks like
func TestSeriveIdStatusRestorePatch(t *testing.T) {
// Request body
send := strings.NewReader(`{"name":"Robert"}`
// this function sends an HTTP request to the API which ultimately calls editNameHandler
// Ignore the variables.The variables are retrieved in code this is to simplify question
ValidTokenTestPatch(API_VERSION+"/accounts/"+TestAccountUUID+"/students/"+TestStudentId, t, send, http.StatusOK)
}
I went through Mock functions in Go which mentions how we can pass a function to mock. I am wondering how we can pass a function while sending http request? How can I mock function in such case. What is the best practice?
I don't think there is single response for this question, but I'll share my approach on how I'm currently doing Dependency Injection on Go with go-gin (but should be the nearly the same with any other router).
From a business point of view, I have a struct that wraps all access to my services which are responsible for business rules/processing.
// WchyContext is an application-wide context
type WchyContext struct {
Health services.HealthCheckService
Tenant services.TenantService
... whatever
}
My services are then just interfaces.
// HealthCheckService is a simple general purpose health check service
type HealthCheckService interface {
IsDatabaseOnline() bool
}
Which have mulitple implementations, like MockedHealthCheck, PostgresHealthCheck, PostgresTenantService and so on.
My router than depends on a WchyContext, which the code looks like this:
func GetMainEngine(ctx context.WchyContext) *gin.Engine {
router := gin.New()
router.Use(gin.Logger())
router.GET("/status", Status(ctx))
router.GET("/tenants/:domain", TenantByDomain(ctx))
return router
}`
Status and TenantByDomain act like a handler-factory, all it does is create a new handler based on given context, like this:
type statusHandler struct {
ctx context.WchyContext
}
// Status creates a new Status HTTP handler
func Status(ctx context.WchyContext) gin.HandlerFunc {
return statusHandler{ctx: ctx}.get()
}
func (h statusHandler) get() gin.HandlerFunc {
return func(c *gin.Context) {
c.JSON(200, gin.H{
"healthy": gin.H{
"database": h.ctx.Health.IsDatabaseOnline(),
},
"now": time.Now().Format("2006.01.02.150405"),
})
}
}
As you can see, my health check handler doesn't care about concrete implementation of my services, I just use it whatever is in the ctx.
The last part depends on current execution environment. During automated tests I create a new WchyContext using mocked/stubbed services and send it to GetMainEngine, like this:
ctx := context.WchyContext{
Health: &services.InMemoryHealthCheckService{Status: false},
Tenant: &services.InMemoryTenantService{Tenants: []*models.Tenant{
&models.Tenant{ID: 1, Name: "Orange Inc.", Domain: "orange"},
&models.Tenant{ID: 2, Name: "The Triathlon Shop", Domain: "trishop"},
}}
}
router := handlers.GetMainEngine(ctx)
request, _ := http.NewRequest(method, url, nil)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
... check if response matches what you expect from your handler
And when you setup it to really listen to a HTTP port, the wiring up looks like this:
var ctx context.WchyContext
var db *sql.DB
func init() {
db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
ctx = context.WchyContext{
Health: &services.PostgresHealthCheckService{DB: db},
Tenant: &services.PostgresTenantService{DB: db}
}
}
func main() {
handlers.GetMainEngine(ctx).Run(":" + util.GetEnvOrDefault("PORT", "3000"))
}
There are a few things that I don't like about this, I'll probably refactor/improve it later, but it has been working well so far.
If you want to see full code reference, I'm working on this project here https://github.com/WeCanHearYou/wchy
Hope it can help you somehow.