github.com/grokify/go-ringcentral-client@v0.3.31/engagedigital/v1/client/client.go (about) 1 /* 2 * Engage Digital API 3 * 4 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) 5 * 6 * API version: 1.0 7 * Generated by: OpenAPI Generator (https://openapi-generator.tech) 8 */ 9 10 package engagedigital 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)/(?:vnd\.[^;]+\+)?json)`) 37 xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) 38 ) 39 40 // APIClient manages communication with the Engage Digital API 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 AgentStatusApi *AgentStatusApiService 49 50 AttachmentsApi *AttachmentsApiService 51 52 CategoriesApi *CategoriesApiService 53 54 ChannelsApi *ChannelsApiService 55 56 CommunitiesApi *CommunitiesApiService 57 58 ContentsApi *ContentsApiService 59 60 CustomFieldsApi *CustomFieldsApiService 61 62 EventsApi *EventsApiService 63 64 FoldersApi *FoldersApiService 65 66 IdentitiesApi *IdentitiesApiService 67 68 IdentityGroupsApi *IdentityGroupsApiService 69 70 InterventionCommentsApi *InterventionCommentsApiService 71 72 InterventionsApi *InterventionsApiService 73 74 LocalesApi *LocalesApiService 75 76 PresenceStatusApi *PresenceStatusApiService 77 78 ReplyAssistantEntriesApi *ReplyAssistantEntriesApiService 79 80 ReplyAssistantGroupsApi *ReplyAssistantGroupsApiService 81 82 ReplyAssistantVersionsApi *ReplyAssistantVersionsApiService 83 84 RolesApi *RolesApiService 85 86 SettingsApi *SettingsApiService 87 88 SourcesApi *SourcesApiService 89 90 TagsApi *TagsApiService 91 92 TasksApi *TasksApiService 93 94 TeamsApi *TeamsApiService 95 96 ThreadsApi *ThreadsApiService 97 98 TimeSheetsApi *TimeSheetsApiService 99 100 TimezonesApi *TimezonesApiService 101 102 UsersApi *UsersApiService 103 104 WebhooksApi *WebhooksApiService 105 } 106 107 type service struct { 108 client *APIClient 109 } 110 111 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 112 // optionally a custom http.Client to allow for advanced features such as caching. 113 func NewAPIClient(cfg *Configuration) *APIClient { 114 if cfg.HTTPClient == nil { 115 cfg.HTTPClient = http.DefaultClient 116 } 117 118 c := &APIClient{} 119 c.cfg = cfg 120 c.common.client = c 121 122 // API Services 123 c.AgentStatusApi = (*AgentStatusApiService)(&c.common) 124 c.AttachmentsApi = (*AttachmentsApiService)(&c.common) 125 c.CategoriesApi = (*CategoriesApiService)(&c.common) 126 c.ChannelsApi = (*ChannelsApiService)(&c.common) 127 c.CommunitiesApi = (*CommunitiesApiService)(&c.common) 128 c.ContentsApi = (*ContentsApiService)(&c.common) 129 c.CustomFieldsApi = (*CustomFieldsApiService)(&c.common) 130 c.EventsApi = (*EventsApiService)(&c.common) 131 c.FoldersApi = (*FoldersApiService)(&c.common) 132 c.IdentitiesApi = (*IdentitiesApiService)(&c.common) 133 c.IdentityGroupsApi = (*IdentityGroupsApiService)(&c.common) 134 c.InterventionCommentsApi = (*InterventionCommentsApiService)(&c.common) 135 c.InterventionsApi = (*InterventionsApiService)(&c.common) 136 c.LocalesApi = (*LocalesApiService)(&c.common) 137 c.PresenceStatusApi = (*PresenceStatusApiService)(&c.common) 138 c.ReplyAssistantEntriesApi = (*ReplyAssistantEntriesApiService)(&c.common) 139 c.ReplyAssistantGroupsApi = (*ReplyAssistantGroupsApiService)(&c.common) 140 c.ReplyAssistantVersionsApi = (*ReplyAssistantVersionsApiService)(&c.common) 141 c.RolesApi = (*RolesApiService)(&c.common) 142 c.SettingsApi = (*SettingsApiService)(&c.common) 143 c.SourcesApi = (*SourcesApiService)(&c.common) 144 c.TagsApi = (*TagsApiService)(&c.common) 145 c.TasksApi = (*TasksApiService)(&c.common) 146 c.TeamsApi = (*TeamsApiService)(&c.common) 147 c.ThreadsApi = (*ThreadsApiService)(&c.common) 148 c.TimeSheetsApi = (*TimeSheetsApiService)(&c.common) 149 c.TimezonesApi = (*TimezonesApiService)(&c.common) 150 c.UsersApi = (*UsersApiService)(&c.common) 151 c.WebhooksApi = (*WebhooksApiService)(&c.common) 152 153 return c 154 } 155 156 func atoi(in string) (int, error) { 157 return strconv.Atoi(in) 158 } 159 160 // selectHeaderContentType select a content type from the available list. 161 func selectHeaderContentType(contentTypes []string) string { 162 if len(contentTypes) == 0 { 163 return "" 164 } 165 if contains(contentTypes, "application/json") { 166 return "application/json" 167 } 168 return contentTypes[0] // use the first content type specified in 'consumes' 169 } 170 171 // selectHeaderAccept join all accept types and return 172 func selectHeaderAccept(accepts []string) string { 173 if len(accepts) == 0 { 174 return "" 175 } 176 177 if contains(accepts, "application/json") { 178 return "application/json" 179 } 180 181 return strings.Join(accepts, ",") 182 } 183 184 // contains is a case insenstive match, finding needle in a haystack 185 func contains(haystack []string, needle string) bool { 186 for _, a := range haystack { 187 if strings.ToLower(a) == strings.ToLower(needle) { 188 return true 189 } 190 } 191 return false 192 } 193 194 // Verify optional parameters are of the correct type. 195 func typeCheckParameter(obj interface{}, expected string, name string) error { 196 // Make sure there is an object. 197 if obj == nil { 198 return nil 199 } 200 201 // Check the type is as expected. 202 if reflect.TypeOf(obj).String() != expected { 203 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 204 } 205 return nil 206 } 207 208 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 209 func parameterToString(obj interface{}, collectionFormat string) string { 210 var delimiter string 211 212 switch collectionFormat { 213 case "pipes": 214 delimiter = "|" 215 case "ssv": 216 delimiter = " " 217 case "tsv": 218 delimiter = "\t" 219 case "csv": 220 delimiter = "," 221 } 222 223 if reflect.TypeOf(obj).Kind() == reflect.Slice { 224 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 225 } else if t, ok := obj.(time.Time); ok { 226 return t.Format(time.RFC3339) 227 } 228 229 return fmt.Sprintf("%v", obj) 230 } 231 232 // helper for converting interface{} parameters to json strings 233 func parameterToJson(obj interface{}) (string, error) { 234 jsonBuf, err := json.Marshal(obj) 235 if err != nil { 236 return "", err 237 } 238 return string(jsonBuf), err 239 } 240 241 // callAPI do the request. 242 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 243 return c.cfg.HTTPClient.Do(request) 244 } 245 246 // Change base path to allow switching to mocks 247 func (c *APIClient) ChangeBasePath(path string) { 248 c.cfg.BasePath = path 249 } 250 251 // prepareRequest build the request 252 func (c *APIClient) prepareRequest( 253 ctx context.Context, 254 path string, method string, 255 postBody interface{}, 256 headerParams map[string]string, 257 queryParams url.Values, 258 formParams url.Values, 259 formFileName string, 260 fileName string, 261 fileBytes []byte) (localVarRequest *http.Request, err error) { 262 263 var body *bytes.Buffer 264 265 // Detect postBody type and post. 266 if postBody != nil { 267 contentType := headerParams["Content-Type"] 268 if contentType == "" { 269 contentType = detectContentType(postBody) 270 headerParams["Content-Type"] = contentType 271 } 272 273 body, err = setBody(postBody, contentType) 274 if err != nil { 275 return nil, err 276 } 277 } 278 279 // add form parameters and file if available. 280 if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 281 if body != nil { 282 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 283 } 284 body = &bytes.Buffer{} 285 w := multipart.NewWriter(body) 286 287 for k, v := range formParams { 288 for _, iv := range v { 289 if strings.HasPrefix(k, "@") { // file 290 err = addFile(w, k[1:], iv) 291 if err != nil { 292 return nil, err 293 } 294 } else { // form value 295 w.WriteField(k, iv) 296 } 297 } 298 } 299 if len(fileBytes) > 0 && fileName != "" { 300 w.Boundary() 301 //_, fileNm := filepath.Split(fileName) 302 part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) 303 if err != nil { 304 return nil, err 305 } 306 _, err = part.Write(fileBytes) 307 if err != nil { 308 return nil, err 309 } 310 } 311 312 // Set the Boundary in the Content-Type 313 headerParams["Content-Type"] = w.FormDataContentType() 314 315 // Set Content-Length 316 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 317 w.Close() 318 } 319 320 if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { 321 if body != nil { 322 return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") 323 } 324 body = &bytes.Buffer{} 325 body.WriteString(formParams.Encode()) 326 // Set Content-Length 327 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 328 } 329 330 // Setup path and query parameters 331 url, err := url.Parse(path) 332 if err != nil { 333 return nil, err 334 } 335 336 // Override request host, if applicable 337 if c.cfg.Host != "" { 338 url.Host = c.cfg.Host 339 } 340 341 // Override request scheme, if applicable 342 if c.cfg.Scheme != "" { 343 url.Scheme = c.cfg.Scheme 344 } 345 346 // Adding Query Param 347 query := url.Query() 348 for k, v := range queryParams { 349 for _, iv := range v { 350 query.Add(k, iv) 351 } 352 } 353 354 // Encode the parameters. 355 url.RawQuery = query.Encode() 356 357 // Generate a new request 358 if body != nil { 359 localVarRequest, err = http.NewRequest(method, url.String(), body) 360 } else { 361 localVarRequest, err = http.NewRequest(method, url.String(), nil) 362 } 363 if err != nil { 364 return nil, err 365 } 366 367 // add header parameters, if any 368 if len(headerParams) > 0 { 369 headers := http.Header{} 370 for h, v := range headerParams { 371 headers.Set(h, v) 372 } 373 localVarRequest.Header = headers 374 } 375 376 // Add the user agent to the request. 377 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 378 379 if ctx != nil { 380 // add context to the request 381 localVarRequest = localVarRequest.WithContext(ctx) 382 383 // Walk through any authentication. 384 385 // OAuth2 authentication 386 if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { 387 // We were able to grab an oauth2 token from the context 388 var latestToken *oauth2.Token 389 if latestToken, err = tok.Token(); err != nil { 390 return nil, err 391 } 392 393 latestToken.SetAuthHeader(localVarRequest) 394 } 395 396 // Basic HTTP Authentication 397 if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { 398 localVarRequest.SetBasicAuth(auth.UserName, auth.Password) 399 } 400 401 // AccessToken Authentication 402 if auth, ok := ctx.Value(ContextAccessToken).(string); ok { 403 localVarRequest.Header.Add("Authorization", "Bearer "+auth) 404 } 405 } 406 407 for header, value := range c.cfg.DefaultHeader { 408 localVarRequest.Header.Add(header, value) 409 } 410 411 return localVarRequest, nil 412 } 413 414 func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { 415 if s, ok := v.(*string); ok { 416 *s = string(b) 417 return nil 418 } 419 if xmlCheck.MatchString(contentType) { 420 if err = xml.Unmarshal(b, v); err != nil { 421 return err 422 } 423 return nil 424 } 425 if jsonCheck.MatchString(contentType) { 426 if err = json.Unmarshal(b, v); err != nil { 427 return err 428 } 429 return nil 430 } 431 return errors.New("undefined response type") 432 } 433 434 // Add a file to the multipart request 435 func addFile(w *multipart.Writer, fieldName, path string) error { 436 file, err := os.Open(path) 437 if err != nil { 438 return err 439 } 440 defer file.Close() 441 442 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 443 if err != nil { 444 return err 445 } 446 _, err = io.Copy(part, file) 447 448 return err 449 } 450 451 // Prevent trying to import "fmt" 452 func reportError(format string, a ...interface{}) error { 453 return fmt.Errorf(format, a...) 454 } 455 456 // Set request body from an interface{} 457 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 458 if bodyBuf == nil { 459 bodyBuf = &bytes.Buffer{} 460 } 461 462 if reader, ok := body.(io.Reader); ok { 463 _, err = bodyBuf.ReadFrom(reader) 464 } else if b, ok := body.([]byte); ok { 465 _, err = bodyBuf.Write(b) 466 } else if s, ok := body.(string); ok { 467 _, err = bodyBuf.WriteString(s) 468 } else if s, ok := body.(*string); ok { 469 _, err = bodyBuf.WriteString(*s) 470 } else if jsonCheck.MatchString(contentType) { 471 err = json.NewEncoder(bodyBuf).Encode(body) 472 } else if xmlCheck.MatchString(contentType) { 473 err = xml.NewEncoder(bodyBuf).Encode(body) 474 } 475 476 if err != nil { 477 return nil, err 478 } 479 480 if bodyBuf.Len() == 0 { 481 err = fmt.Errorf("Invalid body type %s\n", contentType) 482 return nil, err 483 } 484 return bodyBuf, nil 485 } 486 487 // detectContentType method is used to figure out `Request.Body` content type for request header 488 func detectContentType(body interface{}) string { 489 contentType := "text/plain; charset=utf-8" 490 kind := reflect.TypeOf(body).Kind() 491 492 switch kind { 493 case reflect.Struct, reflect.Map, reflect.Ptr: 494 contentType = "application/json; charset=utf-8" 495 case reflect.String: 496 contentType = "text/plain; charset=utf-8" 497 default: 498 if b, ok := body.([]byte); ok { 499 contentType = http.DetectContentType(b) 500 } else if kind == reflect.Slice { 501 contentType = "application/json; charset=utf-8" 502 } 503 } 504 505 return contentType 506 } 507 508 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 509 type cacheControl map[string]string 510 511 func parseCacheControl(headers http.Header) cacheControl { 512 cc := cacheControl{} 513 ccHeader := headers.Get("Cache-Control") 514 for _, part := range strings.Split(ccHeader, ",") { 515 part = strings.Trim(part, " ") 516 if part == "" { 517 continue 518 } 519 if strings.ContainsRune(part, '=') { 520 keyval := strings.Split(part, "=") 521 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 522 } else { 523 cc[part] = "" 524 } 525 } 526 return cc 527 } 528 529 // CacheExpires helper function to determine remaining time before repeating a request. 530 func CacheExpires(r *http.Response) time.Time { 531 // Figure out when the cache expires. 532 var expires time.Time 533 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 534 if err != nil { 535 return time.Now() 536 } 537 respCacheControl := parseCacheControl(r.Header) 538 539 if maxAge, ok := respCacheControl["max-age"]; ok { 540 lifetime, err := time.ParseDuration(maxAge + "s") 541 if err != nil { 542 expires = now 543 } else { 544 expires = now.Add(lifetime) 545 } 546 } else { 547 expiresHeader := r.Header.Get("Expires") 548 if expiresHeader != "" { 549 expires, err = time.Parse(time.RFC1123, expiresHeader) 550 if err != nil { 551 expires = now 552 } 553 } 554 } 555 return expires 556 } 557 558 func strlen(s string) int { 559 return utf8.RuneCountInString(s) 560 } 561 562 // GenericOpenAPIError Provides access to the body, error and model on returned errors. 563 type GenericOpenAPIError struct { 564 body []byte 565 error string 566 model interface{} 567 } 568 569 // Error returns non-empty string if there was an error. 570 func (e GenericOpenAPIError) Error() string { 571 return e.error 572 } 573 574 // Body returns the raw bytes of the response 575 func (e GenericOpenAPIError) Body() []byte { 576 return e.body 577 } 578 579 // Model returns the unpacked model of the error 580 func (e GenericOpenAPIError) Model() interface{} { 581 return e.model 582 } 583 584 func (apiClient *APIClient) HTTPClient() *http.Client { return apiClient.cfg.HTTPClient }