github.com/optim-corp/cios-golang-sdk@v0.5.1/cios/client.go (about)

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