github.com/antihax/goesi@v0.0.0-20240126031043-6c54d0cb7f95/esi/client.go (about)

     1  /*
     2   * EVE Swagger Interface
     3   *
     4   * An OpenAPI for EVE Online
     5   *
     6   * OpenAPI spec version: 1.21
     7   *
     8   * Generated by: https://github.com/swagger-api/swagger-codegen.git
     9   *
    10   * Licensed under the Apache License, Version 2.0 (the "License");
    11   * you may not use this file except in compliance with the License.
    12   * You may obtain a copy of the License at
    13   *
    14   *      http://www.apache.org/licenses/LICENSE-2.0
    15   *
    16   * Unless required by applicable law or agreed to in writing, software
    17   * distributed under the License is distributed on an "AS IS" BASIS,
    18   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    19   * See the License for the specific language governing permissions and
    20   * limitations under the License.
    21   */
    22  
    23  package esi
    24  
    25  import (
    26  	"bytes"
    27  	"encoding/json"
    28  	"encoding/xml"
    29  	"errors"
    30  	"fmt"
    31  	"io"
    32  	"mime/multipart"
    33  	"net/http"
    34  	"net/url"
    35  	"os"
    36  	"path/filepath"
    37  	"reflect"
    38  	"regexp"
    39  	"strconv"
    40  	"strings"
    41  	"time"
    42  	"unicode/utf8"
    43  
    44  	"context"
    45  
    46  	"golang.org/x/oauth2"
    47  )
    48  
    49  var (
    50  	jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
    51  	xmlCheck  = regexp.MustCompile("(?i:[application|text]/xml)")
    52  )
    53  
    54  // APIClient manages communication with the EVE Swagger Interface API v1.21
    55  // In most cases there should be only one, shared, APIClient.
    56  type APIClient struct {
    57  	client    *http.Client // The HTTP client.
    58  	userAgent string       // User Agent
    59  	common    service      // Reuse a single struct instead of allocating one for each service on the heap.
    60  	basePath  string       //
    61  
    62  	// API Services
    63  	AllianceApi             *AllianceApiService
    64  	AssetsApi               *AssetsApiService
    65  	BookmarksApi            *BookmarksApiService
    66  	CalendarApi             *CalendarApiService
    67  	CharacterApi            *CharacterApiService
    68  	ClonesApi               *ClonesApiService
    69  	ContactsApi             *ContactsApiService
    70  	ContractsApi            *ContractsApiService
    71  	CorporationApi          *CorporationApiService
    72  	DogmaApi                *DogmaApiService
    73  	FactionWarfareApi       *FactionWarfareApiService
    74  	FittingsApi             *FittingsApiService
    75  	FleetsApi               *FleetsApiService
    76  	IncursionsApi           *IncursionsApiService
    77  	IndustryApi             *IndustryApiService
    78  	InsuranceApi            *InsuranceApiService
    79  	KillmailsApi            *KillmailsApiService
    80  	LocationApi             *LocationApiService
    81  	LoyaltyApi              *LoyaltyApiService
    82  	MailApi                 *MailApiService
    83  	MarketApi               *MarketApiService
    84  	OpportunitiesApi        *OpportunitiesApiService
    85  	PlanetaryInteractionApi *PlanetaryInteractionApiService
    86  	RoutesApi               *RoutesApiService
    87  	SearchApi               *SearchApiService
    88  	SkillsApi               *SkillsApiService
    89  	SovereigntyApi          *SovereigntyApiService
    90  	StatusApi               *StatusApiService
    91  	UniverseApi             *UniverseApiService
    92  	UserInterfaceApi        *UserInterfaceApiService
    93  	WalletApi               *WalletApiService
    94  	WarsApi                 *WarsApiService
    95  }
    96  
    97  type service struct {
    98  	client *APIClient
    99  }
   100  
   101  // NewAPIClient creates a new API client. Requires a userAgent string describing your application.
   102  // optionally a custom http.Client to allow for advanced features such as caching.
   103  func NewAPIClient(httpClient *http.Client, userAgent string) *APIClient {
   104  	if httpClient == nil {
   105  		httpClient = http.DefaultClient
   106  	}
   107  
   108  	c := &APIClient{}
   109  	c.client = httpClient
   110  	c.basePath = "https://esi.evetech.net"
   111  	c.userAgent = userAgent
   112  	c.common.client = c
   113  
   114  	// API Services
   115  	c.AllianceApi = (*AllianceApiService)(&c.common)
   116  	c.AssetsApi = (*AssetsApiService)(&c.common)
   117  	c.BookmarksApi = (*BookmarksApiService)(&c.common)
   118  	c.CalendarApi = (*CalendarApiService)(&c.common)
   119  	c.CharacterApi = (*CharacterApiService)(&c.common)
   120  	c.ClonesApi = (*ClonesApiService)(&c.common)
   121  	c.ContactsApi = (*ContactsApiService)(&c.common)
   122  	c.ContractsApi = (*ContractsApiService)(&c.common)
   123  	c.CorporationApi = (*CorporationApiService)(&c.common)
   124  	c.DogmaApi = (*DogmaApiService)(&c.common)
   125  	c.FactionWarfareApi = (*FactionWarfareApiService)(&c.common)
   126  	c.FittingsApi = (*FittingsApiService)(&c.common)
   127  	c.FleetsApi = (*FleetsApiService)(&c.common)
   128  	c.IncursionsApi = (*IncursionsApiService)(&c.common)
   129  	c.IndustryApi = (*IndustryApiService)(&c.common)
   130  	c.InsuranceApi = (*InsuranceApiService)(&c.common)
   131  	c.KillmailsApi = (*KillmailsApiService)(&c.common)
   132  	c.LocationApi = (*LocationApiService)(&c.common)
   133  	c.LoyaltyApi = (*LoyaltyApiService)(&c.common)
   134  	c.MailApi = (*MailApiService)(&c.common)
   135  	c.MarketApi = (*MarketApiService)(&c.common)
   136  	c.OpportunitiesApi = (*OpportunitiesApiService)(&c.common)
   137  	c.PlanetaryInteractionApi = (*PlanetaryInteractionApiService)(&c.common)
   138  	c.RoutesApi = (*RoutesApiService)(&c.common)
   139  	c.SearchApi = (*SearchApiService)(&c.common)
   140  	c.SkillsApi = (*SkillsApiService)(&c.common)
   141  	c.SovereigntyApi = (*SovereigntyApiService)(&c.common)
   142  	c.StatusApi = (*StatusApiService)(&c.common)
   143  	c.UniverseApi = (*UniverseApiService)(&c.common)
   144  	c.UserInterfaceApi = (*UserInterfaceApiService)(&c.common)
   145  	c.WalletApi = (*WalletApiService)(&c.common)
   146  	c.WarsApi = (*WarsApiService)(&c.common)
   147  
   148  	return c
   149  }
   150  
   151  func atoi(in string) (int, error) {
   152  	return strconv.Atoi(in)
   153  }
   154  
   155  // selectHeaderContentType select a content type from the available list.
   156  func selectHeaderContentType(contentTypes []string) string {
   157  	if len(contentTypes) == 0 {
   158  		return ""
   159  	}
   160  	if contains(contentTypes, "application/json") {
   161  		return "application/json"
   162  	}
   163  	return contentTypes[0] // use the first content type specified in 'consumes'
   164  }
   165  
   166  // selectHeaderAccept join all accept types and return
   167  func selectHeaderAccept(accepts []string) string {
   168  	if len(accepts) == 0 {
   169  		return ""
   170  	}
   171  
   172  	if contains(accepts, "application/json") {
   173  		return "application/json"
   174  	}
   175  
   176  	return strings.Join(accepts, ",")
   177  }
   178  
   179  // contains is a case insenstive match, finding needle in a haystack
   180  func contains(haystack []string, needle string) bool {
   181  	for _, a := range haystack {
   182  		if strings.ToLower(a) == strings.ToLower(needle) {
   183  			return true
   184  		}
   185  	}
   186  	return false
   187  }
   188  
   189  // Verify optional parameters are of the correct type.
   190  func typeCheckParameter(obj interface{}, expected string, name string) error {
   191  	// Make sure there is an object.
   192  	if obj == nil {
   193  		return nil
   194  	}
   195  
   196  	// Check the type is as expected.
   197  	if reflect.TypeOf(obj).String() != expected {
   198  		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
   199  	}
   200  	return nil
   201  }
   202  
   203  // parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
   204  func parameterToString(obj interface{}, collectionFormat string) string {
   205  	var delimiter string
   206  
   207  	switch collectionFormat {
   208  	case "pipes":
   209  		delimiter = "|"
   210  	case "ssv":
   211  		delimiter = " "
   212  	case "tsv":
   213  		delimiter = "\t"
   214  	case "csv":
   215  		delimiter = ","
   216  	}
   217  
   218  	if reflect.TypeOf(obj).Kind() == reflect.Slice {
   219  		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
   220  	}
   221  
   222  	return fmt.Sprintf("%v", obj)
   223  }
   224  
   225  // callAPI do the request.
   226  func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
   227  	return c.client.Do(request)
   228  }
   229  
   230  // Change base path to allow switching to mocks
   231  func (c *APIClient) ChangeBasePath(path string) {
   232  	c.basePath = path
   233  }
   234  
   235  // prepareRequest build the request
   236  func (c *APIClient) prepareRequest(
   237  	ctx context.Context,
   238  	path string, method string,
   239  	postBody interface{},
   240  	headerParams map[string]string,
   241  	queryParams url.Values,
   242  	formParams url.Values,
   243  	fileName string,
   244  	fileBytes []byte) (localVarRequest *http.Request, err error) {
   245  
   246  	var body *bytes.Buffer
   247  
   248  	// Detect postBody type and post.
   249  	if postBody != nil {
   250  		contentType := headerParams["Content-Type"]
   251  		if contentType == "" {
   252  			contentType = detectContentType(postBody)
   253  			headerParams["Content-Type"] = contentType
   254  		}
   255  
   256  		body, err = setBody(postBody, contentType)
   257  		if err != nil {
   258  			return nil, err
   259  		}
   260  	}
   261  
   262  	// add form parameters and file if available.
   263  	if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
   264  		if body != nil {
   265  			return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
   266  		}
   267  		body = &bytes.Buffer{}
   268  		w := multipart.NewWriter(body)
   269  
   270  		for k, v := range formParams {
   271  			for _, iv := range v {
   272  				if strings.HasPrefix(k, "@") { // file
   273  					err = addFile(w, k[1:], iv)
   274  					if err != nil {
   275  						return nil, err
   276  					}
   277  				} else { // form value
   278  					w.WriteField(k, iv)
   279  				}
   280  			}
   281  		}
   282  		if len(fileBytes) > 0 && fileName != "" {
   283  			w.Boundary()
   284  			//_, fileNm := filepath.Split(fileName)
   285  			part, err := w.CreateFormFile("file", filepath.Base(fileName))
   286  			if err != nil {
   287  				return nil, err
   288  			}
   289  			_, err = part.Write(fileBytes)
   290  			if err != nil {
   291  				return nil, err
   292  			}
   293  			// Set the Boundary in the Content-Type
   294  			headerParams["Content-Type"] = w.FormDataContentType()
   295  		}
   296  
   297  		// Set Content-Length
   298  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   299  		w.Close()
   300  	}
   301  
   302  	// Setup path and query parameters
   303  	url, err := url.Parse(path)
   304  	if err != nil {
   305  		return nil, err
   306  	}
   307  
   308  	// Adding Query Param
   309  	query := url.Query()
   310  	for k, v := range queryParams {
   311  		for _, iv := range v {
   312  			query.Add(k, iv)
   313  		}
   314  	}
   315  
   316  	// Encode the parameters.
   317  	url.RawQuery = query.Encode()
   318  
   319  	// Generate a new request
   320  	if body != nil {
   321  		localVarRequest, err = http.NewRequest(method, url.String(), body)
   322  	} else {
   323  		localVarRequest, err = http.NewRequest(method, url.String(), nil)
   324  	}
   325  	if err != nil {
   326  		return nil, err
   327  	}
   328  
   329  	// add header parameters, if any
   330  	if len(headerParams) > 0 {
   331  		headers := http.Header{}
   332  		for h, v := range headerParams {
   333  			headers.Set(h, v)
   334  		}
   335  		localVarRequest.Header = headers
   336  	}
   337  
   338  	localVarRequest.Header.Add("user-agent", c.userAgent)
   339  
   340  	if ctx != nil {
   341  		// add context to the request
   342  		localVarRequest = localVarRequest.WithContext(ctx)
   343  
   344  		// Walk through any authentication.
   345  
   346  		// OAuth2 authentication
   347  		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
   348  			// We were able to grab an oauth2 token from the context
   349  			var latestToken *oauth2.Token
   350  			if latestToken, err = tok.Token(); err != nil {
   351  				return nil, err
   352  			}
   353  
   354  			latestToken.SetAuthHeader(localVarRequest)
   355  		}
   356  
   357  		// Basic HTTP Authentication
   358  		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
   359  			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
   360  		}
   361  
   362  		// AccessToken Authentication
   363  		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
   364  			localVarRequest.Header.Add("authorization", "Bearer "+auth)
   365  		}
   366  	}
   367  
   368  	return localVarRequest, nil
   369  }
   370  
   371  func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
   372  	if strings.Contains(contentType, "application/xml") {
   373  		if err = xml.Unmarshal(b, v); err != nil {
   374  			return err
   375  		}
   376  		return nil
   377  	} else if strings.Contains(contentType, "application/json") {
   378  		if err = json.Unmarshal(b, v); err != nil {
   379  			return err
   380  		}
   381  		return nil
   382  	}
   383  	return errors.New("undefined response type")
   384  }
   385  
   386  // Add a file to the multipart request
   387  func addFile(w *multipart.Writer, fieldName, path string) error {
   388  	file, err := os.Open(path)
   389  	if err != nil {
   390  		return err
   391  	}
   392  	defer file.Close()
   393  
   394  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   395  	if err != nil {
   396  		return err
   397  	}
   398  	_, err = io.Copy(part, file)
   399  
   400  	return err
   401  }
   402  
   403  // Prevent trying to import "fmt"
   404  func reportError(format string, a ...interface{}) error {
   405  	return fmt.Errorf(format, a...)
   406  }
   407  
   408  // Set request body from an interface{}
   409  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   410  	if bodyBuf == nil {
   411  		bodyBuf = &bytes.Buffer{}
   412  	}
   413  
   414  	if reader, ok := body.(io.Reader); ok {
   415  		_, err = bodyBuf.ReadFrom(reader)
   416  	} else if b, ok := body.([]byte); ok {
   417  		_, err = bodyBuf.Write(b)
   418  	} else if s, ok := body.(string); ok {
   419  		_, err = bodyBuf.WriteString(s)
   420  	} else if s, ok := body.(*string); ok {
   421  		_, err = bodyBuf.WriteString(*s)
   422  	} else if jsonCheck.MatchString(contentType) {
   423  		err = json.NewEncoder(bodyBuf).Encode(body)
   424  	} else if xmlCheck.MatchString(contentType) {
   425  		xml.NewEncoder(bodyBuf).Encode(body)
   426  	}
   427  
   428  	if err != nil {
   429  		return nil, err
   430  	}
   431  
   432  	if bodyBuf.Len() == 0 {
   433  		err = fmt.Errorf("Invalid body type %s\n", contentType)
   434  		return nil, err
   435  	}
   436  	return bodyBuf, nil
   437  }
   438  
   439  // detectContentType method is used to figure out `Request.Body` content type for request header
   440  func detectContentType(body interface{}) string {
   441  	contentType := "text/plain; charset=utf-8"
   442  	kind := reflect.TypeOf(body).Kind()
   443  
   444  	switch kind {
   445  	case reflect.Struct, reflect.Map, reflect.Ptr:
   446  		contentType = "application/json; charset=utf-8"
   447  	case reflect.String:
   448  		contentType = "text/plain; charset=utf-8"
   449  	default:
   450  		if b, ok := body.([]byte); ok {
   451  			contentType = http.DetectContentType(b)
   452  		} else if kind == reflect.Slice {
   453  			contentType = "application/json; charset=utf-8"
   454  		}
   455  	}
   456  
   457  	return contentType
   458  }
   459  
   460  // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
   461  type cacheControl map[string]string
   462  
   463  func parseCacheControl(headers http.Header) cacheControl {
   464  	cc := cacheControl{}
   465  	ccHeader := headers.Get("cache-control")
   466  	for _, part := range strings.Split(ccHeader, ",") {
   467  		part = strings.Trim(part, " ")
   468  		if part == "" {
   469  			continue
   470  		}
   471  		if strings.ContainsRune(part, '=') {
   472  			keyval := strings.Split(part, "=")
   473  			cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
   474  		} else {
   475  			cc[part] = ""
   476  		}
   477  	}
   478  	return cc
   479  }
   480  
   481  // CacheExpires helper function to determine remaining time before repeating a request.
   482  func CacheExpires(r *http.Response) time.Time {
   483  	// Figure out when the cache expires.
   484  	var expires time.Time
   485  	now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
   486  	if err != nil {
   487  		return time.Now()
   488  	}
   489  	respCacheControl := parseCacheControl(r.Header)
   490  
   491  	if maxAge, ok := respCacheControl["max-age"]; ok {
   492  		lifetime, err := time.ParseDuration(maxAge + "s")
   493  		if err != nil {
   494  			expires = now
   495  		}
   496  		expires = now.Add(lifetime)
   497  	} else {
   498  		expiresHeader := r.Header.Get("expires")
   499  		if expiresHeader != "" {
   500  			expires, err = time.Parse(time.RFC1123, expiresHeader)
   501  			if err != nil {
   502  				expires = now
   503  			}
   504  		}
   505  	}
   506  	return expires
   507  }
   508  
   509  func strlen(s string) int {
   510  	return utf8.RuneCountInString(s)
   511  }
   512  
   513  // GenericSwaggerError Provides access to the body, error and model on returned errors.
   514  type GenericSwaggerError struct {
   515  	body  []byte
   516  	error string
   517  	model interface{}
   518  }
   519  
   520  // Error returns non-empty string if there was an error.
   521  func (e GenericSwaggerError) Error() string {
   522  	return e.error
   523  }
   524  
   525  // Body returns the raw bytes of the response
   526  func (e GenericSwaggerError) Body() []byte {
   527  	return e.body
   528  }
   529  
   530  // Model returns the unpacked model of the error
   531  func (e GenericSwaggerError) Model() interface{} {
   532  	return e.model
   533  }