bdpan-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. bdpan_cli/__init__.py +15 -0
  2. bdpan_cli/_vendor/__init__.py +9 -0
  3. bdpan_cli/_vendor/openapi_client/__init__.py +27 -0
  4. bdpan_cli/_vendor/openapi_client/api/__init__.py +6 -0
  5. bdpan_cli/_vendor/openapi_client/api/auth_api.py +649 -0
  6. bdpan_cli/_vendor/openapi_client/api/fileinfo_api.py +737 -0
  7. bdpan_cli/_vendor/openapi_client/api/filemanager_api.py +669 -0
  8. bdpan_cli/_vendor/openapi_client/api/fileupload_api.py +599 -0
  9. bdpan_cli/_vendor/openapi_client/api/multimediafile_api.py +391 -0
  10. bdpan_cli/_vendor/openapi_client/api/userinfo_api.py +315 -0
  11. bdpan_cli/_vendor/openapi_client/api_client.py +864 -0
  12. bdpan_cli/_vendor/openapi_client/configuration.py +454 -0
  13. bdpan_cli/_vendor/openapi_client/exceptions.py +197 -0
  14. bdpan_cli/_vendor/openapi_client/model/__init__.py +5 -0
  15. bdpan_cli/_vendor/openapi_client/model/oauth_token_authorization_code_response.py +276 -0
  16. bdpan_cli/_vendor/openapi_client/model/oauth_token_device_code_response.py +276 -0
  17. bdpan_cli/_vendor/openapi_client/model/oauth_token_device_token_response.py +276 -0
  18. bdpan_cli/_vendor/openapi_client/model/oauth_token_refresh_token_response.py +276 -0
  19. bdpan_cli/_vendor/openapi_client/model/quotaresponse.py +276 -0
  20. bdpan_cli/_vendor/openapi_client/model/uinforesponse.py +284 -0
  21. bdpan_cli/_vendor/openapi_client/model_utils.py +2039 -0
  22. bdpan_cli/_vendor/openapi_client/rest.py +385 -0
  23. bdpan_cli/_version.py +3 -0
  24. bdpan_cli/account.py +78 -0
  25. bdpan_cli/apply_scrape_rename.py +99 -0
  26. bdpan_cli/auth.py +218 -0
  27. bdpan_cli/cli.py +1428 -0
  28. bdpan_cli/config.py +26 -0
  29. bdpan_cli/dedup.py +310 -0
  30. bdpan_cli/downloader.py +178 -0
  31. bdpan_cli/file_manager.py +389 -0
  32. bdpan_cli/foldering.py +181 -0
  33. bdpan_cli/logger.py +101 -0
  34. bdpan_cli/mcp_server.py +547 -0
  35. bdpan_cli/media_info.py +251 -0
  36. bdpan_cli/ops.py +173 -0
  37. bdpan_cli/organize.py +108 -0
  38. bdpan_cli/preview_scrape.py +182 -0
  39. bdpan_cli/scraper.py +505 -0
  40. bdpan_cli/uploader.py +391 -0
  41. bdpan_cli-0.1.0.dist-info/METADATA +167 -0
  42. bdpan_cli-0.1.0.dist-info/RECORD +44 -0
  43. bdpan_cli-0.1.0.dist-info/WHEEL +4 -0
  44. bdpan_cli-0.1.0.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,864 @@
1
+ # !/usr/bin/env python3
2
+ """
3
+ xpan
4
+
5
+ xpanapi # noqa: E501
6
+
7
+ The version of the OpenAPI document: 0.1
8
+ Generated by: https://openapi-generator.tech
9
+ """
10
+
11
+
12
+ import json
13
+ import atexit
14
+ import mimetypes
15
+ from multiprocessing.pool import ThreadPool
16
+ import io
17
+ import os
18
+ import re
19
+ import typing
20
+ from urllib.parse import quote
21
+ from urllib3.fields import RequestField
22
+
23
+
24
+ from bdpan_cli._vendor.openapi_client import rest
25
+ from bdpan_cli._vendor.openapi_client.configuration import Configuration
26
+ from bdpan_cli._vendor.openapi_client.exceptions import ApiTypeError, ApiValueError, ApiException
27
+ from bdpan_cli._vendor.openapi_client.model_utils import (
28
+ ModelNormal,
29
+ ModelSimple,
30
+ ModelComposed,
31
+ check_allowed_values,
32
+ check_validations,
33
+ date,
34
+ datetime,
35
+ deserialize_file,
36
+ file_type,
37
+ model_to_dict,
38
+ none_type,
39
+ validate_and_convert_types
40
+ )
41
+
42
+
43
+ class ApiClient(object):
44
+ """Generic API client for OpenAPI client library builds.
45
+
46
+ OpenAPI generic API client. This client handles the client-
47
+ server communication, and is invariant across implementations. Specifics of
48
+ the methods and models for each application are generated from the OpenAPI
49
+ templates.
50
+
51
+ NOTE: This class is auto generated by OpenAPI Generator.
52
+ Ref: https://openapi-generator.tech
53
+ Do not edit the class manually.
54
+
55
+ :param configuration: .Configuration object for this client
56
+ :param header_name: a header to pass when making calls to the API.
57
+ :param header_value: a header value to pass when making calls to
58
+ the API.
59
+ :param cookie: a cookie to include in the header when making calls
60
+ to the API
61
+ :param pool_threads: The number of threads to use for async requests
62
+ to the API. More threads means more concurrent API requests.
63
+ """
64
+
65
+ _pool = None
66
+
67
+ def __init__(self, configuration=None, header_name=None, header_value=None,
68
+ cookie=None, pool_threads=1):
69
+ if configuration is None:
70
+ configuration = Configuration.get_default_copy()
71
+ self.configuration = configuration
72
+ self.pool_threads = pool_threads
73
+
74
+ self.rest_client = rest.RESTClientObject(configuration)
75
+ self.default_headers = {}
76
+ if header_name is not None:
77
+ self.default_headers[header_name] = header_value
78
+ self.cookie = cookie
79
+ # Set default User-Agent.
80
+ self.user_agent = 'OpenAPI-Generator/1.0.0/python'
81
+
82
+ def __enter__(self):
83
+ return self
84
+
85
+ def __exit__(self, exc_type, exc_value, traceback):
86
+ self.close()
87
+
88
+ def close(self):
89
+ if self._pool:
90
+ self._pool.close()
91
+ self._pool.join()
92
+ self._pool = None
93
+ if hasattr(atexit, 'unregister'):
94
+ atexit.unregister(self.close)
95
+
96
+ @property
97
+ def pool(self):
98
+ """Create thread pool on first request
99
+ avoids instantiating unused threadpool for blocking clients.
100
+ """
101
+ if self._pool is None:
102
+ atexit.register(self.close)
103
+ self._pool = ThreadPool(self.pool_threads)
104
+ return self._pool
105
+
106
+ @property
107
+ def user_agent(self):
108
+ """User agent for this API client"""
109
+ return self.default_headers['User-Agent']
110
+
111
+ @user_agent.setter
112
+ def user_agent(self, value):
113
+ self.default_headers['User-Agent'] = value
114
+
115
+ def set_default_header(self, header_name, header_value):
116
+ self.default_headers[header_name] = header_value
117
+
118
+ def __call_api(
119
+ self,
120
+ resource_path: str,
121
+ method: str,
122
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
123
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
124
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
125
+ body: typing.Optional[typing.Any] = None,
126
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
127
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
128
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
129
+ auth_settings: typing.Optional[typing.List[str]] = None,
130
+ _return_http_data_only: typing.Optional[bool] = None,
131
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
132
+ _preload_content: bool = True,
133
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
134
+ _host: typing.Optional[str] = None,
135
+ _check_type: typing.Optional[bool] = None,
136
+ _content_type: typing.Optional[str] = None
137
+ ):
138
+
139
+ config = self.configuration
140
+
141
+ # header parameters
142
+ header_params = header_params or {}
143
+ header_params.update(self.default_headers)
144
+ if self.cookie:
145
+ header_params['Cookie'] = self.cookie
146
+ if header_params:
147
+ header_params = self.sanitize_for_serialization(header_params)
148
+ header_params = dict(self.parameters_to_tuples(header_params,
149
+ collection_formats))
150
+
151
+ # path parameters
152
+ if path_params:
153
+ path_params = self.sanitize_for_serialization(path_params)
154
+ path_params = self.parameters_to_tuples(path_params,
155
+ collection_formats)
156
+ for k, v in path_params:
157
+ # specified safe chars, encode everything
158
+ resource_path = resource_path.replace(
159
+ '{%s}' % k,
160
+ quote(str(v), safe=config.safe_chars_for_path_param)
161
+ )
162
+
163
+ # query parameters
164
+ if query_params:
165
+ query_params = self.sanitize_for_serialization(query_params)
166
+ query_params = self.parameters_to_tuples(query_params,
167
+ collection_formats)
168
+
169
+ # post parameters
170
+ if post_params or files:
171
+ post_params = post_params if post_params else []
172
+ post_params = self.sanitize_for_serialization(post_params)
173
+ post_params = self.parameters_to_tuples(post_params,
174
+ collection_formats)
175
+ post_params.extend(self.files_parameters(files))
176
+ if header_params['Content-Type'].startswith("multipart"):
177
+ post_params = self.parameters_to_multipart(post_params,
178
+ (dict) )
179
+
180
+ # body
181
+ if body:
182
+ body = self.sanitize_for_serialization(body)
183
+
184
+ # auth setting
185
+ self.update_params_for_auth(header_params, query_params,
186
+ auth_settings, resource_path, method, body)
187
+
188
+ # request url
189
+ if _host is None:
190
+ url = self.configuration.host + resource_path
191
+ else:
192
+ # use server/host defined in path or operation instead
193
+ url = _host + resource_path
194
+
195
+ try:
196
+ # perform request and return response
197
+ response_data = self.request(
198
+ method, url, query_params=query_params, headers=header_params,
199
+ post_params=post_params, body=body,
200
+ _preload_content=_preload_content,
201
+ _request_timeout=_request_timeout)
202
+ except ApiException as e:
203
+ e.body = e.body.decode('utf-8')
204
+ raise e
205
+
206
+ self.last_response = response_data
207
+
208
+ return_data = response_data
209
+
210
+ if not _preload_content:
211
+ return return_data
212
+
213
+ # deserialize response data
214
+ if response_type:
215
+ if response_type != (file_type,):
216
+ encoding = "utf-8"
217
+ content_type = response_data.getheader('content-type')
218
+ if content_type is not None:
219
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
220
+ if match:
221
+ encoding = match.group(1)
222
+ response_data.data = response_data.data.decode(encoding)
223
+
224
+ return_data = self.deserialize(
225
+ response_data,
226
+ response_type,
227
+ _check_type
228
+ )
229
+ else:
230
+ return_data = None
231
+
232
+ if _return_http_data_only:
233
+ return (return_data)
234
+ else:
235
+ return (return_data, response_data.status,
236
+ response_data.getheaders())
237
+
238
+ def parameters_to_multipart(self, params, collection_types):
239
+ """Get parameters as list of tuples, formatting as json if value is collection_types
240
+
241
+ :param params: Parameters as list of two-tuples
242
+ :param dict collection_types: Parameter collection types
243
+ :return: Parameters as list of tuple or urllib3.fields.RequestField
244
+ """
245
+ new_params = []
246
+ if collection_types is None:
247
+ collection_types = (dict)
248
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
249
+ if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json
250
+ v = json.dumps(v, ensure_ascii=False).encode("utf-8")
251
+ field = RequestField(k, v)
252
+ field.make_multipart(content_type="application/json; charset=utf-8")
253
+ new_params.append(field)
254
+ else:
255
+ new_params.append((k, v))
256
+ return new_params
257
+
258
+ @classmethod
259
+ def sanitize_for_serialization(cls, obj):
260
+ """Prepares data for transmission before it is sent with the rest client
261
+ If obj is None, return None.
262
+ If obj is str, int, long, float, bool, return directly.
263
+ If obj is datetime.datetime, datetime.date
264
+ convert to string in iso8601 format.
265
+ If obj is list, sanitize each element in the list.
266
+ If obj is dict, return the dict.
267
+ If obj is OpenAPI model, return the properties dict.
268
+ If obj is io.IOBase, return the bytes
269
+ :param obj: The data to serialize.
270
+ :return: The serialized form of data.
271
+ """
272
+ if isinstance(obj, (ModelNormal, ModelComposed)):
273
+ return {
274
+ key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()
275
+ }
276
+ elif isinstance(obj, io.IOBase):
277
+ return cls.get_file_data_and_close_file(obj)
278
+ elif isinstance(obj, (str, int, float, none_type, bool)):
279
+ return obj
280
+ elif isinstance(obj, (datetime, date)):
281
+ return obj.isoformat()
282
+ elif isinstance(obj, ModelSimple):
283
+ return cls.sanitize_for_serialization(obj.value)
284
+ elif isinstance(obj, (list, tuple)):
285
+ return [cls.sanitize_for_serialization(item) for item in obj]
286
+ if isinstance(obj, dict):
287
+ return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
288
+ raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__))
289
+
290
+ def deserialize(self, response, response_type, _check_type):
291
+ """Deserializes response into an object.
292
+
293
+ :param response: RESTResponse object to be deserialized.
294
+ :param response_type: For the response, a tuple containing:
295
+ valid classes
296
+ a list containing valid classes (for list schemas)
297
+ a dict containing a tuple of valid classes as the value
298
+ Example values:
299
+ (str,)
300
+ (Pet,)
301
+ (float, none_type)
302
+ ([int, none_type],)
303
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
304
+ :param _check_type: boolean, whether to check the types of the data
305
+ received from the server
306
+ :type _check_type: bool
307
+
308
+ :return: deserialized object.
309
+ """
310
+ # handle file downloading
311
+ # save response body into a tmp file and return the instance
312
+ if response_type == (file_type,):
313
+ content_disposition = response.getheader("Content-Disposition")
314
+ return deserialize_file(response.data, self.configuration,
315
+ content_disposition=content_disposition)
316
+
317
+ # fetch data from response object
318
+ try:
319
+ received_data = json.loads(response.data)
320
+ except ValueError:
321
+ received_data = response.data
322
+
323
+ # store our data under the key of 'received_data' so users have some
324
+ # context if they are deserializing a string and the data type is wrong
325
+ deserialized_data = validate_and_convert_types(
326
+ received_data,
327
+ response_type,
328
+ ['received_data'],
329
+ True,
330
+ _check_type,
331
+ configuration=self.configuration
332
+ )
333
+ return deserialized_data
334
+
335
+ def call_api(
336
+ self,
337
+ resource_path: str,
338
+ method: str,
339
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
340
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
341
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
342
+ body: typing.Optional[typing.Any] = None,
343
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
344
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
345
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
346
+ auth_settings: typing.Optional[typing.List[str]] = None,
347
+ async_req: typing.Optional[bool] = None,
348
+ _return_http_data_only: typing.Optional[bool] = None,
349
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
350
+ _preload_content: bool = True,
351
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
352
+ _host: typing.Optional[str] = None,
353
+ _check_type: typing.Optional[bool] = None
354
+ ):
355
+ """Makes the HTTP request (synchronous) and returns deserialized data.
356
+
357
+ To make an async_req request, set the async_req parameter.
358
+
359
+ :param resource_path: Path to method endpoint.
360
+ :param method: Method to call.
361
+ :param path_params: Path parameters in the url.
362
+ :param query_params: Query parameters in the url.
363
+ :param header_params: Header parameters to be
364
+ placed in the request header.
365
+ :param body: Request body.
366
+ :param post_params dict: Request post form parameters,
367
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
368
+ :param auth_settings list: Auth Settings names for the request.
369
+ :param response_type: For the response, a tuple containing:
370
+ valid classes
371
+ a list containing valid classes (for list schemas)
372
+ a dict containing a tuple of valid classes as the value
373
+ Example values:
374
+ (str,)
375
+ (Pet,)
376
+ (float, none_type)
377
+ ([int, none_type],)
378
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
379
+ :param files: key -> field name, value -> a list of open file
380
+ objects for `multipart/form-data`.
381
+ :type files: dict
382
+ :param async_req bool: execute request asynchronously
383
+ :type async_req: bool, optional
384
+ :param _return_http_data_only: response data without head status code
385
+ and headers
386
+ :type _return_http_data_only: bool, optional
387
+ :param collection_formats: dict of collection formats for path, query,
388
+ header, and post parameters.
389
+ :type collection_formats: dict, optional
390
+ :param _preload_content: if False, the urllib3.HTTPResponse object will
391
+ be returned without reading/decoding response
392
+ data. Default is True.
393
+ :type _preload_content: bool, optional
394
+ :param _request_timeout: timeout setting for this request. If one
395
+ number provided, it will be total request
396
+ timeout. It can also be a pair (tuple) of
397
+ (connection, read) timeouts.
398
+ :param _check_type: boolean describing if the data back from the server
399
+ should have its type checked.
400
+ :type _check_type: bool, optional
401
+ :return:
402
+ If async_req parameter is True,
403
+ the request will be called asynchronously.
404
+ The method will return the request thread.
405
+ If parameter async_req is False or missing,
406
+ then the method will return the response directly.
407
+ """
408
+ if not async_req:
409
+ return self.__call_api(resource_path, method,
410
+ path_params, query_params, header_params,
411
+ body, post_params, files,
412
+ response_type, auth_settings,
413
+ _return_http_data_only, collection_formats,
414
+ _preload_content, _request_timeout, _host,
415
+ _check_type)
416
+
417
+ return self.pool.apply_async(self.__call_api, (resource_path,
418
+ method, path_params,
419
+ query_params,
420
+ header_params, body,
421
+ post_params, files,
422
+ response_type,
423
+ auth_settings,
424
+ _return_http_data_only,
425
+ collection_formats,
426
+ _preload_content,
427
+ _request_timeout,
428
+ _host, _check_type))
429
+
430
+ def request(self, method, url, query_params=None, headers=None,
431
+ post_params=None, body=None, _preload_content=True,
432
+ _request_timeout=None):
433
+ """Makes the HTTP request using RESTClient."""
434
+ if method == "GET":
435
+ return self.rest_client.GET(url,
436
+ query_params=query_params,
437
+ _preload_content=_preload_content,
438
+ _request_timeout=_request_timeout,
439
+ headers=headers)
440
+ elif method == "HEAD":
441
+ return self.rest_client.HEAD(url,
442
+ query_params=query_params,
443
+ _preload_content=_preload_content,
444
+ _request_timeout=_request_timeout,
445
+ headers=headers)
446
+ elif method == "OPTIONS":
447
+ return self.rest_client.OPTIONS(url,
448
+ query_params=query_params,
449
+ headers=headers,
450
+ post_params=post_params,
451
+ _preload_content=_preload_content,
452
+ _request_timeout=_request_timeout,
453
+ body=body)
454
+ elif method == "POST":
455
+ return self.rest_client.POST(url,
456
+ query_params=query_params,
457
+ headers=headers,
458
+ post_params=post_params,
459
+ _preload_content=_preload_content,
460
+ _request_timeout=_request_timeout,
461
+ body=body)
462
+ elif method == "PUT":
463
+ return self.rest_client.PUT(url,
464
+ query_params=query_params,
465
+ headers=headers,
466
+ post_params=post_params,
467
+ _preload_content=_preload_content,
468
+ _request_timeout=_request_timeout,
469
+ body=body)
470
+ elif method == "PATCH":
471
+ return self.rest_client.PATCH(url,
472
+ query_params=query_params,
473
+ headers=headers,
474
+ post_params=post_params,
475
+ _preload_content=_preload_content,
476
+ _request_timeout=_request_timeout,
477
+ body=body)
478
+ elif method == "DELETE":
479
+ return self.rest_client.DELETE(url,
480
+ query_params=query_params,
481
+ headers=headers,
482
+ _preload_content=_preload_content,
483
+ _request_timeout=_request_timeout,
484
+ body=body)
485
+ else:
486
+ raise ApiValueError(
487
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
488
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
489
+ )
490
+
491
+ def parameters_to_tuples(self, params, collection_formats):
492
+ """Get parameters as list of tuples, formatting collections.
493
+
494
+ :param params: Parameters as dict or list of two-tuples
495
+ :param dict collection_formats: Parameter collection formats
496
+ :return: Parameters as list of tuples, collections formatted
497
+ """
498
+ new_params = []
499
+ if collection_formats is None:
500
+ collection_formats = {}
501
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
502
+ if k in collection_formats:
503
+ collection_format = collection_formats[k]
504
+ if collection_format == 'multi':
505
+ new_params.extend((k, value) for value in v)
506
+ else:
507
+ if collection_format == 'ssv':
508
+ delimiter = ' '
509
+ elif collection_format == 'tsv':
510
+ delimiter = '\t'
511
+ elif collection_format == 'pipes':
512
+ delimiter = '|'
513
+ else: # csv is the default
514
+ delimiter = ','
515
+ new_params.append(
516
+ (k, delimiter.join(str(value) for value in v)))
517
+ else:
518
+ new_params.append((k, v))
519
+ return new_params
520
+
521
+ @staticmethod
522
+ def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
523
+ file_data = file_instance.read()
524
+ file_instance.close()
525
+ return file_data
526
+
527
+ def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
528
+ """Builds form parameters.
529
+
530
+ :param files: None or a dict with key=param_name and
531
+ value is a list of open file objects
532
+ :return: List of tuples of form parameters with file data
533
+ """
534
+ if files is None:
535
+ return []
536
+
537
+ params = []
538
+ for param_name, file_instances in files.items():
539
+ if file_instances is None:
540
+ # if the file field is nullable, skip None values
541
+ continue
542
+ for file_instance in file_instances:
543
+ if file_instance is None:
544
+ # if the file field is nullable, skip None values
545
+ continue
546
+ if file_instance.closed is True:
547
+ raise ApiValueError(
548
+ "Cannot read a closed file. The passed in file_type "
549
+ "for %s must be open." % param_name
550
+ )
551
+ filename = os.path.basename(file_instance.name)
552
+ filedata = self.get_file_data_and_close_file(file_instance)
553
+ mimetype = (mimetypes.guess_type(filename)[0] or
554
+ 'application/octet-stream')
555
+ params.append(
556
+ tuple([param_name, tuple([filename, filedata, mimetype])]))
557
+
558
+ return params
559
+
560
+ def select_header_accept(self, accepts):
561
+ """Returns `Accept` based on an array of accepts provided.
562
+
563
+ :param accepts: List of headers.
564
+ :return: Accept (e.g. application/json).
565
+ """
566
+ if not accepts:
567
+ return
568
+
569
+ accepts = [x.lower() for x in accepts]
570
+
571
+ if 'application/json' in accepts:
572
+ return 'application/json'
573
+ else:
574
+ return ', '.join(accepts)
575
+
576
+ def select_header_content_type(self, content_types, method=None, body=None):
577
+ """Returns `Content-Type` based on an array of content_types provided.
578
+
579
+ :param content_types: List of content-types.
580
+ :param method: http method (e.g. POST, PATCH).
581
+ :param body: http body to send.
582
+ :return: Content-Type (e.g. application/json).
583
+ """
584
+ if not content_types:
585
+ return 'application/json'
586
+
587
+ content_types = [x.lower() for x in content_types]
588
+
589
+ if (method == 'PATCH' and
590
+ 'application/json-patch+json' in content_types and
591
+ isinstance(body, list)):
592
+ return 'application/json-patch+json'
593
+
594
+ if 'application/json' in content_types or '*/*' in content_types:
595
+ return 'application/json'
596
+ else:
597
+ return content_types[0]
598
+
599
+ def update_params_for_auth(self, headers, queries, auth_settings,
600
+ resource_path, method, body):
601
+ """Updates header and query params based on authentication setting.
602
+
603
+ :param headers: Header parameters dict to be updated.
604
+ :param queries: Query parameters tuple list to be updated.
605
+ :param auth_settings: Authentication setting identifiers list.
606
+ :param resource_path: A string representation of the HTTP request resource path.
607
+ :param method: A string representation of the HTTP request method.
608
+ :param body: A object representing the body of the HTTP request.
609
+ The object type is the return value of _encoder.default().
610
+ """
611
+ if not auth_settings:
612
+ return
613
+
614
+ for auth in auth_settings:
615
+ auth_setting = self.configuration.auth_settings().get(auth)
616
+ if auth_setting:
617
+ if auth_setting['in'] == 'cookie':
618
+ headers['Cookie'] = auth_setting['value']
619
+ elif auth_setting['in'] == 'header':
620
+ if auth_setting['type'] != 'http-signature':
621
+ headers[auth_setting['key']] = auth_setting['value']
622
+ elif auth_setting['in'] == 'query':
623
+ queries.append((auth_setting['key'], auth_setting['value']))
624
+ else:
625
+ raise ApiValueError(
626
+ 'Authentication token must be in `query` or `header`'
627
+ )
628
+
629
+
630
+ class Endpoint(object):
631
+ def __init__(self, settings=None, params_map=None, root_map=None,
632
+ headers_map=None, api_client=None, callable=None):
633
+ """Creates an endpoint
634
+
635
+ Args:
636
+ settings (dict): see below key value pairs
637
+ 'response_type' (tuple/None): response type
638
+ 'auth' (list): a list of auth type keys
639
+ 'endpoint_path' (str): the endpoint path
640
+ 'operation_id' (str): endpoint string identifier
641
+ 'http_method' (str): POST/PUT/PATCH/GET etc
642
+ 'servers' (list): list of str servers that this endpoint is at
643
+ params_map (dict): see below key value pairs
644
+ 'all' (list): list of str endpoint parameter names
645
+ 'required' (list): list of required parameter names
646
+ 'nullable' (list): list of nullable parameter names
647
+ 'enum' (list): list of parameters with enum values
648
+ 'validation' (list): list of parameters with validations
649
+ root_map
650
+ 'validations' (dict): the dict mapping endpoint parameter tuple
651
+ paths to their validation dictionaries
652
+ 'allowed_values' (dict): the dict mapping endpoint parameter
653
+ tuple paths to their allowed_values (enum) dictionaries
654
+ 'openapi_types' (dict): param_name to openapi type
655
+ 'attribute_map' (dict): param_name to camelCase name
656
+ 'location_map' (dict): param_name to 'body', 'file', 'form',
657
+ 'header', 'path', 'query'
658
+ collection_format_map (dict): param_name to `csv` etc.
659
+ headers_map (dict): see below key value pairs
660
+ 'accept' (list): list of Accept header strings
661
+ 'content_type' (list): list of Content-Type header strings
662
+ api_client (ApiClient) api client instance
663
+ callable (function): the function which is invoked when the
664
+ Endpoint is called
665
+ """
666
+ self.settings = settings
667
+ self.params_map = params_map
668
+ self.params_map['all'].extend([
669
+ 'async_req',
670
+ '_host_index',
671
+ '_preload_content',
672
+ '_request_timeout',
673
+ '_return_http_data_only',
674
+ '_check_input_type',
675
+ '_check_return_type',
676
+ '_content_type',
677
+ '_spec_property_naming'
678
+ ])
679
+ self.params_map['nullable'].extend(['_request_timeout'])
680
+ self.validations = root_map['validations']
681
+ self.allowed_values = root_map['allowed_values']
682
+ self.openapi_types = root_map['openapi_types']
683
+ extra_types = {
684
+ 'async_req': (bool,),
685
+ '_host_index': (none_type, int),
686
+ '_preload_content': (bool,),
687
+ '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]),
688
+ '_return_http_data_only': (bool,),
689
+ '_check_input_type': (bool,),
690
+ '_check_return_type': (bool,),
691
+ '_spec_property_naming': (bool,),
692
+ '_content_type': (none_type, str)
693
+ }
694
+ self.openapi_types.update(extra_types)
695
+ self.attribute_map = root_map['attribute_map']
696
+ self.location_map = root_map['location_map']
697
+ self.collection_format_map = root_map['collection_format_map']
698
+ self.headers_map = headers_map
699
+ self.api_client = api_client
700
+ self.callable = callable
701
+
702
+ def __validate_inputs(self, kwargs):
703
+ for param in self.params_map['enum']:
704
+ if param in kwargs:
705
+ check_allowed_values(
706
+ self.allowed_values,
707
+ (param,),
708
+ kwargs[param]
709
+ )
710
+
711
+ for param in self.params_map['validation']:
712
+ if param in kwargs:
713
+ check_validations(
714
+ self.validations,
715
+ (param,),
716
+ kwargs[param],
717
+ configuration=self.api_client.configuration
718
+ )
719
+
720
+ if kwargs['_check_input_type'] is False:
721
+ return
722
+
723
+ for key, value in kwargs.items():
724
+ fixed_val = validate_and_convert_types(
725
+ value,
726
+ self.openapi_types[key],
727
+ [key],
728
+ kwargs['_spec_property_naming'],
729
+ kwargs['_check_input_type'],
730
+ configuration=self.api_client.configuration
731
+ )
732
+ kwargs[key] = fixed_val
733
+
734
+ def __gather_params(self, kwargs):
735
+ params = {
736
+ 'body': None,
737
+ 'collection_format': {},
738
+ 'file': {},
739
+ 'form': [],
740
+ 'header': {},
741
+ 'path': {},
742
+ 'query': []
743
+ }
744
+
745
+ for param_name, param_value in kwargs.items():
746
+ param_location = self.location_map.get(param_name)
747
+ if param_location is None:
748
+ continue
749
+ if param_location:
750
+ if param_location == 'body':
751
+ params['body'] = param_value
752
+ continue
753
+ base_name = self.attribute_map[param_name]
754
+ if (param_location == 'form' and
755
+ self.openapi_types[param_name] == (file_type,)):
756
+ params['file'][param_name] = [param_value]
757
+ elif (param_location == 'form' and
758
+ self.openapi_types[param_name] == ([file_type],)):
759
+ # param_value is already a list
760
+ params['file'][param_name] = param_value
761
+ elif param_location in {'form', 'query'}:
762
+ param_value_full = (base_name, param_value)
763
+ params[param_location].append(param_value_full)
764
+ if param_location not in {'form', 'query'}:
765
+ params[param_location][base_name] = param_value
766
+ collection_format = self.collection_format_map.get(param_name)
767
+ if collection_format:
768
+ params['collection_format'][base_name] = collection_format
769
+
770
+ return params
771
+
772
+ def __call__(self, *args, **kwargs):
773
+ """ This method is invoked when endpoints are called
774
+ Example:
775
+
776
+ api_instance = AuthApi()
777
+ api_instance.oauth_token_code2token # this is an instance of the class Endpoint
778
+ api_instance.oauth_token_code2token() # this invokes api_instance.oauth_token_code2token.__call__()
779
+ which then invokes the callable functions stored in that endpoint at
780
+ api_instance.oauth_token_code2token.callable or self.callable in this class
781
+
782
+ """
783
+ return self.callable(self, *args, **kwargs)
784
+
785
+ def call_with_http_info(self, **kwargs):
786
+ try:
787
+ index = self.api_client.configuration.server_operation_index.get(
788
+ self.settings['operation_id'], self.api_client.configuration.server_index
789
+ ) if kwargs['_host_index'] is None else kwargs['_host_index']
790
+ server_variables = self.api_client.configuration.server_operation_variables.get(
791
+ self.settings['operation_id'], self.api_client.configuration.server_variables
792
+ )
793
+ _host = self.api_client.configuration.get_host_from_settings(
794
+ index, variables=server_variables, servers=self.settings['servers']
795
+ )
796
+ except IndexError:
797
+ if self.settings['servers']:
798
+ raise ApiValueError(
799
+ "Invalid host index. Must be 0 <= index < %s" %
800
+ len(self.settings['servers'])
801
+ )
802
+ _host = None
803
+
804
+ for key, value in kwargs.items():
805
+ if key not in self.params_map['all']:
806
+ raise ApiTypeError(
807
+ "Got an unexpected parameter '%s'"
808
+ " to method `%s`" %
809
+ (key, self.settings['operation_id'])
810
+ )
811
+ # only throw this nullable ApiValueError if _check_input_type
812
+ # is False, if _check_input_type==True we catch this case
813
+ # in self.__validate_inputs
814
+ if (key not in self.params_map['nullable'] and value is None
815
+ and kwargs['_check_input_type'] is False):
816
+ raise ApiValueError(
817
+ "Value may not be None for non-nullable parameter `%s`"
818
+ " when calling `%s`" %
819
+ (key, self.settings['operation_id'])
820
+ )
821
+
822
+ for key in self.params_map['required']:
823
+ if key not in kwargs.keys():
824
+ raise ApiValueError(
825
+ "Missing the required parameter `%s` when calling "
826
+ "`%s`" % (key, self.settings['operation_id'])
827
+ )
828
+
829
+ self.__validate_inputs(kwargs)
830
+
831
+ params = self.__gather_params(kwargs)
832
+
833
+ accept_headers_list = self.headers_map['accept']
834
+ if accept_headers_list:
835
+ params['header']['Accept'] = self.api_client.select_header_accept(
836
+ accept_headers_list)
837
+
838
+ if kwargs.get('_content_type'):
839
+ params['header']['Content-Type'] = kwargs['_content_type']
840
+ else:
841
+ content_type_headers_list = self.headers_map['content_type']
842
+ if content_type_headers_list:
843
+ if params['body'] != "":
844
+ header_list = self.api_client.select_header_content_type(
845
+ content_type_headers_list, self.settings['http_method'],
846
+ params['body'])
847
+ params['header']['Content-Type'] = header_list
848
+ return self.api_client.call_api(
849
+ self.settings['endpoint_path'], self.settings['http_method'],
850
+ params['path'],
851
+ params['query'],
852
+ params['header'],
853
+ body=params['body'],
854
+ post_params=params['form'],
855
+ files=params['file'],
856
+ response_type=self.settings['response_type'],
857
+ auth_settings=self.settings['auth'],
858
+ async_req=kwargs['async_req'],
859
+ _check_type=kwargs['_check_return_type'],
860
+ _return_http_data_only=kwargs['_return_http_data_only'],
861
+ _preload_content=kwargs['_preload_content'],
862
+ _request_timeout=kwargs['_request_timeout'],
863
+ _host=_host,
864
+ collection_formats=params['collection_format'])