github.com/grokify/go-ringcentral-client@v0.3.31/office/v1/client/client.go (about) 1 /* 2 * RingCentral Connect Platform API Explorer 3 * 4 * <p>This is a beta interactive API explorer for the RingCentral Connect Platform. To use this service, you will need to have an account with the proper credentials to generate an OAuth2 access token.</p><p><h2>Quick Start</h2></p><ol><li>1) Go to <b>Authentication > /oauth/token</b></li><li>2) Enter <b>app_key, app_secret, username, password</b> fields and then click \"Try it out!\"</li><li>3) Upon success, your access_token is loaded and you can access any form requiring authorization.</li></ol><h2>Links</h2><ul><li><a href=\"https://github.com/ringcentral\" target=\"_blank\">RingCentral SDKs on Github</a></li><li><a href=\"mailto:devsupport@ringcentral.com\">RingCentral Developer Support Email</a></li></ul> 5 * 6 * API version: 1.0 7 * Generated by: OpenAPI Generator (https://openapi-generator.tech) 8 */ 9 10 package ringcentral 11 12 import ( 13 "bytes" 14 "context" 15 "encoding/json" 16 "encoding/xml" 17 "errors" 18 "fmt" 19 "io" 20 "mime/multipart" 21 "net/http" 22 "net/url" 23 "os" 24 "path/filepath" 25 "reflect" 26 "regexp" 27 "strconv" 28 "strings" 29 "time" 30 "unicode/utf8" 31 32 "golang.org/x/oauth2" 33 ) 34 35 var ( 36 jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") 37 xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") 38 ) 39 40 // APIClient manages communication with the RingCentral Connect Platform API Explorer API v1.0 41 // In most cases there should be only one, shared, APIClient. 42 type APIClient struct { 43 cfg *Configuration 44 common service // Reuse a single struct instead of allocating one for each service on the heap. 45 46 // API Services 47 48 APIInfoApi *APIInfoApiService 49 50 AccountProvisioningApi *AccountProvisioningApiService 51 52 ApplicationSettingsApi *ApplicationSettingsApiService 53 54 CallHandlingSettingsApi *CallHandlingSettingsApiService 55 56 CallLogApi *CallLogApiService 57 58 CompanyContactsApi *CompanyContactsApiService 59 60 CompanySettingsApi *CompanySettingsApiService 61 62 GlipApi *GlipApiService 63 64 MeetingsApi *MeetingsApiService 65 66 MessagesApi *MessagesApiService 67 68 PhoneNumbersApi *PhoneNumbersApiService 69 70 PresenceApi *PresenceApiService 71 72 PushNotificationsApi *PushNotificationsApiService 73 74 RegionalSettingsApi *RegionalSettingsApiService 75 76 ReportingApi *ReportingApiService 77 78 RingOutApi *RingOutApiService 79 80 RolesAndPermissionsApi *RolesAndPermissionsApiService 81 82 SCIMApi *SCIMApiService 83 84 UserContactsApi *UserContactsApiService 85 86 UserSettingsApi *UserSettingsApiService 87 } 88 89 type service struct { 90 client *APIClient 91 } 92 93 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 94 // optionally a custom http.Client to allow for advanced features such as caching. 95 func NewAPIClient(cfg *Configuration) *APIClient { 96 if cfg.HTTPClient == nil { 97 cfg.HTTPClient = http.DefaultClient 98 } 99 100 c := &APIClient{} 101 c.cfg = cfg 102 c.common.client = c 103 104 // API Services 105 c.APIInfoApi = (*APIInfoApiService)(&c.common) 106 c.AccountProvisioningApi = (*AccountProvisioningApiService)(&c.common) 107 c.ApplicationSettingsApi = (*ApplicationSettingsApiService)(&c.common) 108 c.CallHandlingSettingsApi = (*CallHandlingSettingsApiService)(&c.common) 109 c.CallLogApi = (*CallLogApiService)(&c.common) 110 c.CompanyContactsApi = (*CompanyContactsApiService)(&c.common) 111 c.CompanySettingsApi = (*CompanySettingsApiService)(&c.common) 112 c.GlipApi = (*GlipApiService)(&c.common) 113 c.MeetingsApi = (*MeetingsApiService)(&c.common) 114 c.MessagesApi = (*MessagesApiService)(&c.common) 115 c.PhoneNumbersApi = (*PhoneNumbersApiService)(&c.common) 116 c.PresenceApi = (*PresenceApiService)(&c.common) 117 c.PushNotificationsApi = (*PushNotificationsApiService)(&c.common) 118 c.RegionalSettingsApi = (*RegionalSettingsApiService)(&c.common) 119 c.ReportingApi = (*ReportingApiService)(&c.common) 120 c.RingOutApi = (*RingOutApiService)(&c.common) 121 c.RolesAndPermissionsApi = (*RolesAndPermissionsApiService)(&c.common) 122 c.SCIMApi = (*SCIMApiService)(&c.common) 123 c.UserContactsApi = (*UserContactsApiService)(&c.common) 124 c.UserSettingsApi = (*UserSettingsApiService)(&c.common) 125 126 return c 127 } 128 129 func atoi(in string) (int, error) { 130 return strconv.Atoi(in) 131 } 132 133 // selectHeaderContentType select a content type from the available list. 134 func selectHeaderContentType(contentTypes []string) string { 135 if len(contentTypes) == 0 { 136 return "" 137 } 138 if contains(contentTypes, "application/json") { 139 return "application/json" 140 } 141 return contentTypes[0] // use the first content type specified in 'consumes' 142 } 143 144 // selectHeaderAccept join all accept types and return 145 func selectHeaderAccept(accepts []string) string { 146 if len(accepts) == 0 { 147 return "" 148 } 149 150 if contains(accepts, "application/json") { 151 return "application/json" 152 } 153 154 return strings.Join(accepts, ",") 155 } 156 157 // contains is a case insenstive match, finding needle in a haystack 158 func contains(haystack []string, needle string) bool { 159 for _, a := range haystack { 160 if strings.ToLower(a) == strings.ToLower(needle) { 161 return true 162 } 163 } 164 return false 165 } 166 167 // Verify optional parameters are of the correct type. 168 func typeCheckParameter(obj interface{}, expected string, name string) error { 169 // Make sure there is an object. 170 if obj == nil { 171 return nil 172 } 173 174 // Check the type is as expected. 175 if reflect.TypeOf(obj).String() != expected { 176 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 177 } 178 return nil 179 } 180 181 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 182 func parameterToString(obj interface{}, collectionFormat string) string { 183 var delimiter string 184 185 switch collectionFormat { 186 case "pipes": 187 delimiter = "|" 188 case "ssv": 189 delimiter = " " 190 case "tsv": 191 delimiter = "\t" 192 case "csv": 193 delimiter = "," 194 } 195 196 if reflect.TypeOf(obj).Kind() == reflect.Slice { 197 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 198 } else if t, ok := obj.(time.Time); ok { 199 return t.Format(time.RFC3339) 200 } 201 202 return fmt.Sprintf("%v", obj) 203 } 204 205 // callAPI do the request. 206 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 207 return c.cfg.HTTPClient.Do(request) 208 } 209 210 // Change base path to allow switching to mocks 211 func (c *APIClient) ChangeBasePath(path string) { 212 c.cfg.BasePath = path 213 } 214 215 // prepareRequest build the request 216 func (c *APIClient) prepareRequest( 217 ctx context.Context, 218 path string, method string, 219 postBody interface{}, 220 headerParams map[string]string, 221 queryParams url.Values, 222 formParams url.Values, 223 formFileName string, 224 fileName string, 225 fileBytes []byte) (localVarRequest *http.Request, err error) { 226 227 var body *bytes.Buffer 228 229 // Detect postBody type and post. 230 if postBody != nil { 231 contentType := headerParams["Content-Type"] 232 if contentType == "" { 233 contentType = detectContentType(postBody) 234 headerParams["Content-Type"] = contentType 235 } 236 237 body, err = setBody(postBody, contentType) 238 if err != nil { 239 return nil, err 240 } 241 } 242 243 // add form parameters and file if available. 244 if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 245 if body != nil { 246 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 247 } 248 body = &bytes.Buffer{} 249 w := multipart.NewWriter(body) 250 251 for k, v := range formParams { 252 for _, iv := range v { 253 if strings.HasPrefix(k, "@") { // file 254 err = addFile(w, k[1:], iv) 255 if err != nil { 256 return nil, err 257 } 258 } else { // form value 259 w.WriteField(k, iv) 260 } 261 } 262 } 263 if len(fileBytes) > 0 && fileName != "" { 264 w.Boundary() 265 //_, fileNm := filepath.Split(fileName) 266 part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) 267 if err != nil { 268 return nil, err 269 } 270 _, err = part.Write(fileBytes) 271 if err != nil { 272 return nil, err 273 } 274 // Set the Boundary in the Content-Type 275 headerParams["Content-Type"] = w.FormDataContentType() 276 } 277 278 // Set Content-Length 279 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 280 w.Close() 281 } 282 283 if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { 284 if body != nil { 285 return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") 286 } 287 body = &bytes.Buffer{} 288 body.WriteString(formParams.Encode()) 289 // Set Content-Length 290 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 291 } 292 293 // Setup path and query parameters 294 url, err := url.Parse(path) 295 if err != nil { 296 return nil, err 297 } 298 299 // Adding Query Param 300 query := url.Query() 301 for k, v := range queryParams { 302 for _, iv := range v { 303 query.Add(k, iv) 304 } 305 } 306 307 // Encode the parameters. 308 url.RawQuery = query.Encode() 309 310 // Generate a new request 311 if body != nil { 312 localVarRequest, err = http.NewRequest(method, url.String(), body) 313 } else { 314 localVarRequest, err = http.NewRequest(method, url.String(), nil) 315 } 316 if err != nil { 317 return nil, err 318 } 319 320 // add header parameters, if any 321 if len(headerParams) > 0 { 322 headers := http.Header{} 323 for h, v := range headerParams { 324 headers.Set(h, v) 325 } 326 localVarRequest.Header = headers 327 } 328 329 // Override request host, if applicable 330 if c.cfg.Host != "" { 331 localVarRequest.Host = c.cfg.Host 332 } 333 334 // Add the user agent to the request. 335 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 336 337 if ctx != nil { 338 // add context to the request 339 localVarRequest = localVarRequest.WithContext(ctx) 340 341 // Walk through any authentication. 342 343 // OAuth2 authentication 344 if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { 345 // We were able to grab an oauth2 token from the context 346 var latestToken *oauth2.Token 347 if latestToken, err = tok.Token(); err != nil { 348 return nil, err 349 } 350 351 latestToken.SetAuthHeader(localVarRequest) 352 } 353 354 // Basic HTTP Authentication 355 if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { 356 localVarRequest.SetBasicAuth(auth.UserName, auth.Password) 357 } 358 359 // AccessToken Authentication 360 if auth, ok := ctx.Value(ContextAccessToken).(string); ok { 361 localVarRequest.Header.Add("Authorization", "Bearer "+auth) 362 } 363 } 364 365 for header, value := range c.cfg.DefaultHeader { 366 localVarRequest.Header.Add(header, value) 367 } 368 369 return localVarRequest, nil 370 } 371 372 func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { 373 if strings.Contains(contentType, "application/xml") { 374 if err = xml.Unmarshal(b, v); err != nil { 375 return err 376 } 377 return nil 378 } else if strings.Contains(contentType, "application/json") { 379 if err = json.Unmarshal(b, v); err != nil { 380 return err 381 } 382 return nil 383 } 384 return errors.New("undefined response type") 385 } 386 387 // Add a file to the multipart request 388 func addFile(w *multipart.Writer, fieldName, path string) error { 389 file, err := os.Open(path) 390 if err != nil { 391 return err 392 } 393 defer file.Close() 394 395 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 396 if err != nil { 397 return err 398 } 399 _, err = io.Copy(part, file) 400 401 return err 402 } 403 404 // Prevent trying to import "fmt" 405 func reportError(format string, a ...interface{}) error { 406 return fmt.Errorf(format, a...) 407 } 408 409 // Set request body from an interface{} 410 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 411 if bodyBuf == nil { 412 bodyBuf = &bytes.Buffer{} 413 } 414 415 if reader, ok := body.(io.Reader); ok { 416 _, err = bodyBuf.ReadFrom(reader) 417 } else if b, ok := body.([]byte); ok { 418 _, err = bodyBuf.Write(b) 419 } else if s, ok := body.(string); ok { 420 _, err = bodyBuf.WriteString(s) 421 } else if s, ok := body.(*string); ok { 422 _, err = bodyBuf.WriteString(*s) 423 } else if jsonCheck.MatchString(contentType) { 424 err = json.NewEncoder(bodyBuf).Encode(body) 425 } else if xmlCheck.MatchString(contentType) { 426 xml.NewEncoder(bodyBuf).Encode(body) 427 } 428 429 if err != nil { 430 return nil, err 431 } 432 433 if bodyBuf.Len() == 0 { 434 err = fmt.Errorf("Invalid body type %s\n", contentType) 435 return nil, err 436 } 437 return bodyBuf, nil 438 } 439 440 // detectContentType method is used to figure out `Request.Body` content type for request header 441 func detectContentType(body interface{}) string { 442 contentType := "text/plain; charset=utf-8" 443 kind := reflect.TypeOf(body).Kind() 444 445 switch kind { 446 case reflect.Struct, reflect.Map, reflect.Ptr: 447 contentType = "application/json; charset=utf-8" 448 case reflect.String: 449 contentType = "text/plain; charset=utf-8" 450 default: 451 if b, ok := body.([]byte); ok { 452 contentType = http.DetectContentType(b) 453 } else if kind == reflect.Slice { 454 contentType = "application/json; charset=utf-8" 455 } 456 } 457 458 return contentType 459 } 460 461 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 462 type cacheControl map[string]string 463 464 func parseCacheControl(headers http.Header) cacheControl { 465 cc := cacheControl{} 466 ccHeader := headers.Get("Cache-Control") 467 for _, part := range strings.Split(ccHeader, ",") { 468 part = strings.Trim(part, " ") 469 if part == "" { 470 continue 471 } 472 if strings.ContainsRune(part, '=') { 473 keyval := strings.Split(part, "=") 474 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 475 } else { 476 cc[part] = "" 477 } 478 } 479 return cc 480 } 481 482 // CacheExpires helper function to determine remaining time before repeating a request. 483 func CacheExpires(r *http.Response) time.Time { 484 // Figure out when the cache expires. 485 var expires time.Time 486 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 487 if err != nil { 488 return time.Now() 489 } 490 respCacheControl := parseCacheControl(r.Header) 491 492 if maxAge, ok := respCacheControl["max-age"]; ok { 493 lifetime, err := time.ParseDuration(maxAge + "s") 494 if err != nil { 495 expires = now 496 } else { 497 expires = now.Add(lifetime) 498 } 499 } else { 500 expiresHeader := r.Header.Get("Expires") 501 if expiresHeader != "" { 502 expires, err = time.Parse(time.RFC1123, expiresHeader) 503 if err != nil { 504 expires = now 505 } 506 } 507 } 508 return expires 509 } 510 511 func strlen(s string) int { 512 return utf8.RuneCountInString(s) 513 } 514 515 // GenericOpenAPIError Provides access to the body, error and model on returned errors. 516 type GenericOpenAPIError struct { 517 body []byte 518 error string 519 model interface{} 520 } 521 522 // Error returns non-empty string if there was an error. 523 func (e GenericOpenAPIError) Error() string { 524 return e.error 525 } 526 527 // Body returns the raw bytes of the response 528 func (e GenericOpenAPIError) Body() []byte { 529 return e.body 530 } 531 532 // Model returns the unpacked model of the error 533 func (e GenericOpenAPIError) Model() interface{} { 534 return e.model 535 } 536 537 func (apiClient *APIClient) HTTPClient() *http.Client { return apiClient.cfg.HTTPClient }