github.com/grokify/go-ringcentral-client@v0.3.31/engagevoice/v1/client/client.go (about)

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