From a5199cdbedb1f31dfcb30b0e98b8f557de535956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 31 Aug 2023 12:44:52 +0200 Subject: [PATCH 01/20] init --- .gitignore | 160 +++++++++ docker-compose.yaml | 42 +++ jellyfish/__init__.py | 1 + jellyfish/room_client.py | 6 + openapi.yaml | 668 ++++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + tests/__init__.py | 0 tests/test_room_client.py | 61 ++++ 8 files changed, 939 insertions(+) create mode 100644 .gitignore create mode 100644 docker-compose.yaml create mode 100644 jellyfish/__init__.py create mode 100644 jellyfish/room_client.py create mode 100644 openapi.yaml create mode 100644 requirements.txt create mode 100644 tests/__init__.py create mode 100644 tests/test_room_client.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6769e21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..b2bf4a6 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,42 @@ +version: "3" + +services: + jellyfish: + image: "ghcr.io/jellyfish-dev/jellyfish:${TAG:-edge}" + container_name: jellyfish + restart: on-failure + healthcheck: + test: > + curl --fail -H "authorization: Bearer development" http://localhost:5002/room || exit 1 + interval: 3s + retries: 2 + timeout: 2s + start_period: 30s + environment: + VIRTUAL_HOST: "localhost" + USE_INTEGRATED_TURN: "true" + INTEGRATED_TURN_IP: "${INTEGRATED_TURN_IP:-127.0.0.1}" + INTEGRATED_TURN_LISTEN_IP: "0.0.0.0" + INTEGRATED_TURN_PORT_RANGE: "50000-50050" + INTEGRATED_TCP_TURN_PORT: "49999" + SERVER_API_TOKEN: "development" + PORT: 5002 + SECRET_KEY_BASE: "super-secret-key" + ports: + - "5002:5002" + - "49999:49999" + - "50000-50050:50000-50050/udp" + + test: + image: python:3.11.5-alpine3.18 + command: sh -c "cd app/ && pip install -r requirements.txt && pytest" + volumes: + - .:/app + networks: + - network + depends_on: + - jellyfish + +networks: + network: + driver: bridge diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py new file mode 100644 index 0000000..25013b0 --- /dev/null +++ b/jellyfish/__init__.py @@ -0,0 +1 @@ +from .room_client import RoomClient diff --git a/jellyfish/room_client.py b/jellyfish/room_client.py new file mode 100644 index 0000000..fc6a9f4 --- /dev/null +++ b/jellyfish/room_client.py @@ -0,0 +1,6 @@ + + +class RoomClient: + def __init__(self, server_address, server_api_token): + self.server_address = server_address + self.server_api_token = server_api_token diff --git a/openapi.yaml b/openapi.yaml new file mode 100644 index 0000000..89eeecb --- /dev/null +++ b/openapi.yaml @@ -0,0 +1,668 @@ +# This file has been generated using OpenApiSpex. Do not edit manually! +# Run `mix api.spec` to regenerate + +--- +components: + responses: {} + schemas: + AuthToken: + description: Token for authorizing websocket connection + example: 5cdac726-57a3-4ecb-b1d5-72a3d62ec242 + title: AuthToken + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Token + Component: + description: Describes component + properties: + id: + description: Assigned component id + example: component-1 + type: string + metadata: + $ref: '#/components/schemas/ComponentMetadata' + type: + $ref: '#/components/schemas/ComponentType' + required: + - id + - type + - metadata + title: Component + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Component + ComponentDetailsResponse: + description: Response containing component details + properties: + data: + $ref: '#/components/schemas/Component' + required: + - data + title: ComponentDetailsResponse + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.ComponentDetailsResponse + ComponentMetadata: + description: Component-specific metadata + properties: + playable: + type: boolean + title: ComponentMetadata + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Metadata + ComponentOptions: + description: Component-specific options + oneOf: + - $ref: '#/components/schemas/ComponentOptionsHLS' + - $ref: '#/components/schemas/ComponentOptionsRTSP' + title: ComponentOptions + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Options + ComponentOptionsHLS: + description: Options specific to the HLS component + properties: {} + title: ComponentOptionsHLS + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Component.HLS + ComponentOptionsRTSP: + description: Options specific to the RTSP component + properties: + keepAliveInterval: + default: 15000 + description: Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source + minimum: 0 + type: integer + pierceNat: + default: true + description: Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup + type: boolean + reconnectDelay: + default: 15000 + description: Delay (in ms) between successive reconnect attempts + minimum: 0 + type: integer + rtpPort: + default: 20000 + description: Local port RTP stream will be received at + maximum: 65535 + minimum: 1 + type: integer + sourceUri: + description: URI of RTSP source stream + example: rtsp://localhost:554/stream + type: string + required: + - sourceUri + title: ComponentOptionsRTSP + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Component.RTSP + ComponentType: + description: Component type + example: hls + title: ComponentType + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Type + Error: + description: Error message + properties: + errors: + description: Error details + example: Token has expired + type: string + required: + - errors + title: Error + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Error + HlsMsn: + description: Segment sequence number + example: 10 + minimum: 0 + nullable: true + title: HlsMsn + type: integer + x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsMsn + HlsPart: + description: Partial segment sequence number + example: 10 + minimum: 0 + nullable: true + title: HlsPart + type: integer + x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsPart + HlsResponse: + description: Requested file + title: HlsResponse + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Response + HlsSkip: + description: Is delta manifest requested + enum: + - YES + example: YES + nullable: true + title: HlsSkip + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsSkip + Peer: + description: Describes peer status + properties: + id: + description: Assigned peer id + example: peer-1 + type: string + status: + $ref: '#/components/schemas/PeerStatus' + type: + $ref: '#/components/schemas/PeerType' + required: + - id + - type + - status + title: Peer + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer + PeerDetailsResponse: + description: Response containing peer details and their token + properties: + data: + properties: + peer: + $ref: '#/components/schemas/Peer' + token: + $ref: '#/components/schemas/AuthToken' + required: + - peer + - token + type: object + required: + - data + title: PeerDetailsResponse + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.PeerDetailsResponse + PeerOptions: + description: Peer-specific options + oneOf: + - $ref: '#/components/schemas/PeerOptionsWebRTC' + title: PeerOptions + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Options + PeerOptionsWebRTC: + description: Options specific to the WebRTC peer + properties: + enableSimulcast: + default: true + description: Enables the peer to use simulcast + type: boolean + title: PeerOptionsWebRTC + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.WebRTC + PeerStatus: + description: Informs about the peer status + enum: + - connected + - disconnected + example: disconnected + title: PeerStatus + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Status + PeerType: + description: Peer type + example: webrtc + title: PeerType + type: string + x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Type + Room: + description: Description of the room state + properties: + components: + items: + $ref: '#/components/schemas/Component' + type: array + config: + $ref: '#/components/schemas/RoomConfig' + id: + description: Room ID + example: room-1 + type: string + peers: + items: + $ref: '#/components/schemas/Peer' + type: array + required: + - id + - config + - components + - peers + title: Room + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Room + RoomConfig: + description: Room configuration + properties: + maxPeers: + description: Maximum amount of peers allowed into the room + example: 10 + minimum: 1 + nullable: true + type: integer + videoCodec: + description: Enforces video codec for each peer in the room + enum: + - h264 + - vp8 + nullable: true + type: string + title: RoomConfig + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.Room.Config + RoomCreateDetailsResponse: + description: Response containing room details + properties: + data: + properties: + jellyfish_address: + description: Jellyfish instance address where the room was created. This might be different than the address of Jellyfish where the request was sent only when running a cluster of Jellyfishes. + example: jellyfish1:5003 + type: string + room: + $ref: '#/components/schemas/Room' + required: + - room + - jellyfish_address + type: object + required: + - data + title: RoomCreateDetailsResponse + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.RoomCreateDetailsResponse + RoomDetailsResponse: + description: Response containing room details + properties: + data: + $ref: '#/components/schemas/Room' + required: + - data + title: RoomDetailsResponse + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.RoomDetailsResponse + RoomsListingResponse: + description: Response containing list of all rooms + properties: + data: + items: + $ref: '#/components/schemas/Room' + type: array + required: + - data + title: RoomsListingResponse + type: object + x-struct: Elixir.JellyfishWeb.ApiSpec.RoomsListingResponse + securitySchemes: + authorization: + scheme: bearer + type: http +info: + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0 + title: Jellyfish Media Server + version: 0.2.0 +openapi: 3.0.0 +paths: + /hls/{room_id}/{filename}: + get: + callbacks: {} + operationId: JellyfishWeb.HLSController.index + parameters: + - description: Room id + in: path + name: room_id + required: true + schema: + type: string + - description: Name of the file + in: path + name: filename + required: true + schema: + type: string + - description: Byte range of partial segment + in: header + name: range + required: false + schema: + type: string + - description: Segment sequence number + in: query + name: _HLS_msn + required: false + schema: + $ref: '#/components/schemas/HlsMsn' + - description: Partial segment sequence number + in: query + name: _HLS_part + required: false + schema: + $ref: '#/components/schemas/HlsPart' + - description: Is delta manifest requested + in: query + name: _HLS_skip + required: false + schema: + $ref: '#/components/schemas/HlsSkip' + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/HlsResponse' + description: File was found + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: File not found + summary: Send file + tags: [] + /room: + get: + callbacks: {} + operationId: JellyfishWeb.RoomController.index + parameters: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/RoomsListingResponse' + description: Success + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + summary: Show information about all rooms + tags: + - room + post: + callbacks: {} + operationId: JellyfishWeb.RoomController.create + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RoomConfig' + description: Room configuration + required: false + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/RoomCreateDetailsResponse' + description: Room successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Invalid request structure + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + summary: Creates a room + tags: + - room + /room/{room_id}: + delete: + callbacks: {} + operationId: JellyfishWeb.RoomController.delete + parameters: + - description: Room id + in: path + name: room_id + required: true + schema: + type: string + responses: + '204': + description: Successfully deleted room + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Room doesn't exist + summary: Delete the room + tags: + - room + get: + callbacks: {} + operationId: JellyfishWeb.RoomController.show + parameters: + - description: Room ID + in: path + name: room_id + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/RoomDetailsResponse' + description: Success + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Room doesn't exist + summary: Shows information about the room + tags: + - room + /room/{room_id}/component: + post: + callbacks: {} + operationId: JellyfishWeb.ComponentController.create + parameters: + - description: Room ID + in: path + name: room_id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + options: + $ref: '#/components/schemas/ComponentOptions' + type: + $ref: '#/components/schemas/ComponentType' + required: + - type + - options + type: object + description: Component config + required: false + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/ComponentDetailsResponse' + description: Successfully added component + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Invalid request + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Room doesn't exist + summary: Creates the component and adds it to the room + tags: + - component + /room/{room_id}/component/{id}: + delete: + callbacks: {} + operationId: JellyfishWeb.ComponentController.delete + parameters: + - description: Room ID + in: path + name: room_id + required: true + schema: + type: string + - description: Component ID + in: path + name: id + required: true + schema: + type: string + responses: + '204': + description: Successfully deleted + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Either component or the room doesn't exist + summary: Delete the component from the room + tags: + - component + /room/{room_id}/peer: + post: + callbacks: {} + operationId: JellyfishWeb.PeerController.create + parameters: + - description: Room id + in: path + name: room_id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + options: + $ref: '#/components/schemas/PeerOptions' + type: + $ref: '#/components/schemas/PeerType' + required: + - type + - options + type: object + description: Peer specification + required: false + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/PeerDetailsResponse' + description: Peer successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Invalid request body structure + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Room doesn't exist + '503': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Peer limit has been reached + summary: Create peer + tags: + - peer + /room/{room_id}/peer/{id}: + delete: + callbacks: {} + operationId: JellyfishWeb.PeerController.delete + parameters: + - description: Room ID + in: path + name: room_id + required: true + schema: + type: string + - description: Peer id + in: path + name: id + required: true + schema: + type: string + responses: + '204': + description: Peer successfully deleted + '401': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Unauthorized + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + description: Room ID or Peer ID references a resource that doesn't exist + summary: Delete peer + tags: + - peer +security: + - authorization: [] +servers: [] +tags: [] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..55b033e --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pytest \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_room_client.py b/tests/test_room_client.py new file mode 100644 index 0000000..7749f37 --- /dev/null +++ b/tests/test_room_client.py @@ -0,0 +1,61 @@ +import pytest + +from jellyfish import RoomClient + +server_address = "localhost:5002" +server_api_token = "development" + + +def test_create_room_client(): + with pytest.raises(TypeError): + RoomClient() + + with pytest.raises(TypeError): + RoomClient(server_address="address") + + with pytest.raises(TypeError): + RoomClient(server_api_token="api_token") + + room_client = RoomClient(server_address="address", server_api_token="api_token") + + +def test_authorization(): + pass + + +@pytest.fixture +def room_client(): + return RoomClient(server_address=server_address, server_api_token=server_api_token) + + +def test_create_room(room_client): + + room = room_client.create_room(max_peers=10) + + +def test_delete_room(room_client): + pass + + +def test_get_all_rooms(room_client): + pass + + +def test_get_room(room_client): + pass + + +def test_add_component(room_client): + pass + + +def test_delete_component(room_client): + pass + + +def test_add_peer(room_client): + room = room_client.create_room() + + +def test_remove_peer(room_client): + pass From 3da5bbd0f5d113bdeb7e016b26e81e2eac189be3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Fri, 1 Sep 2023 15:11:43 +0200 Subject: [PATCH 02/20] Add templates --- templates/README.mustache | 59 ++ templates/README_onlypackage.mustache | 44 ++ templates/__init__.mustache | 0 templates/__init__api.mustache | 5 + templates/__init__model.mustache | 11 + templates/__init__package.mustache | 35 + templates/api.mustache | 311 ++++++++ templates/api_client.mustache | 783 +++++++++++++++++++++ templates/api_doc.mustache | 74 ++ templates/api_doc_example.mustache | 38 + templates/api_response.mustache | 25 + templates/api_test.mustache | 35 + templates/asyncio/rest.mustache | 241 +++++++ templates/common_README.mustache | 85 +++ templates/configuration.mustache | 615 ++++++++++++++++ templates/exceptions.mustache | 156 ++++ templates/git_push.sh.mustache | 57 ++ templates/github-workflow.mustache | 38 + templates/gitignore.mustache | 66 ++ templates/gitlab-ci.mustache | 25 + templates/model.mustache | 14 + templates/model_anyof.mustache | 180 +++++ templates/model_doc.mustache | 33 + templates/model_enum.mustache | 36 + templates/model_generic.mustache | 361 ++++++++++ templates/model_oneof.mustache | 206 ++++++ templates/model_test.mustache | 62 ++ templates/partial_header.mustache | 19 + templates/py.typed.mustache | 0 templates/pyproject.mustache | 40 ++ templates/python_doc_auth_partial.mustache | 108 +++ templates/requirements.mustache | 8 + templates/rest.mustache | 293 ++++++++ templates/setup.mustache | 56 ++ templates/setup_cfg.mustache | 2 + templates/signing.mustache | 403 +++++++++++ templates/test-requirements.mustache | 6 + templates/tornado/rest.mustache | 223 ++++++ templates/tox.mustache | 9 + templates/travis.mustache | 17 + 40 files changed, 4779 insertions(+) create mode 100644 templates/README.mustache create mode 100644 templates/README_onlypackage.mustache create mode 100644 templates/__init__.mustache create mode 100644 templates/__init__api.mustache create mode 100644 templates/__init__model.mustache create mode 100644 templates/__init__package.mustache create mode 100644 templates/api.mustache create mode 100644 templates/api_client.mustache create mode 100644 templates/api_doc.mustache create mode 100644 templates/api_doc_example.mustache create mode 100644 templates/api_response.mustache create mode 100644 templates/api_test.mustache create mode 100644 templates/asyncio/rest.mustache create mode 100644 templates/common_README.mustache create mode 100644 templates/configuration.mustache create mode 100644 templates/exceptions.mustache create mode 100644 templates/git_push.sh.mustache create mode 100644 templates/github-workflow.mustache create mode 100644 templates/gitignore.mustache create mode 100644 templates/gitlab-ci.mustache create mode 100644 templates/model.mustache create mode 100644 templates/model_anyof.mustache create mode 100644 templates/model_doc.mustache create mode 100644 templates/model_enum.mustache create mode 100644 templates/model_generic.mustache create mode 100644 templates/model_oneof.mustache create mode 100644 templates/model_test.mustache create mode 100644 templates/partial_header.mustache create mode 100644 templates/py.typed.mustache create mode 100644 templates/pyproject.mustache create mode 100644 templates/python_doc_auth_partial.mustache create mode 100644 templates/requirements.mustache create mode 100644 templates/rest.mustache create mode 100644 templates/setup.mustache create mode 100644 templates/setup_cfg.mustache create mode 100644 templates/signing.mustache create mode 100644 templates/test-requirements.mustache create mode 100644 templates/tornado/rest.mustache create mode 100644 templates/tox.mustache create mode 100644 templates/travis.mustache diff --git a/templates/README.mustache b/templates/README.mustache new file mode 100644 index 0000000..201df14 --- /dev/null +++ b/templates/README.mustache @@ -0,0 +1,59 @@ +# {{{projectName}}} +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements. + +Python {{{generatorLanguageVersion}}} + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`) + +Then import the package: +```python +import {{{packageName}}} +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import {{{packageName}}} +``` + +### Tests + +Execute `pytest` to run the tests. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +{{> common_README }} diff --git a/templates/README_onlypackage.mustache b/templates/README_onlypackage.mustache new file mode 100644 index 0000000..d04bc05 --- /dev/null +++ b/templates/README_onlypackage.mustache @@ -0,0 +1,44 @@ +# {{{projectName}}} +{{#appDescription}} +{{{.}}} +{{/appDescription}} + +The `{{packageName}}` package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements. + +Python {{{generatorLanguageVersion}}} + +## Installation & Usage + +This python library package is generated without supporting files like setup.py or requirements files + +To be able to use it, you will need these dependencies in your own package that uses this library: + +* urllib3 >= 1.25.3 +* python-dateutil +{{#asyncio}} +* aiohttp +{{/asyncio}} +{{#tornado}} +* tornado>=4.2,<5 +{{/tornado}} +* pydantic +* aenum + +## Getting Started + +In your own code, to use this library to connect and interact with {{{projectName}}}, +you can run the following: + +{{> common_README }} diff --git a/templates/__init__.mustache b/templates/__init__.mustache new file mode 100644 index 0000000..e69de29 diff --git a/templates/__init__api.mustache b/templates/__init__api.mustache new file mode 100644 index 0000000..8870835 --- /dev/null +++ b/templates/__init__api.mustache @@ -0,0 +1,5 @@ +# flake8: noqa + +# import apis into api package +{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classFilename}} import {{classname}} +{{/apis}}{{/apiInfo}} diff --git a/templates/__init__model.mustache b/templates/__init__model.mustache new file mode 100644 index 0000000..0e1b55e --- /dev/null +++ b/templates/__init__model.mustache @@ -0,0 +1,11 @@ +# coding: utf-8 + +# flake8: noqa +{{>partial_header}} + +# import models into model package +{{#models}} +{{#model}} +from {{modelPackage}}.{{classFilename}} import {{classname}} +{{/model}} +{{/models}} diff --git a/templates/__init__package.mustache b/templates/__init__package.mustache new file mode 100644 index 0000000..7985e6e --- /dev/null +++ b/templates/__init__package.mustache @@ -0,0 +1,35 @@ +# coding: utf-8 + +# flake8: noqa + +{{>partial_header}} + +__version__ = "{{packageVersion}}" + +# import apis into sdk package +{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classFilename}} import {{classname}} +{{/apis}}{{/apiInfo}} +# import ApiClient +from {{packageName}}.api_response import ApiResponse +from {{packageName}}.api_client import ApiClient +from {{packageName}}.configuration import Configuration +from {{packageName}}.exceptions import OpenApiException +from {{packageName}}.exceptions import ApiTypeError +from {{packageName}}.exceptions import ApiValueError +from {{packageName}}.exceptions import ApiKeyError +from {{packageName}}.exceptions import ApiAttributeError +from {{packageName}}.exceptions import ApiException +{{#hasHttpSignatureMethods}} +from {{packageName}}.signing import HttpSigningConfiguration +{{/hasHttpSignatureMethods}} + +# import models into sdk package +{{#models}} +{{#model}} +from {{modelPackage}}.{{classFilename}} import {{classname}} +{{/model}} +{{/models}} +{{#recursionLimit}} + +__import__('sys').setrecursionlimit({{{.}}}) +{{/recursionLimit}} diff --git a/templates/api.mustache b/templates/api.mustache new file mode 100644 index 0000000..913e0db --- /dev/null +++ b/templates/api.mustache @@ -0,0 +1,311 @@ +# coding: utf-8 + +{{>partial_header}} + +import re # noqa: F401 +import io +import warnings + +from pydantic import validate_arguments, ValidationError +from typing_extensions import Annotated{{#asyncio}} +from typing import overload, Optional, Union, Awaitable{{/asyncio}} + +{{#imports}} +{{import}} +{{/imports}} + +from {{packageName}}.api_client import ApiClient +from {{packageName}}.api_response import ApiResponse +from {{packageName}}.exceptions import ( # noqa: F401 + ApiTypeError, + ApiValueError +) + + +{{#operations}} +class {{classname}}(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client +{{#operation}} + +{{#asyncio}} + @overload + async def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501 + ... + + @overload + def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}async_req: Optional[bool]=True, **kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501 + ... + +{{/asyncio}} + @validate_arguments + def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{{returnType}}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 + """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + +{{#notes}} + {{{.}}} # noqa: E501 +{{/notes}} + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) + >>> result = thread.get() + +{{#allParams}} + :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} + :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} +{{/allParams}} + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: {{returnType}}{{^returnType}}None{{/returnType}} + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the {{operationId}}_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") +{{#asyncio}} + if async_req is not None: + kwargs['async_req'] = async_req +{{/asyncio}} + return self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 + + @validate_arguments + def {{operationId}}_with_http_info(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> ApiResponse: # noqa: E501 + """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + +{{#notes}} + {{{.}}} # noqa: E501 +{{/notes}} + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) + >>> result = thread.get() + +{{#allParams}} + :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} + :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} +{{/allParams}} + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: {{#returnType}}tuple({{.}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}} + """ + + {{#isDeprecated}} + warnings.warn("{{{httpMethod}}} {{{path}}} is deprecated.", DeprecationWarning) + + {{/isDeprecated}} + {{#servers.0}} + _hosts = [ +{{#servers}} + '{{{url}}}'{{^-last}},{{/-last}} +{{/servers}} + ] + _host = _hosts[0] + if kwargs.get('_host_index'): + _host_index = int(kwargs.get('_host_index')) + if _host_index < 0 or _host_index >= len(_hosts): + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" + % len(_host) + ) + _host = _hosts[_host_index] + {{/servers.0}} + _params = locals() + + _all_params = [ +{{#allParams}} + '{{paramName}}'{{^-last}},{{/-last}} +{{/allParams}} + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params{{#servers.0}} and _key != "_host_index"{{/servers.0}}: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method {{operationId}}" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} +{{#pathParams}} + if _params['{{paramName}}']: + _path_params['{{baseName}}'] = _params['{{paramName}}'] + {{#isArray}} + _collection_formats['{{baseName}}'] = '{{collectionFormat}}' + {{/isArray}} + +{{/pathParams}} + + # process the query parameters + _query_params = [] +{{#queryParams}} + if _params.get('{{paramName}}') is not None: # noqa: E501 + {{#isDateTime}} + if isinstance(_params['{{paramName}}'], datetime): + _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.datetime_format))) + else: + _query_params.append(('{{baseName}}', _params['{{paramName}}'])) + {{/isDateTime}} + {{^isDateTime}} + {{#isDate}} + if isinstance(_params['{{paramName}}'], date): + _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.date_format))) + else: + _query_params.append(('{{baseName}}', _params['{{paramName}}'])) + {{/isDate}} + {{^isDate}} + _query_params.append(('{{baseName}}', _params['{{paramName}}']{{#isEnumRef}}.value{{/isEnumRef}})) + {{/isDate}} + {{/isDateTime}} + {{#isArray}} + _collection_formats['{{baseName}}'] = '{{collectionFormat}}' + {{/isArray}} + +{{/queryParams}} + # process the header parameters + _header_params = dict(_params.get('_headers', {})) +{{#headerParams}} + if _params['{{paramName}}']: + _header_params['{{baseName}}'] = _params['{{paramName}}'] + {{#isArray}} + _collection_formats['{{baseName}}'] = '{{collectionFormat}}' + {{/isArray}} + +{{/headerParams}} + # process the form parameters + _form_params = [] + _files = {} +{{#formParams}} + if _params['{{paramName}}']: + {{^isFile}} + _form_params.append(('{{{baseName}}}', _params['{{paramName}}'])) + {{/isFile}} + {{#isFile}} + _files['{{{baseName}}}'] = _params['{{paramName}}'] + {{/isFile}} + {{#isArray}} + _collection_formats['{{{baseName}}}'] = '{{collectionFormat}}' + {{/isArray}} + +{{/formParams}} + # process the body parameter + _body_params = None +{{#bodyParam}} + if _params['{{paramName}}'] is not None: + _body_params = _params['{{paramName}}'] + {{#isBinary}} + # convert to byte array if the input is a file name (str) + if isinstance(_body_params, str): + with io.open(_body_params, "rb") as _fp: + _body_params_from_file = _fp.read() + _body_params = _body_params_from_file + {{/isBinary}} + +{{/bodyParam}} + {{#hasProduces}} + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501 + + {{/hasProduces}} + {{#hasConsumes}} + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + {{/hasConsumes}} + # authentication setting + _auth_settings = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501 + + {{#returnType}} + {{#responses}} + {{#-first}} + _response_types_map = { + {{/-first}} + {{^isWildcard}} + '{{code}}': {{#dataType}}"{{.}}"{{/dataType}}{{^dataType}}None{{/dataType}}, + {{/isWildcard}} + {{#-last}} + } + {{/-last}} + {{/responses}} + {{/returnType}} + {{^returnType}} + _response_types_map = {} + {{/returnType}} + + return self.api_client.call_api( + '{{{path}}}', '{{httpMethod}}', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + {{#servers.0}} + _host=_host, + {{/servers.0}} + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) +{{/operation}} +{{/operations}} diff --git a/templates/api_client.mustache b/templates/api_client.mustache new file mode 100644 index 0000000..95fef88 --- /dev/null +++ b/templates/api_client.mustache @@ -0,0 +1,783 @@ +# coding: utf-8 + +{{>partial_header}} + +import atexit +import datetime +from dateutil.parser import parse +import json +import mimetypes +from multiprocessing.pool import ThreadPool +import os +import re +import tempfile + +from urllib.parse import quote +{{#tornado}} +import tornado.gen +{{/tornado}} + +from {{packageName}}.configuration import Configuration +from {{packageName}}.api_response import ApiResponse +import {{modelPackage}} +from {{packageName}} import rest +from {{packageName}}.exceptions import ApiValueError, ApiException + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'object': object, + } + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = '{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}' + self.client_side_validation = configuration.client_side_validation + + {{#asyncio}} + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_value, traceback): + await self.close() + {{/asyncio}} + {{^asyncio}} + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + {{/asyncio}} + + {{#asyncio}}async {{/asyncio}}def close(self): + {{#asyncio}} + await self.rest_client.close() + {{/asyncio}} + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + {{#tornado}} + @tornado.gen.coroutine + {{/tornado}} + {{#asyncio}}async {{/asyncio}}def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_types_map=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None, _host=None, + _request_auth=None): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, query_params, auth_settings, + resource_path, method, body, + request_auth=_request_auth) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query(query_params, + collection_formats) + url += "?" + url_query + + try: + # perform request and return response + response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request( + method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e + + self.last_response = response_data + + return_data = None # assuming derialization is not needed + # data needs deserialization or returns HTTP data (deserialized) only + if _preload_content or _return_http_data_only: + response_type = response_types_map.get(str(response_data.status), None) + + if response_type == "bytearray": + response_data.data = response_data.data + else: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type == "bytearray": + return_data = response_data.data + elif response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None + +{{^tornado}} + if _return_http_data_only: + return return_data + else: + return ApiResponse(status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data) +{{/tornado}} +{{#tornado}} + if _return_http_data_only: + raise tornado.gen.Return(return_data) + else: + raise tornado.gen.Return(ApiResponse(status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data)) +{{/tornado}} + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = obj.to_dict() + + return {key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items()} + + def deserialize(self, response, response_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == "file": + return self.__deserialize_file(response) + + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if type(klass) == str: + if klass.startswith('List['): + sub_kls = re.match(r'List\[(.*)]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr({{modelPackage}}, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_types_map=None, auth_settings=None, + async_req=None, _return_http_data_only=None, + collection_formats=None, _preload_content=True, + _request_timeout=None, _host=None, _request_auth=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_token: dict, optional + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_types_map, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _request_auth) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_types_map, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _request_auth)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.get_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.head_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.options_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + elif method == "POST": + return self.rest_client.post_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.put_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.patch_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.delete_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v))) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(item) for item in new_params]) + + def files_parameters(self, files=None): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + + if files: + for k, v in files.items(): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth(self, headers, queries, auth_settings, + resource_path, method, body, + request_auth=None): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params(headers, queries, + resource_path, method, body, + request_auth) + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params(headers, queries, + resource_path, method, body, + auth_setting) + + def _apply_auth_params(self, headers, queries, + resource_path, method, body, + auth_setting): + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + {{#hasHttpSignatureMethods}} + else: + # The HTTP signature scheme requires multiple HTTP headers + # that are calculated dynamically. + signing_info = self.configuration.signing_info + auth_headers = signing_info.get_http_signature_headers( + resource_path, method, headers, body, queries) + headers.update(auth_headers) + {{/hasHttpSignatureMethods}} + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/templates/api_doc.mustache b/templates/api_doc.mustache new file mode 100644 index 0000000..4a1d364 --- /dev/null +++ b/templates/api_doc.mustache @@ -0,0 +1,74 @@ +# {{packageName}}.{{classname}}{{#description}} +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}={{{paramName}}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{.}}}{{/notes}} + +### Example + +{{#hasAuthMethods}} +{{#authMethods}} +{{#isBasic}} +{{#isBasicBasic}} +* Basic Authentication ({{name}}): +{{/isBasicBasic}} +{{#isBasicBearer}} +* Bearer{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} Authentication ({{name}}): +{{/isBasicBearer}} +{{/isBasic}} +{{#isApiKey}} +* Api Key Authentication ({{name}}): +{{/isApiKey }} +{{#isOAuth}} +* OAuth Authentication ({{name}}): +{{/isOAuth }} +{{/authMethods}} +{{/hasAuthMethods}} +{{> api_doc_example }} + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +**{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/templates/api_doc_example.mustache b/templates/api_doc_example.mustache new file mode 100644 index 0000000..15fbe33 --- /dev/null +++ b/templates/api_doc_example.mustache @@ -0,0 +1,38 @@ +```python +import time +import os +import {{{packageName}}} +{{#vendorExtensions.x-py-example-import}} +{{{.}}} +{{/vendorExtensions.x-py-example-import}} +from {{{packageName}}}.rest import ApiException +from pprint import pprint + +{{> python_doc_auth_partial}} +# Enter a context with an instance of the API client +{{#asyncio}}async {{/asyncio}}with {{{packageName}}}.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = {{{packageName}}}.{{{classname}}}(api_client) + {{#allParams}} + {{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/allParams}} + + try: + {{#summary}} + # {{{.}}} + {{/summary}} + {{#returnType}}api_response = {{/returnType}}{{#asyncio}}await {{/asyncio}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + {{#returnType}} + print("The response of {{classname}}->{{operationId}}:\n") + pprint(api_response) + {{/returnType}} + except Exception as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +``` + +{{#vendorExtensions.x-py-postponed-example-imports.size}} +{{#vendorExtensions.x-py-postponed-example-imports}} +{{{.}}} +{{/vendorExtensions.x-py-postponed-example-imports}} +{{classname}}.update_forward_refs() +{{/vendorExtensions.x-py-postponed-example-imports.size}} \ No newline at end of file diff --git a/templates/api_response.mustache b/templates/api_response.mustache new file mode 100644 index 0000000..d81c2ff --- /dev/null +++ b/templates/api_response.mustache @@ -0,0 +1,25 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Any, Dict, Optional +from pydantic import Field, StrictInt, StrictStr + +class ApiResponse: + """ + API response object + """ + + status_code: Optional[StrictInt] = Field(None, description="HTTP status code") + headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") + data: Optional[Any] = Field(None, description="Deserialized data given the data type") + raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + + def __init__(self, + status_code=None, + headers=None, + data=None, + raw_data=None): + self.status_code = status_code + self.headers = headers + self.data = data + self.raw_data = raw_data diff --git a/templates/api_test.mustache b/templates/api_test.mustache new file mode 100644 index 0000000..c3bbe4b --- /dev/null +++ b/templates/api_test.mustache @@ -0,0 +1,35 @@ +# coding: utf-8 + +{{>partial_header}} + +import unittest + +import {{packageName}} +from {{apiPackage}}.{{classFilename}} import {{classname}} # noqa: E501 +from {{packageName}}.rest import ApiException + + +class {{#operations}}Test{{classname}}(unittest.TestCase): + """{{classname}} unit test stubs""" + + def setUp(self): + self.api = {{apiPackage}}.{{classFilename}}.{{classname}}() # noqa: E501 + + def tearDown(self): + pass + + {{#operation}} + def test_{{operationId}}(self): + """Test case for {{{operationId}}} + +{{#summary}} + {{{.}}} # noqa: E501 +{{/summary}} + """ + pass + + {{/operation}} +{{/operations}} + +if __name__ == '__main__': + unittest.main() diff --git a/templates/asyncio/rest.mustache b/templates/asyncio/rest.mustache new file mode 100644 index 0000000..98c811e --- /dev/null +++ b/templates/asyncio/rest.mustache @@ -0,0 +1,241 @@ +# coding: utf-8 + +{{>partial_header}} + +import io +import json +import logging +import re +import ssl + +import aiohttp +from urllib.parse import urlencode, quote_plus + +from {{packageName}}.exceptions import ApiException, ApiValueError + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp, data): + self.aiohttp_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = data + + def getheaders(self): + """Returns a CIMultiDictProxy of the response headers.""" + return self.aiohttp_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.aiohttp_response.headers.get(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + + # maxsize is number of requests to host that are allowed in parallel + if maxsize is None: + maxsize = configuration.connection_pool_maxsize + + ssl_context = ssl.create_default_context(cafile=configuration.ssl_ca_cert) + if configuration.cert_file: + ssl_context.load_cert_chain( + configuration.cert_file, keyfile=configuration.key_file + ) + + if not configuration.verify_ssl: + ssl_context.check_hostname = False + ssl_context.verify_mode = ssl.CERT_NONE + + connector = aiohttp.TCPConnector( + limit=maxsize, + ssl=ssl_context + ) + + self.proxy = configuration.proxy + self.proxy_headers = configuration.proxy_headers + + # https pool manager + self.pool_manager = aiohttp.ClientSession( + connector=connector, + trust_env=True + ) + + async def close(self): + await self.pool_manager.close() + + async def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Execute request + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + # url already contains the URL query string + # so reset query_params to empty dict + query_params = {} + timeout = _request_timeout or 5 * 60 + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + args = { + "method": method, + "url": url, + "timeout": timeout, + "headers": headers + } + + if self.proxy: + args["proxy"] = self.proxy + if self.proxy_headers: + args["proxy_headers"] = self.proxy_headers + + if query_params: + args["url"] += '?' + urlencode(query_params) + + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if re.search('json', headers['Content-Type'], re.IGNORECASE): + if body is not None: + body = json.dumps(body) + args["data"] = body + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + args["data"] = aiohttp.FormData(post_params) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by aiohttp + del headers['Content-Type'] + data = aiohttp.FormData() + for param in post_params: + k, v = param + if isinstance(v, tuple) and len(v) == 3: + data.add_field(k, + value=v[1], + filename=v[0], + content_type=v[2]) + else: + data.add_field(k, v) + args["data"] = data + + # Pass a `bytes` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, bytes): + args["data"] = body + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + r = await self.pool_manager.request(**args) + if _preload_content: + + data = await r.read() + r = RESTResponse(r, data) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + return r + + async def get_request(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): + return (await self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) + + async def head_request(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): + return (await self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) + + async def options_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def delete_request(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return (await self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def post_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def put_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return (await self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def patch_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) diff --git a/templates/common_README.mustache b/templates/common_README.mustache new file mode 100644 index 0000000..706d9b3 --- /dev/null +++ b/templates/common_README.mustache @@ -0,0 +1,85 @@ +```python +{{#apiInfo}}{{#apis}}{{#-last}}{{#hasHttpSignatureMethods}}import datetime{{/hasHttpSignatureMethods}}{{/-last}}{{/apis}}{{/apiInfo}} +import time +import {{{packageName}}} +from {{{packageName}}}.rest import ApiException +from pprint import pprint +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{> python_doc_auth_partial}} + +# Enter a context with an instance of the API client +{{#asyncio}}async {{/asyncio}}with {{{packageName}}}.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = {{{packageName}}}.{{{classname}}}(api_client) + {{#allParams}} + {{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/allParams}} + + try: + {{#summary}} + # {{{.}}} + {{/summary}} + {{#returnType}}api_response = {{/returnType}}{{#asyncio}}await {{/asyncio}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + {{#returnType}} + print("The response of {{classname}}->{{operationId}}:\n") + pprint(api_response) + {{/returnType}} + except ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + + +## Documentation For Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{{name}}} + +{{#isApiKey}} +- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}} +{{#isBasicBasic}} +- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}} +- **Type**: Bearer authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} +{{/isBasicBearer}} +{{#isHttpSignature}} +- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{/isBasic}} +{{#isOAuth}} +- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/templates/configuration.mustache b/templates/configuration.mustache new file mode 100644 index 0000000..ac51800 --- /dev/null +++ b/templates/configuration.mustache @@ -0,0 +1,615 @@ +# coding: utf-8 + +{{>partial_header}} + +import copy +import logging +{{^asyncio}} +import multiprocessing +{{/asyncio}} +import sys +import urllib3 + +import http.client as httplib +from {{packageName}}.exceptions import ApiValueError + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration(object): + """This class contains various settings of the API client. + + :param host: Base url. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. +{{#hasHttpSignatureMethods}} + :param signing_info: Configuration parameters for the HTTP signature security scheme. + Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration +{{/hasHttpSignatureMethods}} + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + +{{#hasAuthMethods}} + :Example: +{{#hasApiKeyMethods}} + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = {{{packageName}}}.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 +{{/hasApiKeyMethods}} +{{#hasHttpBasicMethods}} + + HTTP Basic Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: basic + + Configure API client with HTTP basic authentication: + +conf = {{{packageName}}}.Configuration( + username='the-user', + password='the-password', +) + +{{/hasHttpBasicMethods}} +{{#hasHttpSignatureMethods}} + + HTTP Signature Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: signature + + Configure API client with HTTP signature authentication. Use the 'hs2019' signature scheme, + sign the HTTP requests with the RSA-SSA-PSS signature algorithm, and set the expiration time + of the signature to 5 minutes after the signature has been created. + Note you can use the constants defined in the {{{packageName}}}.signing module, and you can + also specify arbitrary HTTP headers to be included in the HTTP signature, except for the + 'Authorization' header, which is used to carry the signature. + + One may be tempted to sign all headers by default, but in practice it rarely works. + This is because explicit proxies, transparent proxies, TLS termination endpoints or + load balancers may add/modify/remove headers. Include the HTTP headers that you know + are not going to be modified in transit. + +conf = {{{packageName}}}.Configuration( + signing_info = {{{packageName}}}.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'rsa.pem', + signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, + signing_algorithm = {{{packageName}}}.signing.ALGORITHM_RSASSA_PSS, + signed_headers = [{{{packageName}}}.signing.HEADER_REQUEST_TARGET, + {{{packageName}}}.signing.HEADER_CREATED, + {{{packageName}}}.signing.HEADER_EXPIRES, + {{{packageName}}}.signing.HEADER_HOST, + {{{packageName}}}.signing.HEADER_DATE, + {{{packageName}}}.signing.HEADER_DIGEST, + 'Content-Type', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) +{{/hasHttpSignatureMethods}} +{{/hasAuthMethods}} + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, +{{#hasHttpSignatureMethods}} + signing_info=None, +{{/hasHttpSignatureMethods}} + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor + """ + self._base_path = "{{{basePath}}}" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ +{{#hasHttpSignatureMethods}} + if signing_info is not None: + signing_info.host = host + self.signing_info = signing_info + """The HTTP signing configuration + """ +{{/hasHttpSignatureMethods}} + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("{{packageName}}") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + {{#asyncio}} + self.connection_pool_maxsize = 100 + """This value is passed to the aiohttp to limit simultaneous connections. + Default values is 100, None means no-limit. + """ + {{/asyncio}} + {{^asyncio}} + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + {{/asyncio}} + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "{{{datetimeFormat}}}" + """datetime format + """ + + self.date_format = "{{{dateFormat}}}" + """date format + """ + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) +{{#hasHttpSignatureMethods}} + if name == "signing_info" and value is not None: + # Ensure the host parameter from signing info is the same as + # Configuration.host. + value.host = self.host +{{/hasHttpSignatureMethods}} + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls): + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = Configuration() + return cls._default + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} +{{#authMethods}} +{{#isApiKey}} + if '{{name}}' in self.api_key{{#vendorExtensions.x-auth-id-alias}} or '{{.}}' in self.api_key{{/vendorExtensions.x-auth-id-alias}}: + auth['{{name}}'] = { + 'type': 'api_key', + 'in': {{#isKeyInCookie}}'cookie'{{/isKeyInCookie}}{{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': self.get_api_key_with_prefix( + '{{name}}',{{#vendorExtensions.x-auth-id-alias}} + alias='{{.}}',{{/vendorExtensions.x-auth-id-alias}} + ), + } +{{/isApiKey}} +{{#isBasic}} + {{#isBasicBasic}} + if self.username is not None and self.password is not None: + auth['{{name}}'] = { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + } + {{/isBasicBasic}} + {{#isBasicBearer}} + if self.access_token is not None: + auth['{{name}}'] = { + 'type': 'bearer', + 'in': 'header', + {{#bearerFormat}} + 'format': '{{{.}}}', + {{/bearerFormat}} + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + {{/isBasicBearer}} + {{#isHttpSignature}} + if self.signing_info is not None: + auth['{{name}}'] = { + 'type': 'http-signature', + 'in': 'header', + 'key': 'Authorization', + 'value': None # Signature headers are calculated for every HTTP request + } + {{/isHttpSignature}} +{{/isBasic}} +{{#isOAuth}} + if self.access_token is not None: + auth['{{name}}'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } +{{/isOAuth}} +{{/authMethods}} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: {{version}}\n"\ + "SDK Package Version: {{packageVersion}}".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + {{#servers}} + { + 'url': "{{{url}}}", + 'description': "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + 'variables': { + {{/-first}} + '{{{name}}}': { + 'description': "{{{description}}}{{^description}}No description provided{{/description}}", + 'default_value': "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + 'enum_values': [ + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + }{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/variables}} + }{{^-last}},{{/-last}} + {{/servers}} + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/templates/exceptions.mustache b/templates/exceptions.mustache new file mode 100644 index 0000000..baee900 --- /dev/null +++ b/templates/exceptions.mustache @@ -0,0 +1,156 @@ +# coding: utf-8 + +{{>partial_header}} + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + +class BadRequestException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(BadRequestException, self).__init__(status, reason, http_resp) + +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ServiceException, self).__init__(status, reason, http_resp) + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/templates/git_push.sh.mustache b/templates/git_push.sh.mustache new file mode 100644 index 0000000..0e3776a --- /dev/null +++ b/templates/git_push.sh.mustache @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/templates/github-workflow.mustache b/templates/github-workflow.mustache new file mode 100644 index 0000000..a3aae3f --- /dev/null +++ b/templates/github-workflow.mustache @@ -0,0 +1,38 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: {{packageName}} Python package +{{=<% %>=}} + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test with pytest + run: | + pytest diff --git a/templates/gitignore.mustache b/templates/gitignore.mustache new file mode 100644 index 0000000..43995bd --- /dev/null +++ b/templates/gitignore.mustache @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/templates/gitlab-ci.mustache b/templates/gitlab-ci.mustache new file mode 100644 index 0000000..0bb48fd --- /dev/null +++ b/templates/gitlab-ci.mustache @@ -0,0 +1,25 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.gitlab.com/ee/ci/README.html +# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml + +stages: + - test + +.pytest: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov={{{packageName}}} + +pytest-3.7: + extends: .pytest + image: python:3.7-alpine +pytest-3.8: + extends: .pytest + image: python:3.8-alpine +pytest-3.9: + extends: .pytest + image: python:3.9-alpine \ No newline at end of file diff --git a/templates/model.mustache b/templates/model.mustache new file mode 100644 index 0000000..84792dd --- /dev/null +++ b/templates/model.mustache @@ -0,0 +1,14 @@ +# coding: utf-8 + +{{>partial_header}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>model_enum}} +{{/isEnum}} +{{^isEnum}} +{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_generic}}{{/anyOf}}{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} \ No newline at end of file diff --git a/templates/model_anyof.mustache b/templates/model_anyof.mustache new file mode 100644 index 0000000..74a007f --- /dev/null +++ b/templates/model_anyof.mustache @@ -0,0 +1,180 @@ +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 +{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} +{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} +{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} +{{#vendorExtensions.x-py-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-model-imports}} +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] + +class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): + """ + {{{description}}}{{^description}}{{{classname}}}{{/description}} + """ + +{{#composedSchemas.anyOf}} + # data type: {{{dataType}}} + {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} +{{/composedSchemas.anyOf}} + if TYPE_CHECKING: + actual_instance: Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}] + else: + actual_instance: Any + any_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True +{{#discriminator}} + + discriminator_value_class_map = { +{{#children}} + '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} +{{/children}} + } +{{/discriminator}} + + def __init__(self, *args, **kwargs): + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_anyof(cls, v): + {{#isNullable}} + if v is None: + return v + + {{/isNullable}} + instance = {{{classname}}}.construct() + error_messages = [] + {{#composedSchemas.anyOf}} + # validate data type: {{{dataType}}} + {{#isContainer}} + try: + instance.{{vendorExtensions.x-py-name}} = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} + try: + instance.{{vendorExtensions.x-py-name}} = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{^isPrimitiveType}} + if not isinstance(v, {{{dataType}}}): + error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") + else: + return v + + {{/isPrimitiveType}} + {{/isContainer}} + {{/composedSchemas.anyOf}} + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> {{{classname}}}: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> {{{classname}}}: + """Returns the object represented by the json string""" + instance = {{{classname}}}.construct() + {{#isNullable}} + if json_str is None: + return instance + + {{/isNullable}} + error_messages = [] + {{#composedSchemas.anyOf}} + {{#isContainer}} + # deserialize data into {{{dataType}}} + try: + # validation + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} + # deserialize data into {{{dataType}}} + try: + # validation + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{^isPrimitiveType}} + # {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} + try: + instance.actual_instance = {{{dataType}}}.from_json(json_str) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{/isContainer}} + {{/composedSchemas.anyOf}} + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_dict() + else: + return json.dumps(self.actual_instance) + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + +{{#vendorExtensions.x-py-postponed-model-imports.size}} +{{#vendorExtensions.x-py-postponed-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-postponed-model-imports}} +{{classname}}.update_forward_refs() +{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_doc.mustache b/templates/model_doc.mustache new file mode 100644 index 0000000..dd54470 --- /dev/null +++ b/templates/model_doc.mustache @@ -0,0 +1,33 @@ +{{#models}}{{#model}}# {{classname}} + +{{#description}}{{&description}} +{{/description}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +{{^isEnum}} +## Example + +```python +from {{modelPackage}}.{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} import {{classname}} + +# TODO update the JSON string below +json = "{}" +# create an instance of {{classname}} from a JSON string +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance = {{classname}}.from_json(json) +# print the JSON string representation of the object +print {{classname}}.to_json() + +# convert the object into a dict +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict() +# create an instance of {{classname}} from a dict +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_form_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict) +``` +{{/isEnum}} +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/templates/model_enum.mustache b/templates/model_enum.mustache new file mode 100644 index 0000000..83f0552 --- /dev/null +++ b/templates/model_enum.mustache @@ -0,0 +1,36 @@ +import json +import pprint +import re # noqa: F401 +from aenum import Enum, no_arg +{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} +{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} +{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} + + +class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum): + """ + {{{description}}}{{^description}}{{{classname}}}{{/description}} + """ + + """ + allowed enum values + """ +{{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}} + {{/enumVars}} + + @classmethod + def from_json(cls, json_str: str) -> {{{classname}}}: + """Create an instance of {{classname}} from a JSON string""" + return {{classname}}(json.loads(json_str)) + + {{#defaultValue}} + + # + @classmethod + def _missing_value_(cls, value): + if value is no_arg: + return cls.{{{.}}} + {{/defaultValue}} +{{/allowableValues}} diff --git a/templates/model_generic.mustache b/templates/model_generic.mustache new file mode 100644 index 0000000..1355ddb --- /dev/null +++ b/templates/model_generic.mustache @@ -0,0 +1,361 @@ +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} +{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} +{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} +{{#vendorExtensions.x-py-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-model-imports}} + +class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): + """ + {{{description}}}{{^description}}{{{classname}}}{{/description}} + """ +{{#vars}} + {{name}}: {{{vendorExtensions.x-py-typing}}} +{{/vars}} +{{#isAdditionalPropertiesTrue}} + additional_properties: Dict[str, Any] = {} +{{/isAdditionalPropertiesTrue}} + __properties = [{{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}}] +{{#vars}} + {{#vendorExtensions.x-regex}} + + @validator('{{{name}}}') + def {{{name}}}_validate_regular_expression(cls, value): + """Validates the regular expression""" + {{^required}} + if value is None: + return value + + {{/required}} + {{#required}} + {{#isNullable}} + if value is None: + return value + + {{/isNullable}} + {{/required}} + if not re.match(r"{{{.}}}", value{{#vendorExtensions.x-modifiers}} ,re.{{{.}}}{{/vendorExtensions.x-modifiers}}): + raise ValueError(r"must validate the regular expression {{{vendorExtensions.x-pattern}}}") + return value + {{/vendorExtensions.x-regex}} + {{#isEnum}} + + @validator('{{{name}}}') + def {{{name}}}_validate_enum(cls, value): + """Validates the enum""" + {{^required}} + if value is None: + return value + + {{/required}} + {{#required}} + {{#isNullable}} + if value is None: + return value + + {{/isNullable}} + {{/required}} + {{#isArray}} + for i in value: + if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): + raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + {{/isArray}} + {{^isArray}} + if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): + raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + {{/isArray}} + return value + {{/isEnum}} +{{/vars}} + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + +{{#hasChildren}} +{{#discriminator}} + # JSON field name that stores the object type + __discriminator_property_name = '{{discriminator.propertyBaseName}}' + + {{#mappedModels}} + {{#-first}} + # discriminator mappings + __discriminator_value_class_map = { + {{/-first}} + '{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}} + {{#-last}} + } + + @classmethod + def get_discriminator_value(cls, obj: dict) -> str: + """Returns the discriminator value (object type) of the data""" + discriminator_value = obj[cls.__discriminator_property_name] + if discriminator_value: + return cls.__discriminator_value_class_map.get(discriminator_value) + else: + return None + {{/-last}} + {{/mappedModels}} + +{{/discriminator}} +{{/hasChildren}} + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}: + """Create an instance of {{{classname}}} from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + {{#vendorExtensions.x-py-readonly}} + "{{{.}}}", + {{/vendorExtensions.x-py-readonly}} + {{#isAdditionalPropertiesTrue}} + "additional_properties" + {{/isAdditionalPropertiesTrue}} + }, + exclude_none=True) + {{#allVars}} + {{#isContainer}} + {{#isArray}} + {{#items.isArray}} + {{^items.items.isPrimitiveType}} + # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list of list) + _items = [] + if self.{{{name}}}: + for _item in self.{{{name}}}: + if _item: + _items.append( + [_inner_item.to_dict() for _inner_item in _item if _inner_item is not None] + ) + _dict['{{{baseName}}}'] = _items + {{/items.items.isPrimitiveType}} + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list) + _items = [] + if self.{{{name}}}: + for _item in self.{{{name}}}: + if _item: + _items.append(_item.to_dict()) + _dict['{{{baseName}}}'] = _items + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isArray}} + {{#isMap}} + {{#items.isArray}} + # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict of array) + _field_dict_of_array = {} + if self.{{{name}}}: + for _key in self.{{{name}}}: + if self.{{{name}}}[_key]: + _field_dict_of_array[_key] = [ + _item.to_dict() for _item in self.{{{name}}}[_key] + ] + _dict['{{{baseName}}}'] = _field_dict_of_array + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict) + _field_dict = {} + if self.{{{name}}}: + for _key in self.{{{name}}}: + if self.{{{name}}}[_key]: + _field_dict[_key] = self.{{{name}}}[_key].to_dict() + _dict['{{{baseName}}}'] = _field_dict + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{^isPrimitiveType}} + {{^isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of {{{name}}} + if self.{{{name}}}: + _dict['{{{baseName}}}'] = self.{{{name}}}.to_dict() + {{/isEnumOrRef}} + {{/isPrimitiveType}} + {{/isContainer}} + {{/allVars}} + {{#isAdditionalPropertiesTrue}} + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + {{/isAdditionalPropertiesTrue}} + {{#allVars}} + {{#isNullable}} + # set to None if {{{name}}} (nullable) is None + # and __fields_set__ contains the field + if self.{{name}} is None and "{{{name}}}" in self.__fields_set__: + _dict['{{{baseName}}}'] = None + + {{/isNullable}} + {{/allVars}} + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}: + """Create an instance of {{{classname}}} from a dict""" + {{#hasChildren}} + {{#discriminator}} + # look up the object type based on discriminator mapping + object_type = cls.get_discriminator_value(obj) + if object_type: + klass = globals()[object_type] + return klass.from_dict(obj) + else: + raise ValueError("{{{classname}}} failed to lookup discriminator value from " + + json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + + ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) + {{/discriminator}} + {{/hasChildren}} + {{^hasChildren}} + if obj is None: + return None + + if not isinstance(obj, dict): + return {{{classname}}}.parse_obj(obj) + + {{#disallowAdditionalPropertiesIfNotPresent}} + {{^isAdditionalPropertiesTrue}} + # raise errors for additional fields in the input + for _key in obj.keys(): + if _key not in cls.__properties: + raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + obj) + + {{/isAdditionalPropertiesTrue}} + {{/disallowAdditionalPropertiesIfNotPresent}} + _obj = {{{classname}}}.parse_obj({ + {{#allVars}} + {{#isContainer}} + {{#isArray}} + {{#items.isArray}} + {{#items.items.isPrimitiveType}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.items.isPrimitiveType}} + {{^items.items.isPrimitiveType}} + "{{{name}}}": [ + [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item] + for _item in obj.get("{{{baseName}}}") + ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/items.items.isPrimitiveType}} + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{#items.isEnumOrRef}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{^items.isEnumOrRef}} + "{{{name}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj.get("{{{baseName}}}")] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{#items.isPrimitiveType}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isArray}} + {{#isMap}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + {{#items.isContainer}} + {{#items.isMap}} + "{{{name}}}": dict( + (_k, dict( + (_ik, {{{items.items.dataType}}}.from_dict(_iv)) + for _ik, _iv in _v.items() + ) + if _v is not None + else None + ) + for _k, _v in obj.get("{{{baseName}}}").items() + ) + if obj.get("{{{baseName}}}") is not None + else None{{^-last}},{{/-last}} + {{/items.isMap}} + {{#items.isArray}} + "{{{name}}}": dict( + (_k, + [{{{items.items.dataType}}}.from_dict(_item) for _item in _v] + if _v is not None + else None + ) + for _k, _v in obj.get("{{{baseName}}}").items() + ){{^-last}},{{/-last}} + {{/items.isArray}} + {{/items.isContainer}} + {{^items.isContainer}} + "{{{name}}}": dict( + (_k, {{{items.dataType}}}.from_dict(_v)) + for _k, _v in obj.get("{{{baseName}}}").items() + ) + if obj.get("{{{baseName}}}") is not None + else None{{^-last}},{{/-last}} + {{/items.isContainer}} + {{/items.isEnumOrRef}} + {{#items.isEnumOrRef}} + "{{{name}}}": dict((_k, _v) for _k, _v in obj.get("{{{baseName}}}").items()){{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{#items.isPrimitiveType}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isPrimitiveType}} + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{^isPrimitiveType}} + {{^isEnumOrRef}} + "{{{name}}}": {{{dataType}}}.from_dict(obj.get("{{{baseName}}}")) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/isEnumOrRef}} + {{#isEnumOrRef}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/isEnumOrRef}} + {{/isPrimitiveType}} + {{#isPrimitiveType}} + {{#defaultValue}} + "{{{name}}}": obj.get("{{{baseName}}}") if obj.get("{{{baseName}}}") is not None else {{{defaultValue}}}{{^-last}},{{/-last}} + {{/defaultValue}} + {{^defaultValue}} + "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/defaultValue}} + {{/isPrimitiveType}} + {{/isContainer}} + {{/allVars}} + }) + {{#isAdditionalPropertiesTrue}} + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + {{/isAdditionalPropertiesTrue}} + return _obj + {{/hasChildren}} + +{{#vendorExtensions.x-py-postponed-model-imports.size}} +{{#vendorExtensions.x-py-postponed-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-postponed-model-imports}} +{{classname}}.update_forward_refs() +{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_oneof.mustache b/templates/model_oneof.mustache new file mode 100644 index 0000000..c7afad4 --- /dev/null +++ b/templates/model_oneof.mustache @@ -0,0 +1,206 @@ +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 +{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} +{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} +{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} +{{#vendorExtensions.x-py-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-model-imports}} +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] + +class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): + """ + {{{description}}}{{^description}}{{{classname}}}{{/description}} + """ +{{#composedSchemas.oneOf}} + # data type: {{{dataType}}} + {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} +{{/composedSchemas.oneOf}} + if TYPE_CHECKING: + actual_instance: Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}] + else: + actual_instance: Any + one_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True +{{#discriminator}} + + discriminator_value_class_map = { +{{#children}} + '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} +{{/children}} + } +{{/discriminator}} + + def __init__(self, *args, **kwargs): + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + {{#isNullable}} + if v is None: + return v + + {{/isNullable}} + instance = {{{classname}}}.construct() + error_messages = [] + match = 0 + {{#composedSchemas.oneOf}} + # validate data type: {{{dataType}}} + {{#isContainer}} + try: + instance.{{vendorExtensions.x-py-name}} = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} + try: + instance.{{vendorExtensions.x-py-name}} = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{^isPrimitiveType}} + if not isinstance(v, {{{dataType}}}): + error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") + else: + match += 1 + {{/isPrimitiveType}} + {{/isContainer}} + {{/composedSchemas.oneOf}} + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> {{{classname}}}: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> {{{classname}}}: + """Returns the object represented by the json string""" + instance = {{{classname}}}.construct() + {{#isNullable}} + if json_str is None: + return instance + + {{/isNullable}} + error_messages = [] + match = 0 + + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + {{#mappedModels}} + {{#-first}} + # use oneOf discriminator to lookup the data type + _data_type = json.loads(json_str).get("{{{propertyBaseName}}}") + if not _data_type: + raise ValueError("Failed to lookup data type from the field `{{{propertyBaseName}}}` in the input.") + + {{/-first}} + # check if data type is `{{{modelName}}}` + if _data_type == "{{{mappingName}}}": + instance.actual_instance = {{{modelName}}}.from_json(json_str) + return instance + + {{/mappedModels}} + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + {{#composedSchemas.oneOf}} + {{#isContainer}} + # deserialize data into {{{dataType}}} + try: + # validation + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} + # deserialize data into {{{dataType}}} + try: + # validation + instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.{{vendorExtensions.x-py-name}} + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{^isPrimitiveType}} + # deserialize data into {{{dataType}}} + try: + instance.actual_instance = {{{dataType}}}.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + {{/isPrimitiveType}} + {{/isContainer}} + {{/composedSchemas.oneOf}} + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + +{{#vendorExtensions.x-py-postponed-model-imports.size}} +{{#vendorExtensions.x-py-postponed-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-postponed-model-imports}} +{{classname}}.update_forward_refs() +{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_test.mustache b/templates/model_test.mustache new file mode 100644 index 0000000..93ebf99 --- /dev/null +++ b/templates/model_test.mustache @@ -0,0 +1,62 @@ +# coding: utf-8 + +{{>partial_header}} + +import unittest +import datetime + +{{#models}} +{{#model}} +import {{packageName}} +from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501 +from {{packageName}}.rest import ApiException + +class Test{{classname}}(unittest.TestCase): + """{{classname}} unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass +{{^isEnum}} + + def make_instance(self, include_optional): + """Test {{classname}} + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `{{{classname}}}` + """ + model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501 + if include_optional : + return {{classname}}( + {{#vars}} + {{name}} = {{{example}}}{{^example}}None{{/example}}{{^-last}}, {{/-last}} + {{/vars}} + ) + else : + return {{classname}}( + {{#vars}} + {{#required}} + {{name}} = {{{example}}}{{^example}}None{{/example}}, + {{/required}} + {{/vars}} + ) + """ +{{/isEnum}} + + def test{{classname}}(self): + """Test {{classname}}""" +{{^isEnum}} + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) +{{/isEnum}} +{{#isEnum}} + # inst = {{{classname}}}() +{{/isEnum}} +{{/model}} +{{/models}} + +if __name__ == '__main__': + unittest.main() diff --git a/templates/partial_header.mustache b/templates/partial_header.mustache new file mode 100644 index 0000000..50aa811 --- /dev/null +++ b/templates/partial_header.mustache @@ -0,0 +1,19 @@ +""" +{{#appName}} + {{{.}}} + +{{/appName}} +{{#appDescription}} + {{{.}}} + +{{/appDescription}} + {{#version}} + The version of the OpenAPI document: {{{.}}} + {{/version}} + {{#infoEmail}} + Contact: {{{.}}} + {{/infoEmail}} + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 diff --git a/templates/py.typed.mustache b/templates/py.typed.mustache new file mode 100644 index 0000000..e69de29 diff --git a/templates/pyproject.mustache b/templates/pyproject.mustache new file mode 100644 index 0000000..75900ed --- /dev/null +++ b/templates/pyproject.mustache @@ -0,0 +1,40 @@ +[tool.poetry] +name = "{{{packageName}}}" +version = "{{{packageVersion}}}" +description = "{{{appName}}}" +authors = ["{{infoName}}{{^infoName}}OpenAPI Generator Community{{/infoName}} <{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}>"] +license = "{{{licenseInfo}}}{{^licenseInfo}}NoLicense{{/licenseInfo}}" +readme = "README.md" +repository = "https://github.com/{{{gitUserId}}}/{{{gitRepoId}}}" +keywords = ["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"] +include = ["{{packageName}}/py.typed"] + +[tool.poetry.dependencies] +python = "^3.7" + +urllib3 = ">= 1.25.3" +python-dateutil = ">=2.8.2" +{{#asyncio}} +aiohttp = ">= 3.8.4" +{{/asyncio}} +{{#tornado}} +tornado = ">=4.2,<5" +{{/tornado}} +{{#hasHttpSignatureMethods}} +pem = ">= 19.3.0" +pycryptodome = ">= 3.9.0" +{{/hasHttpSignatureMethods}} +pydantic = "^1.10.5, <2" +aenum = ">=3.1.11" + +[tool.poetry.dev-dependencies] +pytest = ">=7.2.1" +tox = ">=3.9.0" +flake8 = ">=4.0.0" + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.pylint.'MESSAGES CONTROL'] +extension-pkg-whitelist = "pydantic" diff --git a/templates/python_doc_auth_partial.mustache b/templates/python_doc_auth_partial.mustache new file mode 100644 index 0000000..f478fe0 --- /dev/null +++ b/templates/python_doc_auth_partial.mustache @@ -0,0 +1,108 @@ +# Defining the host is optional and defaults to {{{basePath}}} +# See configuration.py for a list of all supported configuration parameters. +configuration = {{{packageName}}}.Configuration( + host = "{{{basePath}}}" +) + +{{#hasAuthMethods}} +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. +{{#authMethods}} +{{#isBasic}} +{{#isBasicBasic}} + +# Configure HTTP basic authorization: {{{name}}} +configuration = {{{packageName}}}.Configuration( + username = os.environ["USERNAME"], + password = os.environ["PASSWORD"] +) +{{/isBasicBasic}} +{{#isBasicBearer}} + +# Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}} +configuration = {{{packageName}}}.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) +{{/isBasicBearer}} +{{#isHttpSignature}} + +# Configure HTTP message signature: {{{name}}} +# The HTTP Signature Header mechanism that can be used by a client to +# authenticate the sender of a message and ensure that particular headers +# have not been modified in transit. +# +# You can specify the signing key-id, private key path, signing scheme, +# signing algorithm, list of signed headers and signature max validity. +# The 'key_id' parameter is an opaque string that the API server can use +# to lookup the client and validate the signature. +# The 'private_key_path' parameter should be the path to a file that +# contains a DER or base-64 encoded private key. +# The 'private_key_passphrase' parameter is optional. Set the passphrase +# if the private key is encrypted. +# The 'signed_headers' parameter is used to specify the list of +# HTTP headers included when generating the signature for the message. +# You can specify HTTP headers that you want to protect with a cryptographic +# signature. Note that proxies may add, modify or remove HTTP headers +# for legitimate reasons, so you should only add headers that you know +# will not be modified. For example, if you want to protect the HTTP request +# body, you can specify the Digest header. In that case, the client calculates +# the digest of the HTTP request body and includes the digest in the message +# signature. +# The 'signature_max_validity' parameter is optional. It is configured as a +# duration to express when the signature ceases to be valid. The client calculates +# the expiration date every time it generates the cryptographic signature +# of an HTTP request. The API server may have its own security policy +# that controls the maximum validity of the signature. The client max validity +# must be lower than the server max validity. +# The time on the client and server must be synchronized, otherwise the +# server may reject the client signature. +# +# The client must use a combination of private key, signing scheme, +# signing algorithm and hash algorithm that matches the security policy of +# the API server. +# +# See {{{packageName}}}.signing for a list of all supported parameters. +from {{{packageName}}} import signing +import datetime + +configuration = {{{packageName}}}.Configuration( + host = "{{{basePath}}}", + signing_info = {{{packageName}}}.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, + signing_algorithm = {{{packageName}}}.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = {{{packageName}}}.signing.SCHEME_RSA_SHA256, + signed_headers = [ + {{{packageName}}}.signing.HEADER_REQUEST_TARGET, + {{{packageName}}}.signing.HEADER_CREATED, + {{{packageName}}}.signing.HEADER_EXPIRES, + {{{packageName}}}.signing.HEADER_HOST, + {{{packageName}}}.signing.HEADER_DATE, + {{{packageName}}}.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) +{{/isHttpSignature}} +{{/isBasic}} +{{#isApiKey}} + +# Configure API key authorization: {{{name}}} +configuration.api_key['{{{name}}}'] = os.environ["API_KEY"] + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['{{name}}'] = 'Bearer' +{{/isApiKey}} +{{#isOAuth}} + +configuration.access_token = os.environ["ACCESS_TOKEN"] +{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} diff --git a/templates/requirements.mustache b/templates/requirements.mustache new file mode 100644 index 0000000..bd4fe39 --- /dev/null +++ b/templates/requirements.mustache @@ -0,0 +1,8 @@ +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.25.3, < 2.1.0 +pydantic >= 1.10.5, < 2 +aenum >= 3.1.11 +{{#asyncio}} +aiohttp >= 3.0.0 +{{/asyncio}} diff --git a/templates/rest.mustache b/templates/rest.mustache new file mode 100644 index 0000000..c8748d7 --- /dev/null +++ b/templates/rest.mustache @@ -0,0 +1,293 @@ +# coding: utf-8 + +{{>partial_header}} + +import io +import json +import logging +import re +import ssl + +from urllib.parse import urlencode, quote_plus +import urllib3 + +from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.headers.get(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + addition_pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + # url already contains the URL query string + # so reset query_params to empty dict + query_params = {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request(method, url, + fields={}, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + if r.status == 400: + raise BadRequestException(http_resp=r) + + if r.status == 401: + raise UnauthorizedException(http_resp=r) + + if r.status == 403: + raise ForbiddenException(http_resp=r) + + if r.status == 404: + raise NotFoundException(http_resp=r) + + if 500 <= r.status <= 599: + raise ServiceException(http_resp=r) + + raise ApiException(http_resp=r) + + return r + + def get_request(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def head_request(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def options_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def delete_request(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def post_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def put_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def patch_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) diff --git a/templates/setup.mustache b/templates/setup.mustache new file mode 100644 index 0000000..538a8df --- /dev/null +++ b/templates/setup.mustache @@ -0,0 +1,56 @@ +# coding: utf-8 + +{{>partial_header}} + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "{{{projectName}}}" +VERSION = "{{packageVersion}}" +PYTHON_REQUIRES = ">=3.7" +{{#apiInfo}} +{{#apis}} +{{#-last}} +REQUIRES = [ + "urllib3 >= 1.25.3, < 2.1.0", + "python-dateutil", +{{#asyncio}} + "aiohttp >= 3.0.0", +{{/asyncio}} +{{#tornado}} + "tornado>=4.2,<5", +{{/tornado}} +{{#hasHttpSignatureMethods}} + "pem>=19.3.0", + "pycryptodome>=3.9.0", +{{/hasHttpSignatureMethods}} + "pydantic >= 1.10.5, < 2", + "aenum" +] + +setup( + name=NAME, + version=VERSION, + description="{{appName}}", + author="{{infoName}}{{^infoName}}OpenAPI Generator community{{/infoName}}", + author_email="{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}", + url="{{packageUrl}}", + keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + {{#licenseInfo}}license="{{.}}", + {{/licenseInfo}}long_description_content_type='text/markdown', + long_description="""\ + {{appDescription}} + """, # noqa: E501 + package_data={"{{{packageName}}}": ["py.typed"]}, +) +{{/-last}} +{{/apis}} +{{/apiInfo}} diff --git a/templates/setup_cfg.mustache b/templates/setup_cfg.mustache new file mode 100644 index 0000000..11433ee --- /dev/null +++ b/templates/setup_cfg.mustache @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/templates/signing.mustache b/templates/signing.mustache new file mode 100644 index 0000000..8dca7e2 --- /dev/null +++ b/templates/signing.mustache @@ -0,0 +1,403 @@ +{{>partial_header}} + +from base64 import b64encode +from Crypto.IO import PEM, PKCS8 +from Crypto.Hash import SHA256, SHA512 +from Crypto.PublicKey import RSA, ECC +from Crypto.Signature import PKCS1_v1_5, pss, DSS +from email.utils import formatdate +import json +import os +import re +from time import time +from urllib.parse import urlencode, urlparse + +# The constants below define a subset of HTTP headers that can be included in the +# HTTP signature scheme. Additional headers may be included in the signature. + +# The '(request-target)' header is a calculated field that includes the HTTP verb, +# the URL path and the URL query. +HEADER_REQUEST_TARGET = '(request-target)' +# The time when the HTTP signature was generated. +HEADER_CREATED = '(created)' +# The time when the HTTP signature expires. The API server should reject HTTP requests +# that have expired. +HEADER_EXPIRES = '(expires)' +# The 'Host' header. +HEADER_HOST = 'Host' +# The 'Date' header. +HEADER_DATE = 'Date' +# When the 'Digest' header is included in the HTTP signature, the client automatically +# computes the digest of the HTTP request body, per RFC 3230. +HEADER_DIGEST = 'Digest' +# The 'Authorization' header is automatically generated by the client. It includes +# the list of signed headers and a base64-encoded signature. +HEADER_AUTHORIZATION = 'Authorization' + +# The constants below define the cryptographic schemes for the HTTP signature scheme. +SCHEME_HS2019 = 'hs2019' +SCHEME_RSA_SHA256 = 'rsa-sha256' +SCHEME_RSA_SHA512 = 'rsa-sha512' + +# The constants below define the signature algorithms that can be used for the HTTP +# signature scheme. +ALGORITHM_RSASSA_PSS = 'RSASSA-PSS' +ALGORITHM_RSASSA_PKCS1v15 = 'RSASSA-PKCS1-v1_5' + +ALGORITHM_ECDSA_MODE_FIPS_186_3 = 'fips-186-3' +ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 = 'deterministic-rfc6979' +ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS = { + ALGORITHM_ECDSA_MODE_FIPS_186_3, + ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 +} + +# The cryptographic hash algorithm for the message signature. +HASH_SHA256 = 'sha256' +HASH_SHA512 = 'sha512' + + +class HttpSigningConfiguration(object): + """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key + which is in possession of the API client. + An 'Authorization' header is calculated by creating a hash of select headers, + and optionally the body of the HTTP request, then signing the hash value using + a private key. The 'Authorization' header is added to outbound HTTP requests. + + :param key_id: A string value specifying the identifier of the cryptographic key, + when signing HTTP requests. + :param signing_scheme: A string value specifying the signature scheme, when + signing HTTP requests. + Supported value are hs2019, rsa-sha256, rsa-sha512. + Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + available for server-side applications that only support the older + HTTP signature algorithms. + :param private_key_path: A string value specifying the path of the file containing + a private key. The private key is used to sign HTTP requests. + :param private_key_passphrase: A string value specifying the passphrase to decrypt + the private key. + :param signed_headers: A list of strings. Each value is the name of a HTTP header + that must be included in the HTTP signature calculation. + The two special signature headers '(request-target)' and '(created)' SHOULD be + included in SignedHeaders. + The '(created)' header expresses when the signature was created. + The '(request-target)' header is a concatenation of the lowercased :method, an + ASCII space, and the :path pseudo-headers. + When signed_headers is not specified, the client defaults to a single value, + '(created)', in the list of HTTP headers. + When SignedHeaders contains the 'Digest' value, the client performs the + following operations: + 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. + 2. Set the 'Digest' header in the request body. + 3. Include the 'Digest' header and value in the HTTP signature. + :param signing_algorithm: A string value specifying the signature algorithm, when + signing HTTP requests. + Supported values are: + 1. For RSA keys: RSASSA-PSS, RSASSA-PKCS1-v1_5. + 2. For ECDSA keys: fips-186-3, deterministic-rfc6979. + If None, the signing algorithm is inferred from the private key. + The default signing algorithm for RSA keys is RSASSA-PSS. + The default signing algorithm for ECDSA keys is fips-186-3. + :param hash_algorithm: The hash algorithm for the signature. Supported values are + sha256 and sha512. + If the signing_scheme is rsa-sha256, the hash algorithm must be set + to None or sha256. + If the signing_scheme is rsa-sha512, the hash algorithm must be set + to None or sha512. + :param signature_max_validity: The signature max validity, expressed as + a datetime.timedelta value. It must be a positive value. + """ + def __init__(self, key_id, signing_scheme, private_key_path, + private_key_passphrase=None, + signed_headers=None, + signing_algorithm=None, + hash_algorithm=None, + signature_max_validity=None): + self.key_id = key_id + if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: + raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) + self.signing_scheme = signing_scheme + if not os.path.exists(private_key_path): + raise Exception("Private key file does not exist") + self.private_key_path = private_key_path + self.private_key_passphrase = private_key_passphrase + self.signing_algorithm = signing_algorithm + self.hash_algorithm = hash_algorithm + if signing_scheme == SCHEME_RSA_SHA256: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm != HASH_SHA256: + raise Exception("Hash algorithm must be sha256 when security scheme is %s" % + SCHEME_RSA_SHA256) + elif signing_scheme == SCHEME_RSA_SHA512: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA512 + elif self.hash_algorithm != HASH_SHA512: + raise Exception("Hash algorithm must be sha512 when security scheme is %s" % + SCHEME_RSA_SHA512) + elif signing_scheme == SCHEME_HS2019: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm not in {HASH_SHA256, HASH_SHA512}: + raise Exception("Invalid hash algorithm") + if signature_max_validity is not None and signature_max_validity.total_seconds() < 0: + raise Exception("The signature max validity must be a positive value") + self.signature_max_validity = signature_max_validity + # If the user has not provided any signed_headers, the default must be set to '(created)', + # as specified in the 'HTTP signature' standard. + if signed_headers is None or len(signed_headers) == 0: + signed_headers = [HEADER_CREATED] + if self.signature_max_validity is None and HEADER_EXPIRES in signed_headers: + raise Exception( + "Signature max validity must be set when " + "'(expires)' signature parameter is specified") + if len(signed_headers) != len(set(signed_headers)): + raise Exception("Cannot have duplicates in the signed_headers parameter") + if HEADER_AUTHORIZATION in signed_headers: + raise Exception("'Authorization' header cannot be included in signed headers") + self.signed_headers = signed_headers + self.private_key = None + """The private key used to sign HTTP requests. + Initialized when the PEM-encoded private key is loaded from a file. + """ + self.host = None + """The host name, optionally followed by a colon and TCP port number. + """ + self._load_private_key() + + def get_http_signature_headers(self, resource_path, method, headers, body, query_params): + """Create a cryptographic message signature for the HTTP request and add the signed headers. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A dict of HTTP headers that must be added to the outbound HTTP request. + """ + if method is None: + raise Exception("HTTP method must be set") + if resource_path is None: + raise Exception("Resource path must be set") + + signed_headers_list, request_headers_dict = self._get_signed_header_info( + resource_path, method, headers, body, query_params) + + header_items = [ + "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] + string_to_sign = "\n".join(header_items) + + digest, digest_prefix = self._get_message_digest(string_to_sign.encode()) + b64_signed_msg = self._sign_digest(digest) + + request_headers_dict[HEADER_AUTHORIZATION] = self._get_authorization_header( + signed_headers_list, b64_signed_msg) + + return request_headers_dict + + def get_public_key(self): + """Returns the public key object associated with the private key. + """ + pubkey = None + if isinstance(self.private_key, RSA.RsaKey): + pubkey = self.private_key.publickey() + elif isinstance(self.private_key, ECC.EccKey): + pubkey = self.private_key.public_key() + return pubkey + + def _load_private_key(self): + """Load the private key used to sign HTTP requests. + The private key is used to sign HTTP requests as defined in + https://datatracker.ietf.org/doc/draft-cavage-http-signatures/. + """ + if self.private_key is not None: + return + with open(self.private_key_path, 'r') as f: + pem_data = f.read() + # Verify PEM Pre-Encapsulation Boundary + r = re.compile(r"\s*-----BEGIN (.*)-----\s+") + m = r.match(pem_data) + if not m: + raise ValueError("Not a valid PEM pre boundary") + pem_header = m.group(1) + if pem_header == 'RSA PRIVATE KEY': + self.private_key = RSA.importKey(pem_data, self.private_key_passphrase) + elif pem_header == 'EC PRIVATE KEY': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: + # Key is in PKCS8 format, which is capable of holding many different + # types of private keys, not just EC keys. + (key_binary, pem_header, is_encrypted) = \ + PEM.decode(pem_data, self.private_key_passphrase) + (oid, privkey, params) = \ + PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) + if oid == '1.2.840.10045.2.1': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + else: + raise Exception("Unsupported key: {0}. OID: {1}".format(pem_header, oid)) + else: + raise Exception("Unsupported key: {0}".format(pem_header)) + # Validate the specified signature algorithm is compatible with the private key. + if self.signing_algorithm is not None: + supported_algs = None + if isinstance(self.private_key, RSA.RsaKey): + supported_algs = {ALGORITHM_RSASSA_PSS, ALGORITHM_RSASSA_PKCS1v15} + elif isinstance(self.private_key, ECC.EccKey): + supported_algs = ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS + if supported_algs is not None and self.signing_algorithm not in supported_algs: + raise Exception( + "Signing algorithm {0} is not compatible with private key".format( + self.signing_algorithm)) + + def _get_signed_header_info(self, resource_path, method, headers, body, query_params): + """Build the HTTP headers (name, value) that need to be included in + the HTTP signature scheme. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object (e.g. a dict) representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A tuple containing two dict objects: + The first dict contains the HTTP headers that are used to calculate + the HTTP signature. + The second dict contains the HTTP headers that must be added to + the outbound HTTP request. + """ + + if body is None: + body = '' + else: + body = body.to_json() + + # Build the '(request-target)' HTTP signature parameter. + target_host = urlparse(self.host).netloc + target_path = urlparse(self.host).path + request_target = method.lower() + " " + target_path + resource_path + if query_params: + request_target += "?" + urlencode(query_params) + + # Get UNIX time, e.g. seconds since epoch, not including leap seconds. + now = time() + # Format date per RFC 7231 section-7.1.1.2. An example is: + # Date: Wed, 21 Oct 2015 07:28:00 GMT + cdate = formatdate(timeval=now, localtime=False, usegmt=True) + # The '(created)' value MUST be a Unix timestamp integer value. + # Subsecond precision is not supported. + created = int(now) + if self.signature_max_validity is not None: + expires = now + self.signature_max_validity.total_seconds() + + signed_headers_list = [] + request_headers_dict = {} + for hdr_key in self.signed_headers: + hdr_key = hdr_key.lower() + if hdr_key == HEADER_REQUEST_TARGET: + value = request_target + elif hdr_key == HEADER_CREATED: + value = '{0}'.format(created) + elif hdr_key == HEADER_EXPIRES: + value = '{0}'.format(expires) + elif hdr_key == HEADER_DATE.lower(): + value = cdate + request_headers_dict[HEADER_DATE] = '{0}'.format(cdate) + elif hdr_key == HEADER_DIGEST.lower(): + request_body = body.encode() + body_digest, digest_prefix = self._get_message_digest(request_body) + b64_body_digest = b64encode(body_digest.digest()) + value = digest_prefix + b64_body_digest.decode('ascii') + request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( + digest_prefix, b64_body_digest.decode('ascii')) + elif hdr_key == HEADER_HOST.lower(): + value = target_host + request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + else: + value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) + if value is None: + raise Exception( + "Cannot sign HTTP request. " + "Request does not contain the '{0}' header".format(hdr_key)) + signed_headers_list.append((hdr_key, value)) + + return signed_headers_list, request_headers_dict + + def _get_message_digest(self, data): + """Calculates and returns a cryptographic digest of a specified HTTP request. + + :param data: The string representation of the date to be hashed with a cryptographic hash. + :return: A tuple of (digest, prefix). + The digest is a hashing object that contains the cryptographic digest of + the HTTP request. + The prefix is a string that identifies the cryptographic hash. It is used + to generate the 'Digest' header as specified in RFC 3230. + """ + if self.hash_algorithm == HASH_SHA512: + digest = SHA512.new() + prefix = 'SHA-512=' + elif self.hash_algorithm == HASH_SHA256: + digest = SHA256.new() + prefix = 'SHA-256=' + else: + raise Exception("Unsupported hash algorithm: {0}".format(self.hash_algorithm)) + digest.update(data) + return digest, prefix + + def _sign_digest(self, digest): + """Signs a message digest with a private key specified in the signing_info. + + :param digest: A hashing object that contains the cryptographic digest of the HTTP request. + :return: A base-64 string representing the cryptographic signature of the input digest. + """ + sig_alg = self.signing_algorithm + if isinstance(self.private_key, RSA.RsaKey): + if sig_alg is None or sig_alg == ALGORITHM_RSASSA_PSS: + # RSASSA-PSS in Section 8.1 of RFC8017. + signature = pss.new(self.private_key).sign(digest) + elif sig_alg == ALGORITHM_RSASSA_PKCS1v15: + # RSASSA-PKCS1-v1_5 in Section 8.2 of RFC8017. + signature = PKCS1_v1_5.new(self.private_key).sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + elif isinstance(self.private_key, ECC.EccKey): + if sig_alg is None: + sig_alg = ALGORITHM_ECDSA_MODE_FIPS_186_3 + if sig_alg in ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS: + # draft-ietf-httpbis-message-signatures-00 does not specify the ECDSA encoding. + # Issue: https://github.com/w3c-ccg/http-signatures/issues/107 + signature = DSS.new(key=self.private_key, mode=sig_alg, + encoding='der').sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + else: + raise Exception("Unsupported private key: {0}".format(type(self.private_key))) + return b64encode(signature) + + def _get_authorization_header(self, signed_headers, signed_msg): + """Calculates and returns the value of the 'Authorization' header when signing HTTP requests. + + :param signed_headers : A list of tuples. Each value is the name of a HTTP header that + must be included in the HTTP signature calculation. + :param signed_msg: A base-64 encoded string representation of the signature. + :return: The string value of the 'Authorization' header, representing the signature + of the HTTP request. + """ + created_ts = None + expires_ts = None + for k, v in signed_headers: + if k == HEADER_CREATED: + created_ts = v + elif k == HEADER_EXPIRES: + expires_ts = v + lower_keys = [k.lower() for k, v in signed_headers] + headers_value = " ".join(lower_keys) + + auth_str = "Signature keyId=\"{0}\",algorithm=\"{1}\",".format( + self.key_id, self.signing_scheme) + if created_ts is not None: + auth_str = auth_str + "created={0},".format(created_ts) + if expires_ts is not None: + auth_str = auth_str + "expires={0},".format(expires_ts) + auth_str = auth_str + "headers=\"{0}\",signature=\"{1}\"".format( + headers_value, signed_msg.decode('ascii')) + + return auth_str diff --git a/templates/test-requirements.mustache b/templates/test-requirements.mustache new file mode 100644 index 0000000..ca8eb27 --- /dev/null +++ b/templates/test-requirements.mustache @@ -0,0 +1,6 @@ +pytest~=7.1.3 +pytest-cov>=2.8.1 +pytest-randomly>=3.12.0 +{{#hasHttpSignatureMethods}} +pycryptodome>=3.9.0 +{{/hasHttpSignatureMethods}} \ No newline at end of file diff --git a/templates/tornado/rest.mustache b/templates/tornado/rest.mustache new file mode 100644 index 0000000..59f14ff --- /dev/null +++ b/templates/tornado/rest.mustache @@ -0,0 +1,223 @@ +# coding: utf-8 + +{{>partial_header}} + +import io +import json +import logging +import re + +from urllib.parse import urlencode, quote_plus +import tornado +import tornado.gen +from tornado import httpclient +from urllib3.filepost import encode_multipart_formdata + +from {{packageName}}.exceptions import ApiException, ApiValueError + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.tornado_response = resp + self.status = resp.code + self.reason = resp.reason + + if resp.body: + self.data = resp.body + else: + self.data = None + + def getheaders(self): + """Returns a CIMultiDictProxy of the response headers.""" + return self.tornado_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.tornado_response.headers.get(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=4): + # maxsize is number of requests to host that are allowed in parallel + + self.ca_certs = configuration.ssl_ca_cert + self.client_key = configuration.key_file + self.client_cert = configuration.cert_file + + self.proxy_port = self.proxy_host = None + + # https pool manager + if configuration.proxy: + self.proxy_port = 80 + self.proxy_host = configuration.proxy + + self.pool_manager = httpclient.AsyncHTTPClient() + + @tornado.gen.coroutine + def request(self, method, url, query_params=None, headers=None, body=None, + post_params=None, _preload_content=True, + _request_timeout=None): + """Execute Request + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + request = httpclient.HTTPRequest(url) + request.allow_nonstandard_methods = True + request.ca_certs = self.ca_certs + request.client_key = self.client_key + request.client_cert = self.client_cert + request.proxy_host = self.proxy_host + request.proxy_port = self.proxy_port + request.method = method + if headers: + request.headers = headers + if 'Content-Type' not in headers: + request.headers['Content-Type'] = 'application/json' + request.request_timeout = _request_timeout or 5 * 60 + + post_params = post_params or {} + + if query_params: + request.url += '?' + urlencode(query_params) + + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if re.search('json', headers['Content-Type'], re.IGNORECASE): + if body: + body = json.dumps(body) + request.body = body + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + request.body = urlencode(post_params) + elif headers['Content-Type'] == 'multipart/form-data': + multipart = encode_multipart_formdata(post_params) + request.body, headers['Content-Type'] = multipart + # Pass a `bytes` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, bytes): + request.body = body + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + r = yield self.pool_manager.fetch(request, raise_error=False) + + if _preload_content: + + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + raise tornado.gen.Return(r) + + @tornado.gen.coroutine + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + result = yield self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + result = yield self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + result = yield self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) diff --git a/templates/tox.mustache b/templates/tox.mustache new file mode 100644 index 0000000..9d717c3 --- /dev/null +++ b/templates/tox.mustache @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov={{{packageName}}} diff --git a/templates/travis.mustache b/templates/travis.mustache new file mode 100644 index 0000000..53cb57e --- /dev/null +++ b/templates/travis.mustache @@ -0,0 +1,17 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + - "3.11" + # uncomment the following if needed + #- "3.11-dev" # 3.11 development branch + #- "nightly" # nightly build +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov={{{packageName}}} From 9619b1e81fd1b0075b41d2d0b6c0e610bb95ad57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Mon, 4 Sep 2023 09:44:55 +0200 Subject: [PATCH 03/20] Templates return tuple --- templates/api.mustache | 11 +++++++++-- templates/model_generic.mustache | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/templates/api.mustache b/templates/api.mustache index 913e0db..8ee0bc2 100644 --- a/templates/api.mustache +++ b/templates/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): {{/asyncio}} @validate_arguments - def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{{returnType}}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 + def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{#returnType}}tuple{{/returnType}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 {{#notes}} @@ -81,7 +81,14 @@ class {{classname}}(object): if async_req is not None: kwargs['async_req'] = async_req {{/asyncio}} - return self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 + api_response = self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 + +{{#returnType}} + return api_response.data +{{/returnType}} +{{^returnType}} + return api_response +{{/returnType}} @validate_arguments def {{operationId}}_with_http_info(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> ApiResponse: # noqa: E501 diff --git a/templates/model_generic.mustache b/templates/model_generic.mustache index 1355ddb..c0433e8 100644 --- a/templates/model_generic.mustache +++ b/templates/model_generic.mustache @@ -353,6 +353,14 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} return _obj {{/hasChildren}} + def to_tuple(self): + """Returns the tuple representation of the model using alias""" + _tuple = tuple(self) + + _keys, values = zip(*_tuple) + + return values + {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} {{{.}}} From 5bd9024d6e616fa9298e5e07f8ad3732c4b541ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Mon, 4 Sep 2023 15:40:19 +0200 Subject: [PATCH 04/20] Revert to default templates, wip test and api. --- generate_client.sh | 7 + jellyfish/README.md | 0 jellyfish/__init__.py | 10 +- jellyfish/pyproject.toml | 26 ++ jellyfish/room_api.py | 45 +++ jellyfish/room_client.py | 6 - jellyfish/setup.py | 50 +++ openapi.yaml | 668 ------------------------------- templates/api.mustache | 11 +- templates/model_generic.mustache | 8 - tests/test_room_api.py | 126 ++++++ tests/test_room_client.py | 61 --- 12 files changed, 265 insertions(+), 753 deletions(-) create mode 100755 generate_client.sh create mode 100644 jellyfish/README.md create mode 100644 jellyfish/pyproject.toml create mode 100644 jellyfish/room_api.py delete mode 100644 jellyfish/room_client.py create mode 100644 jellyfish/setup.py delete mode 100644 openapi.yaml create mode 100644 tests/test_room_api.py delete mode 100644 tests/test_room_client.py diff --git a/generate_client.sh b/generate_client.sh new file mode 100755 index 0000000..8321793 --- /dev/null +++ b/generate_client.sh @@ -0,0 +1,7 @@ +rm -rf jellyfish/openapi_client +openapi-generator-cli generate \ + -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/openapi-generator-compatibility/openapi.yaml \ + -g python \ + -t templates \ + --package-name jellyfish_openapi_client \ + -o jellyfish/openapi_client \ No newline at end of file diff --git a/jellyfish/README.md b/jellyfish/README.md new file mode 100644 index 0000000..e69de29 diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py index 25013b0..cbacc35 100644 --- a/jellyfish/__init__.py +++ b/jellyfish/__init__.py @@ -1 +1,9 @@ -from .room_client import RoomClient +""" + Python server SDK for [Jellyfish](https://github.com/jellyfish-dev/jellyfish) media server. +""" + +__version__ = "0.1.0" + +from import Room, RoomConfig, Peer, Component + +from jellyfish.room_api import RoomApi diff --git a/jellyfish/pyproject.toml b/jellyfish/pyproject.toml new file mode 100644 index 0000000..1891fd8 --- /dev/null +++ b/jellyfish/pyproject.toml @@ -0,0 +1,26 @@ +[tool.poetry] +name = "jellyfish-server-sdk" +version = "0.1.0" +description = "Python server SDK for Jellyfish Media Server" +authors = ["Membrane Team https://github.com/membraneframework"] +license = "Apache 2.0" +readme = "README.md" +repository = "https://github.com/jellyfish-dev/python-server-sdk" + + +[tool.poetry.dependencies] +python = "^3.7" + +urllib3 = ">= 1.25.3" +python-dateutil = ">=2.8.2" +pydantic = "^1.10.5, <2" +aenum = ">=3.1.11" + +[tool.poetry.dev-dependencies] +pytest = ">=7.2.1" +tox = ">=3.9.0" +flake8 = ">=4.0.0" + +[build-system] +requires = ["setuptools ~= 68.1"] +build-backend = "setuptools.build_meta" diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py new file mode 100644 index 0000000..e4633ec --- /dev/null +++ b/jellyfish/room_api.py @@ -0,0 +1,45 @@ +import time +import jellyfish_openapi_client as jellyfish_api +from jellyfish_api.rest import ApiException + +from jellyfish_openapi_client import Room, RoomConfig + + +class RoomApi: + def __init__(self, server_address, server_api_token): + self._configuration = jellyfish_api.Configuration( + host=server_address, + access_token=server_api_token + ) + + self._api_client = jellyfish_api.ApiClient(self._configuration) + self._room_api = jellyfish_api.RoomApi(self._api_client) + + def create_room(self, max_peers: int = None, video_codec: str = None) -> Room: + """Creates a room""" + + room_config = RoomConfig(maxPeers=max_peers, videoCodec=video_codec) + room = self._room_api.create(room_config) + + return (room.data.jellyfish_address, room.data.room) + + def delete_room(self): + pass + + def get_all_rooms(self): + pass + + def get_room(self): + pass + + def add_peer(): + pass + + def delete_peer(): + pass + + def add_component(): + pass + + def delete_component(): + pass diff --git a/jellyfish/room_client.py b/jellyfish/room_client.py deleted file mode 100644 index fc6a9f4..0000000 --- a/jellyfish/room_client.py +++ /dev/null @@ -1,6 +0,0 @@ - - -class RoomClient: - def __init__(self, server_address, server_api_token): - self.server_address = server_address - self.server_api_token = server_api_token diff --git a/jellyfish/setup.py b/jellyfish/setup.py new file mode 100644 index 0000000..23917d0 --- /dev/null +++ b/jellyfish/setup.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "jellyfish-server-sdk" +VERSION = "0.1.0" +PYTHON_REQUIRES = ">=3.7" +REQUIRES = [ + "urllib3 >= 1.25.3, < 2.1.0", + "python-dateutil", + "pydantic >= 1.10.5, < 2", + "aenum" +] + +setup( + name=NAME, + version=VERSION, + description="Jellyfish Media Server", + author="Jellyfish team", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "Jellyfish Media Server"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache 2.0", + long_description_content_type='text/markdown', + long_description="""\ + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + """, # noqa: E501 + package_data={"jellyfish_openapi_client": ["py.typed"]}, +) diff --git a/openapi.yaml b/openapi.yaml deleted file mode 100644 index 89eeecb..0000000 --- a/openapi.yaml +++ /dev/null @@ -1,668 +0,0 @@ -# This file has been generated using OpenApiSpex. Do not edit manually! -# Run `mix api.spec` to regenerate - ---- -components: - responses: {} - schemas: - AuthToken: - description: Token for authorizing websocket connection - example: 5cdac726-57a3-4ecb-b1d5-72a3d62ec242 - title: AuthToken - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Token - Component: - description: Describes component - properties: - id: - description: Assigned component id - example: component-1 - type: string - metadata: - $ref: '#/components/schemas/ComponentMetadata' - type: - $ref: '#/components/schemas/ComponentType' - required: - - id - - type - - metadata - title: Component - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Component - ComponentDetailsResponse: - description: Response containing component details - properties: - data: - $ref: '#/components/schemas/Component' - required: - - data - title: ComponentDetailsResponse - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.ComponentDetailsResponse - ComponentMetadata: - description: Component-specific metadata - properties: - playable: - type: boolean - title: ComponentMetadata - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Metadata - ComponentOptions: - description: Component-specific options - oneOf: - - $ref: '#/components/schemas/ComponentOptionsHLS' - - $ref: '#/components/schemas/ComponentOptionsRTSP' - title: ComponentOptions - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Options - ComponentOptionsHLS: - description: Options specific to the HLS component - properties: {} - title: ComponentOptionsHLS - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Component.HLS - ComponentOptionsRTSP: - description: Options specific to the RTSP component - properties: - keepAliveInterval: - default: 15000 - description: Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source - minimum: 0 - type: integer - pierceNat: - default: true - description: Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup - type: boolean - reconnectDelay: - default: 15000 - description: Delay (in ms) between successive reconnect attempts - minimum: 0 - type: integer - rtpPort: - default: 20000 - description: Local port RTP stream will be received at - maximum: 65535 - minimum: 1 - type: integer - sourceUri: - description: URI of RTSP source stream - example: rtsp://localhost:554/stream - type: string - required: - - sourceUri - title: ComponentOptionsRTSP - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Component.RTSP - ComponentType: - description: Component type - example: hls - title: ComponentType - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.Component.Type - Error: - description: Error message - properties: - errors: - description: Error details - example: Token has expired - type: string - required: - - errors - title: Error - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Error - HlsMsn: - description: Segment sequence number - example: 10 - minimum: 0 - nullable: true - title: HlsMsn - type: integer - x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsMsn - HlsPart: - description: Partial segment sequence number - example: 10 - minimum: 0 - nullable: true - title: HlsPart - type: integer - x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsPart - HlsResponse: - description: Requested file - title: HlsResponse - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Response - HlsSkip: - description: Is delta manifest requested - enum: - - YES - example: YES - nullable: true - title: HlsSkip - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.HLS.Params.HlsSkip - Peer: - description: Describes peer status - properties: - id: - description: Assigned peer id - example: peer-1 - type: string - status: - $ref: '#/components/schemas/PeerStatus' - type: - $ref: '#/components/schemas/PeerType' - required: - - id - - type - - status - title: Peer - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer - PeerDetailsResponse: - description: Response containing peer details and their token - properties: - data: - properties: - peer: - $ref: '#/components/schemas/Peer' - token: - $ref: '#/components/schemas/AuthToken' - required: - - peer - - token - type: object - required: - - data - title: PeerDetailsResponse - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.PeerDetailsResponse - PeerOptions: - description: Peer-specific options - oneOf: - - $ref: '#/components/schemas/PeerOptionsWebRTC' - title: PeerOptions - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Options - PeerOptionsWebRTC: - description: Options specific to the WebRTC peer - properties: - enableSimulcast: - default: true - description: Enables the peer to use simulcast - type: boolean - title: PeerOptionsWebRTC - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.WebRTC - PeerStatus: - description: Informs about the peer status - enum: - - connected - - disconnected - example: disconnected - title: PeerStatus - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Status - PeerType: - description: Peer type - example: webrtc - title: PeerType - type: string - x-struct: Elixir.JellyfishWeb.ApiSpec.Peer.Type - Room: - description: Description of the room state - properties: - components: - items: - $ref: '#/components/schemas/Component' - type: array - config: - $ref: '#/components/schemas/RoomConfig' - id: - description: Room ID - example: room-1 - type: string - peers: - items: - $ref: '#/components/schemas/Peer' - type: array - required: - - id - - config - - components - - peers - title: Room - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Room - RoomConfig: - description: Room configuration - properties: - maxPeers: - description: Maximum amount of peers allowed into the room - example: 10 - minimum: 1 - nullable: true - type: integer - videoCodec: - description: Enforces video codec for each peer in the room - enum: - - h264 - - vp8 - nullable: true - type: string - title: RoomConfig - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.Room.Config - RoomCreateDetailsResponse: - description: Response containing room details - properties: - data: - properties: - jellyfish_address: - description: Jellyfish instance address where the room was created. This might be different than the address of Jellyfish where the request was sent only when running a cluster of Jellyfishes. - example: jellyfish1:5003 - type: string - room: - $ref: '#/components/schemas/Room' - required: - - room - - jellyfish_address - type: object - required: - - data - title: RoomCreateDetailsResponse - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.RoomCreateDetailsResponse - RoomDetailsResponse: - description: Response containing room details - properties: - data: - $ref: '#/components/schemas/Room' - required: - - data - title: RoomDetailsResponse - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.RoomDetailsResponse - RoomsListingResponse: - description: Response containing list of all rooms - properties: - data: - items: - $ref: '#/components/schemas/Room' - type: array - required: - - data - title: RoomsListingResponse - type: object - x-struct: Elixir.JellyfishWeb.ApiSpec.RoomsListingResponse - securitySchemes: - authorization: - scheme: bearer - type: http -info: - license: - name: Apache 2.0 - url: https://www.apache.org/licenses/LICENSE-2.0 - title: Jellyfish Media Server - version: 0.2.0 -openapi: 3.0.0 -paths: - /hls/{room_id}/{filename}: - get: - callbacks: {} - operationId: JellyfishWeb.HLSController.index - parameters: - - description: Room id - in: path - name: room_id - required: true - schema: - type: string - - description: Name of the file - in: path - name: filename - required: true - schema: - type: string - - description: Byte range of partial segment - in: header - name: range - required: false - schema: - type: string - - description: Segment sequence number - in: query - name: _HLS_msn - required: false - schema: - $ref: '#/components/schemas/HlsMsn' - - description: Partial segment sequence number - in: query - name: _HLS_part - required: false - schema: - $ref: '#/components/schemas/HlsPart' - - description: Is delta manifest requested - in: query - name: _HLS_skip - required: false - schema: - $ref: '#/components/schemas/HlsSkip' - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/HlsResponse' - description: File was found - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: File not found - summary: Send file - tags: [] - /room: - get: - callbacks: {} - operationId: JellyfishWeb.RoomController.index - parameters: [] - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/RoomsListingResponse' - description: Success - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - summary: Show information about all rooms - tags: - - room - post: - callbacks: {} - operationId: JellyfishWeb.RoomController.create - parameters: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/RoomConfig' - description: Room configuration - required: false - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/RoomCreateDetailsResponse' - description: Room successfully created - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Invalid request structure - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - summary: Creates a room - tags: - - room - /room/{room_id}: - delete: - callbacks: {} - operationId: JellyfishWeb.RoomController.delete - parameters: - - description: Room id - in: path - name: room_id - required: true - schema: - type: string - responses: - '204': - description: Successfully deleted room - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Room doesn't exist - summary: Delete the room - tags: - - room - get: - callbacks: {} - operationId: JellyfishWeb.RoomController.show - parameters: - - description: Room ID - in: path - name: room_id - required: true - schema: - type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/RoomDetailsResponse' - description: Success - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Room doesn't exist - summary: Shows information about the room - tags: - - room - /room/{room_id}/component: - post: - callbacks: {} - operationId: JellyfishWeb.ComponentController.create - parameters: - - description: Room ID - in: path - name: room_id - required: true - schema: - type: string - requestBody: - content: - application/json: - schema: - properties: - options: - $ref: '#/components/schemas/ComponentOptions' - type: - $ref: '#/components/schemas/ComponentType' - required: - - type - - options - type: object - description: Component config - required: false - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/ComponentDetailsResponse' - description: Successfully added component - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Invalid request - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Room doesn't exist - summary: Creates the component and adds it to the room - tags: - - component - /room/{room_id}/component/{id}: - delete: - callbacks: {} - operationId: JellyfishWeb.ComponentController.delete - parameters: - - description: Room ID - in: path - name: room_id - required: true - schema: - type: string - - description: Component ID - in: path - name: id - required: true - schema: - type: string - responses: - '204': - description: Successfully deleted - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Either component or the room doesn't exist - summary: Delete the component from the room - tags: - - component - /room/{room_id}/peer: - post: - callbacks: {} - operationId: JellyfishWeb.PeerController.create - parameters: - - description: Room id - in: path - name: room_id - required: true - schema: - type: string - requestBody: - content: - application/json: - schema: - properties: - options: - $ref: '#/components/schemas/PeerOptions' - type: - $ref: '#/components/schemas/PeerType' - required: - - type - - options - type: object - description: Peer specification - required: false - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/PeerDetailsResponse' - description: Peer successfully created - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Invalid request body structure - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Room doesn't exist - '503': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Peer limit has been reached - summary: Create peer - tags: - - peer - /room/{room_id}/peer/{id}: - delete: - callbacks: {} - operationId: JellyfishWeb.PeerController.delete - parameters: - - description: Room ID - in: path - name: room_id - required: true - schema: - type: string - - description: Peer id - in: path - name: id - required: true - schema: - type: string - responses: - '204': - description: Peer successfully deleted - '401': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Unauthorized - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - description: Room ID or Peer ID references a resource that doesn't exist - summary: Delete peer - tags: - - peer -security: - - authorization: [] -servers: [] -tags: [] diff --git a/templates/api.mustache b/templates/api.mustache index 8ee0bc2..913e0db 100644 --- a/templates/api.mustache +++ b/templates/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): {{/asyncio}} @validate_arguments - def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{#returnType}}tuple{{/returnType}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 + def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{{returnType}}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 {{#notes}} @@ -81,14 +81,7 @@ class {{classname}}(object): if async_req is not None: kwargs['async_req'] = async_req {{/asyncio}} - api_response = self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 - -{{#returnType}} - return api_response.data -{{/returnType}} -{{^returnType}} - return api_response -{{/returnType}} + return self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 @validate_arguments def {{operationId}}_with_http_info(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> ApiResponse: # noqa: E501 diff --git a/templates/model_generic.mustache b/templates/model_generic.mustache index c0433e8..1355ddb 100644 --- a/templates/model_generic.mustache +++ b/templates/model_generic.mustache @@ -353,14 +353,6 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} return _obj {{/hasChildren}} - def to_tuple(self): - """Returns the tuple representation of the model using alias""" - _tuple = tuple(self) - - _keys, values = zip(*_tuple) - - return values - {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} {{{.}}} diff --git a/tests/test_room_api.py b/tests/test_room_api.py new file mode 100644 index 0000000..9d978ef --- /dev/null +++ b/tests/test_room_api.py @@ -0,0 +1,126 @@ +# pylint: disable=locally-disabled, missing-class-docstring, missing-function-docstring + +import pytest + +import jellyfish + +from jellyfish import RoomApi, RoomConfig +from jellyfish import Room, Peer, Component + + +SERVER_ADDRESS = "http://localhost:5002" +SERVER_API_TOKEN = "development" + +MAX_PEERS = 10 +VIDEO_CODEC = "h264" + + +def test_create_room_client(): + with pytest.raises(TypeError): + RoomApi() + + with pytest.raises(TypeError): + RoomApi(server_address="address") + + with pytest.raises(TypeError): + RoomApi(server_api_token="api_token") + + RoomApi(server_address="address", server_api_token="api_token") + + +class Authentication: + def test_invalid_token(): + room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token="invalid") + + with pytest.raises(TypeError): + room_api.create_room() + + def test_valid_token(): + room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) + + room = room_api.create_room() + + all_rooms = room_api.get_all_rooms() + + assert room in all_rooms + + +@pytest.fixture +def room_api(): + return jellyfish.RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) + + +class CreateRoom: + def __init__(self) -> None: + self.room_api = room_api() + + def test_no_params(self): + _, room = self.room_api.create_room() + + assert room == Room(components=[], config=RoomConfig(max_peers=None, video_codec=None), + id=room.id, peers=[]) + + assert room in self.room_api.get_all_rooms() + + def test_valid_params(self): + _, room = self.room_api.create_room(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC) + + assert room == Room(components=[], config=RoomConfig(max_peers=None, video_codec=None), + id=room.id, peers=[]) + assert room in self.room_api.get_all_rooms() + + def test_invalid_max_peers(self): + with pytest.raises(TypeError): + self.room_api.create_room(max_peers="10", video_codec=VIDEO_CODEC) + + def test_invalid_video_codec(self): + with pytest.raises(TypeError): + self.room_api.create_room(max_peers=MAX_PEERS, video_codec="h420") + + +class DeleteRoom: + def __init__(self) -> None: + self.room_api = room_api() + + def test_valid(self): + _, room = self.room_api.create_room() + + room_api.delete(room.id) + assert room not in self.room_api.get_all_rooms() + + def test_invalid(self): + with pytest.raises(TypeError): + self.room_api.delete_room("invalid_id") + + +class GetAllRooms: + # def __init__(self) -> None: + # self.room_api = room_api() + + def test_valid(self, room_api): + assert room_api.get_all_rooms() is list + + +def test_get_all_rooms(room_api): + pass + + +def test_get_room(room_api): + pass + + +def test_add_component(room_api): + pass + + +def test_delete_component(room_api): + pass + + +def test_add_peer(room_api): + # room = room_client.create_room() + pass + + +def test_remove_peer(room_api): + pass diff --git a/tests/test_room_client.py b/tests/test_room_client.py deleted file mode 100644 index 7749f37..0000000 --- a/tests/test_room_client.py +++ /dev/null @@ -1,61 +0,0 @@ -import pytest - -from jellyfish import RoomClient - -server_address = "localhost:5002" -server_api_token = "development" - - -def test_create_room_client(): - with pytest.raises(TypeError): - RoomClient() - - with pytest.raises(TypeError): - RoomClient(server_address="address") - - with pytest.raises(TypeError): - RoomClient(server_api_token="api_token") - - room_client = RoomClient(server_address="address", server_api_token="api_token") - - -def test_authorization(): - pass - - -@pytest.fixture -def room_client(): - return RoomClient(server_address=server_address, server_api_token=server_api_token) - - -def test_create_room(room_client): - - room = room_client.create_room(max_peers=10) - - -def test_delete_room(room_client): - pass - - -def test_get_all_rooms(room_client): - pass - - -def test_get_room(room_client): - pass - - -def test_add_component(room_client): - pass - - -def test_delete_component(room_client): - pass - - -def test_add_peer(room_client): - room = room_client.create_room() - - -def test_remove_peer(room_client): - pass From 8ddcc783b3d362351a7ac32b5545f1e7918f98bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 11:11:18 +0200 Subject: [PATCH 05/20] Create tests --- tests/test_room_api.py | 167 +++++++++++++++++++++++++++++------------ 1 file changed, 118 insertions(+), 49 deletions(-) diff --git a/tests/test_room_api.py b/tests/test_room_api.py index 9d978ef..665722c 100644 --- a/tests/test_room_api.py +++ b/tests/test_room_api.py @@ -1,12 +1,16 @@ # pylint: disable=locally-disabled, missing-class-docstring, missing-function-docstring +import random import pytest import jellyfish +import pydantic from jellyfish import RoomApi, RoomConfig from jellyfish import Room, Peer, Component +from jellyfish import ComponentOptionsRTSP, PeerOptionsWebRTC +from jellyfish import ValidationError SERVER_ADDRESS = "http://localhost:5002" SERVER_API_TOKEN = "development" @@ -15,6 +19,13 @@ VIDEO_CODEC = "h264" +COMPONENT_HLS = "hls" +COMPONENT_RTSP = "rtsp" + +HLS_OPTIONS = None +RTSP_OPTIONS = ComponentOptionsRTSP(sourceUri="rtsp://ef36c6dff23ecc5bbe311cc880d95dc8.se:2137/does/not/matter") + + def test_create_room_client(): with pytest.raises(TypeError): RoomApi() @@ -28,14 +39,14 @@ def test_create_room_client(): RoomApi(server_address="address", server_api_token="api_token") -class Authentication: - def test_invalid_token(): +class TestAuthentication: + def test_invalid_token(self, room_api): room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token="invalid") - with pytest.raises(TypeError): + with pytest.raises(NotImplementedError): room_api.create_room() - def test_valid_token(): + def test_valid_token(self, room_api): room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) room = room_api.create_room() @@ -50,77 +61,135 @@ def room_api(): return jellyfish.RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) -class CreateRoom: - def __init__(self) -> None: - self.room_api = room_api() - - def test_no_params(self): - _, room = self.room_api.create_room() +class TestCreateRoom: + def test_no_params(self, room_api): + _, room = room_api.create_room() assert room == Room(components=[], config=RoomConfig(max_peers=None, video_codec=None), id=room.id, peers=[]) - assert room in self.room_api.get_all_rooms() + assert room in room_api.get_all_rooms() - def test_valid_params(self): - _, room = self.room_api.create_room(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC) + def test_valid_params(self, room_api): + _, room = room_api.create_room(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC) - assert room == Room(components=[], config=RoomConfig(max_peers=None, video_codec=None), + assert room == Room(components=[], config=RoomConfig(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC), id=room.id, peers=[]) - assert room in self.room_api.get_all_rooms() + assert room in room_api.get_all_rooms() - def test_invalid_max_peers(self): - with pytest.raises(TypeError): - self.room_api.create_room(max_peers="10", video_codec=VIDEO_CODEC) + def test_invalid_max_peers(self, room_api): + with pytest.raises(ValidationError): + room_api.create_room(max_peers="10", video_codec=VIDEO_CODEC) - def test_invalid_video_codec(self): - with pytest.raises(TypeError): - self.room_api.create_room(max_peers=MAX_PEERS, video_codec="h420") + def test_invalid_video_codec(self, room_api): + with pytest.raises(ValidationError): + room_api.create_room(max_peers=MAX_PEERS, video_codec="h420") -class DeleteRoom: - def __init__(self) -> None: - self.room_api = room_api() - - def test_valid(self): - _, room = self.room_api.create_room() +class TestDeleteRoom: + def test_valid(self, room_api): + _, room = room_api.create_room() room_api.delete(room.id) - assert room not in self.room_api.get_all_rooms() - - def test_invalid(self): - with pytest.raises(TypeError): - self.room_api.delete_room("invalid_id") + assert room not in room_api.get_all_rooms() + def test_invalid(self, room_api): + with pytest.raises(RuntimeError): + room_api.delete_room("invalid_id") -class GetAllRooms: - # def __init__(self) -> None: - # self.room_api = room_api() +class TestGetAllRooms: def test_valid(self, room_api): - assert room_api.get_all_rooms() is list + room = room_api.create_room() + + all_rooms = room_api.get_all_rooms() + assert all_rooms is list + assert room in all_rooms + + +class TestGetRoom: + def test_valid(self, room_api: RoomApi): + room = room_api.create_room() + + assert Room(components=[], peers=[], id=room.id, config=RoomConfig( + maxPeers=None, videoCodec=None)) == room_api.get_room(room.id) + + def test_invalid(self, room_api: RoomApi): + with pytest.raises(NotImplementedError): + room_api.get_room("invalid_id") + + +class TestAddComponent: + def test_with_options(self, room_api: RoomApi): + room_id = room_api.create_room().id + + component = room_api.add_component(room_id, type=COMPONENT_HLS, options=HLS_OPTIONS) + assert component == Component(id=component.id, type=COMPONENT_HLS) + + component = room_api.add_component(room_id, type=COMPONENT_RTSP, options=RTSP_OPTIONS) + assert component == Component(id=component.id, type=COMPONENT_RTSP) + + def test_without_options(self, room_api: RoomApi): + room_id = room_api.create_room().id + + component = room_api.add_component(room_id, type=COMPONENT_HLS) + assert component == Component(id=component.id, type=COMPONENT_HLS) + + with pytest.raises(NotImplementedError): + room_api.add_component(room_id, type=COMPONENT_RTSP) + + def test_invalid_type(self, room_api: RoomApi): + room_id = room_api.create_room().id + + with pytest.raises(NotImplementedError): + room_api.add_component(room_id, type="CsmaCd") + + +class TestDeleteComponent: + def test_valid_component(self, room_api: RoomApi): + room_id = room_api.create_room().id + component = room_api.add_component(room_id, type=COMPONENT_HLS, options=HLS_OPTIONS) + + room_api.delete_component(room_id, component.id) + assert [] == room_api.get_room(room_id).components + + def test_invalid_component(self, room_api: RoomApi): + room_id = room_api.create_room().id + + with pytest.raises(TypeError): + room_api.delete_component(room_id, "invalid_id") + +class TestAddPeer: + def test_valid(self, room_api: RoomApi): + room_id = room_api.create_room().id -def test_get_all_rooms(room_api): - pass + peer = room_api.add_peer(room_id, type="webrtc", options=PeerOptionsWebRTC(enableSimulcast=True)) + assert peer.status == "disconnected" + assert peer.type == "webrtc" -def test_get_room(room_api): - pass + room = room_api.get_room(room_id) + assert peer in room.peers + def test_invalid(self, room_api: RoomApi): + room_id = room_api.create_room().id -def test_add_component(room_api): - pass + with pytest.raises(NotImplementedError): + room_api.add_peer(room_id, type="invalid_type") -def test_delete_component(room_api): - pass +class TestDeletePeer: + def test_valid(self, room_api: RoomApi): + room_id = room_api.create_room().id + peer = room_api.add_peer(room_id, type="webrtc", options=PeerOptionsWebRTC(enableSimulcast=True)) + room_api.delete_peer(peer.id) -def test_add_peer(room_api): - # room = room_client.create_room() - pass + assert [] == room_api.get_room(room_id).peers + def test_invalid(self, room_api: RoomApi): + room_id = room_api.create_room().id -def test_remove_peer(room_api): - pass + with pytest.raises(NotImplementedError): + room_api.delete_peer("invalid_peer_id") From 467e006968208878693a7fd3ab1ef6f0edcbe2b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 11:11:56 +0200 Subject: [PATCH 06/20] Generate openapi client --- jellyfish/__init__.py | 6 +- .../.github/workflows/python.yml | 37 + jellyfish/openapi_client/.gitignore | 66 + jellyfish/openapi_client/.gitlab-ci.yml | 25 + .../openapi_client/.openapi-generator-ignore | 23 + .../openapi_client/.openapi-generator/FILES | 92 ++ .../openapi_client/.openapi-generator/VERSION | 1 + jellyfish/openapi_client/.travis.yml | 17 + jellyfish/openapi_client/README.md | 153 +++ .../docs/AddComponentRequest.md | 29 + .../openapi_client/docs/AddPeerRequest.md | 29 + jellyfish/openapi_client/docs/Component.md | 31 + .../docs/ComponentDetailsResponse.md | 29 + .../openapi_client/docs/ComponentMetadata.md | 29 + .../openapi_client/docs/ComponentOptions.md | 33 + .../docs/ComponentOptionsRTSP.md | 33 + jellyfish/openapi_client/docs/DefaultApi.md | 95 ++ jellyfish/openapi_client/docs/Error.md | 29 + jellyfish/openapi_client/docs/HlsSkip.md | 11 + jellyfish/openapi_client/docs/Peer.md | 31 + .../docs/PeerDetailsResponse.md | 29 + .../docs/PeerDetailsResponseData.md | 29 + jellyfish/openapi_client/docs/PeerOptions.md | 29 + .../openapi_client/docs/PeerOptionsWebRTC.md | 29 + jellyfish/openapi_client/docs/PeerStatus.md | 11 + jellyfish/openapi_client/docs/Room.md | 32 + jellyfish/openapi_client/docs/RoomApi.md | 632 +++++++++ jellyfish/openapi_client/docs/RoomConfig.md | 30 + .../docs/RoomCreateDetailsResponse.md | 29 + .../docs/RoomCreateDetailsResponseData.md | 29 + .../docs/RoomDetailsResponse.md | 29 + .../docs/RoomsListingResponse.md | 29 + jellyfish/openapi_client/git_push.sh | 57 + .../jellyfish_openapi_client/__init__.py | 55 + .../jellyfish_openapi_client/api/__init__.py | 6 + .../api/default_api.py | 224 +++ .../jellyfish_openapi_client/api/room_api.py | 1200 +++++++++++++++++ .../jellyfish_openapi_client/api_client.py | 755 +++++++++++ .../jellyfish_openapi_client/api_response.py | 25 + .../jellyfish_openapi_client/configuration.py | 442 ++++++ .../jellyfish_openapi_client/exceptions.py | 166 +++ .../models/__init__.py | 37 + .../models/add_component_request.py | 77 ++ .../models/add_peer_request.py | 77 ++ .../models/component.py | 79 ++ .../models/component_details_response.py | 75 ++ .../models/component_metadata.py | 71 + .../models/component_options.py | 144 ++ .../models/component_options_rtsp.py | 79 ++ .../jellyfish_openapi_client/models/error.py | 71 + .../models/hls_skip.py | 39 + .../jellyfish_openapi_client/models/peer.py | 76 ++ .../models/peer_details_response.py | 75 ++ .../models/peer_details_response_data.py | 77 ++ .../models/peer_options.py | 127 ++ .../models/peer_options_web_rtc.py | 71 + .../models/peer_status.py | 40 + .../jellyfish_openapi_client/models/room.py | 97 ++ .../models/room_config.py | 93 ++ .../models/room_create_details_response.py | 75 ++ .../room_create_details_response_data.py | 77 ++ .../models/room_details_response.py | 75 ++ .../models/rooms_listing_response.py | 79 ++ .../jellyfish_openapi_client/py.typed | 0 .../jellyfish_openapi_client/rest.py | 303 +++++ jellyfish/openapi_client/pyproject.toml | 30 + jellyfish/openapi_client/requirements.txt | 5 + jellyfish/openapi_client/setup.cfg | 2 + jellyfish/openapi_client/setup.py | 50 + .../openapi_client/test-requirements.txt | 3 + jellyfish/openapi_client/test/__init__.py | 0 .../test/test_add_component_request.py | 57 + .../test/test_add_peer_request.py | 57 + .../openapi_client/test/test_component.py | 61 + .../test/test_component_details_response.py | 63 + .../test/test_component_metadata.py | 54 + .../test/test_component_options.py | 59 + .../test/test_component_options_rtsp.py | 59 + .../openapi_client/test/test_default_api.py | 40 + jellyfish/openapi_client/test/test_error.py | 55 + .../openapi_client/test/test_hls_skip.py | 36 + jellyfish/openapi_client/test/test_peer.py | 59 + .../test/test_peer_details_response.py | 65 + .../test/test_peer_details_response_data.py | 63 + .../openapi_client/test/test_peer_options.py | 54 + .../test/test_peer_options_web_rtc.py | 54 + .../openapi_client/test/test_peer_status.py | 36 + jellyfish/openapi_client/test/test_room.py | 87 ++ .../openapi_client/test/test_room_api.py | 89 ++ .../openapi_client/test/test_room_config.py | 55 + .../test/test_room_create_details_response.py | 93 ++ .../test_room_create_details_response_data.py | 91 ++ .../test/test_room_details_response.py | 89 ++ .../test/test_rooms_listing_response.py | 93 ++ jellyfish/openapi_client/tox.ini | 9 + jellyfish/room_api.py | 4 +- 96 files changed, 8249 insertions(+), 3 deletions(-) create mode 100644 jellyfish/openapi_client/.github/workflows/python.yml create mode 100644 jellyfish/openapi_client/.gitignore create mode 100644 jellyfish/openapi_client/.gitlab-ci.yml create mode 100644 jellyfish/openapi_client/.openapi-generator-ignore create mode 100644 jellyfish/openapi_client/.openapi-generator/FILES create mode 100644 jellyfish/openapi_client/.openapi-generator/VERSION create mode 100644 jellyfish/openapi_client/.travis.yml create mode 100644 jellyfish/openapi_client/README.md create mode 100644 jellyfish/openapi_client/docs/AddComponentRequest.md create mode 100644 jellyfish/openapi_client/docs/AddPeerRequest.md create mode 100644 jellyfish/openapi_client/docs/Component.md create mode 100644 jellyfish/openapi_client/docs/ComponentDetailsResponse.md create mode 100644 jellyfish/openapi_client/docs/ComponentMetadata.md create mode 100644 jellyfish/openapi_client/docs/ComponentOptions.md create mode 100644 jellyfish/openapi_client/docs/ComponentOptionsRTSP.md create mode 100644 jellyfish/openapi_client/docs/DefaultApi.md create mode 100644 jellyfish/openapi_client/docs/Error.md create mode 100644 jellyfish/openapi_client/docs/HlsSkip.md create mode 100644 jellyfish/openapi_client/docs/Peer.md create mode 100644 jellyfish/openapi_client/docs/PeerDetailsResponse.md create mode 100644 jellyfish/openapi_client/docs/PeerDetailsResponseData.md create mode 100644 jellyfish/openapi_client/docs/PeerOptions.md create mode 100644 jellyfish/openapi_client/docs/PeerOptionsWebRTC.md create mode 100644 jellyfish/openapi_client/docs/PeerStatus.md create mode 100644 jellyfish/openapi_client/docs/Room.md create mode 100644 jellyfish/openapi_client/docs/RoomApi.md create mode 100644 jellyfish/openapi_client/docs/RoomConfig.md create mode 100644 jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md create mode 100644 jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md create mode 100644 jellyfish/openapi_client/docs/RoomDetailsResponse.md create mode 100644 jellyfish/openapi_client/docs/RoomsListingResponse.md create mode 100644 jellyfish/openapi_client/git_push.sh create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/__init__.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api_client.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/configuration.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/component.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/error.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/room.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/py.typed create mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/rest.py create mode 100644 jellyfish/openapi_client/pyproject.toml create mode 100644 jellyfish/openapi_client/requirements.txt create mode 100644 jellyfish/openapi_client/setup.cfg create mode 100644 jellyfish/openapi_client/setup.py create mode 100644 jellyfish/openapi_client/test-requirements.txt create mode 100644 jellyfish/openapi_client/test/__init__.py create mode 100644 jellyfish/openapi_client/test/test_add_component_request.py create mode 100644 jellyfish/openapi_client/test/test_add_peer_request.py create mode 100644 jellyfish/openapi_client/test/test_component.py create mode 100644 jellyfish/openapi_client/test/test_component_details_response.py create mode 100644 jellyfish/openapi_client/test/test_component_metadata.py create mode 100644 jellyfish/openapi_client/test/test_component_options.py create mode 100644 jellyfish/openapi_client/test/test_component_options_rtsp.py create mode 100644 jellyfish/openapi_client/test/test_default_api.py create mode 100644 jellyfish/openapi_client/test/test_error.py create mode 100644 jellyfish/openapi_client/test/test_hls_skip.py create mode 100644 jellyfish/openapi_client/test/test_peer.py create mode 100644 jellyfish/openapi_client/test/test_peer_details_response.py create mode 100644 jellyfish/openapi_client/test/test_peer_details_response_data.py create mode 100644 jellyfish/openapi_client/test/test_peer_options.py create mode 100644 jellyfish/openapi_client/test/test_peer_options_web_rtc.py create mode 100644 jellyfish/openapi_client/test/test_peer_status.py create mode 100644 jellyfish/openapi_client/test/test_room.py create mode 100644 jellyfish/openapi_client/test/test_room_api.py create mode 100644 jellyfish/openapi_client/test/test_room_config.py create mode 100644 jellyfish/openapi_client/test/test_room_create_details_response.py create mode 100644 jellyfish/openapi_client/test/test_room_create_details_response_data.py create mode 100644 jellyfish/openapi_client/test/test_room_details_response.py create mode 100644 jellyfish/openapi_client/test/test_rooms_listing_response.py create mode 100644 jellyfish/openapi_client/tox.ini diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py index cbacc35..8f82a63 100644 --- a/jellyfish/__init__.py +++ b/jellyfish/__init__.py @@ -4,6 +4,10 @@ __version__ = "0.1.0" -from import Room, RoomConfig, Peer, Component +from pydantic.error_wrappers import ValidationError + +from jellyfish_openapi_client import Room, RoomConfig, Peer, Component +from jellyfish_openapi_client import ComponentOptionsRTSP +from jellyfish_openapi_client import PeerOptionsWebRTC from jellyfish.room_api import RoomApi diff --git a/jellyfish/openapi_client/.github/workflows/python.yml b/jellyfish/openapi_client/.github/workflows/python.yml new file mode 100644 index 0000000..43f1e6e --- /dev/null +++ b/jellyfish/openapi_client/.github/workflows/python.yml @@ -0,0 +1,37 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: jellyfish_openapi_client Python package + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test with pytest + run: | + pytest diff --git a/jellyfish/openapi_client/.gitignore b/jellyfish/openapi_client/.gitignore new file mode 100644 index 0000000..43995bd --- /dev/null +++ b/jellyfish/openapi_client/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/jellyfish/openapi_client/.gitlab-ci.yml b/jellyfish/openapi_client/.gitlab-ci.yml new file mode 100644 index 0000000..bec95ad --- /dev/null +++ b/jellyfish/openapi_client/.gitlab-ci.yml @@ -0,0 +1,25 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.gitlab.com/ee/ci/README.html +# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml + +stages: + - test + +.pytest: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov=jellyfish_openapi_client + +pytest-3.7: + extends: .pytest + image: python:3.7-alpine +pytest-3.8: + extends: .pytest + image: python:3.8-alpine +pytest-3.9: + extends: .pytest + image: python:3.9-alpine \ No newline at end of file diff --git a/jellyfish/openapi_client/.openapi-generator-ignore b/jellyfish/openapi_client/.openapi-generator-ignore new file mode 100644 index 0000000..7484ee5 --- /dev/null +++ b/jellyfish/openapi_client/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/jellyfish/openapi_client/.openapi-generator/FILES b/jellyfish/openapi_client/.openapi-generator/FILES new file mode 100644 index 0000000..8f966b2 --- /dev/null +++ b/jellyfish/openapi_client/.openapi-generator/FILES @@ -0,0 +1,92 @@ +.github/workflows/python.yml +.gitignore +.gitlab-ci.yml +.openapi-generator-ignore +.travis.yml +README.md +docs/AddComponentRequest.md +docs/AddPeerRequest.md +docs/Component.md +docs/ComponentDetailsResponse.md +docs/ComponentMetadata.md +docs/ComponentOptions.md +docs/ComponentOptionsRTSP.md +docs/DefaultApi.md +docs/Error.md +docs/HlsSkip.md +docs/Peer.md +docs/PeerDetailsResponse.md +docs/PeerDetailsResponseData.md +docs/PeerOptions.md +docs/PeerOptionsWebRTC.md +docs/PeerStatus.md +docs/Room.md +docs/RoomApi.md +docs/RoomConfig.md +docs/RoomCreateDetailsResponse.md +docs/RoomCreateDetailsResponseData.md +docs/RoomDetailsResponse.md +docs/RoomsListingResponse.md +git_push.sh +jellyfish_openapi_client/__init__.py +jellyfish_openapi_client/api/__init__.py +jellyfish_openapi_client/api/default_api.py +jellyfish_openapi_client/api/room_api.py +jellyfish_openapi_client/api_client.py +jellyfish_openapi_client/api_response.py +jellyfish_openapi_client/configuration.py +jellyfish_openapi_client/exceptions.py +jellyfish_openapi_client/models/__init__.py +jellyfish_openapi_client/models/add_component_request.py +jellyfish_openapi_client/models/add_peer_request.py +jellyfish_openapi_client/models/component.py +jellyfish_openapi_client/models/component_details_response.py +jellyfish_openapi_client/models/component_metadata.py +jellyfish_openapi_client/models/component_options.py +jellyfish_openapi_client/models/component_options_rtsp.py +jellyfish_openapi_client/models/error.py +jellyfish_openapi_client/models/hls_skip.py +jellyfish_openapi_client/models/peer.py +jellyfish_openapi_client/models/peer_details_response.py +jellyfish_openapi_client/models/peer_details_response_data.py +jellyfish_openapi_client/models/peer_options.py +jellyfish_openapi_client/models/peer_options_web_rtc.py +jellyfish_openapi_client/models/peer_status.py +jellyfish_openapi_client/models/room.py +jellyfish_openapi_client/models/room_config.py +jellyfish_openapi_client/models/room_create_details_response.py +jellyfish_openapi_client/models/room_create_details_response_data.py +jellyfish_openapi_client/models/room_details_response.py +jellyfish_openapi_client/models/rooms_listing_response.py +jellyfish_openapi_client/py.typed +jellyfish_openapi_client/rest.py +pyproject.toml +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +test/test_add_component_request.py +test/test_add_peer_request.py +test/test_component.py +test/test_component_details_response.py +test/test_component_metadata.py +test/test_component_options.py +test/test_component_options_rtsp.py +test/test_default_api.py +test/test_error.py +test/test_hls_skip.py +test/test_peer.py +test/test_peer_details_response.py +test/test_peer_details_response_data.py +test/test_peer_options.py +test/test_peer_options_web_rtc.py +test/test_peer_status.py +test/test_room.py +test/test_room_api.py +test/test_room_config.py +test/test_room_create_details_response.py +test/test_room_create_details_response_data.py +test/test_room_details_response.py +test/test_rooms_listing_response.py +tox.ini diff --git a/jellyfish/openapi_client/.openapi-generator/VERSION b/jellyfish/openapi_client/.openapi-generator/VERSION new file mode 100644 index 0000000..4122521 --- /dev/null +++ b/jellyfish/openapi_client/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0 \ No newline at end of file diff --git a/jellyfish/openapi_client/.travis.yml b/jellyfish/openapi_client/.travis.yml new file mode 100644 index 0000000..8fe29fe --- /dev/null +++ b/jellyfish/openapi_client/.travis.yml @@ -0,0 +1,17 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + - "3.11" + # uncomment the following if needed + #- "3.11-dev" # 3.11 development branch + #- "nightly" # nightly build +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov=jellyfish_openapi_client diff --git a/jellyfish/openapi_client/README.md b/jellyfish/openapi_client/README.md new file mode 100644 index 0000000..8a7caff --- /dev/null +++ b/jellyfish/openapi_client/README.md @@ -0,0 +1,153 @@ +# jellyfish-openapi-client +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.2.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonClientCodegen + +## Requirements. + +Python 3.7+ + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import jellyfish_openapi_client +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import jellyfish_openapi_client +``` + +### Tests + +Execute `pytest` to run the tests. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import jellyfish_openapi_client +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.DefaultApi(api_client) + room_id = 'room_id_example' # str | Room id + filename = 'filename_example' # str | Name of the file + range = 'range_example' # str | Byte range of partial segment (optional) + hls_msn = 56 # int | Segment sequence number (optional) + hls_part = 56 # int | Partial segment sequence number (optional) + hls_skip = jellyfish_openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) + + try: + # Send file + api_response = api_instance.jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) + print("The response of DefaultApi->jellyfish_web_hls_controller_index:\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->jellyfish_web_hls_controller_index: %s\n" % e) + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**jellyfish_web_hls_controller_index**](docs/DefaultApi.md#jellyfish_web_hls_controller_index) | **GET** /hls/{room_id}/{filename} | Send file +*RoomApi* | [**add_component**](docs/RoomApi.md#add_component) | **POST** /room/{room_id}/component | Creates the component and adds it to the room +*RoomApi* | [**add_peer**](docs/RoomApi.md#add_peer) | **POST** /room/{room_id}/peer | Create peer +*RoomApi* | [**create_room**](docs/RoomApi.md#create_room) | **POST** /room | Creates a room +*RoomApi* | [**delete_component**](docs/RoomApi.md#delete_component) | **DELETE** /room/{room_id}/component/{id} | Delete the component from the room +*RoomApi* | [**delete_peer**](docs/RoomApi.md#delete_peer) | **DELETE** /room/{room_id}/peer/{id} | Delete peer +*RoomApi* | [**delete_room**](docs/RoomApi.md#delete_room) | **DELETE** /room/{room_id} | Delete the room +*RoomApi* | [**get_all_rooms**](docs/RoomApi.md#get_all_rooms) | **GET** /room | Show information about all rooms +*RoomApi* | [**get_room**](docs/RoomApi.md#get_room) | **GET** /room/{room_id} | Shows information about the room + + +## Documentation For Models + + - [AddComponentRequest](docs/AddComponentRequest.md) + - [AddPeerRequest](docs/AddPeerRequest.md) + - [Component](docs/Component.md) + - [ComponentDetailsResponse](docs/ComponentDetailsResponse.md) + - [ComponentMetadata](docs/ComponentMetadata.md) + - [ComponentOptions](docs/ComponentOptions.md) + - [ComponentOptionsRTSP](docs/ComponentOptionsRTSP.md) + - [Error](docs/Error.md) + - [HlsSkip](docs/HlsSkip.md) + - [Peer](docs/Peer.md) + - [PeerDetailsResponse](docs/PeerDetailsResponse.md) + - [PeerDetailsResponseData](docs/PeerDetailsResponseData.md) + - [PeerOptions](docs/PeerOptions.md) + - [PeerOptionsWebRTC](docs/PeerOptionsWebRTC.md) + - [PeerStatus](docs/PeerStatus.md) + - [Room](docs/Room.md) + - [RoomConfig](docs/RoomConfig.md) + - [RoomCreateDetailsResponse](docs/RoomCreateDetailsResponse.md) + - [RoomCreateDetailsResponseData](docs/RoomCreateDetailsResponseData.md) + - [RoomDetailsResponse](docs/RoomDetailsResponse.md) + - [RoomsListingResponse](docs/RoomsListingResponse.md) + + + +## Documentation For Authorization + + +Authentication schemes defined for the API: + +### authorization + +- **Type**: Bearer authentication + + +## Author + + + + diff --git a/jellyfish/openapi_client/docs/AddComponentRequest.md b/jellyfish/openapi_client/docs/AddComponentRequest.md new file mode 100644 index 0000000..32afca2 --- /dev/null +++ b/jellyfish/openapi_client/docs/AddComponentRequest.md @@ -0,0 +1,29 @@ +# AddComponentRequest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**options** | [**ComponentOptions**](ComponentOptions.md) | | +**type** | **str** | Component type | + +## Example + +```python +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest + +# TODO update the JSON string below +json = "{}" +# create an instance of AddComponentRequest from a JSON string +add_component_request_instance = AddComponentRequest.from_json(json) +# print the JSON string representation of the object +print AddComponentRequest.to_json() + +# convert the object into a dict +add_component_request_dict = add_component_request_instance.to_dict() +# create an instance of AddComponentRequest from a dict +add_component_request_form_dict = add_component_request.from_dict(add_component_request_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/AddPeerRequest.md b/jellyfish/openapi_client/docs/AddPeerRequest.md new file mode 100644 index 0000000..1c4aaaa --- /dev/null +++ b/jellyfish/openapi_client/docs/AddPeerRequest.md @@ -0,0 +1,29 @@ +# AddPeerRequest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**options** | [**PeerOptions**](PeerOptions.md) | | +**type** | **str** | Peer type | + +## Example + +```python +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest + +# TODO update the JSON string below +json = "{}" +# create an instance of AddPeerRequest from a JSON string +add_peer_request_instance = AddPeerRequest.from_json(json) +# print the JSON string representation of the object +print AddPeerRequest.to_json() + +# convert the object into a dict +add_peer_request_dict = add_peer_request_instance.to_dict() +# create an instance of AddPeerRequest from a dict +add_peer_request_form_dict = add_peer_request.from_dict(add_peer_request_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/Component.md b/jellyfish/openapi_client/docs/Component.md new file mode 100644 index 0000000..71f4fbb --- /dev/null +++ b/jellyfish/openapi_client/docs/Component.md @@ -0,0 +1,31 @@ +# Component + +Describes component + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | Assigned component id | +**metadata** | [**ComponentMetadata**](ComponentMetadata.md) | | +**type** | **str** | Component type | + +## Example + +```python +from jellyfish_openapi_client.models.component import Component + +# TODO update the JSON string below +json = "{}" +# create an instance of Component from a JSON string +component_instance = Component.from_json(json) +# print the JSON string representation of the object +print Component.to_json() + +# convert the object into a dict +component_dict = component_instance.to_dict() +# create an instance of Component from a dict +component_form_dict = component.from_dict(component_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/ComponentDetailsResponse.md b/jellyfish/openapi_client/docs/ComponentDetailsResponse.md new file mode 100644 index 0000000..16ce318 --- /dev/null +++ b/jellyfish/openapi_client/docs/ComponentDetailsResponse.md @@ -0,0 +1,29 @@ +# ComponentDetailsResponse + +Response containing component details + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**data** | [**Component**](Component.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of ComponentDetailsResponse from a JSON string +component_details_response_instance = ComponentDetailsResponse.from_json(json) +# print the JSON string representation of the object +print ComponentDetailsResponse.to_json() + +# convert the object into a dict +component_details_response_dict = component_details_response_instance.to_dict() +# create an instance of ComponentDetailsResponse from a dict +component_details_response_form_dict = component_details_response.from_dict(component_details_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/ComponentMetadata.md b/jellyfish/openapi_client/docs/ComponentMetadata.md new file mode 100644 index 0000000..9093104 --- /dev/null +++ b/jellyfish/openapi_client/docs/ComponentMetadata.md @@ -0,0 +1,29 @@ +# ComponentMetadata + +Component-specific metadata + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**playable** | **bool** | | [optional] + +## Example + +```python +from jellyfish_openapi_client.models.component_metadata import ComponentMetadata + +# TODO update the JSON string below +json = "{}" +# create an instance of ComponentMetadata from a JSON string +component_metadata_instance = ComponentMetadata.from_json(json) +# print the JSON string representation of the object +print ComponentMetadata.to_json() + +# convert the object into a dict +component_metadata_dict = component_metadata_instance.to_dict() +# create an instance of ComponentMetadata from a dict +component_metadata_form_dict = component_metadata.from_dict(component_metadata_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/ComponentOptions.md b/jellyfish/openapi_client/docs/ComponentOptions.md new file mode 100644 index 0000000..01a2f01 --- /dev/null +++ b/jellyfish/openapi_client/docs/ComponentOptions.md @@ -0,0 +1,33 @@ +# ComponentOptions + +Component-specific options + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**keep_alive_interval** | **int** | Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source | [optional] [default to 15000] +**pierce_nat** | **bool** | Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup | [optional] [default to True] +**reconnect_delay** | **int** | Delay (in ms) between successive reconnect attempts | [optional] [default to 15000] +**rtp_port** | **int** | Local port RTP stream will be received at | [optional] [default to 20000] +**source_uri** | **str** | URI of RTSP source stream | + +## Example + +```python +from jellyfish_openapi_client.models.component_options import ComponentOptions + +# TODO update the JSON string below +json = "{}" +# create an instance of ComponentOptions from a JSON string +component_options_instance = ComponentOptions.from_json(json) +# print the JSON string representation of the object +print ComponentOptions.to_json() + +# convert the object into a dict +component_options_dict = component_options_instance.to_dict() +# create an instance of ComponentOptions from a dict +component_options_form_dict = component_options.from_dict(component_options_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/ComponentOptionsRTSP.md b/jellyfish/openapi_client/docs/ComponentOptionsRTSP.md new file mode 100644 index 0000000..2500676 --- /dev/null +++ b/jellyfish/openapi_client/docs/ComponentOptionsRTSP.md @@ -0,0 +1,33 @@ +# ComponentOptionsRTSP + +Options specific to the RTSP component + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**keep_alive_interval** | **int** | Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source | [optional] [default to 15000] +**pierce_nat** | **bool** | Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup | [optional] [default to True] +**reconnect_delay** | **int** | Delay (in ms) between successive reconnect attempts | [optional] [default to 15000] +**rtp_port** | **int** | Local port RTP stream will be received at | [optional] [default to 20000] +**source_uri** | **str** | URI of RTSP source stream | + +## Example + +```python +from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP + +# TODO update the JSON string below +json = "{}" +# create an instance of ComponentOptionsRTSP from a JSON string +component_options_rtsp_instance = ComponentOptionsRTSP.from_json(json) +# print the JSON string representation of the object +print ComponentOptionsRTSP.to_json() + +# convert the object into a dict +component_options_rtsp_dict = component_options_rtsp_instance.to_dict() +# create an instance of ComponentOptionsRTSP from a dict +component_options_rtsp_form_dict = component_options_rtsp.from_dict(component_options_rtsp_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/DefaultApi.md b/jellyfish/openapi_client/docs/DefaultApi.md new file mode 100644 index 0000000..6dbccfc --- /dev/null +++ b/jellyfish/openapi_client/docs/DefaultApi.md @@ -0,0 +1,95 @@ +# jellyfish_openapi_client.DefaultApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**jellyfish_web_hls_controller_index**](DefaultApi.md#jellyfish_web_hls_controller_index) | **GET** /hls/{room_id}/{filename} | Send file + + +# **jellyfish_web_hls_controller_index** +> str jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) + +Send file + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.hls_skip import HlsSkip +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.DefaultApi(api_client) + room_id = 'room_id_example' # str | Room id + filename = 'filename_example' # str | Name of the file + range = 'range_example' # str | Byte range of partial segment (optional) + hls_msn = 56 # int | Segment sequence number (optional) + hls_part = 56 # int | Partial segment sequence number (optional) + hls_skip = jellyfish_openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) + + try: + # Send file + api_response = api_instance.jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) + print("The response of DefaultApi->jellyfish_web_hls_controller_index:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->jellyfish_web_hls_controller_index: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room id | + **filename** | **str**| Name of the file | + **range** | **str**| Byte range of partial segment | [optional] + **hls_msn** | **int**| Segment sequence number | [optional] + **hls_part** | **int**| Partial segment sequence number | [optional] + **hls_skip** | [**HlsSkip**](.md)| Is delta manifest requested | [optional] + +### Return type + +**str** + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | File was found | - | +**404** | File not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/jellyfish/openapi_client/docs/Error.md b/jellyfish/openapi_client/docs/Error.md new file mode 100644 index 0000000..db5796a --- /dev/null +++ b/jellyfish/openapi_client/docs/Error.md @@ -0,0 +1,29 @@ +# Error + +Error message + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**errors** | **str** | Error details | + +## Example + +```python +from jellyfish_openapi_client.models.error import Error + +# TODO update the JSON string below +json = "{}" +# create an instance of Error from a JSON string +error_instance = Error.from_json(json) +# print the JSON string representation of the object +print Error.to_json() + +# convert the object into a dict +error_dict = error_instance.to_dict() +# create an instance of Error from a dict +error_form_dict = error.from_dict(error_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/HlsSkip.md b/jellyfish/openapi_client/docs/HlsSkip.md new file mode 100644 index 0000000..c141496 --- /dev/null +++ b/jellyfish/openapi_client/docs/HlsSkip.md @@ -0,0 +1,11 @@ +# HlsSkip + +Is delta manifest requested + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/Peer.md b/jellyfish/openapi_client/docs/Peer.md new file mode 100644 index 0000000..cfca89f --- /dev/null +++ b/jellyfish/openapi_client/docs/Peer.md @@ -0,0 +1,31 @@ +# Peer + +Describes peer status + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | Assigned peer id | +**status** | [**PeerStatus**](PeerStatus.md) | | +**type** | **str** | Peer type | + +## Example + +```python +from jellyfish_openapi_client.models.peer import Peer + +# TODO update the JSON string below +json = "{}" +# create an instance of Peer from a JSON string +peer_instance = Peer.from_json(json) +# print the JSON string representation of the object +print Peer.to_json() + +# convert the object into a dict +peer_dict = peer_instance.to_dict() +# create an instance of Peer from a dict +peer_form_dict = peer.from_dict(peer_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/PeerDetailsResponse.md b/jellyfish/openapi_client/docs/PeerDetailsResponse.md new file mode 100644 index 0000000..ef90210 --- /dev/null +++ b/jellyfish/openapi_client/docs/PeerDetailsResponse.md @@ -0,0 +1,29 @@ +# PeerDetailsResponse + +Response containing peer details and their token + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**data** | [**PeerDetailsResponseData**](PeerDetailsResponseData.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of PeerDetailsResponse from a JSON string +peer_details_response_instance = PeerDetailsResponse.from_json(json) +# print the JSON string representation of the object +print PeerDetailsResponse.to_json() + +# convert the object into a dict +peer_details_response_dict = peer_details_response_instance.to_dict() +# create an instance of PeerDetailsResponse from a dict +peer_details_response_form_dict = peer_details_response.from_dict(peer_details_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/PeerDetailsResponseData.md b/jellyfish/openapi_client/docs/PeerDetailsResponseData.md new file mode 100644 index 0000000..cd1df4d --- /dev/null +++ b/jellyfish/openapi_client/docs/PeerDetailsResponseData.md @@ -0,0 +1,29 @@ +# PeerDetailsResponseData + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**peer** | [**Peer**](Peer.md) | | +**token** | **str** | Token for authorizing websocket connection | + +## Example + +```python +from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData + +# TODO update the JSON string below +json = "{}" +# create an instance of PeerDetailsResponseData from a JSON string +peer_details_response_data_instance = PeerDetailsResponseData.from_json(json) +# print the JSON string representation of the object +print PeerDetailsResponseData.to_json() + +# convert the object into a dict +peer_details_response_data_dict = peer_details_response_data_instance.to_dict() +# create an instance of PeerDetailsResponseData from a dict +peer_details_response_data_form_dict = peer_details_response_data.from_dict(peer_details_response_data_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/PeerOptions.md b/jellyfish/openapi_client/docs/PeerOptions.md new file mode 100644 index 0000000..130cf5a --- /dev/null +++ b/jellyfish/openapi_client/docs/PeerOptions.md @@ -0,0 +1,29 @@ +# PeerOptions + +Peer-specific options + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enable_simulcast** | **bool** | Enables the peer to use simulcast | [optional] [default to True] + +## Example + +```python +from jellyfish_openapi_client.models.peer_options import PeerOptions + +# TODO update the JSON string below +json = "{}" +# create an instance of PeerOptions from a JSON string +peer_options_instance = PeerOptions.from_json(json) +# print the JSON string representation of the object +print PeerOptions.to_json() + +# convert the object into a dict +peer_options_dict = peer_options_instance.to_dict() +# create an instance of PeerOptions from a dict +peer_options_form_dict = peer_options.from_dict(peer_options_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/PeerOptionsWebRTC.md b/jellyfish/openapi_client/docs/PeerOptionsWebRTC.md new file mode 100644 index 0000000..ba68e93 --- /dev/null +++ b/jellyfish/openapi_client/docs/PeerOptionsWebRTC.md @@ -0,0 +1,29 @@ +# PeerOptionsWebRTC + +Options specific to the WebRTC peer + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enable_simulcast** | **bool** | Enables the peer to use simulcast | [optional] [default to True] + +## Example + +```python +from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC + +# TODO update the JSON string below +json = "{}" +# create an instance of PeerOptionsWebRTC from a JSON string +peer_options_web_rtc_instance = PeerOptionsWebRTC.from_json(json) +# print the JSON string representation of the object +print PeerOptionsWebRTC.to_json() + +# convert the object into a dict +peer_options_web_rtc_dict = peer_options_web_rtc_instance.to_dict() +# create an instance of PeerOptionsWebRTC from a dict +peer_options_web_rtc_form_dict = peer_options_web_rtc.from_dict(peer_options_web_rtc_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/PeerStatus.md b/jellyfish/openapi_client/docs/PeerStatus.md new file mode 100644 index 0000000..951877e --- /dev/null +++ b/jellyfish/openapi_client/docs/PeerStatus.md @@ -0,0 +1,11 @@ +# PeerStatus + +Informs about the peer status + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/Room.md b/jellyfish/openapi_client/docs/Room.md new file mode 100644 index 0000000..7f09afa --- /dev/null +++ b/jellyfish/openapi_client/docs/Room.md @@ -0,0 +1,32 @@ +# Room + +Description of the room state + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**components** | [**List[Component]**](Component.md) | | +**config** | [**RoomConfig**](RoomConfig.md) | | +**id** | **str** | Room ID | +**peers** | [**List[Peer]**](Peer.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.room import Room + +# TODO update the JSON string below +json = "{}" +# create an instance of Room from a JSON string +room_instance = Room.from_json(json) +# print the JSON string representation of the object +print Room.to_json() + +# convert the object into a dict +room_dict = room_instance.to_dict() +# create an instance of Room from a dict +room_form_dict = room.from_dict(room_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/RoomApi.md b/jellyfish/openapi_client/docs/RoomApi.md new file mode 100644 index 0000000..51be161 --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomApi.md @@ -0,0 +1,632 @@ +# jellyfish_openapi_client.RoomApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_component**](RoomApi.md#add_component) | **POST** /room/{room_id}/component | Creates the component and adds it to the room +[**add_peer**](RoomApi.md#add_peer) | **POST** /room/{room_id}/peer | Create peer +[**create_room**](RoomApi.md#create_room) | **POST** /room | Creates a room +[**delete_component**](RoomApi.md#delete_component) | **DELETE** /room/{room_id}/component/{id} | Delete the component from the room +[**delete_peer**](RoomApi.md#delete_peer) | **DELETE** /room/{room_id}/peer/{id} | Delete peer +[**delete_room**](RoomApi.md#delete_room) | **DELETE** /room/{room_id} | Delete the room +[**get_all_rooms**](RoomApi.md#get_all_rooms) | **GET** /room | Show information about all rooms +[**get_room**](RoomApi.md#get_room) | **GET** /room/{room_id} | Shows information about the room + + +# **add_component** +> ComponentDetailsResponse add_component(room_id, add_component_request=add_component_request) + +Creates the component and adds it to the room + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room ID + add_component_request = jellyfish_openapi_client.AddComponentRequest() # AddComponentRequest | Component config (optional) + + try: + # Creates the component and adds it to the room + api_response = api_instance.add_component(room_id, add_component_request=add_component_request) + print("The response of RoomApi->add_component:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling RoomApi->add_component: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room ID | + **add_component_request** | [**AddComponentRequest**](AddComponentRequest.md)| Component config | [optional] + +### Return type + +[**ComponentDetailsResponse**](ComponentDetailsResponse.md) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**201** | Successfully added component | - | +**400** | Invalid request | - | +**401** | Unauthorized | - | +**404** | Room doesn't exist | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **add_peer** +> PeerDetailsResponse add_peer(room_id, add_peer_request=add_peer_request) + +Create peer + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room id + add_peer_request = jellyfish_openapi_client.AddPeerRequest() # AddPeerRequest | Peer specification (optional) + + try: + # Create peer + api_response = api_instance.add_peer(room_id, add_peer_request=add_peer_request) + print("The response of RoomApi->add_peer:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling RoomApi->add_peer: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room id | + **add_peer_request** | [**AddPeerRequest**](AddPeerRequest.md)| Peer specification | [optional] + +### Return type + +[**PeerDetailsResponse**](PeerDetailsResponse.md) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**201** | Peer successfully created | - | +**400** | Invalid request body structure | - | +**401** | Unauthorized | - | +**404** | Room doesn't exist | - | +**503** | Peer limit has been reached | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_room** +> RoomCreateDetailsResponse create_room(room_config=room_config) + +Creates a room + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_config import RoomConfig +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_config = jellyfish_openapi_client.RoomConfig() # RoomConfig | Room configuration (optional) + + try: + # Creates a room + api_response = api_instance.create_room(room_config=room_config) + print("The response of RoomApi->create_room:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling RoomApi->create_room: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_config** | [**RoomConfig**](RoomConfig.md)| Room configuration | [optional] + +### Return type + +[**RoomCreateDetailsResponse**](RoomCreateDetailsResponse.md) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**201** | Room successfully created | - | +**400** | Invalid request structure | - | +**401** | Unauthorized | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_component** +> delete_component(room_id, id) + +Delete the component from the room + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room ID + id = 'id_example' # str | Component ID + + try: + # Delete the component from the room + api_instance.delete_component(room_id, id) + except Exception as e: + print("Exception when calling RoomApi->delete_component: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room ID | + **id** | **str**| Component ID | + +### Return type + +void (empty response body) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Successfully deleted | - | +**401** | Unauthorized | - | +**404** | Either component or the room doesn't exist | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_peer** +> delete_peer(room_id, id) + +Delete peer + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room ID + id = 'id_example' # str | Peer id + + try: + # Delete peer + api_instance.delete_peer(room_id, id) + except Exception as e: + print("Exception when calling RoomApi->delete_peer: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room ID | + **id** | **str**| Peer id | + +### Return type + +void (empty response body) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Peer successfully deleted | - | +**401** | Unauthorized | - | +**404** | Room ID or Peer ID references a resource that doesn't exist | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_room** +> delete_room(room_id) + +Delete the room + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room id + + try: + # Delete the room + api_instance.delete_room(room_id) + except Exception as e: + print("Exception when calling RoomApi->delete_room: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room id | + +### Return type + +void (empty response body) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Successfully deleted room | - | +**401** | Unauthorized | - | +**404** | Room doesn't exist | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_all_rooms** +> RoomsListingResponse get_all_rooms() + +Show information about all rooms + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + + try: + # Show information about all rooms + api_response = api_instance.get_all_rooms() + print("The response of RoomApi->get_all_rooms:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling RoomApi->get_all_rooms: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**RoomsListingResponse**](RoomsListingResponse.md) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | +**401** | Unauthorized | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_room** +> RoomDetailsResponse get_room(room_id) + +Shows information about the room + +### Example + +* Bearer Authentication (authorization): +```python +import time +import os +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse +from jellyfish_openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = jellyfish_openapi_client.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: authorization +configuration = jellyfish_openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with jellyfish_openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = jellyfish_openapi_client.RoomApi(api_client) + room_id = 'room_id_example' # str | Room ID + + try: + # Shows information about the room + api_response = api_instance.get_room(room_id) + print("The response of RoomApi->get_room:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling RoomApi->get_room: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **room_id** | **str**| Room ID | + +### Return type + +[**RoomDetailsResponse**](RoomDetailsResponse.md) + +### Authorization + +[authorization](../README.md#authorization) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | +**401** | Unauthorized | - | +**404** | Room doesn't exist | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/jellyfish/openapi_client/docs/RoomConfig.md b/jellyfish/openapi_client/docs/RoomConfig.md new file mode 100644 index 0000000..f2e7dc2 --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomConfig.md @@ -0,0 +1,30 @@ +# RoomConfig + +Room configuration + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**max_peers** | **int** | Maximum amount of peers allowed into the room | [optional] +**video_codec** | **str** | Enforces video codec for each peer in the room | [optional] + +## Example + +```python +from jellyfish_openapi_client.models.room_config import RoomConfig + +# TODO update the JSON string below +json = "{}" +# create an instance of RoomConfig from a JSON string +room_config_instance = RoomConfig.from_json(json) +# print the JSON string representation of the object +print RoomConfig.to_json() + +# convert the object into a dict +room_config_dict = room_config_instance.to_dict() +# create an instance of RoomConfig from a dict +room_config_form_dict = room_config.from_dict(room_config_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md b/jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md new file mode 100644 index 0000000..6f9298c --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md @@ -0,0 +1,29 @@ +# RoomCreateDetailsResponse + +Response containing room details + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**data** | [**RoomCreateDetailsResponseData**](RoomCreateDetailsResponseData.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of RoomCreateDetailsResponse from a JSON string +room_create_details_response_instance = RoomCreateDetailsResponse.from_json(json) +# print the JSON string representation of the object +print RoomCreateDetailsResponse.to_json() + +# convert the object into a dict +room_create_details_response_dict = room_create_details_response_instance.to_dict() +# create an instance of RoomCreateDetailsResponse from a dict +room_create_details_response_form_dict = room_create_details_response.from_dict(room_create_details_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md b/jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md new file mode 100644 index 0000000..f646a64 --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md @@ -0,0 +1,29 @@ +# RoomCreateDetailsResponseData + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**jellyfish_address** | **str** | Jellyfish instance address where the room was created. This might be different than the address of Jellyfish where the request was sent only when running a cluster of Jellyfishes. | +**room** | [**Room**](Room.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData + +# TODO update the JSON string below +json = "{}" +# create an instance of RoomCreateDetailsResponseData from a JSON string +room_create_details_response_data_instance = RoomCreateDetailsResponseData.from_json(json) +# print the JSON string representation of the object +print RoomCreateDetailsResponseData.to_json() + +# convert the object into a dict +room_create_details_response_data_dict = room_create_details_response_data_instance.to_dict() +# create an instance of RoomCreateDetailsResponseData from a dict +room_create_details_response_data_form_dict = room_create_details_response_data.from_dict(room_create_details_response_data_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/RoomDetailsResponse.md b/jellyfish/openapi_client/docs/RoomDetailsResponse.md new file mode 100644 index 0000000..9f3dc18 --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomDetailsResponse.md @@ -0,0 +1,29 @@ +# RoomDetailsResponse + +Response containing room details + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**data** | [**Room**](Room.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of RoomDetailsResponse from a JSON string +room_details_response_instance = RoomDetailsResponse.from_json(json) +# print the JSON string representation of the object +print RoomDetailsResponse.to_json() + +# convert the object into a dict +room_details_response_dict = room_details_response_instance.to_dict() +# create an instance of RoomDetailsResponse from a dict +room_details_response_form_dict = room_details_response.from_dict(room_details_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/docs/RoomsListingResponse.md b/jellyfish/openapi_client/docs/RoomsListingResponse.md new file mode 100644 index 0000000..bc10d23 --- /dev/null +++ b/jellyfish/openapi_client/docs/RoomsListingResponse.md @@ -0,0 +1,29 @@ +# RoomsListingResponse + +Response containing list of all rooms + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**data** | [**List[Room]**](Room.md) | | + +## Example + +```python +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of RoomsListingResponse from a JSON string +rooms_listing_response_instance = RoomsListingResponse.from_json(json) +# print the JSON string representation of the object +print RoomsListingResponse.to_json() + +# convert the object into a dict +rooms_listing_response_dict = rooms_listing_response_instance.to_dict() +# create an instance of RoomsListingResponse from a dict +rooms_listing_response_form_dict = rooms_listing_response.from_dict(rooms_listing_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/jellyfish/openapi_client/git_push.sh b/jellyfish/openapi_client/git_push.sh new file mode 100644 index 0000000..f53a75d --- /dev/null +++ b/jellyfish/openapi_client/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py new file mode 100644 index 0000000..2e35e28 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +# flake8: noqa + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from jellyfish_openapi_client.api.default_api import DefaultApi +from jellyfish_openapi_client.api.room_api import RoomApi + +# import ApiClient +from jellyfish_openapi_client.api_response import ApiResponse +from jellyfish_openapi_client.api_client import ApiClient +from jellyfish_openapi_client.configuration import Configuration +from jellyfish_openapi_client.exceptions import OpenApiException +from jellyfish_openapi_client.exceptions import ApiTypeError +from jellyfish_openapi_client.exceptions import ApiValueError +from jellyfish_openapi_client.exceptions import ApiKeyError +from jellyfish_openapi_client.exceptions import ApiAttributeError +from jellyfish_openapi_client.exceptions import ApiException + +# import models into sdk package +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest +from jellyfish_openapi_client.models.component import Component +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse +from jellyfish_openapi_client.models.component_metadata import ComponentMetadata +from jellyfish_openapi_client.models.component_options import ComponentOptions +from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from jellyfish_openapi_client.models.error import Error +from jellyfish_openapi_client.models.hls_skip import HlsSkip +from jellyfish_openapi_client.models.peer import Peer +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse +from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from jellyfish_openapi_client.models.peer_options import PeerOptions +from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from jellyfish_openapi_client.models.peer_status import PeerStatus +from jellyfish_openapi_client.models.room import Room +from jellyfish_openapi_client.models.room_config import RoomConfig +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py new file mode 100644 index 0000000..e62e609 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa + +# import apis into api package +from jellyfish_openapi_client.api.default_api import DefaultApi +from jellyfish_openapi_client.api.room_api import RoomApi + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py b/jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py new file mode 100644 index 0000000..e5c3569 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import re # noqa: F401 +import io +import warnings + +from pydantic import validate_arguments, ValidationError +from typing_extensions import Annotated + +from pydantic import Field, StrictStr, conint + +from typing import Optional + +from jellyfish_openapi_client.models.hls_skip import HlsSkip + +from jellyfish_openapi_client.api_client import ApiClient +from jellyfish_openapi_client.api_response import ApiResponse +from jellyfish_openapi_client.exceptions import ( # noqa: F401 + ApiTypeError, + ApiValueError +) + + +class DefaultApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + @validate_arguments + def jellyfish_web_hls_controller_index(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], filename : Annotated[StrictStr, Field(..., description="Name of the file")], range : Annotated[Optional[StrictStr], Field(description="Byte range of partial segment")] = None, hls_msn : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Segment sequence number")] = None, hls_part : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Partial segment sequence number")] = None, hls_skip : Annotated[Optional[HlsSkip], Field(description="Is delta manifest requested")] = None, **kwargs) -> str: # noqa: E501 + """Send file # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.jellyfish_web_hls_controller_index(room_id, filename, range, hls_msn, hls_part, hls_skip, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param filename: Name of the file (required) + :type filename: str + :param range: Byte range of partial segment + :type range: str + :param hls_msn: Segment sequence number + :type hls_msn: int + :param hls_part: Partial segment sequence number + :type hls_part: int + :param hls_skip: Is delta manifest requested + :type hls_skip: HlsSkip + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the jellyfish_web_hls_controller_index_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.jellyfish_web_hls_controller_index_with_http_info(room_id, filename, range, hls_msn, hls_part, hls_skip, **kwargs) # noqa: E501 + + @validate_arguments + def jellyfish_web_hls_controller_index_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], filename : Annotated[StrictStr, Field(..., description="Name of the file")], range : Annotated[Optional[StrictStr], Field(description="Byte range of partial segment")] = None, hls_msn : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Segment sequence number")] = None, hls_part : Annotated[Optional[conint(strict=True, ge=0)], Field(description="Partial segment sequence number")] = None, hls_skip : Annotated[Optional[HlsSkip], Field(description="Is delta manifest requested")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Send file # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.jellyfish_web_hls_controller_index_with_http_info(room_id, filename, range, hls_msn, hls_part, hls_skip, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param filename: Name of the file (required) + :type filename: str + :param range: Byte range of partial segment + :type range: str + :param hls_msn: Segment sequence number + :type hls_msn: int + :param hls_part: Partial segment sequence number + :type hls_part: int + :param hls_skip: Is delta manifest requested + :type hls_skip: HlsSkip + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'room_id', + 'filename', + 'range', + 'hls_msn', + 'hls_part', + 'hls_skip' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method jellyfish_web_hls_controller_index" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + if _params['filename']: + _path_params['filename'] = _params['filename'] + + + # process the query parameters + _query_params = [] + if _params.get('hls_msn') is not None: # noqa: E501 + _query_params.append(('_HLS_msn', _params['hls_msn'])) + + if _params.get('hls_part') is not None: # noqa: E501 + _query_params.append(('_HLS_part', _params['hls_part'])) + + if _params.get('hls_skip') is not None: # noqa: E501 + _query_params.append(('_HLS_skip', _params['hls_skip'].value)) + + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + if _params['range']: + _header_params['range'] = _params['range'] + + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '200': "str", + '404': "Error", + } + + return self.api_client.call_api( + '/hls/{room_id}/{filename}', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py b/jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py new file mode 100644 index 0000000..6d67b19 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py @@ -0,0 +1,1200 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import re # noqa: F401 +import io +import warnings + +from pydantic import validate_arguments, ValidationError +from typing_extensions import Annotated + +from pydantic import Field, StrictStr + +from typing import Optional + +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse +from jellyfish_openapi_client.models.room_config import RoomConfig +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse + +from jellyfish_openapi_client.api_client import ApiClient +from jellyfish_openapi_client.api_response import ApiResponse +from jellyfish_openapi_client.exceptions import ( # noqa: F401 + ApiTypeError, + ApiValueError +) + + +class RoomApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + @validate_arguments + def add_component(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], add_component_request : Annotated[Optional[AddComponentRequest], Field(description="Component config")] = None, **kwargs) -> ComponentDetailsResponse: # noqa: E501 + """Creates the component and adds it to the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.add_component(room_id, add_component_request, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param add_component_request: Component config + :type add_component_request: AddComponentRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ComponentDetailsResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the add_component_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.add_component_with_http_info(room_id, add_component_request, **kwargs) # noqa: E501 + + @validate_arguments + def add_component_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], add_component_request : Annotated[Optional[AddComponentRequest], Field(description="Component config")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Creates the component and adds it to the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.add_component_with_http_info(room_id, add_component_request, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param add_component_request: Component config + :type add_component_request: AddComponentRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ComponentDetailsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'room_id', + 'add_component_request' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method add_component" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['add_component_request'] is not None: + _body_params = _params['add_component_request'] + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '201': "ComponentDetailsResponse", + '400': "Error", + '401': "Error", + '404': "Error", + } + + return self.api_client.call_api( + '/room/{room_id}/component', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def add_peer(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], add_peer_request : Annotated[Optional[AddPeerRequest], Field(description="Peer specification")] = None, **kwargs) -> PeerDetailsResponse: # noqa: E501 + """Create peer # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.add_peer(room_id, add_peer_request, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param add_peer_request: Peer specification + :type add_peer_request: AddPeerRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: PeerDetailsResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the add_peer_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.add_peer_with_http_info(room_id, add_peer_request, **kwargs) # noqa: E501 + + @validate_arguments + def add_peer_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], add_peer_request : Annotated[Optional[AddPeerRequest], Field(description="Peer specification")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Create peer # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.add_peer_with_http_info(room_id, add_peer_request, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param add_peer_request: Peer specification + :type add_peer_request: AddPeerRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(PeerDetailsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'room_id', + 'add_peer_request' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method add_peer" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['add_peer_request'] is not None: + _body_params = _params['add_peer_request'] + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '201': "PeerDetailsResponse", + '400': "Error", + '401': "Error", + '404': "Error", + '503': "Error", + } + + return self.api_client.call_api( + '/room/{room_id}/peer', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def create_room(self, room_config : Annotated[Optional[RoomConfig], Field(description="Room configuration")] = None, **kwargs) -> RoomCreateDetailsResponse: # noqa: E501 + """Creates a room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_room(room_config, async_req=True) + >>> result = thread.get() + + :param room_config: Room configuration + :type room_config: RoomConfig + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: RoomCreateDetailsResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the create_room_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.create_room_with_http_info(room_config, **kwargs) # noqa: E501 + + @validate_arguments + def create_room_with_http_info(self, room_config : Annotated[Optional[RoomConfig], Field(description="Room configuration")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Creates a room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_room_with_http_info(room_config, async_req=True) + >>> result = thread.get() + + :param room_config: Room configuration + :type room_config: RoomConfig + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(RoomCreateDetailsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'room_config' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method create_room" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['room_config'] is not None: + _body_params = _params['room_config'] + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '201': "RoomCreateDetailsResponse", + '400': "Error", + '401': "Error", + } + + return self.api_client.call_api( + '/room', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def delete_component(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], id : Annotated[StrictStr, Field(..., description="Component ID")], **kwargs) -> None: # noqa: E501 + """Delete the component from the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_component(room_id, id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param id: Component ID (required) + :type id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the delete_component_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.delete_component_with_http_info(room_id, id, **kwargs) # noqa: E501 + + @validate_arguments + def delete_component_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], id : Annotated[StrictStr, Field(..., description="Component ID")], **kwargs) -> ApiResponse: # noqa: E501 + """Delete the component from the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_component_with_http_info(room_id, id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param id: Component ID (required) + :type id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + 'room_id', + 'id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_component" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + if _params['id']: + _path_params['id'] = _params['id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/room/{room_id}/component/{id}', 'DELETE', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def delete_peer(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], id : Annotated[StrictStr, Field(..., description="Peer id")], **kwargs) -> None: # noqa: E501 + """Delete peer # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_peer(room_id, id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param id: Peer id (required) + :type id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the delete_peer_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.delete_peer_with_http_info(room_id, id, **kwargs) # noqa: E501 + + @validate_arguments + def delete_peer_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], id : Annotated[StrictStr, Field(..., description="Peer id")], **kwargs) -> ApiResponse: # noqa: E501 + """Delete peer # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_peer_with_http_info(room_id, id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param id: Peer id (required) + :type id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + 'room_id', + 'id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_peer" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + if _params['id']: + _path_params['id'] = _params['id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/room/{room_id}/peer/{id}', 'DELETE', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def delete_room(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], **kwargs) -> None: # noqa: E501 + """Delete the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_room(room_id, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the delete_room_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.delete_room_with_http_info(room_id, **kwargs) # noqa: E501 + + @validate_arguments + def delete_room_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room id")], **kwargs) -> ApiResponse: # noqa: E501 + """Delete the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_room_with_http_info(room_id, async_req=True) + >>> result = thread.get() + + :param room_id: Room id (required) + :type room_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + 'room_id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_room" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/room/{room_id}', 'DELETE', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def get_all_rooms(self, **kwargs) -> RoomsListingResponse: # noqa: E501 + """Show information about all rooms # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_all_rooms(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: RoomsListingResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the get_all_rooms_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.get_all_rooms_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def get_all_rooms_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Show information about all rooms # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_all_rooms_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(RoomsListingResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_all_rooms" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '200': "RoomsListingResponse", + '401': "Error", + } + + return self.api_client.call_api( + '/room', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def get_room(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], **kwargs) -> RoomDetailsResponse: # noqa: E501 + """Shows information about the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_room(room_id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: RoomDetailsResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + raise ValueError("Error! Please call the get_room_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + return self.get_room_with_http_info(room_id, **kwargs) # noqa: E501 + + @validate_arguments + def get_room_with_http_info(self, room_id : Annotated[StrictStr, Field(..., description="Room ID")], **kwargs) -> ApiResponse: # noqa: E501 + """Shows information about the room # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_room_with_http_info(room_id, async_req=True) + >>> result = thread.get() + + :param room_id: Room ID (required) + :type room_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(RoomDetailsResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'room_id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_room" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['room_id']: + _path_params['room_id'] = _params['room_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['authorization'] # noqa: E501 + + _response_types_map = { + '200': "RoomDetailsResponse", + '401': "Error", + '404': "Error", + } + + return self.api_client.call_api( + '/room/{room_id}', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api_client.py b/jellyfish/openapi_client/jellyfish_openapi_client/api_client.py new file mode 100644 index 0000000..f9fe646 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/api_client.py @@ -0,0 +1,755 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import atexit +import datetime +from dateutil.parser import parse +import json +import mimetypes +from multiprocessing.pool import ThreadPool +import os +import re +import tempfile + +from urllib.parse import quote + +from jellyfish_openapi_client.configuration import Configuration +from jellyfish_openapi_client.api_response import ApiResponse +import jellyfish_openapi_client.models +from jellyfish_openapi_client import rest +from jellyfish_openapi_client.exceptions import ApiValueError, ApiException + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'object': object, + } + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_types_map=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None, _host=None, + _request_auth=None): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, query_params, auth_settings, + resource_path, method, body, + request_auth=_request_auth) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query(query_params, + collection_formats) + url += "?" + url_query + + try: + # perform request and return response + response_data = self.request( + method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e + + self.last_response = response_data + + return_data = None # assuming derialization is not needed + # data needs deserialization or returns HTTP data (deserialized) only + if _preload_content or _return_http_data_only: + response_type = response_types_map.get(str(response_data.status), None) + + if response_type == "bytearray": + response_data.data = response_data.data + else: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type == "bytearray": + return_data = response_data.data + elif response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None + + if _return_http_data_only: + return return_data + else: + return ApiResponse(status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = obj.to_dict() + + return {key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items()} + + def deserialize(self, response, response_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == "file": + return self.__deserialize_file(response) + + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if type(klass) == str: + if klass.startswith('List['): + sub_kls = re.match(r'List\[(.*)]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(jellyfish_openapi_client.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_types_map=None, auth_settings=None, + async_req=None, _return_http_data_only=None, + collection_formats=None, _preload_content=True, + _request_timeout=None, _host=None, _request_auth=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_token: dict, optional + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_types_map, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _request_auth) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_types_map, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _request_auth)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.get_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.head_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.options_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + elif method == "POST": + return self.rest_client.post_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.put_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.patch_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.delete_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v))) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(item) for item in new_params]) + + def files_parameters(self, files=None): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + + if files: + for k, v in files.items(): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth(self, headers, queries, auth_settings, + resource_path, method, body, + request_auth=None): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params(headers, queries, + resource_path, method, body, + request_auth) + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params(headers, queries, + resource_path, method, body, + auth_setting) + + def _apply_auth_params(self, headers, queries, + resource_path, method, body, + auth_setting): + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/api_response.py new file mode 100644 index 0000000..d81c2ff --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/api_response.py @@ -0,0 +1,25 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Any, Dict, Optional +from pydantic import Field, StrictInt, StrictStr + +class ApiResponse: + """ + API response object + """ + + status_code: Optional[StrictInt] = Field(None, description="HTTP status code") + headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") + data: Optional[Any] = Field(None, description="Deserialized data given the data type") + raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + + def __init__(self, + status_code=None, + headers=None, + data=None, + raw_data=None): + self.status_code = status_code + self.headers = headers + self.data = data + self.raw_data = raw_data diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/configuration.py b/jellyfish/openapi_client/jellyfish_openapi_client/configuration.py new file mode 100644 index 0000000..69a81a7 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/configuration.py @@ -0,0 +1,442 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +import http.client as httplib +from jellyfish_openapi_client.exceptions import ApiValueError + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration(object): + """This class contains various settings of the API client. + + :param host: Base url. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + + :Example: + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor + """ + self._base_path = "http://localhost" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("jellyfish_openapi_client") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls): + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = Configuration() + return cls._default + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + if self.access_token is not None: + auth['authorization'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 0.2.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "", + 'description': "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py b/jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py new file mode 100644 index 0000000..c62a6ba --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + +class BadRequestException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(BadRequestException, self).__init__(status, reason, http_resp) + +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ServiceException, self).__init__(status, reason, http_resp) + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py new file mode 100644 index 0000000..bd70acb --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +# flake8: noqa +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest +from jellyfish_openapi_client.models.component import Component +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse +from jellyfish_openapi_client.models.component_metadata import ComponentMetadata +from jellyfish_openapi_client.models.component_options import ComponentOptions +from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from jellyfish_openapi_client.models.error import Error +from jellyfish_openapi_client.models.hls_skip import HlsSkip +from jellyfish_openapi_client.models.peer import Peer +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse +from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from jellyfish_openapi_client.models.peer_options import PeerOptions +from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from jellyfish_openapi_client.models.peer_status import PeerStatus +from jellyfish_openapi_client.models.room import Room +from jellyfish_openapi_client.models.room_config import RoomConfig +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py new file mode 100644 index 0000000..c577a8c --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.component_options import ComponentOptions + +class AddComponentRequest(BaseModel): + """ + AddComponentRequest + """ + options: ComponentOptions = Field(...) + type: StrictStr = Field(..., description="Component type") + __properties = ["options", "type"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AddComponentRequest: + """Create an instance of AddComponentRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of options + if self.options: + _dict['options'] = self.options.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AddComponentRequest: + """Create an instance of AddComponentRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AddComponentRequest.parse_obj(obj) + + _obj = AddComponentRequest.parse_obj({ + "options": ComponentOptions.from_dict(obj.get("options")) if obj.get("options") is not None else None, + "type": obj.get("type") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py new file mode 100644 index 0000000..e7c3bae --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.peer_options import PeerOptions + +class AddPeerRequest(BaseModel): + """ + AddPeerRequest + """ + options: PeerOptions = Field(...) + type: StrictStr = Field(..., description="Peer type") + __properties = ["options", "type"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AddPeerRequest: + """Create an instance of AddPeerRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of options + if self.options: + _dict['options'] = self.options.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AddPeerRequest: + """Create an instance of AddPeerRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AddPeerRequest.parse_obj(obj) + + _obj = AddPeerRequest.parse_obj({ + "options": PeerOptions.from_dict(obj.get("options")) if obj.get("options") is not None else None, + "type": obj.get("type") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/component.py new file mode 100644 index 0000000..8a0a8ac --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/component.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.component_metadata import ComponentMetadata + +class Component(BaseModel): + """ + Describes component + """ + id: StrictStr = Field(..., description="Assigned component id") + metadata: ComponentMetadata = Field(...) + type: StrictStr = Field(..., description="Component type") + __properties = ["id", "metadata", "type"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Component: + """Create an instance of Component from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Component: + """Create an instance of Component from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Component.parse_obj(obj) + + _obj = Component.parse_obj({ + "id": obj.get("id"), + "metadata": ComponentMetadata.from_dict(obj.get("metadata")) if obj.get("metadata") is not None else None, + "type": obj.get("type") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py new file mode 100644 index 0000000..20aeb23 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field +from jellyfish_openapi_client.models.component import Component + +class ComponentDetailsResponse(BaseModel): + """ + Response containing component details + """ + data: Component = Field(...) + __properties = ["data"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ComponentDetailsResponse: + """Create an instance of ComponentDetailsResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ComponentDetailsResponse: + """Create an instance of ComponentDetailsResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ComponentDetailsResponse.parse_obj(obj) + + _obj = ComponentDetailsResponse.parse_obj({ + "data": Component.from_dict(obj.get("data")) if obj.get("data") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py new file mode 100644 index 0000000..20f80b9 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictBool + +class ComponentMetadata(BaseModel): + """ + Component-specific metadata + """ + playable: Optional[StrictBool] = None + __properties = ["playable"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ComponentMetadata: + """Create an instance of ComponentMetadata from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ComponentMetadata: + """Create an instance of ComponentMetadata from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ComponentMetadata.parse_obj(obj) + + _obj = ComponentMetadata.parse_obj({ + "playable": obj.get("playable") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py new file mode 100644 index 0000000..c8e9a9a --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py @@ -0,0 +1,144 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, Dict, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +COMPONENTOPTIONS_ONE_OF_SCHEMAS = ["ComponentOptionsRTSP", "object"] + +class ComponentOptions(BaseModel): + """ + Component-specific options + """ + # data type: object + oneof_schema_1_validator: Optional[Dict[str, Any]] = Field(None, description="Options specific to the HLS component") + # data type: ComponentOptionsRTSP + oneof_schema_2_validator: Optional[ComponentOptionsRTSP] = None + if TYPE_CHECKING: + actual_instance: Union[ComponentOptionsRTSP, object] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(COMPONENTOPTIONS_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs): + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ComponentOptions.construct() + error_messages = [] + match = 0 + # validate data type: object + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: ComponentOptionsRTSP + if not isinstance(v, ComponentOptionsRTSP): + error_messages.append(f"Error! Input type `{type(v)}` is not `ComponentOptionsRTSP`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> ComponentOptions: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> ComponentOptions: + """Returns the object represented by the json string""" + instance = ComponentOptions.construct() + error_messages = [] + match = 0 + + # deserialize data into object + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into ComponentOptionsRTSP + try: + instance.actual_instance = ComponentOptionsRTSP.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py new file mode 100644 index 0000000..d2bf321 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictBool, StrictStr, conint + +class ComponentOptionsRTSP(BaseModel): + """ + Options specific to the RTSP component + """ + keep_alive_interval: Optional[conint(strict=True, ge=0)] = Field(15000, alias="keepAliveInterval", description="Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source") + pierce_nat: Optional[StrictBool] = Field(True, alias="pierceNat", description="Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup") + reconnect_delay: Optional[conint(strict=True, ge=0)] = Field(15000, alias="reconnectDelay", description="Delay (in ms) between successive reconnect attempts") + rtp_port: Optional[conint(strict=True, le=65535, ge=1)] = Field(20000, alias="rtpPort", description="Local port RTP stream will be received at") + source_uri: StrictStr = Field(..., alias="sourceUri", description="URI of RTSP source stream") + __properties = ["keepAliveInterval", "pierceNat", "reconnectDelay", "rtpPort", "sourceUri"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ComponentOptionsRTSP: + """Create an instance of ComponentOptionsRTSP from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ComponentOptionsRTSP: + """Create an instance of ComponentOptionsRTSP from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ComponentOptionsRTSP.parse_obj(obj) + + _obj = ComponentOptionsRTSP.parse_obj({ + "keep_alive_interval": obj.get("keepAliveInterval") if obj.get("keepAliveInterval") is not None else 15000, + "pierce_nat": obj.get("pierceNat") if obj.get("pierceNat") is not None else True, + "reconnect_delay": obj.get("reconnectDelay") if obj.get("reconnectDelay") is not None else 15000, + "rtp_port": obj.get("rtpPort") if obj.get("rtpPort") is not None else 20000, + "source_uri": obj.get("sourceUri") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/error.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/error.py new file mode 100644 index 0000000..5635824 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/error.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr + +class Error(BaseModel): + """ + Error message + """ + errors: StrictStr = Field(..., description="Error details") + __properties = ["errors"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Error: + """Create an instance of Error from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Error: + """Create an instance of Error from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Error.parse_obj(obj) + + _obj = Error.parse_obj({ + "errors": obj.get("errors") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py new file mode 100644 index 0000000..aea7ae3 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import json +import pprint +import re # noqa: F401 +from aenum import Enum, no_arg + + + + + +class HlsSkip(str, Enum): + """ + Is delta manifest requested + """ + + """ + allowed enum values + """ + TRUE = 'true' + + @classmethod + def from_json(cls, json_str: str) -> HlsSkip: + """Create an instance of HlsSkip from a JSON string""" + return HlsSkip(json.loads(json_str)) + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py new file mode 100644 index 0000000..b7ae8ae --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py @@ -0,0 +1,76 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.peer_status import PeerStatus + +class Peer(BaseModel): + """ + Describes peer status + """ + id: StrictStr = Field(..., description="Assigned peer id") + status: PeerStatus = Field(...) + type: StrictStr = Field(..., description="Peer type") + __properties = ["id", "status", "type"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Peer: + """Create an instance of Peer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Peer: + """Create an instance of Peer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Peer.parse_obj(obj) + + _obj = Peer.parse_obj({ + "id": obj.get("id"), + "status": obj.get("status"), + "type": obj.get("type") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py new file mode 100644 index 0000000..9698306 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field +from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData + +class PeerDetailsResponse(BaseModel): + """ + Response containing peer details and their token + """ + data: PeerDetailsResponseData = Field(...) + __properties = ["data"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> PeerDetailsResponse: + """Create an instance of PeerDetailsResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> PeerDetailsResponse: + """Create an instance of PeerDetailsResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PeerDetailsResponse.parse_obj(obj) + + _obj = PeerDetailsResponse.parse_obj({ + "data": PeerDetailsResponseData.from_dict(obj.get("data")) if obj.get("data") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py new file mode 100644 index 0000000..9414438 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.peer import Peer + +class PeerDetailsResponseData(BaseModel): + """ + PeerDetailsResponseData + """ + peer: Peer = Field(...) + token: StrictStr = Field(..., description="Token for authorizing websocket connection") + __properties = ["peer", "token"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> PeerDetailsResponseData: + """Create an instance of PeerDetailsResponseData from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of peer + if self.peer: + _dict['peer'] = self.peer.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> PeerDetailsResponseData: + """Create an instance of PeerDetailsResponseData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PeerDetailsResponseData.parse_obj(obj) + + _obj = PeerDetailsResponseData.parse_obj({ + "peer": Peer.from_dict(obj.get("peer")) if obj.get("peer") is not None else None, + "token": obj.get("token") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py new file mode 100644 index 0000000..ddf5190 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, validator +from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from typing import Union, Any, List, TYPE_CHECKING +from pydantic import StrictStr, Field + +PEEROPTIONS_ONE_OF_SCHEMAS = ["PeerOptionsWebRTC"] + +class PeerOptions(BaseModel): + """ + Peer-specific options + """ + # data type: PeerOptionsWebRTC + oneof_schema_1_validator: Optional[PeerOptionsWebRTC] = None + if TYPE_CHECKING: + actual_instance: Union[PeerOptionsWebRTC] + else: + actual_instance: Any + one_of_schemas: List[str] = Field(PEEROPTIONS_ONE_OF_SCHEMAS, const=True) + + class Config: + validate_assignment = True + + def __init__(self, *args, **kwargs): + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = PeerOptions.construct() + error_messages = [] + match = 0 + # validate data type: PeerOptionsWebRTC + if not isinstance(v, PeerOptionsWebRTC): + error_messages.append(f"Error! Input type `{type(v)}` is not `PeerOptionsWebRTC`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in PeerOptions with oneOf schemas: PeerOptionsWebRTC. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in PeerOptions with oneOf schemas: PeerOptionsWebRTC. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> PeerOptions: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> PeerOptions: + """Returns the object represented by the json string""" + instance = PeerOptions.construct() + error_messages = [] + match = 0 + + # deserialize data into PeerOptionsWebRTC + try: + instance.actual_instance = PeerOptionsWebRTC.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into PeerOptions with oneOf schemas: PeerOptionsWebRTC. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into PeerOptions with oneOf schemas: PeerOptionsWebRTC. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.dict()) + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py new file mode 100644 index 0000000..0f9d99b --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictBool + +class PeerOptionsWebRTC(BaseModel): + """ + Options specific to the WebRTC peer + """ + enable_simulcast: Optional[StrictBool] = Field(True, alias="enableSimulcast", description="Enables the peer to use simulcast") + __properties = ["enableSimulcast"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> PeerOptionsWebRTC: + """Create an instance of PeerOptionsWebRTC from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> PeerOptionsWebRTC: + """Create an instance of PeerOptionsWebRTC from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return PeerOptionsWebRTC.parse_obj(obj) + + _obj = PeerOptionsWebRTC.parse_obj({ + "enable_simulcast": obj.get("enableSimulcast") if obj.get("enableSimulcast") is not None else True + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py new file mode 100644 index 0000000..e9441bc --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import json +import pprint +import re # noqa: F401 +from aenum import Enum, no_arg + + + + + +class PeerStatus(str, Enum): + """ + Informs about the peer status + """ + + """ + allowed enum values + """ + CONNECTED = 'connected' + DISCONNECTED = 'disconnected' + + @classmethod + def from_json(cls, json_str: str) -> PeerStatus: + """Create an instance of PeerStatus from a JSON string""" + return PeerStatus(json.loads(json_str)) + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/room.py new file mode 100644 index 0000000..71c635a --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/room.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List +from pydantic import BaseModel, Field, StrictStr, conlist +from jellyfish_openapi_client.models.component import Component +from jellyfish_openapi_client.models.peer import Peer +from jellyfish_openapi_client.models.room_config import RoomConfig + +class Room(BaseModel): + """ + Description of the room state + """ + components: conlist(Component) = Field(...) + config: RoomConfig = Field(...) + id: StrictStr = Field(..., description="Room ID") + peers: conlist(Peer) = Field(...) + __properties = ["components", "config", "id", "peers"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Room: + """Create an instance of Room from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in components (list) + _items = [] + if self.components: + for _item in self.components: + if _item: + _items.append(_item.to_dict()) + _dict['components'] = _items + # override the default output from pydantic by calling `to_dict()` of config + if self.config: + _dict['config'] = self.config.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in peers (list) + _items = [] + if self.peers: + for _item in self.peers: + if _item: + _items.append(_item.to_dict()) + _dict['peers'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> Room: + """Create an instance of Room from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return Room.parse_obj(obj) + + _obj = Room.parse_obj({ + "components": [Component.from_dict(_item) for _item in obj.get("components")] if obj.get("components") is not None else None, + "config": RoomConfig.from_dict(obj.get("config")) if obj.get("config") is not None else None, + "id": obj.get("id"), + "peers": [Peer.from_dict(_item) for _item in obj.get("peers")] if obj.get("peers") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py new file mode 100644 index 0000000..b1edda1 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, Field, StrictStr, conint, validator + +class RoomConfig(BaseModel): + """ + Room configuration + """ + max_peers: Optional[conint(strict=True, ge=1)] = Field(None, alias="maxPeers", description="Maximum amount of peers allowed into the room") + video_codec: Optional[StrictStr] = Field(None, alias="videoCodec", description="Enforces video codec for each peer in the room") + __properties = ["maxPeers", "videoCodec"] + + @validator('video_codec') + def video_codec_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in ('h264', 'vp8'): + raise ValueError("must be one of enum values ('h264', 'vp8')") + return value + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RoomConfig: + """Create an instance of RoomConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # set to None if max_peers (nullable) is None + # and __fields_set__ contains the field + if self.max_peers is None and "max_peers" in self.__fields_set__: + _dict['maxPeers'] = None + + # set to None if video_codec (nullable) is None + # and __fields_set__ contains the field + if self.video_codec is None and "video_codec" in self.__fields_set__: + _dict['videoCodec'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RoomConfig: + """Create an instance of RoomConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RoomConfig.parse_obj(obj) + + _obj = RoomConfig.parse_obj({ + "max_peers": obj.get("maxPeers"), + "video_codec": obj.get("videoCodec") + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py new file mode 100644 index 0000000..2859029 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field +from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData + +class RoomCreateDetailsResponse(BaseModel): + """ + Response containing room details + """ + data: RoomCreateDetailsResponseData = Field(...) + __properties = ["data"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RoomCreateDetailsResponse: + """Create an instance of RoomCreateDetailsResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RoomCreateDetailsResponse: + """Create an instance of RoomCreateDetailsResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RoomCreateDetailsResponse.parse_obj(obj) + + _obj = RoomCreateDetailsResponse.parse_obj({ + "data": RoomCreateDetailsResponseData.from_dict(obj.get("data")) if obj.get("data") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py new file mode 100644 index 0000000..69ef4cc --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field, StrictStr +from jellyfish_openapi_client.models.room import Room + +class RoomCreateDetailsResponseData(BaseModel): + """ + RoomCreateDetailsResponseData + """ + jellyfish_address: StrictStr = Field(..., description="Jellyfish instance address where the room was created. This might be different than the address of Jellyfish where the request was sent only when running a cluster of Jellyfishes.") + room: Room = Field(...) + __properties = ["jellyfish_address", "room"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RoomCreateDetailsResponseData: + """Create an instance of RoomCreateDetailsResponseData from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of room + if self.room: + _dict['room'] = self.room.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RoomCreateDetailsResponseData: + """Create an instance of RoomCreateDetailsResponseData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RoomCreateDetailsResponseData.parse_obj(obj) + + _obj = RoomCreateDetailsResponseData.parse_obj({ + "jellyfish_address": obj.get("jellyfish_address"), + "room": Room.from_dict(obj.get("room")) if obj.get("room") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py new file mode 100644 index 0000000..764ece8 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + + +from pydantic import BaseModel, Field +from jellyfish_openapi_client.models.room import Room + +class RoomDetailsResponse(BaseModel): + """ + Response containing room details + """ + data: Room = Field(...) + __properties = ["data"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RoomDetailsResponse: + """Create an instance of RoomDetailsResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RoomDetailsResponse: + """Create an instance of RoomDetailsResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RoomDetailsResponse.parse_obj(obj) + + _obj = RoomDetailsResponse.parse_obj({ + "data": Room.from_dict(obj.get("data")) if obj.get("data") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py new file mode 100644 index 0000000..3129f65 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import List +from pydantic import BaseModel, Field, conlist +from jellyfish_openapi_client.models.room import Room + +class RoomsListingResponse(BaseModel): + """ + Response containing list of all rooms + """ + data: conlist(Room) = Field(...) + __properties = ["data"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> RoomsListingResponse: + """Create an instance of RoomsListingResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item in self.data: + if _item: + _items.append(_item.to_dict()) + _dict['data'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> RoomsListingResponse: + """Create an instance of RoomsListingResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return RoomsListingResponse.parse_obj(obj) + + _obj = RoomsListingResponse.parse_obj({ + "data": [Room.from_dict(_item) for _item in obj.get("data")] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/py.typed b/jellyfish/openapi_client/jellyfish_openapi_client/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/rest.py b/jellyfish/openapi_client/jellyfish_openapi_client/rest.py new file mode 100644 index 0000000..5b2f7f0 --- /dev/null +++ b/jellyfish/openapi_client/jellyfish_openapi_client/rest.py @@ -0,0 +1,303 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import logging +import re +import ssl + +from urllib.parse import urlencode, quote_plus +import urllib3 + +from jellyfish_openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.headers.get(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + addition_pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + # url already contains the URL query string + # so reset query_params to empty dict + query_params = {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request(method, url, + fields={}, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + if r.status == 400: + raise BadRequestException(http_resp=r) + + if r.status == 401: + raise UnauthorizedException(http_resp=r) + + if r.status == 403: + raise ForbiddenException(http_resp=r) + + if r.status == 404: + raise NotFoundException(http_resp=r) + + if 500 <= r.status <= 599: + raise ServiceException(http_resp=r) + + raise ApiException(http_resp=r) + + return r + + def get_request(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def head_request(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def options_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def delete_request(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def post_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def put_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def patch_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) diff --git a/jellyfish/openapi_client/pyproject.toml b/jellyfish/openapi_client/pyproject.toml new file mode 100644 index 0000000..3feba39 --- /dev/null +++ b/jellyfish/openapi_client/pyproject.toml @@ -0,0 +1,30 @@ +[tool.poetry] +name = "jellyfish_openapi_client" +version = "1.0.0" +description = "Jellyfish Media Server" +authors = ["OpenAPI Generator Community "] +license = "Apache 2.0" +readme = "README.md" +repository = "https://github.com/GIT_USER_ID/GIT_REPO_ID" +keywords = ["OpenAPI", "OpenAPI-Generator", "Jellyfish Media Server"] +include = ["jellyfish_openapi_client/py.typed"] + +[tool.poetry.dependencies] +python = "^3.7" + +urllib3 = ">= 1.25.3" +python-dateutil = ">=2.8.2" +pydantic = "^1.10.5, <2" +aenum = ">=3.1.11" + +[tool.poetry.dev-dependencies] +pytest = ">=7.2.1" +tox = ">=3.9.0" +flake8 = ">=4.0.0" + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.pylint.'MESSAGES CONTROL'] +extension-pkg-whitelist = "pydantic" diff --git a/jellyfish/openapi_client/requirements.txt b/jellyfish/openapi_client/requirements.txt new file mode 100644 index 0000000..258c179 --- /dev/null +++ b/jellyfish/openapi_client/requirements.txt @@ -0,0 +1,5 @@ +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.25.3, < 2.1.0 +pydantic >= 1.10.5, < 2 +aenum >= 3.1.11 diff --git a/jellyfish/openapi_client/setup.cfg b/jellyfish/openapi_client/setup.cfg new file mode 100644 index 0000000..11433ee --- /dev/null +++ b/jellyfish/openapi_client/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/jellyfish/openapi_client/setup.py b/jellyfish/openapi_client/setup.py new file mode 100644 index 0000000..1c32565 --- /dev/null +++ b/jellyfish/openapi_client/setup.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "jellyfish-openapi-client" +VERSION = "1.0.0" +PYTHON_REQUIRES = ">=3.7" +REQUIRES = [ + "urllib3 >= 1.25.3, < 2.1.0", + "python-dateutil", + "pydantic >= 1.10.5, < 2", + "aenum" +] + +setup( + name=NAME, + version=VERSION, + description="Jellyfish Media Server", + author="OpenAPI Generator community", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "Jellyfish Media Server"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache 2.0", + long_description_content_type='text/markdown', + long_description="""\ + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + """, # noqa: E501 + package_data={"jellyfish_openapi_client": ["py.typed"]}, +) diff --git a/jellyfish/openapi_client/test-requirements.txt b/jellyfish/openapi_client/test-requirements.txt new file mode 100644 index 0000000..3a0d0b9 --- /dev/null +++ b/jellyfish/openapi_client/test-requirements.txt @@ -0,0 +1,3 @@ +pytest~=7.1.3 +pytest-cov>=2.8.1 +pytest-randomly>=3.12.0 diff --git a/jellyfish/openapi_client/test/__init__.py b/jellyfish/openapi_client/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/jellyfish/openapi_client/test/test_add_component_request.py b/jellyfish/openapi_client/test/test_add_component_request.py new file mode 100644 index 0000000..e8c1491 --- /dev/null +++ b/jellyfish/openapi_client/test/test_add_component_request.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.add_component_request import AddComponentRequest # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestAddComponentRequest(unittest.TestCase): + """AddComponentRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AddComponentRequest + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AddComponentRequest` + """ + model = jellyfish_openapi_client.models.add_component_request.AddComponentRequest() # noqa: E501 + if include_optional : + return AddComponentRequest( + options = jellyfish_openapi_client.models.component_options.ComponentOptions(), + type = 'hls' + ) + else : + return AddComponentRequest( + options = jellyfish_openapi_client.models.component_options.ComponentOptions(), + type = 'hls', + ) + """ + + def testAddComponentRequest(self): + """Test AddComponentRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_add_peer_request.py b/jellyfish/openapi_client/test/test_add_peer_request.py new file mode 100644 index 0000000..2cb4131 --- /dev/null +++ b/jellyfish/openapi_client/test/test_add_peer_request.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestAddPeerRequest(unittest.TestCase): + """AddPeerRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AddPeerRequest + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AddPeerRequest` + """ + model = jellyfish_openapi_client.models.add_peer_request.AddPeerRequest() # noqa: E501 + if include_optional : + return AddPeerRequest( + options = jellyfish_openapi_client.models.peer_options.PeerOptions(), + type = 'webrtc' + ) + else : + return AddPeerRequest( + options = jellyfish_openapi_client.models.peer_options.PeerOptions(), + type = 'webrtc', + ) + """ + + def testAddPeerRequest(self): + """Test AddPeerRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_component.py b/jellyfish/openapi_client/test/test_component.py new file mode 100644 index 0000000..a9a3fcb --- /dev/null +++ b/jellyfish/openapi_client/test/test_component.py @@ -0,0 +1,61 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.component import Component # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestComponent(unittest.TestCase): + """Component unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test Component + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Component` + """ + model = jellyfish_openapi_client.models.component.Component() # noqa: E501 + if include_optional : + return Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls' + ) + else : + return Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', + ) + """ + + def testComponent(self): + """Test Component""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_component_details_response.py b/jellyfish/openapi_client/test/test_component_details_response.py new file mode 100644 index 0000000..056e056 --- /dev/null +++ b/jellyfish/openapi_client/test/test_component_details_response.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestComponentDetailsResponse(unittest.TestCase): + """ComponentDetailsResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test ComponentDetailsResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ComponentDetailsResponse` + """ + model = jellyfish_openapi_client.models.component_details_response.ComponentDetailsResponse() # noqa: E501 + if include_optional : + return ComponentDetailsResponse( + data = jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ) + else : + return ComponentDetailsResponse( + data = jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ), + ) + """ + + def testComponentDetailsResponse(self): + """Test ComponentDetailsResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_component_metadata.py b/jellyfish/openapi_client/test/test_component_metadata.py new file mode 100644 index 0000000..c37075c --- /dev/null +++ b/jellyfish/openapi_client/test/test_component_metadata.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.component_metadata import ComponentMetadata # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestComponentMetadata(unittest.TestCase): + """ComponentMetadata unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test ComponentMetadata + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ComponentMetadata` + """ + model = jellyfish_openapi_client.models.component_metadata.ComponentMetadata() # noqa: E501 + if include_optional : + return ComponentMetadata( + playable = True + ) + else : + return ComponentMetadata( + ) + """ + + def testComponentMetadata(self): + """Test ComponentMetadata""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_component_options.py b/jellyfish/openapi_client/test/test_component_options.py new file mode 100644 index 0000000..0f8323b --- /dev/null +++ b/jellyfish/openapi_client/test/test_component_options.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.component_options import ComponentOptions # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestComponentOptions(unittest.TestCase): + """ComponentOptions unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test ComponentOptions + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ComponentOptions` + """ + model = jellyfish_openapi_client.models.component_options.ComponentOptions() # noqa: E501 + if include_optional : + return ComponentOptions( + keep_alive_interval = 0, + pierce_nat = True, + reconnect_delay = 0, + rtp_port = 1, + source_uri = 'rtsp://localhost:554/stream' + ) + else : + return ComponentOptions( + source_uri = 'rtsp://localhost:554/stream', + ) + """ + + def testComponentOptions(self): + """Test ComponentOptions""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_component_options_rtsp.py b/jellyfish/openapi_client/test/test_component_options_rtsp.py new file mode 100644 index 0000000..2c31369 --- /dev/null +++ b/jellyfish/openapi_client/test/test_component_options_rtsp.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestComponentOptionsRTSP(unittest.TestCase): + """ComponentOptionsRTSP unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test ComponentOptionsRTSP + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ComponentOptionsRTSP` + """ + model = jellyfish_openapi_client.models.component_options_rtsp.ComponentOptionsRTSP() # noqa: E501 + if include_optional : + return ComponentOptionsRTSP( + keep_alive_interval = 0, + pierce_nat = True, + reconnect_delay = 0, + rtp_port = 1, + source_uri = 'rtsp://localhost:554/stream' + ) + else : + return ComponentOptionsRTSP( + source_uri = 'rtsp://localhost:554/stream', + ) + """ + + def testComponentOptionsRTSP(self): + """Test ComponentOptionsRTSP""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_default_api.py b/jellyfish/openapi_client/test/test_default_api.py new file mode 100644 index 0000000..b4f5cc5 --- /dev/null +++ b/jellyfish/openapi_client/test/test_default_api.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +import jellyfish_openapi_client +from jellyfish_openapi_client.api.default_api import DefaultApi # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + + +class TestDefaultApi(unittest.TestCase): + """DefaultApi unit test stubs""" + + def setUp(self): + self.api = jellyfish_openapi_client.api.default_api.DefaultApi() # noqa: E501 + + def tearDown(self): + pass + + def test_jellyfish_web_hls_controller_index(self): + """Test case for jellyfish_web_hls_controller_index + + Send file # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_error.py b/jellyfish/openapi_client/test/test_error.py new file mode 100644 index 0000000..b825fe3 --- /dev/null +++ b/jellyfish/openapi_client/test/test_error.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.error import Error # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestError(unittest.TestCase): + """Error unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test Error + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Error` + """ + model = jellyfish_openapi_client.models.error.Error() # noqa: E501 + if include_optional : + return Error( + errors = 'Token has expired' + ) + else : + return Error( + errors = 'Token has expired', + ) + """ + + def testError(self): + """Test Error""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_hls_skip.py b/jellyfish/openapi_client/test/test_hls_skip.py new file mode 100644 index 0000000..0aa9883 --- /dev/null +++ b/jellyfish/openapi_client/test/test_hls_skip.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.hls_skip import HlsSkip # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestHlsSkip(unittest.TestCase): + """HlsSkip unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testHlsSkip(self): + """Test HlsSkip""" + # inst = HlsSkip() + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer.py b/jellyfish/openapi_client/test/test_peer.py new file mode 100644 index 0000000..468964b --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer import Peer # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeer(unittest.TestCase): + """Peer unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test Peer + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Peer` + """ + model = jellyfish_openapi_client.models.peer.Peer() # noqa: E501 + if include_optional : + return Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc' + ) + else : + return Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', + ) + """ + + def testPeer(self): + """Test Peer""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer_details_response.py b/jellyfish/openapi_client/test/test_peer_details_response.py new file mode 100644 index 0000000..6f631c2 --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer_details_response.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeerDetailsResponse(unittest.TestCase): + """PeerDetailsResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test PeerDetailsResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PeerDetailsResponse` + """ + model = jellyfish_openapi_client.models.peer_details_response.PeerDetailsResponse() # noqa: E501 + if include_optional : + return PeerDetailsResponse( + data = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( + peer = jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ), + token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', ) + ) + else : + return PeerDetailsResponse( + data = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( + peer = jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ), + token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', ), + ) + """ + + def testPeerDetailsResponse(self): + """Test PeerDetailsResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer_details_response_data.py b/jellyfish/openapi_client/test/test_peer_details_response_data.py new file mode 100644 index 0000000..0a26c24 --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer_details_response_data.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeerDetailsResponseData(unittest.TestCase): + """PeerDetailsResponseData unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test PeerDetailsResponseData + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PeerDetailsResponseData` + """ + model = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponseData() # noqa: E501 + if include_optional : + return PeerDetailsResponseData( + peer = jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ), + token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242' + ) + else : + return PeerDetailsResponseData( + peer = jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ), + token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', + ) + """ + + def testPeerDetailsResponseData(self): + """Test PeerDetailsResponseData""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer_options.py b/jellyfish/openapi_client/test/test_peer_options.py new file mode 100644 index 0000000..3a010ad --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer_options.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer_options import PeerOptions # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeerOptions(unittest.TestCase): + """PeerOptions unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test PeerOptions + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PeerOptions` + """ + model = jellyfish_openapi_client.models.peer_options.PeerOptions() # noqa: E501 + if include_optional : + return PeerOptions( + enable_simulcast = True + ) + else : + return PeerOptions( + ) + """ + + def testPeerOptions(self): + """Test PeerOptions""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer_options_web_rtc.py b/jellyfish/openapi_client/test/test_peer_options_web_rtc.py new file mode 100644 index 0000000..d5bb003 --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer_options_web_rtc.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeerOptionsWebRTC(unittest.TestCase): + """PeerOptionsWebRTC unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test PeerOptionsWebRTC + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `PeerOptionsWebRTC` + """ + model = jellyfish_openapi_client.models.peer_options_web_rtc.PeerOptionsWebRTC() # noqa: E501 + if include_optional : + return PeerOptionsWebRTC( + enable_simulcast = True + ) + else : + return PeerOptionsWebRTC( + ) + """ + + def testPeerOptionsWebRTC(self): + """Test PeerOptionsWebRTC""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_peer_status.py b/jellyfish/openapi_client/test/test_peer_status.py new file mode 100644 index 0000000..77d3bc3 --- /dev/null +++ b/jellyfish/openapi_client/test/test_peer_status.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.peer_status import PeerStatus # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestPeerStatus(unittest.TestCase): + """PeerStatus unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testPeerStatus(self): + """Test PeerStatus""" + # inst = PeerStatus() + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room.py b/jellyfish/openapi_client/test/test_room.py new file mode 100644 index 0000000..4b5a424 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room import Room # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoom(unittest.TestCase): + """Room unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test Room + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Room` + """ + model = jellyfish_openapi_client.models.room.Room() # noqa: E501 + if include_optional : + return Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ] + ) + else : + return Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], + ) + """ + + def testRoom(self): + """Test Room""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room_api.py b/jellyfish/openapi_client/test/test_room_api.py new file mode 100644 index 0000000..4052620 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room_api.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +import jellyfish_openapi_client +from jellyfish_openapi_client.api.room_api import RoomApi # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + + +class TestRoomApi(unittest.TestCase): + """RoomApi unit test stubs""" + + def setUp(self): + self.api = jellyfish_openapi_client.api.room_api.RoomApi() # noqa: E501 + + def tearDown(self): + pass + + def test_add_component(self): + """Test case for add_component + + Creates the component and adds it to the room # noqa: E501 + """ + pass + + def test_add_peer(self): + """Test case for add_peer + + Create peer # noqa: E501 + """ + pass + + def test_create_room(self): + """Test case for create_room + + Creates a room # noqa: E501 + """ + pass + + def test_delete_component(self): + """Test case for delete_component + + Delete the component from the room # noqa: E501 + """ + pass + + def test_delete_peer(self): + """Test case for delete_peer + + Delete peer # noqa: E501 + """ + pass + + def test_delete_room(self): + """Test case for delete_room + + Delete the room # noqa: E501 + """ + pass + + def test_get_all_rooms(self): + """Test case for get_all_rooms + + Show information about all rooms # noqa: E501 + """ + pass + + def test_get_room(self): + """Test case for get_room + + Shows information about the room # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room_config.py b/jellyfish/openapi_client/test/test_room_config.py new file mode 100644 index 0000000..085f8c9 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room_config.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_config import RoomConfig # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoomConfig(unittest.TestCase): + """RoomConfig unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test RoomConfig + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RoomConfig` + """ + model = jellyfish_openapi_client.models.room_config.RoomConfig() # noqa: E501 + if include_optional : + return RoomConfig( + max_peers = 10, + video_codec = 'h264' + ) + else : + return RoomConfig( + ) + """ + + def testRoomConfig(self): + """Test RoomConfig""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room_create_details_response.py b/jellyfish/openapi_client/test/test_room_create_details_response.py new file mode 100644 index 0000000..0027583 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room_create_details_response.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoomCreateDetailsResponse(unittest.TestCase): + """RoomCreateDetailsResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test RoomCreateDetailsResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RoomCreateDetailsResponse` + """ + model = jellyfish_openapi_client.models.room_create_details_response.RoomCreateDetailsResponse() # noqa: E501 + if include_optional : + return RoomCreateDetailsResponse( + data = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( + jellyfish_address = 'jellyfish1:5003', + room = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ), ) + ) + else : + return RoomCreateDetailsResponse( + data = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( + jellyfish_address = 'jellyfish1:5003', + room = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ), ), + ) + """ + + def testRoomCreateDetailsResponse(self): + """Test RoomCreateDetailsResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room_create_details_response_data.py b/jellyfish/openapi_client/test/test_room_create_details_response_data.py new file mode 100644 index 0000000..cefc635 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room_create_details_response_data.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoomCreateDetailsResponseData(unittest.TestCase): + """RoomCreateDetailsResponseData unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test RoomCreateDetailsResponseData + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RoomCreateDetailsResponseData` + """ + model = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponseData() # noqa: E501 + if include_optional : + return RoomCreateDetailsResponseData( + jellyfish_address = 'jellyfish1:5003', + room = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ) + ) + else : + return RoomCreateDetailsResponseData( + jellyfish_address = 'jellyfish1:5003', + room = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ), + ) + """ + + def testRoomCreateDetailsResponseData(self): + """Test RoomCreateDetailsResponseData""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_room_details_response.py b/jellyfish/openapi_client/test/test_room_details_response.py new file mode 100644 index 0000000..bd82c93 --- /dev/null +++ b/jellyfish/openapi_client/test/test_room_details_response.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoomDetailsResponse(unittest.TestCase): + """RoomDetailsResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test RoomDetailsResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RoomDetailsResponse` + """ + model = jellyfish_openapi_client.models.room_details_response.RoomDetailsResponse() # noqa: E501 + if include_optional : + return RoomDetailsResponse( + data = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ) + ) + else : + return RoomDetailsResponse( + data = jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ), + ) + """ + + def testRoomDetailsResponse(self): + """Test RoomDetailsResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/test/test_rooms_listing_response.py b/jellyfish/openapi_client/test/test_rooms_listing_response.py new file mode 100644 index 0000000..3ea8d82 --- /dev/null +++ b/jellyfish/openapi_client/test/test_rooms_listing_response.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +import jellyfish_openapi_client +from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse # noqa: E501 +from jellyfish_openapi_client.rest import ApiException + +class TestRoomsListingResponse(unittest.TestCase): + """RoomsListingResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test RoomsListingResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RoomsListingResponse` + """ + model = jellyfish_openapi_client.models.rooms_listing_response.RoomsListingResponse() # noqa: E501 + if include_optional : + return RoomsListingResponse( + data = [ + jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ) + ] + ) + else : + return RoomsListingResponse( + data = [ + jellyfish_openapi_client.models.room.Room( + components = [ + jellyfish_openapi_client.models.component.Component( + id = 'component-1', + metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + playable = True, ), + type = 'hls', ) + ], + config = jellyfish_openapi_client.models.room_config.RoomConfig( + max_peers = 10, + video_codec = 'h264', ), + id = 'room-1', + peers = [ + jellyfish_openapi_client.models.peer.Peer( + id = 'peer-1', + status = 'disconnected', + type = 'webrtc', ) + ], ) + ], + ) + """ + + def testRoomsListingResponse(self): + """Test RoomsListingResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/jellyfish/openapi_client/tox.ini b/jellyfish/openapi_client/tox.ini new file mode 100644 index 0000000..b47cf30 --- /dev/null +++ b/jellyfish/openapi_client/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=jellyfish_openapi_client diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py index e4633ec..ad47b8b 100644 --- a/jellyfish/room_api.py +++ b/jellyfish/room_api.py @@ -1,6 +1,6 @@ import time import jellyfish_openapi_client as jellyfish_api -from jellyfish_api.rest import ApiException +from jellyfish_openapi_client.rest import ApiException from jellyfish_openapi_client import Room, RoomConfig @@ -19,7 +19,7 @@ def create_room(self, max_peers: int = None, video_codec: str = None) -> Room: """Creates a room""" room_config = RoomConfig(maxPeers=max_peers, videoCodec=video_codec) - room = self._room_api.create(room_config) + room = self._room_api.create_room(room_config) return (room.data.jellyfish_address, room.data.room) From fe3d15f5e90ce8269bafbea8d93ea3a6e5da8315 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 11:16:37 +0200 Subject: [PATCH 07/20] Add circleCI config --- .circleci/config.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .circleci/config.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..28025f5 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,24 @@ +version: 2.1 + +orbs: + python: circleci/python@2.0.3 + +jobs: + build_and_test: + executor: python/default + steps: + - checkout # checkout source code + - python/install-packages: + pkg-manager: pip + - run: + name: Run tests + command: python -m pytest + - persist_to_workspace: + root: ~/project + paths: + - . + +workflows: + test_my_app: + jobs: + - build_and_test \ No newline at end of file From 5847bb4d122e67f0825e4abb3e6f286497719eb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 12:02:58 +0200 Subject: [PATCH 08/20] Setup lint --- .circleci/config.yml | 12 +- jellyfish/__init__.py | 2 +- jellyfish/setup.py | 4 +- openapitools.json | 7 + pylintrc | 631 +++++++++++++++++++++++++++++++++++++++++ requirements.txt | 8 +- tests/test_room_api.py | 39 ++- 7 files changed, 671 insertions(+), 32 deletions(-) create mode 100644 openapitools.json create mode 100644 pylintrc diff --git a/.circleci/config.yml b/.circleci/config.yml index 28025f5..76bb0a0 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,21 +4,21 @@ orbs: python: circleci/python@2.0.3 jobs: - build_and_test: + lint: executor: python/default steps: - - checkout # checkout source code + - checkout - python/install-packages: pkg-manager: pip - run: - name: Run tests - command: python -m pytest + name: Lint + command: pylint --rcfile=pylintrc jellyfish tests - persist_to_workspace: root: ~/project paths: - . workflows: - test_my_app: + build: jobs: - - build_and_test \ No newline at end of file + - lint \ No newline at end of file diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py index 8f82a63..ad172ed 100644 --- a/jellyfish/__init__.py +++ b/jellyfish/__init__.py @@ -4,7 +4,7 @@ __version__ = "0.1.0" -from pydantic.error_wrappers import ValidationError +from pydantic.error_wrappers import ValidationError # pylint: disable=no-name-in-module from jellyfish_openapi_client import Room, RoomConfig, Peer, Component from jellyfish_openapi_client import ComponentOptionsRTSP diff --git a/jellyfish/setup.py b/jellyfish/setup.py index 23917d0..76e8ff9 100644 --- a/jellyfish/setup.py +++ b/jellyfish/setup.py @@ -1,5 +1,7 @@ # coding: utf-8 +# pylint: disable=locally-disabled, line-too-long + """ Jellyfish Media Server @@ -9,7 +11,7 @@ Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manually. -""" # noqa: E501 +""" from setuptools import setup, find_packages # noqa: H301 diff --git a/openapitools.json b/openapitools.json new file mode 100644 index 0000000..3015568 --- /dev/null +++ b/openapitools.json @@ -0,0 +1,7 @@ +{ + "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "7.0.0" + } +} diff --git a/pylintrc b/pylintrc new file mode 100644 index 0000000..9078b89 --- /dev/null +++ b/pylintrc @@ -0,0 +1,631 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.11 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work.. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/requirements.txt b/requirements.txt index 55b033e..e2f6c56 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,7 @@ -pytest \ No newline at end of file +aenum==3.1.15 +pydantic==1.10.12 +pytest==7.1.3 +python_dateutil==2.8.2 +setuptools==67.6.1 +typing_extensions==4.7.1 +urllib3==2.0.4 diff --git a/tests/test_room_api.py b/tests/test_room_api.py index 665722c..a1f64f0 100644 --- a/tests/test_room_api.py +++ b/tests/test_room_api.py @@ -1,13 +1,16 @@ -# pylint: disable=locally-disabled, missing-class-docstring, missing-function-docstring +# pylint: disable=locally-disabled, missing-class-docstring, missing-function-docstring, redefined-outer-name, too-few-public-methods + +""" + Tests room api +""" + -import random import pytest import jellyfish -import pydantic from jellyfish import RoomApi, RoomConfig -from jellyfish import Room, Peer, Component +from jellyfish import Room, Component from jellyfish import ComponentOptionsRTSP, PeerOptionsWebRTC from jellyfish import ValidationError @@ -23,20 +26,8 @@ COMPONENT_RTSP = "rtsp" HLS_OPTIONS = None -RTSP_OPTIONS = ComponentOptionsRTSP(sourceUri="rtsp://ef36c6dff23ecc5bbe311cc880d95dc8.se:2137/does/not/matter") - - -def test_create_room_client(): - with pytest.raises(TypeError): - RoomApi() - - with pytest.raises(TypeError): - RoomApi(server_address="address") - - with pytest.raises(TypeError): - RoomApi(server_api_token="api_token") - - RoomApi(server_address="address", server_api_token="api_token") +RTSP_OPTIONS = ComponentOptionsRTSP( + sourceUri="rtsp://ef36c6dff23ecc5bbe311cc880d95dc8.se:2137/does/not/matter") class TestAuthentication: @@ -73,8 +64,8 @@ def test_no_params(self, room_api): def test_valid_params(self, room_api): _, room = room_api.create_room(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC) - assert room == Room(components=[], config=RoomConfig(max_peers=MAX_PEERS, video_codec=VIDEO_CODEC), - id=room.id, peers=[]) + assert room == Room(components=[], config=RoomConfig( + max_peers=MAX_PEERS, video_codec=VIDEO_CODEC), id=room.id, peers=[]) assert room in room_api.get_all_rooms() def test_invalid_max_peers(self, room_api): @@ -164,7 +155,8 @@ class TestAddPeer: def test_valid(self, room_api: RoomApi): room_id = room_api.create_room().id - peer = room_api.add_peer(room_id, type="webrtc", options=PeerOptionsWebRTC(enableSimulcast=True)) + peer = room_api.add_peer(room_id, type="webrtc", + options=PeerOptionsWebRTC(enableSimulcast=True)) assert peer.status == "disconnected" assert peer.type == "webrtc" @@ -182,7 +174,8 @@ def test_invalid(self, room_api: RoomApi): class TestDeletePeer: def test_valid(self, room_api: RoomApi): room_id = room_api.create_room().id - peer = room_api.add_peer(room_id, type="webrtc", options=PeerOptionsWebRTC(enableSimulcast=True)) + peer = room_api.add_peer(room_id, type="webrtc", + options=PeerOptionsWebRTC(enableSimulcast=True)) room_api.delete_peer(peer.id) @@ -192,4 +185,4 @@ def test_invalid(self, room_api: RoomApi): room_id = room_api.create_room().id with pytest.raises(NotImplementedError): - room_api.delete_peer("invalid_peer_id") + room_api.delete_peer(room_id, peer_id="invalid_peer_id") From b890d81ff56a8751611185469a091c59a7bd3568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 12:04:28 +0200 Subject: [PATCH 09/20] Add pylint to reqs --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index e2f6c56..ffb4ad9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ python_dateutil==2.8.2 setuptools==67.6.1 typing_extensions==4.7.1 urllib3==2.0.4 +pylint==2.17.5 \ No newline at end of file From ccf6cfad12add7b73b2ad4fbb23f677c4ebc4f42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 12:21:07 +0200 Subject: [PATCH 10/20] Fix imports --- jellyfish/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py index ad172ed..16ffeed 100644 --- a/jellyfish/__init__.py +++ b/jellyfish/__init__.py @@ -6,8 +6,8 @@ from pydantic.error_wrappers import ValidationError # pylint: disable=no-name-in-module -from jellyfish_openapi_client import Room, RoomConfig, Peer, Component -from jellyfish_openapi_client import ComponentOptionsRTSP -from jellyfish_openapi_client import PeerOptionsWebRTC - from jellyfish.room_api import RoomApi + +from .openapi_client.jellyfish_openapi_client import Room, RoomConfig, Peer, Component +from .openapi_client.jellyfish_openapi_client import ComponentOptionsRTSP +from .openapi_client.jellyfish_openapi_client import PeerOptionsWebRTC From 4ae9cca5d0e9dc091a62f606d986a5343480e293 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Tue, 5 Sep 2023 12:24:44 +0200 Subject: [PATCH 11/20] Add test to CI --- .circleci/config.yml | 19 ++++++++++++++++++- ...r-compose.yaml => docker-compose-test.yaml | 0 2 files changed, 18 insertions(+), 1 deletion(-) rename docker-compose.yaml => docker-compose-test.yaml (100%) diff --git a/.circleci/config.yml b/.circleci/config.yml index 76bb0a0..895d348 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,6 +3,15 @@ version: 2.1 orbs: python: circleci/python@2.0.3 +executors: + machine_executor_amd64: + machine: + image: ubuntu-2204:2022.04.2 + environment: + architecture: "amd64" + platform: "linux/amd64" + + jobs: lint: executor: python/default @@ -17,8 +26,16 @@ jobs: root: ~/project paths: - . + + test: + executor: machine_executor_amd64 + steps: + - checkout + - run: docker compose -f docker-compose-test.yaml run test + workflows: build: jobs: - - lint \ No newline at end of file + - lint + - test \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose-test.yaml similarity index 100% rename from docker-compose.yaml rename to docker-compose-test.yaml From 3f8c395178d6c3f5f03886d9b9423be0a71148b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 7 Sep 2023 11:58:21 +0200 Subject: [PATCH 12/20] Fix lint --- generate_client.sh | 6 +- jellyfish/__init__.py | 13 +- .../openapi_client/.openapi-generator/FILES | 92 -------------- .../jellyfish_openapi_client/__init__.py | 55 -------- .../jellyfish_openapi_client/api/__init__.py | 6 - .../models/__init__.py | 37 ------ jellyfish/room_api.py | 70 +++++++--- .../.github/workflows/python.yml | 2 +- .../openapi_client => openapi}/.gitignore | 0 .../openapi_client => openapi}/.gitlab-ci.yml | 2 +- .../.openapi-generator-ignore | 0 openapi/.openapi-generator/FILES | 92 ++++++++++++++ .../.openapi-generator/VERSION | 0 .../openapi_client => openapi}/.travis.yml | 2 +- .../openapi_client => openapi}/README.md | 20 +-- .../docs/AddComponentRequest.md | 4 +- .../docs/AddPeerRequest.md | 2 +- .../docs/Component.md | 2 +- .../docs/ComponentDetailsResponse.md | 2 +- .../docs/ComponentMetadata.md | 2 +- .../docs/ComponentOptions.md | 2 +- .../docs/ComponentOptionsRTSP.md | 2 +- .../docs/DefaultApi.md | 18 +-- .../openapi_client => openapi}/docs/Error.md | 2 +- .../docs/HlsSkip.md | 0 .../openapi_client => openapi}/docs/Peer.md | 2 +- .../docs/PeerDetailsResponse.md | 2 +- .../docs/PeerDetailsResponseData.md | 2 +- .../docs/PeerOptions.md | 2 +- .../docs/PeerOptionsWebRTC.md | 2 +- .../docs/PeerStatus.md | 0 .../openapi_client => openapi}/docs/Room.md | 2 +- .../docs/RoomApi.md | 120 +++++++++--------- .../docs/RoomConfig.md | 2 +- .../docs/RoomCreateDetailsResponse.md | 2 +- .../docs/RoomCreateDetailsResponseData.md | 2 +- .../docs/RoomDetailsResponse.md | 2 +- .../docs/RoomsListingResponse.md | 2 +- .../openapi_client => openapi}/git_push.sh | 0 openapi/openapi_client/__init__.py | 55 ++++++++ openapi/openapi_client/api/__init__.py | 6 + .../openapi_client}/api/default_api.py | 8 +- .../openapi_client}/api/room_api.py | 24 ++-- .../openapi_client}/api_client.py | 12 +- .../openapi_client}/api_response.py | 0 .../openapi_client}/configuration.py | 4 +- .../openapi_client}/exceptions.py | 0 openapi/openapi_client/models/__init__.py | 37 ++++++ .../models/add_component_request.py | 11 +- .../models/add_peer_request.py | 2 +- .../openapi_client}/models/component.py | 2 +- .../models/component_details_response.py | 2 +- .../models/component_metadata.py | 0 .../models/component_options.py | 41 +++--- .../models/component_options_rtsp.py | 0 .../openapi_client}/models/error.py | 0 .../openapi_client}/models/hls_skip.py | 0 .../openapi_client}/models/peer.py | 2 +- .../models/peer_details_response.py | 2 +- .../models/peer_details_response_data.py | 2 +- .../openapi_client}/models/peer_options.py | 2 +- .../models/peer_options_web_rtc.py | 0 .../openapi_client}/models/peer_status.py | 0 .../openapi_client}/models/room.py | 6 +- .../openapi_client}/models/room_config.py | 0 .../models/room_create_details_response.py | 2 +- .../room_create_details_response_data.py | 2 +- .../models/room_details_response.py | 2 +- .../models/rooms_listing_response.py | 2 +- .../openapi_client}/py.typed | 0 .../openapi_client}/rest.py | 2 +- .../openapi_client => openapi}/pyproject.toml | 4 +- .../requirements.txt | 0 .../openapi_client => openapi}/setup.cfg | 0 .../openapi_client => openapi}/setup.py | 4 +- .../test-requirements.txt | 0 .../test/__init__.py | 0 .../test/test_add_component_request.py | 11 +- .../test/test_add_peer_request.py | 12 +- .../test/test_component.py | 12 +- .../test/test_component_details_response.py | 16 +-- .../test/test_component_metadata.py | 8 +- .../test/test_component_options.py | 8 +- .../test/test_component_options_rtsp.py | 8 +- .../test/test_default_api.py | 8 +- .../test/test_error.py | 8 +- .../test/test_hls_skip.py | 6 +- .../test/test_peer.py | 8 +- .../test/test_peer_details_response.py | 16 +-- .../test/test_peer_details_response_data.py | 12 +- .../test/test_peer_options.py | 8 +- .../test/test_peer_options_web_rtc.py | 8 +- .../test/test_peer_status.py | 6 +- .../test/test_room.py | 24 ++-- .../test/test_room_api.py | 8 +- .../test/test_room_config.py | 8 +- .../test/test_room_create_details_response.py | 32 ++--- .../test_room_create_details_response_data.py | 28 ++-- .../test/test_room_details_response.py | 28 ++-- .../test/test_rooms_listing_response.py | 28 ++-- {jellyfish/openapi_client => openapi}/tox.ini | 2 +- tests/test_room_api.py | 115 +++++++++-------- 102 files changed, 639 insertions(+), 600 deletions(-) delete mode 100644 jellyfish/openapi_client/.openapi-generator/FILES delete mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/__init__.py delete mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py delete mode 100644 jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py rename {jellyfish/openapi_client => openapi}/.github/workflows/python.yml (96%) rename {jellyfish/openapi_client => openapi}/.gitignore (100%) rename {jellyfish/openapi_client => openapi}/.gitlab-ci.yml (92%) rename {jellyfish/openapi_client => openapi}/.openapi-generator-ignore (100%) create mode 100644 openapi/.openapi-generator/FILES rename {jellyfish/openapi_client => openapi}/.openapi-generator/VERSION (100%) rename {jellyfish/openapi_client => openapi}/.travis.yml (89%) rename {jellyfish/openapi_client => openapi}/README.md (90%) rename {jellyfish/openapi_client => openapi}/docs/AddComponentRequest.md (85%) rename {jellyfish/openapi_client => openapi}/docs/AddPeerRequest.md (92%) rename {jellyfish/openapi_client => openapi}/docs/Component.md (93%) rename {jellyfish/openapi_client => openapi}/docs/ComponentDetailsResponse.md (91%) rename {jellyfish/openapi_client => openapi}/docs/ComponentMetadata.md (91%) rename {jellyfish/openapi_client => openapi}/docs/ComponentOptions.md (94%) rename {jellyfish/openapi_client => openapi}/docs/ComponentOptionsRTSP.md (94%) rename {jellyfish/openapi_client => openapi}/docs/DefaultApi.md (84%) rename {jellyfish/openapi_client => openapi}/docs/Error.md (92%) rename {jellyfish/openapi_client => openapi}/docs/HlsSkip.md (100%) rename {jellyfish/openapi_client => openapi}/docs/Peer.md (93%) rename {jellyfish/openapi_client => openapi}/docs/PeerDetailsResponse.md (91%) rename {jellyfish/openapi_client => openapi}/docs/PeerDetailsResponseData.md (91%) rename {jellyfish/openapi_client => openapi}/docs/PeerOptions.md (92%) rename {jellyfish/openapi_client => openapi}/docs/PeerOptionsWebRTC.md (92%) rename {jellyfish/openapi_client => openapi}/docs/PeerStatus.md (100%) rename {jellyfish/openapi_client => openapi}/docs/Room.md (94%) rename {jellyfish/openapi_client => openapi}/docs/RoomApi.md (81%) rename {jellyfish/openapi_client => openapi}/docs/RoomConfig.md (93%) rename {jellyfish/openapi_client => openapi}/docs/RoomCreateDetailsResponse.md (91%) rename {jellyfish/openapi_client => openapi}/docs/RoomCreateDetailsResponseData.md (91%) rename {jellyfish/openapi_client => openapi}/docs/RoomDetailsResponse.md (91%) rename {jellyfish/openapi_client => openapi}/docs/RoomsListingResponse.md (91%) rename {jellyfish/openapi_client => openapi}/git_push.sh (100%) create mode 100644 openapi/openapi_client/__init__.py create mode 100644 openapi/openapi_client/api/__init__.py rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/api/default_api.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/api/room_api.py (98%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/api_client.py (98%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/api_response.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/configuration.py (98%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/exceptions.py (100%) create mode 100644 openapi/openapi_client/models/__init__.py rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/add_component_request.py (86%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/add_peer_request.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/component.py (96%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/component_details_response.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/component_metadata.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/component_options.py (75%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/component_options_rtsp.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/error.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/hls_skip.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer.py (96%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer_details_response.py (95%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer_details_response_data.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer_options.py (98%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer_options_web_rtc.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/peer_status.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/room.py (94%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/room_config.py (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/room_create_details_response.py (95%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/room_create_details_response_data.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/room_details_response.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/models/rooms_listing_response.py (97%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/py.typed (100%) rename {jellyfish/openapi_client/jellyfish_openapi_client => openapi/openapi_client}/rest.py (98%) rename {jellyfish/openapi_client => openapi}/pyproject.toml (89%) rename {jellyfish/openapi_client => openapi}/requirements.txt (100%) rename {jellyfish/openapi_client => openapi}/setup.cfg (100%) rename {jellyfish/openapi_client => openapi}/setup.py (93%) rename {jellyfish/openapi_client => openapi}/test-requirements.txt (100%) rename {jellyfish/openapi_client => openapi}/test/__init__.py (100%) rename {jellyfish/openapi_client => openapi}/test/test_add_component_request.py (73%) rename {jellyfish/openapi_client => openapi}/test/test_add_peer_request.py (74%) rename {jellyfish/openapi_client => openapi}/test/test_component.py (76%) rename {jellyfish/openapi_client => openapi}/test/test_component_details_response.py (70%) rename {jellyfish/openapi_client => openapi}/test/test_component_metadata.py (82%) rename {jellyfish/openapi_client => openapi}/test/test_component_options.py (84%) rename {jellyfish/openapi_client => openapi}/test/test_component_options_rtsp.py (84%) rename {jellyfish/openapi_client => openapi}/test/test_default_api.py (73%) rename {jellyfish/openapi_client => openapi}/test/test_error.py (84%) rename {jellyfish/openapi_client => openapi}/test/test_hls_skip.py (79%) rename {jellyfish/openapi_client => openapi}/test/test_peer.py (85%) rename {jellyfish/openapi_client => openapi}/test/test_peer_details_response.py (72%) rename {jellyfish/openapi_client => openapi}/test/test_peer_details_response_data.py (79%) rename {jellyfish/openapi_client => openapi}/test/test_peer_options.py (83%) rename {jellyfish/openapi_client => openapi}/test/test_peer_options_web_rtc.py (82%) rename {jellyfish/openapi_client => openapi}/test/test_peer_status.py (79%) rename {jellyfish/openapi_client => openapi}/test/test_room.py (71%) rename {jellyfish/openapi_client => openapi}/test/test_room_api.py (87%) rename {jellyfish/openapi_client => openapi}/test/test_room_config.py (83%) rename {jellyfish/openapi_client => openapi}/test/test_room_create_details_response.py (65%) rename {jellyfish/openapi_client => openapi}/test/test_room_create_details_response_data.py (69%) rename {jellyfish/openapi_client => openapi}/test/test_room_details_response.py (68%) rename {jellyfish/openapi_client => openapi}/test/test_rooms_listing_response.py (69%) rename {jellyfish/openapi_client => openapi}/tox.ini (74%) diff --git a/generate_client.sh b/generate_client.sh index 8321793..ab4d53a 100755 --- a/generate_client.sh +++ b/generate_client.sh @@ -1,7 +1,7 @@ -rm -rf jellyfish/openapi_client +rm -rf openapi openapi-generator-cli generate \ -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/openapi-generator-compatibility/openapi.yaml \ -g python \ -t templates \ - --package-name jellyfish_openapi_client \ - -o jellyfish/openapi_client \ No newline at end of file + -o openapi \ + --package-name openapi_client \ No newline at end of file diff --git a/jellyfish/__init__.py b/jellyfish/__init__.py index 16ffeed..7f9cde3 100644 --- a/jellyfish/__init__.py +++ b/jellyfish/__init__.py @@ -4,10 +4,13 @@ __version__ = "0.1.0" -from pydantic.error_wrappers import ValidationError # pylint: disable=no-name-in-module +# pylint: disable=locally-disabled, no-name-in-module, import-error -from jellyfish.room_api import RoomApi +from pydantic.error_wrappers import ValidationError + +from openapi_client import Room, RoomConfig, Peer, Component +from openapi_client import ComponentOptions, ComponentOptionsRTSP, PeerOptionsWebRTC -from .openapi_client.jellyfish_openapi_client import Room, RoomConfig, Peer, Component -from .openapi_client.jellyfish_openapi_client import ComponentOptionsRTSP -from .openapi_client.jellyfish_openapi_client import PeerOptionsWebRTC +from openapi_client.exceptions import UnauthorizedException, NotFoundException, BadRequestException + +from jellyfish.room_api import RoomApi diff --git a/jellyfish/openapi_client/.openapi-generator/FILES b/jellyfish/openapi_client/.openapi-generator/FILES deleted file mode 100644 index 8f966b2..0000000 --- a/jellyfish/openapi_client/.openapi-generator/FILES +++ /dev/null @@ -1,92 +0,0 @@ -.github/workflows/python.yml -.gitignore -.gitlab-ci.yml -.openapi-generator-ignore -.travis.yml -README.md -docs/AddComponentRequest.md -docs/AddPeerRequest.md -docs/Component.md -docs/ComponentDetailsResponse.md -docs/ComponentMetadata.md -docs/ComponentOptions.md -docs/ComponentOptionsRTSP.md -docs/DefaultApi.md -docs/Error.md -docs/HlsSkip.md -docs/Peer.md -docs/PeerDetailsResponse.md -docs/PeerDetailsResponseData.md -docs/PeerOptions.md -docs/PeerOptionsWebRTC.md -docs/PeerStatus.md -docs/Room.md -docs/RoomApi.md -docs/RoomConfig.md -docs/RoomCreateDetailsResponse.md -docs/RoomCreateDetailsResponseData.md -docs/RoomDetailsResponse.md -docs/RoomsListingResponse.md -git_push.sh -jellyfish_openapi_client/__init__.py -jellyfish_openapi_client/api/__init__.py -jellyfish_openapi_client/api/default_api.py -jellyfish_openapi_client/api/room_api.py -jellyfish_openapi_client/api_client.py -jellyfish_openapi_client/api_response.py -jellyfish_openapi_client/configuration.py -jellyfish_openapi_client/exceptions.py -jellyfish_openapi_client/models/__init__.py -jellyfish_openapi_client/models/add_component_request.py -jellyfish_openapi_client/models/add_peer_request.py -jellyfish_openapi_client/models/component.py -jellyfish_openapi_client/models/component_details_response.py -jellyfish_openapi_client/models/component_metadata.py -jellyfish_openapi_client/models/component_options.py -jellyfish_openapi_client/models/component_options_rtsp.py -jellyfish_openapi_client/models/error.py -jellyfish_openapi_client/models/hls_skip.py -jellyfish_openapi_client/models/peer.py -jellyfish_openapi_client/models/peer_details_response.py -jellyfish_openapi_client/models/peer_details_response_data.py -jellyfish_openapi_client/models/peer_options.py -jellyfish_openapi_client/models/peer_options_web_rtc.py -jellyfish_openapi_client/models/peer_status.py -jellyfish_openapi_client/models/room.py -jellyfish_openapi_client/models/room_config.py -jellyfish_openapi_client/models/room_create_details_response.py -jellyfish_openapi_client/models/room_create_details_response_data.py -jellyfish_openapi_client/models/room_details_response.py -jellyfish_openapi_client/models/rooms_listing_response.py -jellyfish_openapi_client/py.typed -jellyfish_openapi_client/rest.py -pyproject.toml -requirements.txt -setup.cfg -setup.py -test-requirements.txt -test/__init__.py -test/test_add_component_request.py -test/test_add_peer_request.py -test/test_component.py -test/test_component_details_response.py -test/test_component_metadata.py -test/test_component_options.py -test/test_component_options_rtsp.py -test/test_default_api.py -test/test_error.py -test/test_hls_skip.py -test/test_peer.py -test/test_peer_details_response.py -test/test_peer_details_response_data.py -test/test_peer_options.py -test/test_peer_options_web_rtc.py -test/test_peer_status.py -test/test_room.py -test/test_room_api.py -test/test_room_config.py -test/test_room_create_details_response.py -test/test_room_create_details_response_data.py -test/test_room_details_response.py -test/test_rooms_listing_response.py -tox.ini diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py deleted file mode 100644 index 2e35e28..0000000 --- a/jellyfish/openapi_client/jellyfish_openapi_client/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -__version__ = "1.0.0" - -# import apis into sdk package -from jellyfish_openapi_client.api.default_api import DefaultApi -from jellyfish_openapi_client.api.room_api import RoomApi - -# import ApiClient -from jellyfish_openapi_client.api_response import ApiResponse -from jellyfish_openapi_client.api_client import ApiClient -from jellyfish_openapi_client.configuration import Configuration -from jellyfish_openapi_client.exceptions import OpenApiException -from jellyfish_openapi_client.exceptions import ApiTypeError -from jellyfish_openapi_client.exceptions import ApiValueError -from jellyfish_openapi_client.exceptions import ApiKeyError -from jellyfish_openapi_client.exceptions import ApiAttributeError -from jellyfish_openapi_client.exceptions import ApiException - -# import models into sdk package -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest -from jellyfish_openapi_client.models.component import Component -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse -from jellyfish_openapi_client.models.component_metadata import ComponentMetadata -from jellyfish_openapi_client.models.component_options import ComponentOptions -from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP -from jellyfish_openapi_client.models.error import Error -from jellyfish_openapi_client.models.hls_skip import HlsSkip -from jellyfish_openapi_client.models.peer import Peer -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse -from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData -from jellyfish_openapi_client.models.peer_options import PeerOptions -from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC -from jellyfish_openapi_client.models.peer_status import PeerStatus -from jellyfish_openapi_client.models.room import Room -from jellyfish_openapi_client.models.room_config import RoomConfig -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse -from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py deleted file mode 100644 index e62e609..0000000 --- a/jellyfish/openapi_client/jellyfish_openapi_client/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# flake8: noqa - -# import apis into api package -from jellyfish_openapi_client.api.default_api import DefaultApi -from jellyfish_openapi_client.api.room_api import RoomApi - diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py b/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py deleted file mode 100644 index bd70acb..0000000 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -# import models into model package -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest -from jellyfish_openapi_client.models.component import Component -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse -from jellyfish_openapi_client.models.component_metadata import ComponentMetadata -from jellyfish_openapi_client.models.component_options import ComponentOptions -from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP -from jellyfish_openapi_client.models.error import Error -from jellyfish_openapi_client.models.hls_skip import HlsSkip -from jellyfish_openapi_client.models.peer import Peer -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse -from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData -from jellyfish_openapi_client.models.peer_options import PeerOptions -from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC -from jellyfish_openapi_client.models.peer_status import PeerStatus -from jellyfish_openapi_client.models.room import Room -from jellyfish_openapi_client.models.room_config import RoomConfig -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse -from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py index ad47b8b..72be4ce 100644 --- a/jellyfish/room_api.py +++ b/jellyfish/room_api.py @@ -1,11 +1,16 @@ -import time -import jellyfish_openapi_client as jellyfish_api -from jellyfish_openapi_client.rest import ApiException +""" + RoomApi used to manage rooms +""" -from jellyfish_openapi_client import Room, RoomConfig +import openapi_client as jellyfish_api + +from openapi_client import AddPeerRequest, AddComponentRequest, PeerOptions, ComponentOptions +from openapi_client import Room, RoomConfig class RoomApi: + """Allows for managing rooms""" + def __init__(self, server_address, server_api_token): self._configuration = jellyfish_api.Configuration( host=server_address, @@ -15,31 +20,54 @@ def __init__(self, server_address, server_api_token): self._api_client = jellyfish_api.ApiClient(self._configuration) self._room_api = jellyfish_api.RoomApi(self._api_client) - def create_room(self, max_peers: int = None, video_codec: str = None) -> Room: + def create_room(self, max_peers: int = None, video_codec: str = None) -> (str, Room): """Creates a room""" room_config = RoomConfig(maxPeers=max_peers, videoCodec=video_codec) - room = self._room_api.create_room(room_config) + resp = self._room_api.create_room(room_config) + + return (resp.data.jellyfish_address, resp.data.room) + + def delete_room(self, room_id: str) -> None: + """Deletes a room""" + + return self._room_api.delete_room(room_id) + + def get_all_rooms(self) -> list[Room]: + """Returns list of all rooms""" + + return self._room_api.get_all_rooms().data + + def get_room(self, room_id: str) -> Room: + """Returns room with the given id""" + + return self._room_api.get_room(room_id).data + + def add_peer(self, room_id: str, peer_type: str, options: PeerOptions): + """Creates peer in the room""" + + options = PeerOptions(options) + request = AddPeerRequest(type=peer_type, options=options) + + resp = self._room_api.add_peer(room_id, request) + return (resp.data.token, resp.data.peer) - return (room.data.jellyfish_address, room.data.room) + def delete_peer(self, room_id, peer_id): + """Deletes peer""" - def delete_room(self): - pass + return self._room_api.delete_peer(room_id, peer_id) - def get_all_rooms(self): - pass + def add_component(self, room_id, component_type, options=None): + """Creates component in the room""" - def get_room(self): - pass + if options: + options = ComponentOptions(options) - def add_peer(): - pass + request = AddComponentRequest(type=component_type, options=options) - def delete_peer(): - pass + return self._room_api.add_component(room_id, request).data - def add_component(): - pass + def delete_component(self, room_id, component_id): + """Deletes component""" - def delete_component(): - pass + return self._room_api.delete_component(room_id, component_id) diff --git a/jellyfish/openapi_client/.github/workflows/python.yml b/openapi/.github/workflows/python.yml similarity index 96% rename from jellyfish/openapi_client/.github/workflows/python.yml rename to openapi/.github/workflows/python.yml index 43f1e6e..bcc6ea7 100644 --- a/jellyfish/openapi_client/.github/workflows/python.yml +++ b/openapi/.github/workflows/python.yml @@ -3,7 +3,7 @@ # # ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python -name: jellyfish_openapi_client Python package +name: openapi_client Python package on: [push, pull_request] diff --git a/jellyfish/openapi_client/.gitignore b/openapi/.gitignore similarity index 100% rename from jellyfish/openapi_client/.gitignore rename to openapi/.gitignore diff --git a/jellyfish/openapi_client/.gitlab-ci.yml b/openapi/.gitlab-ci.yml similarity index 92% rename from jellyfish/openapi_client/.gitlab-ci.yml rename to openapi/.gitlab-ci.yml index bec95ad..00e696f 100644 --- a/jellyfish/openapi_client/.gitlab-ci.yml +++ b/openapi/.gitlab-ci.yml @@ -12,7 +12,7 @@ stages: script: - pip install -r requirements.txt - pip install -r test-requirements.txt - - pytest --cov=jellyfish_openapi_client + - pytest --cov=openapi_client pytest-3.7: extends: .pytest diff --git a/jellyfish/openapi_client/.openapi-generator-ignore b/openapi/.openapi-generator-ignore similarity index 100% rename from jellyfish/openapi_client/.openapi-generator-ignore rename to openapi/.openapi-generator-ignore diff --git a/openapi/.openapi-generator/FILES b/openapi/.openapi-generator/FILES new file mode 100644 index 0000000..56dbf7d --- /dev/null +++ b/openapi/.openapi-generator/FILES @@ -0,0 +1,92 @@ +.github/workflows/python.yml +.gitignore +.gitlab-ci.yml +.openapi-generator-ignore +.travis.yml +README.md +docs/AddComponentRequest.md +docs/AddPeerRequest.md +docs/Component.md +docs/ComponentDetailsResponse.md +docs/ComponentMetadata.md +docs/ComponentOptions.md +docs/ComponentOptionsRTSP.md +docs/DefaultApi.md +docs/Error.md +docs/HlsSkip.md +docs/Peer.md +docs/PeerDetailsResponse.md +docs/PeerDetailsResponseData.md +docs/PeerOptions.md +docs/PeerOptionsWebRTC.md +docs/PeerStatus.md +docs/Room.md +docs/RoomApi.md +docs/RoomConfig.md +docs/RoomCreateDetailsResponse.md +docs/RoomCreateDetailsResponseData.md +docs/RoomDetailsResponse.md +docs/RoomsListingResponse.md +git_push.sh +openapi_client/__init__.py +openapi_client/api/__init__.py +openapi_client/api/default_api.py +openapi_client/api/room_api.py +openapi_client/api_client.py +openapi_client/api_response.py +openapi_client/configuration.py +openapi_client/exceptions.py +openapi_client/models/__init__.py +openapi_client/models/add_component_request.py +openapi_client/models/add_peer_request.py +openapi_client/models/component.py +openapi_client/models/component_details_response.py +openapi_client/models/component_metadata.py +openapi_client/models/component_options.py +openapi_client/models/component_options_rtsp.py +openapi_client/models/error.py +openapi_client/models/hls_skip.py +openapi_client/models/peer.py +openapi_client/models/peer_details_response.py +openapi_client/models/peer_details_response_data.py +openapi_client/models/peer_options.py +openapi_client/models/peer_options_web_rtc.py +openapi_client/models/peer_status.py +openapi_client/models/room.py +openapi_client/models/room_config.py +openapi_client/models/room_create_details_response.py +openapi_client/models/room_create_details_response_data.py +openapi_client/models/room_details_response.py +openapi_client/models/rooms_listing_response.py +openapi_client/py.typed +openapi_client/rest.py +pyproject.toml +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +test/test_add_component_request.py +test/test_add_peer_request.py +test/test_component.py +test/test_component_details_response.py +test/test_component_metadata.py +test/test_component_options.py +test/test_component_options_rtsp.py +test/test_default_api.py +test/test_error.py +test/test_hls_skip.py +test/test_peer.py +test/test_peer_details_response.py +test/test_peer_details_response_data.py +test/test_peer_options.py +test/test_peer_options_web_rtc.py +test/test_peer_status.py +test/test_room.py +test/test_room_api.py +test/test_room_config.py +test/test_room_create_details_response.py +test/test_room_create_details_response_data.py +test/test_room_details_response.py +test/test_rooms_listing_response.py +tox.ini diff --git a/jellyfish/openapi_client/.openapi-generator/VERSION b/openapi/.openapi-generator/VERSION similarity index 100% rename from jellyfish/openapi_client/.openapi-generator/VERSION rename to openapi/.openapi-generator/VERSION diff --git a/jellyfish/openapi_client/.travis.yml b/openapi/.travis.yml similarity index 89% rename from jellyfish/openapi_client/.travis.yml rename to openapi/.travis.yml index 8fe29fe..fd888f7 100644 --- a/jellyfish/openapi_client/.travis.yml +++ b/openapi/.travis.yml @@ -14,4 +14,4 @@ install: - "pip install -r requirements.txt" - "pip install -r test-requirements.txt" # command to run tests -script: pytest --cov=jellyfish_openapi_client +script: pytest --cov=openapi_client diff --git a/jellyfish/openapi_client/README.md b/openapi/README.md similarity index 90% rename from jellyfish/openapi_client/README.md rename to openapi/README.md index 8a7caff..c205c1e 100644 --- a/jellyfish/openapi_client/README.md +++ b/openapi/README.md @@ -1,4 +1,4 @@ -# jellyfish-openapi-client +# openapi-client No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import jellyfish_openapi_client +import openapi_client ``` ### Setuptools @@ -37,7 +37,7 @@ python setup.py install --user Then import the package: ```python -import jellyfish_openapi_client +import openapi_client ``` ### Tests @@ -51,13 +51,13 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python import time -import jellyfish_openapi_client -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -67,21 +67,21 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.DefaultApi(api_client) + api_instance = openapi_client.DefaultApi(api_client) room_id = 'room_id_example' # str | Room id filename = 'filename_example' # str | Name of the file range = 'range_example' # str | Byte range of partial segment (optional) hls_msn = 56 # int | Segment sequence number (optional) hls_part = 56 # int | Partial segment sequence number (optional) - hls_skip = jellyfish_openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) + hls_skip = openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) try: # Send file diff --git a/jellyfish/openapi_client/docs/AddComponentRequest.md b/openapi/docs/AddComponentRequest.md similarity index 85% rename from jellyfish/openapi_client/docs/AddComponentRequest.md rename to openapi/docs/AddComponentRequest.md index 32afca2..47f87df 100644 --- a/jellyfish/openapi_client/docs/AddComponentRequest.md +++ b/openapi/docs/AddComponentRequest.md @@ -4,13 +4,13 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**options** | [**ComponentOptions**](ComponentOptions.md) | | +**options** | [**ComponentOptions**](ComponentOptions.md) | | [optional] **type** | **str** | Component type | ## Example ```python -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest +from openapi_client.models.add_component_request import AddComponentRequest # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/AddPeerRequest.md b/openapi/docs/AddPeerRequest.md similarity index 92% rename from jellyfish/openapi_client/docs/AddPeerRequest.md rename to openapi/docs/AddPeerRequest.md index 1c4aaaa..b9aa940 100644 --- a/jellyfish/openapi_client/docs/AddPeerRequest.md +++ b/openapi/docs/AddPeerRequest.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest +from openapi_client.models.add_peer_request import AddPeerRequest # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/Component.md b/openapi/docs/Component.md similarity index 93% rename from jellyfish/openapi_client/docs/Component.md rename to openapi/docs/Component.md index 71f4fbb..889c277 100644 --- a/jellyfish/openapi_client/docs/Component.md +++ b/openapi/docs/Component.md @@ -12,7 +12,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.component import Component +from openapi_client.models.component import Component # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/ComponentDetailsResponse.md b/openapi/docs/ComponentDetailsResponse.md similarity index 91% rename from jellyfish/openapi_client/docs/ComponentDetailsResponse.md rename to openapi/docs/ComponentDetailsResponse.md index 16ce318..13c9791 100644 --- a/jellyfish/openapi_client/docs/ComponentDetailsResponse.md +++ b/openapi/docs/ComponentDetailsResponse.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse +from openapi_client.models.component_details_response import ComponentDetailsResponse # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/ComponentMetadata.md b/openapi/docs/ComponentMetadata.md similarity index 91% rename from jellyfish/openapi_client/docs/ComponentMetadata.md rename to openapi/docs/ComponentMetadata.md index 9093104..cc45057 100644 --- a/jellyfish/openapi_client/docs/ComponentMetadata.md +++ b/openapi/docs/ComponentMetadata.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.component_metadata import ComponentMetadata +from openapi_client.models.component_metadata import ComponentMetadata # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/ComponentOptions.md b/openapi/docs/ComponentOptions.md similarity index 94% rename from jellyfish/openapi_client/docs/ComponentOptions.md rename to openapi/docs/ComponentOptions.md index 01a2f01..3ad562a 100644 --- a/jellyfish/openapi_client/docs/ComponentOptions.md +++ b/openapi/docs/ComponentOptions.md @@ -14,7 +14,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.component_options import ComponentOptions +from openapi_client.models.component_options import ComponentOptions # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/ComponentOptionsRTSP.md b/openapi/docs/ComponentOptionsRTSP.md similarity index 94% rename from jellyfish/openapi_client/docs/ComponentOptionsRTSP.md rename to openapi/docs/ComponentOptionsRTSP.md index 2500676..dd6385e 100644 --- a/jellyfish/openapi_client/docs/ComponentOptionsRTSP.md +++ b/openapi/docs/ComponentOptionsRTSP.md @@ -14,7 +14,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/DefaultApi.md b/openapi/docs/DefaultApi.md similarity index 84% rename from jellyfish/openapi_client/docs/DefaultApi.md rename to openapi/docs/DefaultApi.md index 6dbccfc..42ece10 100644 --- a/jellyfish/openapi_client/docs/DefaultApi.md +++ b/openapi/docs/DefaultApi.md @@ -1,4 +1,4 @@ -# jellyfish_openapi_client.DefaultApi +# openapi_client.DefaultApi All URIs are relative to *http://localhost* @@ -18,14 +18,14 @@ Send file ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.hls_skip import HlsSkip -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.hls_skip import HlsSkip +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -35,20 +35,20 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.DefaultApi(api_client) + api_instance = openapi_client.DefaultApi(api_client) room_id = 'room_id_example' # str | Room id filename = 'filename_example' # str | Name of the file range = 'range_example' # str | Byte range of partial segment (optional) hls_msn = 56 # int | Segment sequence number (optional) hls_part = 56 # int | Partial segment sequence number (optional) - hls_skip = jellyfish_openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) + hls_skip = openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) try: # Send file diff --git a/jellyfish/openapi_client/docs/Error.md b/openapi/docs/Error.md similarity index 92% rename from jellyfish/openapi_client/docs/Error.md rename to openapi/docs/Error.md index db5796a..f863d4b 100644 --- a/jellyfish/openapi_client/docs/Error.md +++ b/openapi/docs/Error.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.error import Error +from openapi_client.models.error import Error # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/HlsSkip.md b/openapi/docs/HlsSkip.md similarity index 100% rename from jellyfish/openapi_client/docs/HlsSkip.md rename to openapi/docs/HlsSkip.md diff --git a/jellyfish/openapi_client/docs/Peer.md b/openapi/docs/Peer.md similarity index 93% rename from jellyfish/openapi_client/docs/Peer.md rename to openapi/docs/Peer.md index cfca89f..73f0021 100644 --- a/jellyfish/openapi_client/docs/Peer.md +++ b/openapi/docs/Peer.md @@ -12,7 +12,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.peer import Peer +from openapi_client.models.peer import Peer # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/PeerDetailsResponse.md b/openapi/docs/PeerDetailsResponse.md similarity index 91% rename from jellyfish/openapi_client/docs/PeerDetailsResponse.md rename to openapi/docs/PeerDetailsResponse.md index ef90210..77ea231 100644 --- a/jellyfish/openapi_client/docs/PeerDetailsResponse.md +++ b/openapi/docs/PeerDetailsResponse.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse +from openapi_client.models.peer_details_response import PeerDetailsResponse # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/PeerDetailsResponseData.md b/openapi/docs/PeerDetailsResponseData.md similarity index 91% rename from jellyfish/openapi_client/docs/PeerDetailsResponseData.md rename to openapi/docs/PeerDetailsResponseData.md index cd1df4d..41bb19b 100644 --- a/jellyfish/openapi_client/docs/PeerDetailsResponseData.md +++ b/openapi/docs/PeerDetailsResponseData.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from openapi_client.models.peer_details_response_data import PeerDetailsResponseData # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/PeerOptions.md b/openapi/docs/PeerOptions.md similarity index 92% rename from jellyfish/openapi_client/docs/PeerOptions.md rename to openapi/docs/PeerOptions.md index 130cf5a..1d1d9a2 100644 --- a/jellyfish/openapi_client/docs/PeerOptions.md +++ b/openapi/docs/PeerOptions.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.peer_options import PeerOptions +from openapi_client.models.peer_options import PeerOptions # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/PeerOptionsWebRTC.md b/openapi/docs/PeerOptionsWebRTC.md similarity index 92% rename from jellyfish/openapi_client/docs/PeerOptionsWebRTC.md rename to openapi/docs/PeerOptionsWebRTC.md index ba68e93..bebb22e 100644 --- a/jellyfish/openapi_client/docs/PeerOptionsWebRTC.md +++ b/openapi/docs/PeerOptionsWebRTC.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/PeerStatus.md b/openapi/docs/PeerStatus.md similarity index 100% rename from jellyfish/openapi_client/docs/PeerStatus.md rename to openapi/docs/PeerStatus.md diff --git a/jellyfish/openapi_client/docs/Room.md b/openapi/docs/Room.md similarity index 94% rename from jellyfish/openapi_client/docs/Room.md rename to openapi/docs/Room.md index 7f09afa..6a1c3c1 100644 --- a/jellyfish/openapi_client/docs/Room.md +++ b/openapi/docs/Room.md @@ -13,7 +13,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.room import Room +from openapi_client.models.room import Room # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/RoomApi.md b/openapi/docs/RoomApi.md similarity index 81% rename from jellyfish/openapi_client/docs/RoomApi.md rename to openapi/docs/RoomApi.md index 51be161..8aed42f 100644 --- a/jellyfish/openapi_client/docs/RoomApi.md +++ b/openapi/docs/RoomApi.md @@ -1,4 +1,4 @@ -# jellyfish_openapi_client.RoomApi +# openapi_client.RoomApi All URIs are relative to *http://localhost* @@ -25,15 +25,15 @@ Creates the component and adds it to the room ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.add_component_request import AddComponentRequest +from openapi_client.models.component_details_response import ComponentDetailsResponse +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -43,16 +43,16 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room ID - add_component_request = jellyfish_openapi_client.AddComponentRequest() # AddComponentRequest | Component config (optional) + add_component_request = openapi_client.AddComponentRequest() # AddComponentRequest | Component config (optional) try: # Creates the component and adds it to the room @@ -106,15 +106,15 @@ Create peer ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.add_peer_request import AddPeerRequest +from openapi_client.models.peer_details_response import PeerDetailsResponse +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -124,16 +124,16 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room id - add_peer_request = jellyfish_openapi_client.AddPeerRequest() # AddPeerRequest | Peer specification (optional) + add_peer_request = openapi_client.AddPeerRequest() # AddPeerRequest | Peer specification (optional) try: # Create peer @@ -188,15 +188,15 @@ Creates a room ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_config import RoomConfig -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_config import RoomConfig +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -206,15 +206,15 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) - room_config = jellyfish_openapi_client.RoomConfig() # RoomConfig | Room configuration (optional) + api_instance = openapi_client.RoomApi(api_client) + room_config = openapi_client.RoomConfig() # RoomConfig | Room configuration (optional) try: # Creates a room @@ -266,13 +266,13 @@ Delete the component from the room ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -282,14 +282,14 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room ID id = 'id_example' # str | Component ID @@ -342,13 +342,13 @@ Delete peer ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -358,14 +358,14 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room ID id = 'id_example' # str | Peer id @@ -418,13 +418,13 @@ Delete the room ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -434,14 +434,14 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room id try: @@ -492,14 +492,14 @@ Show information about all rooms ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.rooms_listing_response import RoomsListingResponse +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -509,14 +509,14 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) try: # Show information about all rooms @@ -564,14 +564,14 @@ Shows information about the room ```python import time import os -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_details_response import RoomDetailsResponse +from openapi_client.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to http://localhost # See configuration.py for a list of all supported configuration parameters. -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( host = "http://localhost" ) @@ -581,14 +581,14 @@ configuration = jellyfish_openapi_client.Configuration( # satisfies your auth use case. # Configure Bearer authorization: authorization -configuration = jellyfish_openapi_client.Configuration( +configuration = openapi_client.Configuration( access_token = os.environ["BEARER_TOKEN"] ) # Enter a context with an instance of the API client -with jellyfish_openapi_client.ApiClient(configuration) as api_client: +with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class - api_instance = jellyfish_openapi_client.RoomApi(api_client) + api_instance = openapi_client.RoomApi(api_client) room_id = 'room_id_example' # str | Room ID try: diff --git a/jellyfish/openapi_client/docs/RoomConfig.md b/openapi/docs/RoomConfig.md similarity index 93% rename from jellyfish/openapi_client/docs/RoomConfig.md rename to openapi/docs/RoomConfig.md index f2e7dc2..deaa81c 100644 --- a/jellyfish/openapi_client/docs/RoomConfig.md +++ b/openapi/docs/RoomConfig.md @@ -11,7 +11,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.room_config import RoomConfig +from openapi_client.models.room_config import RoomConfig # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md b/openapi/docs/RoomCreateDetailsResponse.md similarity index 91% rename from jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md rename to openapi/docs/RoomCreateDetailsResponse.md index 6f9298c..a7fb5fc 100644 --- a/jellyfish/openapi_client/docs/RoomCreateDetailsResponse.md +++ b/openapi/docs/RoomCreateDetailsResponse.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md b/openapi/docs/RoomCreateDetailsResponseData.md similarity index 91% rename from jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md rename to openapi/docs/RoomCreateDetailsResponseData.md index f646a64..402523f 100644 --- a/jellyfish/openapi_client/docs/RoomCreateDetailsResponseData.md +++ b/openapi/docs/RoomCreateDetailsResponseData.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/RoomDetailsResponse.md b/openapi/docs/RoomDetailsResponse.md similarity index 91% rename from jellyfish/openapi_client/docs/RoomDetailsResponse.md rename to openapi/docs/RoomDetailsResponse.md index 9f3dc18..785f8ba 100644 --- a/jellyfish/openapi_client/docs/RoomDetailsResponse.md +++ b/openapi/docs/RoomDetailsResponse.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse +from openapi_client.models.room_details_response import RoomDetailsResponse # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/docs/RoomsListingResponse.md b/openapi/docs/RoomsListingResponse.md similarity index 91% rename from jellyfish/openapi_client/docs/RoomsListingResponse.md rename to openapi/docs/RoomsListingResponse.md index bc10d23..6ad2695 100644 --- a/jellyfish/openapi_client/docs/RoomsListingResponse.md +++ b/openapi/docs/RoomsListingResponse.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ## Example ```python -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse +from openapi_client.models.rooms_listing_response import RoomsListingResponse # TODO update the JSON string below json = "{}" diff --git a/jellyfish/openapi_client/git_push.sh b/openapi/git_push.sh similarity index 100% rename from jellyfish/openapi_client/git_push.sh rename to openapi/git_push.sh diff --git a/openapi/openapi_client/__init__.py b/openapi/openapi_client/__init__.py new file mode 100644 index 0000000..d6a545c --- /dev/null +++ b/openapi/openapi_client/__init__.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +# flake8: noqa + +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from openapi_client.api.default_api import DefaultApi +from openapi_client.api.room_api import RoomApi + +# import ApiClient +from openapi_client.api_response import ApiResponse +from openapi_client.api_client import ApiClient +from openapi_client.configuration import Configuration +from openapi_client.exceptions import OpenApiException +from openapi_client.exceptions import ApiTypeError +from openapi_client.exceptions import ApiValueError +from openapi_client.exceptions import ApiKeyError +from openapi_client.exceptions import ApiAttributeError +from openapi_client.exceptions import ApiException + +# import models into sdk package +from openapi_client.models.add_component_request import AddComponentRequest +from openapi_client.models.add_peer_request import AddPeerRequest +from openapi_client.models.component import Component +from openapi_client.models.component_details_response import ComponentDetailsResponse +from openapi_client.models.component_metadata import ComponentMetadata +from openapi_client.models.component_options import ComponentOptions +from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from openapi_client.models.error import Error +from openapi_client.models.hls_skip import HlsSkip +from openapi_client.models.peer import Peer +from openapi_client.models.peer_details_response import PeerDetailsResponse +from openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from openapi_client.models.peer_options import PeerOptions +from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from openapi_client.models.peer_status import PeerStatus +from openapi_client.models.room import Room +from openapi_client.models.room_config import RoomConfig +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from openapi_client.models.room_details_response import RoomDetailsResponse +from openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/openapi/openapi_client/api/__init__.py b/openapi/openapi_client/api/__init__.py new file mode 100644 index 0000000..cb871fc --- /dev/null +++ b/openapi/openapi_client/api/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa + +# import apis into api package +from openapi_client.api.default_api import DefaultApi +from openapi_client.api.room_api import RoomApi + diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py b/openapi/openapi_client/api/default_api.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py rename to openapi/openapi_client/api/default_api.py index e5c3569..a5828b4 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/api/default_api.py +++ b/openapi/openapi_client/api/default_api.py @@ -23,11 +23,11 @@ from typing import Optional -from jellyfish_openapi_client.models.hls_skip import HlsSkip +from openapi_client.models.hls_skip import HlsSkip -from jellyfish_openapi_client.api_client import ApiClient -from jellyfish_openapi_client.api_response import ApiResponse -from jellyfish_openapi_client.exceptions import ( # noqa: F401 +from openapi_client.api_client import ApiClient +from openapi_client.api_response import ApiResponse +from openapi_client.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py b/openapi/openapi_client/api/room_api.py similarity index 98% rename from jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py rename to openapi/openapi_client/api/room_api.py index 6d67b19..c779e2a 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/api/room_api.py +++ b/openapi/openapi_client/api/room_api.py @@ -23,18 +23,18 @@ from typing import Optional -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse -from jellyfish_openapi_client.models.room_config import RoomConfig -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse - -from jellyfish_openapi_client.api_client import ApiClient -from jellyfish_openapi_client.api_response import ApiResponse -from jellyfish_openapi_client.exceptions import ( # noqa: F401 +from openapi_client.models.add_component_request import AddComponentRequest +from openapi_client.models.add_peer_request import AddPeerRequest +from openapi_client.models.component_details_response import ComponentDetailsResponse +from openapi_client.models.peer_details_response import PeerDetailsResponse +from openapi_client.models.room_config import RoomConfig +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from openapi_client.models.room_details_response import RoomDetailsResponse +from openapi_client.models.rooms_listing_response import RoomsListingResponse + +from openapi_client.api_client import ApiClient +from openapi_client.api_response import ApiResponse +from openapi_client.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api_client.py b/openapi/openapi_client/api_client.py similarity index 98% rename from jellyfish/openapi_client/jellyfish_openapi_client/api_client.py rename to openapi/openapi_client/api_client.py index f9fe646..cb105e1 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/api_client.py +++ b/openapi/openapi_client/api_client.py @@ -24,11 +24,11 @@ from urllib.parse import quote -from jellyfish_openapi_client.configuration import Configuration -from jellyfish_openapi_client.api_response import ApiResponse -import jellyfish_openapi_client.models -from jellyfish_openapi_client import rest -from jellyfish_openapi_client.exceptions import ApiValueError, ApiException +from openapi_client.configuration import Configuration +from openapi_client.api_response import ApiResponse +import openapi_client.models +from openapi_client import rest +from openapi_client.exceptions import ApiValueError, ApiException class ApiClient(object): @@ -341,7 +341,7 @@ def __deserialize(self, data, klass): if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(jellyfish_openapi_client.models, klass) + klass = getattr(openapi_client.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/api_response.py b/openapi/openapi_client/api_response.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/api_response.py rename to openapi/openapi_client/api_response.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/configuration.py b/openapi/openapi_client/configuration.py similarity index 98% rename from jellyfish/openapi_client/jellyfish_openapi_client/configuration.py rename to openapi/openapi_client/configuration.py index 69a81a7..fd876d5 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/configuration.py +++ b/openapi/openapi_client/configuration.py @@ -19,7 +19,7 @@ import urllib3 import http.client as httplib -from jellyfish_openapi_client.exceptions import ApiValueError +from openapi_client.exceptions import ApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { 'multipleOf', 'maximum', 'exclusiveMaximum', @@ -108,7 +108,7 @@ def __init__(self, host=None, self.logger = {} """Logging Settings """ - self.logger["package_logger"] = logging.getLogger("jellyfish_openapi_client") + self.logger["package_logger"] = logging.getLogger("openapi_client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") self.logger_format = '%(asctime)s %(levelname)s %(message)s' """Log format diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py b/openapi/openapi_client/exceptions.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/exceptions.py rename to openapi/openapi_client/exceptions.py diff --git a/openapi/openapi_client/models/__init__.py b/openapi/openapi_client/models/__init__.py new file mode 100644 index 0000000..df259e8 --- /dev/null +++ b/openapi/openapi_client/models/__init__.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +# flake8: noqa +""" + Jellyfish Media Server + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 0.2.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from openapi_client.models.add_component_request import AddComponentRequest +from openapi_client.models.add_peer_request import AddPeerRequest +from openapi_client.models.component import Component +from openapi_client.models.component_details_response import ComponentDetailsResponse +from openapi_client.models.component_metadata import ComponentMetadata +from openapi_client.models.component_options import ComponentOptions +from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from openapi_client.models.error import Error +from openapi_client.models.hls_skip import HlsSkip +from openapi_client.models.peer import Peer +from openapi_client.models.peer_details_response import PeerDetailsResponse +from openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from openapi_client.models.peer_options import PeerOptions +from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from openapi_client.models.peer_status import PeerStatus +from openapi_client.models.room import Room +from openapi_client.models.room_config import RoomConfig +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse +from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from openapi_client.models.room_details_response import RoomDetailsResponse +from openapi_client.models.rooms_listing_response import RoomsListingResponse diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py b/openapi/openapi_client/models/add_component_request.py similarity index 86% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py rename to openapi/openapi_client/models/add_component_request.py index c577a8c..1723ea0 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_component_request.py +++ b/openapi/openapi_client/models/add_component_request.py @@ -18,15 +18,15 @@ import json - +from typing import Optional from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.component_options import ComponentOptions +from openapi_client.models.component_options import ComponentOptions class AddComponentRequest(BaseModel): """ AddComponentRequest """ - options: ComponentOptions = Field(...) + options: Optional[ComponentOptions] = None type: StrictStr = Field(..., description="Component type") __properties = ["options", "type"] @@ -57,6 +57,11 @@ def to_dict(self): # override the default output from pydantic by calling `to_dict()` of options if self.options: _dict['options'] = self.options.to_dict() + # set to None if options (nullable) is None + # and __fields_set__ contains the field + if self.options is None and "options" in self.__fields_set__: + _dict['options'] = None + return _dict @classmethod diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py b/openapi/openapi_client/models/add_peer_request.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py rename to openapi/openapi_client/models/add_peer_request.py index e7c3bae..d649fdf 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/add_peer_request.py +++ b/openapi/openapi_client/models/add_peer_request.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.peer_options import PeerOptions +from openapi_client.models.peer_options import PeerOptions class AddPeerRequest(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component.py b/openapi/openapi_client/models/component.py similarity index 96% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/component.py rename to openapi/openapi_client/models/component.py index 8a0a8ac..18e0d34 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/component.py +++ b/openapi/openapi_client/models/component.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.component_metadata import ComponentMetadata +from openapi_client.models.component_metadata import ComponentMetadata class Component(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py b/openapi/openapi_client/models/component_details_response.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py rename to openapi/openapi_client/models/component_details_response.py index 20aeb23..d3ec75f 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_details_response.py +++ b/openapi/openapi_client/models/component_details_response.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field -from jellyfish_openapi_client.models.component import Component +from openapi_client.models.component import Component class ComponentDetailsResponse(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py b/openapi/openapi_client/models/component_metadata.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/component_metadata.py rename to openapi/openapi_client/models/component_metadata.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py b/openapi/openapi_client/models/component_options.py similarity index 75% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py rename to openapi/openapi_client/models/component_options.py index c8e9a9a..7501ebc 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options.py +++ b/openapi/openapi_client/models/component_options.py @@ -18,24 +18,22 @@ import pprint import re # noqa: F401 -from typing import Any, Dict, List, Optional +from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP +from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP from typing import Union, Any, List, TYPE_CHECKING from pydantic import StrictStr, Field -COMPONENTOPTIONS_ONE_OF_SCHEMAS = ["ComponentOptionsRTSP", "object"] +COMPONENTOPTIONS_ONE_OF_SCHEMAS = ["ComponentOptionsRTSP"] class ComponentOptions(BaseModel): """ Component-specific options """ - # data type: object - oneof_schema_1_validator: Optional[Dict[str, Any]] = Field(None, description="Options specific to the HLS component") # data type: ComponentOptionsRTSP - oneof_schema_2_validator: Optional[ComponentOptionsRTSP] = None + oneof_schema_1_validator: Optional[ComponentOptionsRTSP] = None if TYPE_CHECKING: - actual_instance: Union[ComponentOptionsRTSP, object] + actual_instance: Union[ComponentOptionsRTSP] else: actual_instance: Any one_of_schemas: List[str] = Field(COMPONENTOPTIONS_ONE_OF_SCHEMAS, const=True) @@ -55,15 +53,12 @@ def __init__(self, *args, **kwargs): @validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): + if v is None: + return v + instance = ComponentOptions.construct() error_messages = [] match = 0 - # validate data type: object - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) # validate data type: ComponentOptionsRTSP if not isinstance(v, ComponentOptionsRTSP): error_messages.append(f"Error! Input type `{type(v)}` is not `ComponentOptionsRTSP`") @@ -71,10 +66,10 @@ def actual_instance_must_validate_oneof(cls, v): match += 1 if match > 1: # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when setting `actual_instance` in ComponentOptions with oneOf schemas: ComponentOptionsRTSP. Details: " + ", ".join(error_messages)) else: return v @@ -86,18 +81,12 @@ def from_dict(cls, obj: dict) -> ComponentOptions: def from_json(cls, json_str: str) -> ComponentOptions: """Returns the object represented by the json string""" instance = ComponentOptions.construct() + if json_str is None: + return instance + error_messages = [] match = 0 - # deserialize data into object - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) # deserialize data into ComponentOptionsRTSP try: instance.actual_instance = ComponentOptionsRTSP.from_json(json_str) @@ -107,10 +96,10 @@ def from_json(cls, json_str: str) -> ComponentOptions: if match > 1: # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP, object. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when deserializing the JSON string into ComponentOptions with oneOf schemas: ComponentOptionsRTSP. Details: " + ", ".join(error_messages)) else: return instance diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py b/openapi/openapi_client/models/component_options_rtsp.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/component_options_rtsp.py rename to openapi/openapi_client/models/component_options_rtsp.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/error.py b/openapi/openapi_client/models/error.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/error.py rename to openapi/openapi_client/models/error.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py b/openapi/openapi_client/models/hls_skip.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/hls_skip.py rename to openapi/openapi_client/models/hls_skip.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py b/openapi/openapi_client/models/peer.py similarity index 96% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py rename to openapi/openapi_client/models/peer.py index b7ae8ae..9e0cbac 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer.py +++ b/openapi/openapi_client/models/peer.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.peer_status import PeerStatus +from openapi_client.models.peer_status import PeerStatus class Peer(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py b/openapi/openapi_client/models/peer_details_response.py similarity index 95% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py rename to openapi/openapi_client/models/peer_details_response.py index 9698306..e7e779f 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response.py +++ b/openapi/openapi_client/models/peer_details_response.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field -from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData +from openapi_client.models.peer_details_response_data import PeerDetailsResponseData class PeerDetailsResponse(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py b/openapi/openapi_client/models/peer_details_response_data.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py rename to openapi/openapi_client/models/peer_details_response_data.py index 9414438..0bdbab3 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_details_response_data.py +++ b/openapi/openapi_client/models/peer_details_response_data.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.peer import Peer +from openapi_client.models.peer import Peer class PeerDetailsResponseData(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py b/openapi/openapi_client/models/peer_options.py similarity index 98% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py rename to openapi/openapi_client/models/peer_options.py index ddf5190..c12fb8d 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options.py +++ b/openapi/openapi_client/models/peer_options.py @@ -20,7 +20,7 @@ from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, validator -from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC +from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC from typing import Union, Any, List, TYPE_CHECKING from pydantic import StrictStr, Field diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py b/openapi/openapi_client/models/peer_options_web_rtc.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer_options_web_rtc.py rename to openapi/openapi_client/models/peer_options_web_rtc.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py b/openapi/openapi_client/models/peer_status.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/peer_status.py rename to openapi/openapi_client/models/peer_status.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room.py b/openapi/openapi_client/models/room.py similarity index 94% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/room.py rename to openapi/openapi_client/models/room.py index 71c635a..00a498a 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/room.py +++ b/openapi/openapi_client/models/room.py @@ -20,9 +20,9 @@ from typing import List from pydantic import BaseModel, Field, StrictStr, conlist -from jellyfish_openapi_client.models.component import Component -from jellyfish_openapi_client.models.peer import Peer -from jellyfish_openapi_client.models.room_config import RoomConfig +from openapi_client.models.component import Component +from openapi_client.models.peer import Peer +from openapi_client.models.room_config import RoomConfig class Room(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py b/openapi/openapi_client/models/room_config.py similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/room_config.py rename to openapi/openapi_client/models/room_config.py diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py b/openapi/openapi_client/models/room_create_details_response.py similarity index 95% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py rename to openapi/openapi_client/models/room_create_details_response.py index 2859029..d700a62 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response.py +++ b/openapi/openapi_client/models/room_create_details_response.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field -from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData +from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData class RoomCreateDetailsResponse(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py b/openapi/openapi_client/models/room_create_details_response_data.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py rename to openapi/openapi_client/models/room_create_details_response_data.py index 69ef4cc..5c8f34d 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_create_details_response_data.py +++ b/openapi/openapi_client/models/room_create_details_response_data.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field, StrictStr -from jellyfish_openapi_client.models.room import Room +from openapi_client.models.room import Room class RoomCreateDetailsResponseData(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py b/openapi/openapi_client/models/room_details_response.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py rename to openapi/openapi_client/models/room_details_response.py index 764ece8..9c13cb6 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/room_details_response.py +++ b/openapi/openapi_client/models/room_details_response.py @@ -20,7 +20,7 @@ from pydantic import BaseModel, Field -from jellyfish_openapi_client.models.room import Room +from openapi_client.models.room import Room class RoomDetailsResponse(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py b/openapi/openapi_client/models/rooms_listing_response.py similarity index 97% rename from jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py rename to openapi/openapi_client/models/rooms_listing_response.py index 3129f65..9f83026 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/models/rooms_listing_response.py +++ b/openapi/openapi_client/models/rooms_listing_response.py @@ -20,7 +20,7 @@ from typing import List from pydantic import BaseModel, Field, conlist -from jellyfish_openapi_client.models.room import Room +from openapi_client.models.room import Room class RoomsListingResponse(BaseModel): """ diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/py.typed b/openapi/openapi_client/py.typed similarity index 100% rename from jellyfish/openapi_client/jellyfish_openapi_client/py.typed rename to openapi/openapi_client/py.typed diff --git a/jellyfish/openapi_client/jellyfish_openapi_client/rest.py b/openapi/openapi_client/rest.py similarity index 98% rename from jellyfish/openapi_client/jellyfish_openapi_client/rest.py rename to openapi/openapi_client/rest.py index 5b2f7f0..bd9c595 100644 --- a/jellyfish/openapi_client/jellyfish_openapi_client/rest.py +++ b/openapi/openapi_client/rest.py @@ -21,7 +21,7 @@ from urllib.parse import urlencode, quote_plus import urllib3 -from jellyfish_openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException +from openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException logger = logging.getLogger(__name__) diff --git a/jellyfish/openapi_client/pyproject.toml b/openapi/pyproject.toml similarity index 89% rename from jellyfish/openapi_client/pyproject.toml rename to openapi/pyproject.toml index 3feba39..102ba39 100644 --- a/jellyfish/openapi_client/pyproject.toml +++ b/openapi/pyproject.toml @@ -1,5 +1,5 @@ [tool.poetry] -name = "jellyfish_openapi_client" +name = "openapi_client" version = "1.0.0" description = "Jellyfish Media Server" authors = ["OpenAPI Generator Community "] @@ -7,7 +7,7 @@ license = "Apache 2.0" readme = "README.md" repository = "https://github.com/GIT_USER_ID/GIT_REPO_ID" keywords = ["OpenAPI", "OpenAPI-Generator", "Jellyfish Media Server"] -include = ["jellyfish_openapi_client/py.typed"] +include = ["openapi_client/py.typed"] [tool.poetry.dependencies] python = "^3.7" diff --git a/jellyfish/openapi_client/requirements.txt b/openapi/requirements.txt similarity index 100% rename from jellyfish/openapi_client/requirements.txt rename to openapi/requirements.txt diff --git a/jellyfish/openapi_client/setup.cfg b/openapi/setup.cfg similarity index 100% rename from jellyfish/openapi_client/setup.cfg rename to openapi/setup.cfg diff --git a/jellyfish/openapi_client/setup.py b/openapi/setup.py similarity index 93% rename from jellyfish/openapi_client/setup.py rename to openapi/setup.py index 1c32565..d7d8399 100644 --- a/jellyfish/openapi_client/setup.py +++ b/openapi/setup.py @@ -20,7 +20,7 @@ # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -NAME = "jellyfish-openapi-client" +NAME = "openapi-client" VERSION = "1.0.0" PYTHON_REQUIRES = ">=3.7" REQUIRES = [ @@ -46,5 +46,5 @@ long_description="""\ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) """, # noqa: E501 - package_data={"jellyfish_openapi_client": ["py.typed"]}, + package_data={"openapi_client": ["py.typed"]}, ) diff --git a/jellyfish/openapi_client/test-requirements.txt b/openapi/test-requirements.txt similarity index 100% rename from jellyfish/openapi_client/test-requirements.txt rename to openapi/test-requirements.txt diff --git a/jellyfish/openapi_client/test/__init__.py b/openapi/test/__init__.py similarity index 100% rename from jellyfish/openapi_client/test/__init__.py rename to openapi/test/__init__.py diff --git a/jellyfish/openapi_client/test/test_add_component_request.py b/openapi/test/test_add_component_request.py similarity index 73% rename from jellyfish/openapi_client/test/test_add_component_request.py rename to openapi/test/test_add_component_request.py index e8c1491..c55bc83 100644 --- a/jellyfish/openapi_client/test/test_add_component_request.py +++ b/openapi/test/test_add_component_request.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.add_component_request import AddComponentRequest # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.add_component_request import AddComponentRequest # noqa: E501 +from openapi_client.rest import ApiException class TestAddComponentRequest(unittest.TestCase): """AddComponentRequest unit test stubs""" @@ -35,15 +35,14 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `AddComponentRequest` """ - model = jellyfish_openapi_client.models.add_component_request.AddComponentRequest() # noqa: E501 + model = openapi_client.models.add_component_request.AddComponentRequest() # noqa: E501 if include_optional : return AddComponentRequest( - options = jellyfish_openapi_client.models.component_options.ComponentOptions(), + options = openapi_client.models.component_options.ComponentOptions(), type = 'hls' ) else : return AddComponentRequest( - options = jellyfish_openapi_client.models.component_options.ComponentOptions(), type = 'hls', ) """ diff --git a/jellyfish/openapi_client/test/test_add_peer_request.py b/openapi/test/test_add_peer_request.py similarity index 74% rename from jellyfish/openapi_client/test/test_add_peer_request.py rename to openapi/test/test_add_peer_request.py index 2cb4131..0540f60 100644 --- a/jellyfish/openapi_client/test/test_add_peer_request.py +++ b/openapi/test/test_add_peer_request.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.add_peer_request import AddPeerRequest # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.add_peer_request import AddPeerRequest # noqa: E501 +from openapi_client.rest import ApiException class TestAddPeerRequest(unittest.TestCase): """AddPeerRequest unit test stubs""" @@ -35,15 +35,15 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `AddPeerRequest` """ - model = jellyfish_openapi_client.models.add_peer_request.AddPeerRequest() # noqa: E501 + model = openapi_client.models.add_peer_request.AddPeerRequest() # noqa: E501 if include_optional : return AddPeerRequest( - options = jellyfish_openapi_client.models.peer_options.PeerOptions(), + options = openapi_client.models.peer_options.PeerOptions(), type = 'webrtc' ) else : return AddPeerRequest( - options = jellyfish_openapi_client.models.peer_options.PeerOptions(), + options = openapi_client.models.peer_options.PeerOptions(), type = 'webrtc', ) """ diff --git a/jellyfish/openapi_client/test/test_component.py b/openapi/test/test_component.py similarity index 76% rename from jellyfish/openapi_client/test/test_component.py rename to openapi/test/test_component.py index a9a3fcb..324fff9 100644 --- a/jellyfish/openapi_client/test/test_component.py +++ b/openapi/test/test_component.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.component import Component # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.component import Component # noqa: E501 +from openapi_client.rest import ApiException class TestComponent(unittest.TestCase): """Component unit test stubs""" @@ -35,18 +35,18 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `Component` """ - model = jellyfish_openapi_client.models.component.Component() # noqa: E501 + model = openapi_client.models.component.Component() # noqa: E501 if include_optional : return Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls' ) else : return Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) diff --git a/jellyfish/openapi_client/test/test_component_details_response.py b/openapi/test/test_component_details_response.py similarity index 70% rename from jellyfish/openapi_client/test/test_component_details_response.py rename to openapi/test/test_component_details_response.py index 056e056..c405839 100644 --- a/jellyfish/openapi_client/test/test_component_details_response.py +++ b/openapi/test/test_component_details_response.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.component_details_response import ComponentDetailsResponse # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.component_details_response import ComponentDetailsResponse # noqa: E501 +from openapi_client.rest import ApiException class TestComponentDetailsResponse(unittest.TestCase): """ComponentDetailsResponse unit test stubs""" @@ -35,20 +35,20 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `ComponentDetailsResponse` """ - model = jellyfish_openapi_client.models.component_details_response.ComponentDetailsResponse() # noqa: E501 + model = openapi_client.models.component_details_response.ComponentDetailsResponse() # noqa: E501 if include_optional : return ComponentDetailsResponse( - data = jellyfish_openapi_client.models.component.Component( + data = openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ) else : return ComponentDetailsResponse( - data = jellyfish_openapi_client.models.component.Component( + data = openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ), ) diff --git a/jellyfish/openapi_client/test/test_component_metadata.py b/openapi/test/test_component_metadata.py similarity index 82% rename from jellyfish/openapi_client/test/test_component_metadata.py rename to openapi/test/test_component_metadata.py index c37075c..44a90c4 100644 --- a/jellyfish/openapi_client/test/test_component_metadata.py +++ b/openapi/test/test_component_metadata.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.component_metadata import ComponentMetadata # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.component_metadata import ComponentMetadata # noqa: E501 +from openapi_client.rest import ApiException class TestComponentMetadata(unittest.TestCase): """ComponentMetadata unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `ComponentMetadata` """ - model = jellyfish_openapi_client.models.component_metadata.ComponentMetadata() # noqa: E501 + model = openapi_client.models.component_metadata.ComponentMetadata() # noqa: E501 if include_optional : return ComponentMetadata( playable = True diff --git a/jellyfish/openapi_client/test/test_component_options.py b/openapi/test/test_component_options.py similarity index 84% rename from jellyfish/openapi_client/test/test_component_options.py rename to openapi/test/test_component_options.py index 0f8323b..80b250f 100644 --- a/jellyfish/openapi_client/test/test_component_options.py +++ b/openapi/test/test_component_options.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.component_options import ComponentOptions # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.component_options import ComponentOptions # noqa: E501 +from openapi_client.rest import ApiException class TestComponentOptions(unittest.TestCase): """ComponentOptions unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `ComponentOptions` """ - model = jellyfish_openapi_client.models.component_options.ComponentOptions() # noqa: E501 + model = openapi_client.models.component_options.ComponentOptions() # noqa: E501 if include_optional : return ComponentOptions( keep_alive_interval = 0, diff --git a/jellyfish/openapi_client/test/test_component_options_rtsp.py b/openapi/test/test_component_options_rtsp.py similarity index 84% rename from jellyfish/openapi_client/test/test_component_options_rtsp.py rename to openapi/test/test_component_options_rtsp.py index 2c31369..60ec8f4 100644 --- a/jellyfish/openapi_client/test/test_component_options_rtsp.py +++ b/openapi/test/test_component_options_rtsp.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.component_options_rtsp import ComponentOptionsRTSP # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP # noqa: E501 +from openapi_client.rest import ApiException class TestComponentOptionsRTSP(unittest.TestCase): """ComponentOptionsRTSP unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `ComponentOptionsRTSP` """ - model = jellyfish_openapi_client.models.component_options_rtsp.ComponentOptionsRTSP() # noqa: E501 + model = openapi_client.models.component_options_rtsp.ComponentOptionsRTSP() # noqa: E501 if include_optional : return ComponentOptionsRTSP( keep_alive_interval = 0, diff --git a/jellyfish/openapi_client/test/test_default_api.py b/openapi/test/test_default_api.py similarity index 73% rename from jellyfish/openapi_client/test/test_default_api.py rename to openapi/test/test_default_api.py index b4f5cc5..2ca2031 100644 --- a/jellyfish/openapi_client/test/test_default_api.py +++ b/openapi/test/test_default_api.py @@ -14,16 +14,16 @@ import unittest -import jellyfish_openapi_client -from jellyfish_openapi_client.api.default_api import DefaultApi # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.api.default_api import DefaultApi # noqa: E501 +from openapi_client.rest import ApiException class TestDefaultApi(unittest.TestCase): """DefaultApi unit test stubs""" def setUp(self): - self.api = jellyfish_openapi_client.api.default_api.DefaultApi() # noqa: E501 + self.api = openapi_client.api.default_api.DefaultApi() # noqa: E501 def tearDown(self): pass diff --git a/jellyfish/openapi_client/test/test_error.py b/openapi/test/test_error.py similarity index 84% rename from jellyfish/openapi_client/test/test_error.py rename to openapi/test/test_error.py index b825fe3..7dccfca 100644 --- a/jellyfish/openapi_client/test/test_error.py +++ b/openapi/test/test_error.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.error import Error # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.error import Error # noqa: E501 +from openapi_client.rest import ApiException class TestError(unittest.TestCase): """Error unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `Error` """ - model = jellyfish_openapi_client.models.error.Error() # noqa: E501 + model = openapi_client.models.error.Error() # noqa: E501 if include_optional : return Error( errors = 'Token has expired' diff --git a/jellyfish/openapi_client/test/test_hls_skip.py b/openapi/test/test_hls_skip.py similarity index 79% rename from jellyfish/openapi_client/test/test_hls_skip.py rename to openapi/test/test_hls_skip.py index 0aa9883..7beafc5 100644 --- a/jellyfish/openapi_client/test/test_hls_skip.py +++ b/openapi/test/test_hls_skip.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.hls_skip import HlsSkip # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.hls_skip import HlsSkip # noqa: E501 +from openapi_client.rest import ApiException class TestHlsSkip(unittest.TestCase): """HlsSkip unit test stubs""" diff --git a/jellyfish/openapi_client/test/test_peer.py b/openapi/test/test_peer.py similarity index 85% rename from jellyfish/openapi_client/test/test_peer.py rename to openapi/test/test_peer.py index 468964b..7b77c18 100644 --- a/jellyfish/openapi_client/test/test_peer.py +++ b/openapi/test/test_peer.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer import Peer # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer import Peer # noqa: E501 +from openapi_client.rest import ApiException class TestPeer(unittest.TestCase): """Peer unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `Peer` """ - model = jellyfish_openapi_client.models.peer.Peer() # noqa: E501 + model = openapi_client.models.peer.Peer() # noqa: E501 if include_optional : return Peer( id = 'peer-1', diff --git a/jellyfish/openapi_client/test/test_peer_details_response.py b/openapi/test/test_peer_details_response.py similarity index 72% rename from jellyfish/openapi_client/test/test_peer_details_response.py rename to openapi/test/test_peer_details_response.py index 6f631c2..c3cbb36 100644 --- a/jellyfish/openapi_client/test/test_peer_details_response.py +++ b/openapi/test/test_peer_details_response.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer_details_response import PeerDetailsResponse # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer_details_response import PeerDetailsResponse # noqa: E501 +from openapi_client.rest import ApiException class TestPeerDetailsResponse(unittest.TestCase): """PeerDetailsResponse unit test stubs""" @@ -35,11 +35,11 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `PeerDetailsResponse` """ - model = jellyfish_openapi_client.models.peer_details_response.PeerDetailsResponse() # noqa: E501 + model = openapi_client.models.peer_details_response.PeerDetailsResponse() # noqa: E501 if include_optional : return PeerDetailsResponse( - data = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( - peer = jellyfish_openapi_client.models.peer.Peer( + data = openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( + peer = openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ), @@ -47,8 +47,8 @@ def make_instance(self, include_optional): ) else : return PeerDetailsResponse( - data = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( - peer = jellyfish_openapi_client.models.peer.Peer( + data = openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( + peer = openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ), diff --git a/jellyfish/openapi_client/test/test_peer_details_response_data.py b/openapi/test/test_peer_details_response_data.py similarity index 79% rename from jellyfish/openapi_client/test/test_peer_details_response_data.py rename to openapi/test/test_peer_details_response_data.py index 0a26c24..55ab37e 100644 --- a/jellyfish/openapi_client/test/test_peer_details_response_data.py +++ b/openapi/test/test_peer_details_response_data.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer_details_response_data import PeerDetailsResponseData # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer_details_response_data import PeerDetailsResponseData # noqa: E501 +from openapi_client.rest import ApiException class TestPeerDetailsResponseData(unittest.TestCase): """PeerDetailsResponseData unit test stubs""" @@ -35,10 +35,10 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `PeerDetailsResponseData` """ - model = jellyfish_openapi_client.models.peer_details_response_data.PeerDetailsResponseData() # noqa: E501 + model = openapi_client.models.peer_details_response_data.PeerDetailsResponseData() # noqa: E501 if include_optional : return PeerDetailsResponseData( - peer = jellyfish_openapi_client.models.peer.Peer( + peer = openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ), @@ -46,7 +46,7 @@ def make_instance(self, include_optional): ) else : return PeerDetailsResponseData( - peer = jellyfish_openapi_client.models.peer.Peer( + peer = openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ), diff --git a/jellyfish/openapi_client/test/test_peer_options.py b/openapi/test/test_peer_options.py similarity index 83% rename from jellyfish/openapi_client/test/test_peer_options.py rename to openapi/test/test_peer_options.py index 3a010ad..9031995 100644 --- a/jellyfish/openapi_client/test/test_peer_options.py +++ b/openapi/test/test_peer_options.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer_options import PeerOptions # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer_options import PeerOptions # noqa: E501 +from openapi_client.rest import ApiException class TestPeerOptions(unittest.TestCase): """PeerOptions unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `PeerOptions` """ - model = jellyfish_openapi_client.models.peer_options.PeerOptions() # noqa: E501 + model = openapi_client.models.peer_options.PeerOptions() # noqa: E501 if include_optional : return PeerOptions( enable_simulcast = True diff --git a/jellyfish/openapi_client/test/test_peer_options_web_rtc.py b/openapi/test/test_peer_options_web_rtc.py similarity index 82% rename from jellyfish/openapi_client/test/test_peer_options_web_rtc.py rename to openapi/test/test_peer_options_web_rtc.py index d5bb003..2f4b1b6 100644 --- a/jellyfish/openapi_client/test/test_peer_options_web_rtc.py +++ b/openapi/test/test_peer_options_web_rtc.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC # noqa: E501 +from openapi_client.rest import ApiException class TestPeerOptionsWebRTC(unittest.TestCase): """PeerOptionsWebRTC unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `PeerOptionsWebRTC` """ - model = jellyfish_openapi_client.models.peer_options_web_rtc.PeerOptionsWebRTC() # noqa: E501 + model = openapi_client.models.peer_options_web_rtc.PeerOptionsWebRTC() # noqa: E501 if include_optional : return PeerOptionsWebRTC( enable_simulcast = True diff --git a/jellyfish/openapi_client/test/test_peer_status.py b/openapi/test/test_peer_status.py similarity index 79% rename from jellyfish/openapi_client/test/test_peer_status.py rename to openapi/test/test_peer_status.py index 77d3bc3..b2d16f2 100644 --- a/jellyfish/openapi_client/test/test_peer_status.py +++ b/openapi/test/test_peer_status.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.peer_status import PeerStatus # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.peer_status import PeerStatus # noqa: E501 +from openapi_client.rest import ApiException class TestPeerStatus(unittest.TestCase): """PeerStatus unit test stubs""" diff --git a/jellyfish/openapi_client/test/test_room.py b/openapi/test/test_room.py similarity index 71% rename from jellyfish/openapi_client/test/test_room.py rename to openapi/test/test_room.py index 4b5a424..902ce53 100644 --- a/jellyfish/openapi_client/test/test_room.py +++ b/openapi/test/test_room.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room import Room # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room import Room # noqa: E501 +from openapi_client.rest import ApiException class TestRoom(unittest.TestCase): """Room unit test stubs""" @@ -35,22 +35,22 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `Room` """ - model = jellyfish_openapi_client.models.room.Room() # noqa: E501 + model = openapi_client.models.room.Room() # noqa: E501 if include_optional : return Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) @@ -59,18 +59,18 @@ def make_instance(self, include_optional): else : return Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) diff --git a/jellyfish/openapi_client/test/test_room_api.py b/openapi/test/test_room_api.py similarity index 87% rename from jellyfish/openapi_client/test/test_room_api.py rename to openapi/test/test_room_api.py index 4052620..0bf6684 100644 --- a/jellyfish/openapi_client/test/test_room_api.py +++ b/openapi/test/test_room_api.py @@ -14,16 +14,16 @@ import unittest -import jellyfish_openapi_client -from jellyfish_openapi_client.api.room_api import RoomApi # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.api.room_api import RoomApi # noqa: E501 +from openapi_client.rest import ApiException class TestRoomApi(unittest.TestCase): """RoomApi unit test stubs""" def setUp(self): - self.api = jellyfish_openapi_client.api.room_api.RoomApi() # noqa: E501 + self.api = openapi_client.api.room_api.RoomApi() # noqa: E501 def tearDown(self): pass diff --git a/jellyfish/openapi_client/test/test_room_config.py b/openapi/test/test_room_config.py similarity index 83% rename from jellyfish/openapi_client/test/test_room_config.py rename to openapi/test/test_room_config.py index 085f8c9..bb02f27 100644 --- a/jellyfish/openapi_client/test/test_room_config.py +++ b/openapi/test/test_room_config.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_config import RoomConfig # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_config import RoomConfig # noqa: E501 +from openapi_client.rest import ApiException class TestRoomConfig(unittest.TestCase): """RoomConfig unit test stubs""" @@ -35,7 +35,7 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `RoomConfig` """ - model = jellyfish_openapi_client.models.room_config.RoomConfig() # noqa: E501 + model = openapi_client.models.room_config.RoomConfig() # noqa: E501 if include_optional : return RoomConfig( max_peers = 10, diff --git a/jellyfish/openapi_client/test/test_room_create_details_response.py b/openapi/test/test_room_create_details_response.py similarity index 65% rename from jellyfish/openapi_client/test/test_room_create_details_response.py rename to openapi/test/test_room_create_details_response.py index 0027583..e4b5184 100644 --- a/jellyfish/openapi_client/test/test_room_create_details_response.py +++ b/openapi/test/test_room_create_details_response.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_create_details_response import RoomCreateDetailsResponse # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse # noqa: E501 +from openapi_client.rest import ApiException class TestRoomCreateDetailsResponse(unittest.TestCase): """RoomCreateDetailsResponse unit test stubs""" @@ -35,25 +35,25 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `RoomCreateDetailsResponse` """ - model = jellyfish_openapi_client.models.room_create_details_response.RoomCreateDetailsResponse() # noqa: E501 + model = openapi_client.models.room_create_details_response.RoomCreateDetailsResponse() # noqa: E501 if include_optional : return RoomCreateDetailsResponse( - data = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( + data = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( jellyfish_address = 'jellyfish1:5003', - room = jellyfish_openapi_client.models.room.Room( + room = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) @@ -61,22 +61,22 @@ def make_instance(self, include_optional): ) else : return RoomCreateDetailsResponse( - data = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( + data = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( jellyfish_address = 'jellyfish1:5003', - room = jellyfish_openapi_client.models.room.Room( + room = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) diff --git a/jellyfish/openapi_client/test/test_room_create_details_response_data.py b/openapi/test/test_room_create_details_response_data.py similarity index 69% rename from jellyfish/openapi_client/test/test_room_create_details_response_data.py rename to openapi/test/test_room_create_details_response_data.py index cefc635..e8281a3 100644 --- a/jellyfish/openapi_client/test/test_room_create_details_response_data.py +++ b/openapi/test/test_room_create_details_response_data.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData # noqa: E501 +from openapi_client.rest import ApiException class TestRoomCreateDetailsResponseData(unittest.TestCase): """RoomCreateDetailsResponseData unit test stubs""" @@ -35,24 +35,24 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `RoomCreateDetailsResponseData` """ - model = jellyfish_openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponseData() # noqa: E501 + model = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponseData() # noqa: E501 if include_optional : return RoomCreateDetailsResponseData( jellyfish_address = 'jellyfish1:5003', - room = jellyfish_openapi_client.models.room.Room( + room = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) @@ -61,20 +61,20 @@ def make_instance(self, include_optional): else : return RoomCreateDetailsResponseData( jellyfish_address = 'jellyfish1:5003', - room = jellyfish_openapi_client.models.room.Room( + room = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) diff --git a/jellyfish/openapi_client/test/test_room_details_response.py b/openapi/test/test_room_details_response.py similarity index 68% rename from jellyfish/openapi_client/test/test_room_details_response.py rename to openapi/test/test_room_details_response.py index bd82c93..8af5861 100644 --- a/jellyfish/openapi_client/test/test_room_details_response.py +++ b/openapi/test/test_room_details_response.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.room_details_response import RoomDetailsResponse # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.room_details_response import RoomDetailsResponse # noqa: E501 +from openapi_client.rest import ApiException class TestRoomDetailsResponse(unittest.TestCase): """RoomDetailsResponse unit test stubs""" @@ -35,23 +35,23 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `RoomDetailsResponse` """ - model = jellyfish_openapi_client.models.room_details_response.RoomDetailsResponse() # noqa: E501 + model = openapi_client.models.room_details_response.RoomDetailsResponse() # noqa: E501 if include_optional : return RoomDetailsResponse( - data = jellyfish_openapi_client.models.room.Room( + data = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) @@ -59,20 +59,20 @@ def make_instance(self, include_optional): ) else : return RoomDetailsResponse( - data = jellyfish_openapi_client.models.room.Room( + data = openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) diff --git a/jellyfish/openapi_client/test/test_rooms_listing_response.py b/openapi/test/test_rooms_listing_response.py similarity index 69% rename from jellyfish/openapi_client/test/test_rooms_listing_response.py rename to openapi/test/test_rooms_listing_response.py index 3ea8d82..55b52ad 100644 --- a/jellyfish/openapi_client/test/test_rooms_listing_response.py +++ b/openapi/test/test_rooms_listing_response.py @@ -15,9 +15,9 @@ import unittest import datetime -import jellyfish_openapi_client -from jellyfish_openapi_client.models.rooms_listing_response import RoomsListingResponse # noqa: E501 -from jellyfish_openapi_client.rest import ApiException +import openapi_client +from openapi_client.models.rooms_listing_response import RoomsListingResponse # noqa: E501 +from openapi_client.rest import ApiException class TestRoomsListingResponse(unittest.TestCase): """RoomsListingResponse unit test stubs""" @@ -35,24 +35,24 @@ def make_instance(self, include_optional): optional params are included """ # uncomment below to create an instance of `RoomsListingResponse` """ - model = jellyfish_openapi_client.models.rooms_listing_response.RoomsListingResponse() # noqa: E501 + model = openapi_client.models.rooms_listing_response.RoomsListingResponse() # noqa: E501 if include_optional : return RoomsListingResponse( data = [ - jellyfish_openapi_client.models.room.Room( + openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) @@ -62,20 +62,20 @@ def make_instance(self, include_optional): else : return RoomsListingResponse( data = [ - jellyfish_openapi_client.models.room.Room( + openapi_client.models.room.Room( components = [ - jellyfish_openapi_client.models.component.Component( + openapi_client.models.component.Component( id = 'component-1', - metadata = jellyfish_openapi_client.models.component_metadata.ComponentMetadata( + metadata = openapi_client.models.component_metadata.ComponentMetadata( playable = True, ), type = 'hls', ) ], - config = jellyfish_openapi_client.models.room_config.RoomConfig( + config = openapi_client.models.room_config.RoomConfig( max_peers = 10, video_codec = 'h264', ), id = 'room-1', peers = [ - jellyfish_openapi_client.models.peer.Peer( + openapi_client.models.peer.Peer( id = 'peer-1', status = 'disconnected', type = 'webrtc', ) diff --git a/jellyfish/openapi_client/tox.ini b/openapi/tox.ini similarity index 74% rename from jellyfish/openapi_client/tox.ini rename to openapi/tox.ini index b47cf30..1a9028b 100644 --- a/jellyfish/openapi_client/tox.ini +++ b/openapi/tox.ini @@ -6,4 +6,4 @@ deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt commands= - pytest --cov=jellyfish_openapi_client + pytest --cov=openapi_client diff --git a/tests/test_room_api.py b/tests/test_room_api.py index a1f64f0..f31595d 100644 --- a/tests/test_room_api.py +++ b/tests/test_room_api.py @@ -4,17 +4,17 @@ Tests room api """ - import pytest -import jellyfish - from jellyfish import RoomApi, RoomConfig -from jellyfish import Room, Component +from jellyfish import Room from jellyfish import ComponentOptionsRTSP, PeerOptionsWebRTC from jellyfish import ValidationError +from jellyfish import UnauthorizedException, NotFoundException, BadRequestException + + SERVER_ADDRESS = "http://localhost:5002" SERVER_API_TOKEN = "development" @@ -34,13 +34,13 @@ class TestAuthentication: def test_invalid_token(self, room_api): room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token="invalid") - with pytest.raises(NotImplementedError): + with pytest.raises(UnauthorizedException): room_api.create_room() def test_valid_token(self, room_api): room_api = RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) - room = room_api.create_room() + _, room = room_api.create_room() all_rooms = room_api.get_all_rooms() @@ -49,7 +49,7 @@ def test_valid_token(self, room_api): @pytest.fixture def room_api(): - return jellyfish.RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) + return RoomApi(server_address=SERVER_ADDRESS, server_api_token=SERVER_API_TOKEN) class TestCreateRoom: @@ -81,108 +81,123 @@ class TestDeleteRoom: def test_valid(self, room_api): _, room = room_api.create_room() - room_api.delete(room.id) + room_api.delete_room(room.id) assert room not in room_api.get_all_rooms() def test_invalid(self, room_api): - with pytest.raises(RuntimeError): + with pytest.raises(NotFoundException): room_api.delete_room("invalid_id") class TestGetAllRooms: def test_valid(self, room_api): - room = room_api.create_room() + _, room = room_api.create_room() all_rooms = room_api.get_all_rooms() - assert all_rooms is list + assert isinstance(all_rooms, list) assert room in all_rooms class TestGetRoom: def test_valid(self, room_api: RoomApi): - room = room_api.create_room() + _, room = room_api.create_room() assert Room(components=[], peers=[], id=room.id, config=RoomConfig( maxPeers=None, videoCodec=None)) == room_api.get_room(room.id) def test_invalid(self, room_api: RoomApi): - with pytest.raises(NotImplementedError): + with pytest.raises(NotFoundException): room_api.get_room("invalid_id") class TestAddComponent: - def test_with_options(self, room_api: RoomApi): - room_id = room_api.create_room().id + def test_with_options_hls(self, room_api: RoomApi): + _, room = room_api.create_room(video_codec="h264") + + room_api.add_component( + room.id, component_type=COMPONENT_HLS, options=HLS_OPTIONS) - component = room_api.add_component(room_id, type=COMPONENT_HLS, options=HLS_OPTIONS) - assert component == Component(id=component.id, type=COMPONENT_HLS) + component = room_api.get_room(room.id).components[0] - component = room_api.add_component(room_id, type=COMPONENT_RTSP, options=RTSP_OPTIONS) - assert component == Component(id=component.id, type=COMPONENT_RTSP) + assert component.type == "hls" - def test_without_options(self, room_api: RoomApi): - room_id = room_api.create_room().id + def test_with_options_rtsp(self, room_api: RoomApi): + _, room = room_api.create_room(video_codec="h264") - component = room_api.add_component(room_id, type=COMPONENT_HLS) - assert component == Component(id=component.id, type=COMPONENT_HLS) + room_api.add_component( + room.id, component_type=COMPONENT_RTSP, options=RTSP_OPTIONS) + component = room_api.get_room(room.id).components[0] + assert component.type == "rtsp" - with pytest.raises(NotImplementedError): - room_api.add_component(room_id, type=COMPONENT_RTSP) + def test_without_options_hls(self, room_api: RoomApi): + _, room = room_api.create_room(video_codec="h264") + + component = room_api.add_component(room.id, component_type=COMPONENT_HLS) + assert component.type == "hls" + + def test_without_options_rtsp(self, room_api: RoomApi): + _, room = room_api.create_room(video_codec="h264") + + with pytest.raises(BadRequestException): + room_api.add_component(room.id, component_type=COMPONENT_RTSP) def test_invalid_type(self, room_api: RoomApi): - room_id = room_api.create_room().id + _, room = room_api.create_room(video_codec="h264") - with pytest.raises(NotImplementedError): - room_api.add_component(room_id, type="CsmaCd") + with pytest.raises(BadRequestException): + room_api.add_component(room.id, component_type="CsmaCd") class TestDeleteComponent: def test_valid_component(self, room_api: RoomApi): - room_id = room_api.create_room().id - component = room_api.add_component(room_id, type=COMPONENT_HLS, options=HLS_OPTIONS) + _, room = room_api.create_room(video_codec="h264") + component = room_api.add_component( + room.id, component_type=COMPONENT_HLS) - room_api.delete_component(room_id, component.id) - assert [] == room_api.get_room(room_id).components + room_api.delete_component(room.id, component.id) + assert [] == room_api.get_room(room.id).components def test_invalid_component(self, room_api: RoomApi): - room_id = room_api.create_room().id + _, room = room_api.create_room() - with pytest.raises(TypeError): - room_api.delete_component(room_id, "invalid_id") + with pytest.raises(NotFoundException): + room_api.delete_component(room.id, "invalid_id") class TestAddPeer: def test_valid(self, room_api: RoomApi): - room_id = room_api.create_room().id + _, room = room_api.create_room() - peer = room_api.add_peer(room_id, type="webrtc", - options=PeerOptionsWebRTC(enableSimulcast=True)) + _token, peer = room_api.add_peer(room.id, peer_type="webrtc", + options=PeerOptionsWebRTC(enableSimulcast=True)) assert peer.status == "disconnected" assert peer.type == "webrtc" - room = room_api.get_room(room_id) + room = room_api.get_room(room.id) assert peer in room.peers def test_invalid(self, room_api: RoomApi): - room_id = room_api.create_room().id + _, room = room_api.create_room() - with pytest.raises(NotImplementedError): - room_api.add_peer(room_id, type="invalid_type") + with pytest.raises(BadRequestException): + room_api.add_peer( + room.id, peer_type="invalid_type", + options=PeerOptionsWebRTC(enableSimulcast=True)) class TestDeletePeer: def test_valid(self, room_api: RoomApi): - room_id = room_api.create_room().id - peer = room_api.add_peer(room_id, type="webrtc", - options=PeerOptionsWebRTC(enableSimulcast=True)) + _, room = room_api.create_room() + _, peer = room_api.add_peer(room.id, peer_type="webrtc", + options=PeerOptionsWebRTC(enableSimulcast=True)) - room_api.delete_peer(peer.id) + room_api.delete_peer(room.id, peer.id) - assert [] == room_api.get_room(room_id).peers + assert [] == room_api.get_room(room.id).peers def test_invalid(self, room_api: RoomApi): - room_id = room_api.create_room().id + _, room = room_api.create_room() - with pytest.raises(NotImplementedError): - room_api.delete_peer(room_id, peer_id="invalid_peer_id") + with pytest.raises(NotFoundException): + room_api.delete_peer(room.id, peer_id="invalid_peer_id") From 5abd2f4cc5eede53dcb61dce5b3eee4e4db1f580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 7 Sep 2023 12:32:50 +0200 Subject: [PATCH 13/20] Add local dependency --- jellyfish/room_api.py | 2 +- requirements.txt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py index 72be4ce..8bcc895 100644 --- a/jellyfish/room_api.py +++ b/jellyfish/room_api.py @@ -33,7 +33,7 @@ def delete_room(self, room_id: str) -> None: return self._room_api.delete_room(room_id) - def get_all_rooms(self) -> list[Room]: + def get_all_rooms(self) -> list: """Returns list of all rooms""" return self._room_api.get_all_rooms().data diff --git a/requirements.txt b/requirements.txt index ffb4ad9..33ba987 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ python_dateutil==2.8.2 setuptools==67.6.1 typing_extensions==4.7.1 urllib3==2.0.4 -pylint==2.17.5 \ No newline at end of file +pylint==2.17.5 +./openapi \ No newline at end of file From 29990fc2c1aa418c1e7dd95c62875a03be5fce04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 7 Sep 2023 16:26:02 +0200 Subject: [PATCH 14/20] Remove some generated files --- .circleci/config.yml | 2 +- .gitignore | 2 +- docker-compose-test.yaml | 4 +- generate_client.sh | 6 +- jellyfish/README.md | 0 jellyfish/room_api.py | 14 +- openapi/.github/workflows/python.yml | 37 - openapi/.gitignore | 66 -- openapi/.gitlab-ci.yml | 25 - openapi/.openapi-generator-ignore | 23 - openapi/.openapi-generator/FILES | 92 --- openapi/.openapi-generator/VERSION | 1 - openapi/.travis.yml | 17 - openapi/README.md | 153 ----- openapi/docs/AddComponentRequest.md | 29 - openapi/docs/AddPeerRequest.md | 29 - openapi/docs/Component.md | 31 - openapi/docs/ComponentDetailsResponse.md | 29 - openapi/docs/ComponentMetadata.md | 29 - openapi/docs/ComponentOptions.md | 33 - openapi/docs/ComponentOptionsRTSP.md | 33 - openapi/docs/DefaultApi.md | 95 --- openapi/docs/Error.md | 29 - openapi/docs/HlsSkip.md | 11 - openapi/docs/Peer.md | 31 - openapi/docs/PeerDetailsResponse.md | 29 - openapi/docs/PeerDetailsResponseData.md | 29 - openapi/docs/PeerOptions.md | 29 - openapi/docs/PeerOptionsWebRTC.md | 29 - openapi/docs/PeerStatus.md | 11 - openapi/docs/Room.md | 32 - openapi/docs/RoomApi.md | 632 ------------------ openapi/docs/RoomConfig.md | 30 - openapi/docs/RoomCreateDetailsResponse.md | 29 - openapi/docs/RoomCreateDetailsResponseData.md | 29 - openapi/docs/RoomDetailsResponse.md | 29 - openapi/docs/RoomsListingResponse.md | 29 - openapi/git_push.sh | 57 -- openapi/setup.cfg | 2 - openapi/test-requirements.txt | 3 - openapi/test/__init__.py | 0 openapi/test/test_add_component_request.py | 56 -- openapi/test/test_add_peer_request.py | 57 -- openapi/test/test_component.py | 61 -- .../test/test_component_details_response.py | 63 -- openapi/test/test_component_metadata.py | 54 -- openapi/test/test_component_options.py | 59 -- openapi/test/test_component_options_rtsp.py | 59 -- openapi/test/test_default_api.py | 40 -- openapi/test/test_error.py | 55 -- openapi/test/test_hls_skip.py | 36 - openapi/test/test_peer.py | 59 -- openapi/test/test_peer_details_response.py | 65 -- .../test/test_peer_details_response_data.py | 63 -- openapi/test/test_peer_options.py | 54 -- openapi/test/test_peer_options_web_rtc.py | 54 -- openapi/test/test_peer_status.py | 36 - openapi/test/test_room.py | 87 --- openapi/test/test_room_api.py | 89 --- openapi/test/test_room_config.py | 55 -- .../test/test_room_create_details_response.py | 93 --- .../test_room_create_details_response_data.py | 91 --- openapi/test/test_room_details_response.py | 89 --- openapi/test/test_rooms_listing_response.py | 93 --- openapi/tox.ini | 9 - tests/__init__.py | 0 66 files changed, 15 insertions(+), 3282 deletions(-) delete mode 100644 jellyfish/README.md delete mode 100644 openapi/.github/workflows/python.yml delete mode 100644 openapi/.gitignore delete mode 100644 openapi/.gitlab-ci.yml delete mode 100644 openapi/.openapi-generator-ignore delete mode 100644 openapi/.openapi-generator/FILES delete mode 100644 openapi/.openapi-generator/VERSION delete mode 100644 openapi/.travis.yml delete mode 100644 openapi/README.md delete mode 100644 openapi/docs/AddComponentRequest.md delete mode 100644 openapi/docs/AddPeerRequest.md delete mode 100644 openapi/docs/Component.md delete mode 100644 openapi/docs/ComponentDetailsResponse.md delete mode 100644 openapi/docs/ComponentMetadata.md delete mode 100644 openapi/docs/ComponentOptions.md delete mode 100644 openapi/docs/ComponentOptionsRTSP.md delete mode 100644 openapi/docs/DefaultApi.md delete mode 100644 openapi/docs/Error.md delete mode 100644 openapi/docs/HlsSkip.md delete mode 100644 openapi/docs/Peer.md delete mode 100644 openapi/docs/PeerDetailsResponse.md delete mode 100644 openapi/docs/PeerDetailsResponseData.md delete mode 100644 openapi/docs/PeerOptions.md delete mode 100644 openapi/docs/PeerOptionsWebRTC.md delete mode 100644 openapi/docs/PeerStatus.md delete mode 100644 openapi/docs/Room.md delete mode 100644 openapi/docs/RoomApi.md delete mode 100644 openapi/docs/RoomConfig.md delete mode 100644 openapi/docs/RoomCreateDetailsResponse.md delete mode 100644 openapi/docs/RoomCreateDetailsResponseData.md delete mode 100644 openapi/docs/RoomDetailsResponse.md delete mode 100644 openapi/docs/RoomsListingResponse.md delete mode 100644 openapi/git_push.sh delete mode 100644 openapi/setup.cfg delete mode 100644 openapi/test-requirements.txt delete mode 100644 openapi/test/__init__.py delete mode 100644 openapi/test/test_add_component_request.py delete mode 100644 openapi/test/test_add_peer_request.py delete mode 100644 openapi/test/test_component.py delete mode 100644 openapi/test/test_component_details_response.py delete mode 100644 openapi/test/test_component_metadata.py delete mode 100644 openapi/test/test_component_options.py delete mode 100644 openapi/test/test_component_options_rtsp.py delete mode 100644 openapi/test/test_default_api.py delete mode 100644 openapi/test/test_error.py delete mode 100644 openapi/test/test_hls_skip.py delete mode 100644 openapi/test/test_peer.py delete mode 100644 openapi/test/test_peer_details_response.py delete mode 100644 openapi/test/test_peer_details_response_data.py delete mode 100644 openapi/test/test_peer_options.py delete mode 100644 openapi/test/test_peer_options_web_rtc.py delete mode 100644 openapi/test/test_peer_status.py delete mode 100644 openapi/test/test_room.py delete mode 100644 openapi/test/test_room_api.py delete mode 100644 openapi/test/test_room_config.py delete mode 100644 openapi/test/test_room_create_details_response.py delete mode 100644 openapi/test/test_room_create_details_response_data.py delete mode 100644 openapi/test/test_room_details_response.py delete mode 100644 openapi/test/test_rooms_listing_response.py delete mode 100644 openapi/tox.ini delete mode 100644 tests/__init__.py diff --git a/.circleci/config.yml b/.circleci/config.yml index 895d348..0a03cc4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -38,4 +38,4 @@ workflows: build: jobs: - lint - - test \ No newline at end of file + - test diff --git a/.gitignore b/.gitignore index 6769e21..68bc17f 100644 --- a/.gitignore +++ b/.gitignore @@ -157,4 +157,4 @@ cython_debug/ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ \ No newline at end of file +#.idea/ diff --git a/docker-compose-test.yaml b/docker-compose-test.yaml index b2bf4a6..6ddeb76 100644 --- a/docker-compose-test.yaml +++ b/docker-compose-test.yaml @@ -26,9 +26,9 @@ services: - "5002:5002" - "49999:49999" - "50000-50050:50000-50050/udp" - + test: - image: python:3.11.5-alpine3.18 + image: python:3.7-alpine3.18 command: sh -c "cd app/ && pip install -r requirements.txt && pytest" volumes: - .:/app diff --git a/generate_client.sh b/generate_client.sh index ab4d53a..6112a91 100755 --- a/generate_client.sh +++ b/generate_client.sh @@ -2,6 +2,8 @@ rm -rf openapi openapi-generator-cli generate \ -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/openapi-generator-compatibility/openapi.yaml \ -g python \ - -t templates \ -o openapi \ - --package-name openapi_client \ No newline at end of file + --package-name openapi_client \ + --global-property apis,models,modelTests=false,supportingFiles + +rm -rf openapi/{docs,test,.github,.openapi-generator,.gitignore,.gitlab-ci.yml,.travis.yml,.openapi-generator-ignore,git_push.sh,README.md,setup.cfg,test-requirements.txt,tox.ini} \ No newline at end of file diff --git a/jellyfish/README.md b/jellyfish/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py index 8bcc895..23e335d 100644 --- a/jellyfish/room_api.py +++ b/jellyfish/room_api.py @@ -4,14 +4,14 @@ import openapi_client as jellyfish_api -from openapi_client import AddPeerRequest, AddComponentRequest, PeerOptions, ComponentOptions -from openapi_client import Room, RoomConfig +from openapi_client import (AddPeerRequest, AddComponentRequest, PeerOptions, + ComponentOptions, Room, RoomConfig, Peer, Component) class RoomApi: """Allows for managing rooms""" - def __init__(self, server_address, server_api_token): + def __init__(self, server_address: str, server_api_token: str): self._configuration = jellyfish_api.Configuration( host=server_address, access_token=server_api_token @@ -43,7 +43,7 @@ def get_room(self, room_id: str) -> Room: return self._room_api.get_room(room_id).data - def add_peer(self, room_id: str, peer_type: str, options: PeerOptions): + def add_peer(self, room_id: str, peer_type: str, options) -> (str, Peer): """Creates peer in the room""" options = PeerOptions(options) @@ -52,12 +52,12 @@ def add_peer(self, room_id: str, peer_type: str, options: PeerOptions): resp = self._room_api.add_peer(room_id, request) return (resp.data.token, resp.data.peer) - def delete_peer(self, room_id, peer_id): + def delete_peer(self, room_id: str, peer_id: str) -> None: """Deletes peer""" return self._room_api.delete_peer(room_id, peer_id) - def add_component(self, room_id, component_type, options=None): + def add_component(self, room_id: str, component_type: str, options=None) -> Component: """Creates component in the room""" if options: @@ -67,7 +67,7 @@ def add_component(self, room_id, component_type, options=None): return self._room_api.add_component(room_id, request).data - def delete_component(self, room_id, component_id): + def delete_component(self, room_id: str, component_id: str) -> None: """Deletes component""" return self._room_api.delete_component(room_id, component_id) diff --git a/openapi/.github/workflows/python.yml b/openapi/.github/workflows/python.yml deleted file mode 100644 index bcc6ea7..0000000 --- a/openapi/.github/workflows/python.yml +++ /dev/null @@ -1,37 +0,0 @@ -# NOTE: This file is auto generated by OpenAPI Generator. -# URL: https://openapi-generator.tech -# -# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python - -name: openapi_client Python package - -on: [push, pull_request] - -jobs: - build: - - runs-on: ubuntu-latest - strategy: - matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] - - steps: - - uses: actions/checkout@v3 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install flake8 pytest - if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - - name: Lint with flake8 - run: | - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - - name: Test with pytest - run: | - pytest diff --git a/openapi/.gitignore b/openapi/.gitignore deleted file mode 100644 index 43995bd..0000000 --- a/openapi/.gitignore +++ /dev/null @@ -1,66 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ -venv/ -.venv/ -.python-version -.pytest_cache - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -#Ipython Notebook -.ipynb_checkpoints diff --git a/openapi/.gitlab-ci.yml b/openapi/.gitlab-ci.yml deleted file mode 100644 index 00e696f..0000000 --- a/openapi/.gitlab-ci.yml +++ /dev/null @@ -1,25 +0,0 @@ -# NOTE: This file is auto generated by OpenAPI Generator. -# URL: https://openapi-generator.tech -# -# ref: https://docs.gitlab.com/ee/ci/README.html -# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml - -stages: - - test - -.pytest: - stage: test - script: - - pip install -r requirements.txt - - pip install -r test-requirements.txt - - pytest --cov=openapi_client - -pytest-3.7: - extends: .pytest - image: python:3.7-alpine -pytest-3.8: - extends: .pytest - image: python:3.8-alpine -pytest-3.9: - extends: .pytest - image: python:3.9-alpine \ No newline at end of file diff --git a/openapi/.openapi-generator-ignore b/openapi/.openapi-generator-ignore deleted file mode 100644 index 7484ee5..0000000 --- a/openapi/.openapi-generator-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# OpenAPI Generator Ignore -# Generated by openapi-generator https://github.com/openapitools/openapi-generator - -# Use this file to prevent files from being overwritten by the generator. -# The patterns follow closely to .gitignore or .dockerignore. - -# As an example, the C# client generator defines ApiClient.cs. -# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: -#ApiClient.cs - -# You can match any string of characters against a directory, file or extension with a single asterisk (*): -#foo/*/qux -# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux - -# You can recursively match patterns against a directory, file or extension with a double asterisk (**): -#foo/**/qux -# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux - -# You can also negate patterns with an exclamation (!). -# For example, you can ignore all files in a docs folder with the file extension .md: -#docs/*.md -# Then explicitly reverse the ignore rule for a single file: -#!docs/README.md diff --git a/openapi/.openapi-generator/FILES b/openapi/.openapi-generator/FILES deleted file mode 100644 index 56dbf7d..0000000 --- a/openapi/.openapi-generator/FILES +++ /dev/null @@ -1,92 +0,0 @@ -.github/workflows/python.yml -.gitignore -.gitlab-ci.yml -.openapi-generator-ignore -.travis.yml -README.md -docs/AddComponentRequest.md -docs/AddPeerRequest.md -docs/Component.md -docs/ComponentDetailsResponse.md -docs/ComponentMetadata.md -docs/ComponentOptions.md -docs/ComponentOptionsRTSP.md -docs/DefaultApi.md -docs/Error.md -docs/HlsSkip.md -docs/Peer.md -docs/PeerDetailsResponse.md -docs/PeerDetailsResponseData.md -docs/PeerOptions.md -docs/PeerOptionsWebRTC.md -docs/PeerStatus.md -docs/Room.md -docs/RoomApi.md -docs/RoomConfig.md -docs/RoomCreateDetailsResponse.md -docs/RoomCreateDetailsResponseData.md -docs/RoomDetailsResponse.md -docs/RoomsListingResponse.md -git_push.sh -openapi_client/__init__.py -openapi_client/api/__init__.py -openapi_client/api/default_api.py -openapi_client/api/room_api.py -openapi_client/api_client.py -openapi_client/api_response.py -openapi_client/configuration.py -openapi_client/exceptions.py -openapi_client/models/__init__.py -openapi_client/models/add_component_request.py -openapi_client/models/add_peer_request.py -openapi_client/models/component.py -openapi_client/models/component_details_response.py -openapi_client/models/component_metadata.py -openapi_client/models/component_options.py -openapi_client/models/component_options_rtsp.py -openapi_client/models/error.py -openapi_client/models/hls_skip.py -openapi_client/models/peer.py -openapi_client/models/peer_details_response.py -openapi_client/models/peer_details_response_data.py -openapi_client/models/peer_options.py -openapi_client/models/peer_options_web_rtc.py -openapi_client/models/peer_status.py -openapi_client/models/room.py -openapi_client/models/room_config.py -openapi_client/models/room_create_details_response.py -openapi_client/models/room_create_details_response_data.py -openapi_client/models/room_details_response.py -openapi_client/models/rooms_listing_response.py -openapi_client/py.typed -openapi_client/rest.py -pyproject.toml -requirements.txt -setup.cfg -setup.py -test-requirements.txt -test/__init__.py -test/test_add_component_request.py -test/test_add_peer_request.py -test/test_component.py -test/test_component_details_response.py -test/test_component_metadata.py -test/test_component_options.py -test/test_component_options_rtsp.py -test/test_default_api.py -test/test_error.py -test/test_hls_skip.py -test/test_peer.py -test/test_peer_details_response.py -test/test_peer_details_response_data.py -test/test_peer_options.py -test/test_peer_options_web_rtc.py -test/test_peer_status.py -test/test_room.py -test/test_room_api.py -test/test_room_config.py -test/test_room_create_details_response.py -test/test_room_create_details_response_data.py -test/test_room_details_response.py -test/test_rooms_listing_response.py -tox.ini diff --git a/openapi/.openapi-generator/VERSION b/openapi/.openapi-generator/VERSION deleted file mode 100644 index 4122521..0000000 --- a/openapi/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -7.0.0 \ No newline at end of file diff --git a/openapi/.travis.yml b/openapi/.travis.yml deleted file mode 100644 index fd888f7..0000000 --- a/openapi/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -# ref: https://docs.travis-ci.com/user/languages/python -language: python -python: - - "3.7" - - "3.8" - - "3.9" - - "3.10" - - "3.11" - # uncomment the following if needed - #- "3.11-dev" # 3.11 development branch - #- "nightly" # nightly build -# command to install dependencies -install: - - "pip install -r requirements.txt" - - "pip install -r test-requirements.txt" -# command to run tests -script: pytest --cov=openapi_client diff --git a/openapi/README.md b/openapi/README.md deleted file mode 100644 index c205c1e..0000000 --- a/openapi/README.md +++ /dev/null @@ -1,153 +0,0 @@ -# openapi-client -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 0.2.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonClientCodegen - -## Requirements. - -Python 3.7+ - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import openapi_client -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import openapi_client -``` - -### Tests - -Execute `pytest` to run the tests. - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python - -import time -import openapi_client -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.DefaultApi(api_client) - room_id = 'room_id_example' # str | Room id - filename = 'filename_example' # str | Name of the file - range = 'range_example' # str | Byte range of partial segment (optional) - hls_msn = 56 # int | Segment sequence number (optional) - hls_part = 56 # int | Partial segment sequence number (optional) - hls_skip = openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) - - try: - # Send file - api_response = api_instance.jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) - print("The response of DefaultApi->jellyfish_web_hls_controller_index:\n") - pprint(api_response) - except ApiException as e: - print("Exception when calling DefaultApi->jellyfish_web_hls_controller_index: %s\n" % e) - -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**jellyfish_web_hls_controller_index**](docs/DefaultApi.md#jellyfish_web_hls_controller_index) | **GET** /hls/{room_id}/{filename} | Send file -*RoomApi* | [**add_component**](docs/RoomApi.md#add_component) | **POST** /room/{room_id}/component | Creates the component and adds it to the room -*RoomApi* | [**add_peer**](docs/RoomApi.md#add_peer) | **POST** /room/{room_id}/peer | Create peer -*RoomApi* | [**create_room**](docs/RoomApi.md#create_room) | **POST** /room | Creates a room -*RoomApi* | [**delete_component**](docs/RoomApi.md#delete_component) | **DELETE** /room/{room_id}/component/{id} | Delete the component from the room -*RoomApi* | [**delete_peer**](docs/RoomApi.md#delete_peer) | **DELETE** /room/{room_id}/peer/{id} | Delete peer -*RoomApi* | [**delete_room**](docs/RoomApi.md#delete_room) | **DELETE** /room/{room_id} | Delete the room -*RoomApi* | [**get_all_rooms**](docs/RoomApi.md#get_all_rooms) | **GET** /room | Show information about all rooms -*RoomApi* | [**get_room**](docs/RoomApi.md#get_room) | **GET** /room/{room_id} | Shows information about the room - - -## Documentation For Models - - - [AddComponentRequest](docs/AddComponentRequest.md) - - [AddPeerRequest](docs/AddPeerRequest.md) - - [Component](docs/Component.md) - - [ComponentDetailsResponse](docs/ComponentDetailsResponse.md) - - [ComponentMetadata](docs/ComponentMetadata.md) - - [ComponentOptions](docs/ComponentOptions.md) - - [ComponentOptionsRTSP](docs/ComponentOptionsRTSP.md) - - [Error](docs/Error.md) - - [HlsSkip](docs/HlsSkip.md) - - [Peer](docs/Peer.md) - - [PeerDetailsResponse](docs/PeerDetailsResponse.md) - - [PeerDetailsResponseData](docs/PeerDetailsResponseData.md) - - [PeerOptions](docs/PeerOptions.md) - - [PeerOptionsWebRTC](docs/PeerOptionsWebRTC.md) - - [PeerStatus](docs/PeerStatus.md) - - [Room](docs/Room.md) - - [RoomConfig](docs/RoomConfig.md) - - [RoomCreateDetailsResponse](docs/RoomCreateDetailsResponse.md) - - [RoomCreateDetailsResponseData](docs/RoomCreateDetailsResponseData.md) - - [RoomDetailsResponse](docs/RoomDetailsResponse.md) - - [RoomsListingResponse](docs/RoomsListingResponse.md) - - - -## Documentation For Authorization - - -Authentication schemes defined for the API: - -### authorization - -- **Type**: Bearer authentication - - -## Author - - - - diff --git a/openapi/docs/AddComponentRequest.md b/openapi/docs/AddComponentRequest.md deleted file mode 100644 index 47f87df..0000000 --- a/openapi/docs/AddComponentRequest.md +++ /dev/null @@ -1,29 +0,0 @@ -# AddComponentRequest - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**options** | [**ComponentOptions**](ComponentOptions.md) | | [optional] -**type** | **str** | Component type | - -## Example - -```python -from openapi_client.models.add_component_request import AddComponentRequest - -# TODO update the JSON string below -json = "{}" -# create an instance of AddComponentRequest from a JSON string -add_component_request_instance = AddComponentRequest.from_json(json) -# print the JSON string representation of the object -print AddComponentRequest.to_json() - -# convert the object into a dict -add_component_request_dict = add_component_request_instance.to_dict() -# create an instance of AddComponentRequest from a dict -add_component_request_form_dict = add_component_request.from_dict(add_component_request_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/AddPeerRequest.md b/openapi/docs/AddPeerRequest.md deleted file mode 100644 index b9aa940..0000000 --- a/openapi/docs/AddPeerRequest.md +++ /dev/null @@ -1,29 +0,0 @@ -# AddPeerRequest - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**options** | [**PeerOptions**](PeerOptions.md) | | -**type** | **str** | Peer type | - -## Example - -```python -from openapi_client.models.add_peer_request import AddPeerRequest - -# TODO update the JSON string below -json = "{}" -# create an instance of AddPeerRequest from a JSON string -add_peer_request_instance = AddPeerRequest.from_json(json) -# print the JSON string representation of the object -print AddPeerRequest.to_json() - -# convert the object into a dict -add_peer_request_dict = add_peer_request_instance.to_dict() -# create an instance of AddPeerRequest from a dict -add_peer_request_form_dict = add_peer_request.from_dict(add_peer_request_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/Component.md b/openapi/docs/Component.md deleted file mode 100644 index 889c277..0000000 --- a/openapi/docs/Component.md +++ /dev/null @@ -1,31 +0,0 @@ -# Component - -Describes component - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **str** | Assigned component id | -**metadata** | [**ComponentMetadata**](ComponentMetadata.md) | | -**type** | **str** | Component type | - -## Example - -```python -from openapi_client.models.component import Component - -# TODO update the JSON string below -json = "{}" -# create an instance of Component from a JSON string -component_instance = Component.from_json(json) -# print the JSON string representation of the object -print Component.to_json() - -# convert the object into a dict -component_dict = component_instance.to_dict() -# create an instance of Component from a dict -component_form_dict = component.from_dict(component_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/ComponentDetailsResponse.md b/openapi/docs/ComponentDetailsResponse.md deleted file mode 100644 index 13c9791..0000000 --- a/openapi/docs/ComponentDetailsResponse.md +++ /dev/null @@ -1,29 +0,0 @@ -# ComponentDetailsResponse - -Response containing component details - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**data** | [**Component**](Component.md) | | - -## Example - -```python -from openapi_client.models.component_details_response import ComponentDetailsResponse - -# TODO update the JSON string below -json = "{}" -# create an instance of ComponentDetailsResponse from a JSON string -component_details_response_instance = ComponentDetailsResponse.from_json(json) -# print the JSON string representation of the object -print ComponentDetailsResponse.to_json() - -# convert the object into a dict -component_details_response_dict = component_details_response_instance.to_dict() -# create an instance of ComponentDetailsResponse from a dict -component_details_response_form_dict = component_details_response.from_dict(component_details_response_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/ComponentMetadata.md b/openapi/docs/ComponentMetadata.md deleted file mode 100644 index cc45057..0000000 --- a/openapi/docs/ComponentMetadata.md +++ /dev/null @@ -1,29 +0,0 @@ -# ComponentMetadata - -Component-specific metadata - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**playable** | **bool** | | [optional] - -## Example - -```python -from openapi_client.models.component_metadata import ComponentMetadata - -# TODO update the JSON string below -json = "{}" -# create an instance of ComponentMetadata from a JSON string -component_metadata_instance = ComponentMetadata.from_json(json) -# print the JSON string representation of the object -print ComponentMetadata.to_json() - -# convert the object into a dict -component_metadata_dict = component_metadata_instance.to_dict() -# create an instance of ComponentMetadata from a dict -component_metadata_form_dict = component_metadata.from_dict(component_metadata_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/ComponentOptions.md b/openapi/docs/ComponentOptions.md deleted file mode 100644 index 3ad562a..0000000 --- a/openapi/docs/ComponentOptions.md +++ /dev/null @@ -1,33 +0,0 @@ -# ComponentOptions - -Component-specific options - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**keep_alive_interval** | **int** | Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source | [optional] [default to 15000] -**pierce_nat** | **bool** | Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup | [optional] [default to True] -**reconnect_delay** | **int** | Delay (in ms) between successive reconnect attempts | [optional] [default to 15000] -**rtp_port** | **int** | Local port RTP stream will be received at | [optional] [default to 20000] -**source_uri** | **str** | URI of RTSP source stream | - -## Example - -```python -from openapi_client.models.component_options import ComponentOptions - -# TODO update the JSON string below -json = "{}" -# create an instance of ComponentOptions from a JSON string -component_options_instance = ComponentOptions.from_json(json) -# print the JSON string representation of the object -print ComponentOptions.to_json() - -# convert the object into a dict -component_options_dict = component_options_instance.to_dict() -# create an instance of ComponentOptions from a dict -component_options_form_dict = component_options.from_dict(component_options_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/ComponentOptionsRTSP.md b/openapi/docs/ComponentOptionsRTSP.md deleted file mode 100644 index dd6385e..0000000 --- a/openapi/docs/ComponentOptionsRTSP.md +++ /dev/null @@ -1,33 +0,0 @@ -# ComponentOptionsRTSP - -Options specific to the RTSP component - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**keep_alive_interval** | **int** | Interval (in ms) in which keep-alive RTSP messages will be sent to the remote stream source | [optional] [default to 15000] -**pierce_nat** | **bool** | Whether to attempt to create client-side NAT binding by sending an empty datagram from client to source, after the completion of RTSP setup | [optional] [default to True] -**reconnect_delay** | **int** | Delay (in ms) between successive reconnect attempts | [optional] [default to 15000] -**rtp_port** | **int** | Local port RTP stream will be received at | [optional] [default to 20000] -**source_uri** | **str** | URI of RTSP source stream | - -## Example - -```python -from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP - -# TODO update the JSON string below -json = "{}" -# create an instance of ComponentOptionsRTSP from a JSON string -component_options_rtsp_instance = ComponentOptionsRTSP.from_json(json) -# print the JSON string representation of the object -print ComponentOptionsRTSP.to_json() - -# convert the object into a dict -component_options_rtsp_dict = component_options_rtsp_instance.to_dict() -# create an instance of ComponentOptionsRTSP from a dict -component_options_rtsp_form_dict = component_options_rtsp.from_dict(component_options_rtsp_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/DefaultApi.md b/openapi/docs/DefaultApi.md deleted file mode 100644 index 42ece10..0000000 --- a/openapi/docs/DefaultApi.md +++ /dev/null @@ -1,95 +0,0 @@ -# openapi_client.DefaultApi - -All URIs are relative to *http://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**jellyfish_web_hls_controller_index**](DefaultApi.md#jellyfish_web_hls_controller_index) | **GET** /hls/{room_id}/{filename} | Send file - - -# **jellyfish_web_hls_controller_index** -> str jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) - -Send file - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.hls_skip import HlsSkip -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.DefaultApi(api_client) - room_id = 'room_id_example' # str | Room id - filename = 'filename_example' # str | Name of the file - range = 'range_example' # str | Byte range of partial segment (optional) - hls_msn = 56 # int | Segment sequence number (optional) - hls_part = 56 # int | Partial segment sequence number (optional) - hls_skip = openapi_client.HlsSkip() # HlsSkip | Is delta manifest requested (optional) - - try: - # Send file - api_response = api_instance.jellyfish_web_hls_controller_index(room_id, filename, range=range, hls_msn=hls_msn, hls_part=hls_part, hls_skip=hls_skip) - print("The response of DefaultApi->jellyfish_web_hls_controller_index:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling DefaultApi->jellyfish_web_hls_controller_index: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room id | - **filename** | **str**| Name of the file | - **range** | **str**| Byte range of partial segment | [optional] - **hls_msn** | **int**| Segment sequence number | [optional] - **hls_part** | **int**| Partial segment sequence number | [optional] - **hls_skip** | [**HlsSkip**](.md)| Is delta manifest requested | [optional] - -### Return type - -**str** - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | File was found | - | -**404** | File not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/openapi/docs/Error.md b/openapi/docs/Error.md deleted file mode 100644 index f863d4b..0000000 --- a/openapi/docs/Error.md +++ /dev/null @@ -1,29 +0,0 @@ -# Error - -Error message - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**errors** | **str** | Error details | - -## Example - -```python -from openapi_client.models.error import Error - -# TODO update the JSON string below -json = "{}" -# create an instance of Error from a JSON string -error_instance = Error.from_json(json) -# print the JSON string representation of the object -print Error.to_json() - -# convert the object into a dict -error_dict = error_instance.to_dict() -# create an instance of Error from a dict -error_form_dict = error.from_dict(error_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/HlsSkip.md b/openapi/docs/HlsSkip.md deleted file mode 100644 index c141496..0000000 --- a/openapi/docs/HlsSkip.md +++ /dev/null @@ -1,11 +0,0 @@ -# HlsSkip - -Is delta manifest requested - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/Peer.md b/openapi/docs/Peer.md deleted file mode 100644 index 73f0021..0000000 --- a/openapi/docs/Peer.md +++ /dev/null @@ -1,31 +0,0 @@ -# Peer - -Describes peer status - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **str** | Assigned peer id | -**status** | [**PeerStatus**](PeerStatus.md) | | -**type** | **str** | Peer type | - -## Example - -```python -from openapi_client.models.peer import Peer - -# TODO update the JSON string below -json = "{}" -# create an instance of Peer from a JSON string -peer_instance = Peer.from_json(json) -# print the JSON string representation of the object -print Peer.to_json() - -# convert the object into a dict -peer_dict = peer_instance.to_dict() -# create an instance of Peer from a dict -peer_form_dict = peer.from_dict(peer_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/PeerDetailsResponse.md b/openapi/docs/PeerDetailsResponse.md deleted file mode 100644 index 77ea231..0000000 --- a/openapi/docs/PeerDetailsResponse.md +++ /dev/null @@ -1,29 +0,0 @@ -# PeerDetailsResponse - -Response containing peer details and their token - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**data** | [**PeerDetailsResponseData**](PeerDetailsResponseData.md) | | - -## Example - -```python -from openapi_client.models.peer_details_response import PeerDetailsResponse - -# TODO update the JSON string below -json = "{}" -# create an instance of PeerDetailsResponse from a JSON string -peer_details_response_instance = PeerDetailsResponse.from_json(json) -# print the JSON string representation of the object -print PeerDetailsResponse.to_json() - -# convert the object into a dict -peer_details_response_dict = peer_details_response_instance.to_dict() -# create an instance of PeerDetailsResponse from a dict -peer_details_response_form_dict = peer_details_response.from_dict(peer_details_response_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/PeerDetailsResponseData.md b/openapi/docs/PeerDetailsResponseData.md deleted file mode 100644 index 41bb19b..0000000 --- a/openapi/docs/PeerDetailsResponseData.md +++ /dev/null @@ -1,29 +0,0 @@ -# PeerDetailsResponseData - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**peer** | [**Peer**](Peer.md) | | -**token** | **str** | Token for authorizing websocket connection | - -## Example - -```python -from openapi_client.models.peer_details_response_data import PeerDetailsResponseData - -# TODO update the JSON string below -json = "{}" -# create an instance of PeerDetailsResponseData from a JSON string -peer_details_response_data_instance = PeerDetailsResponseData.from_json(json) -# print the JSON string representation of the object -print PeerDetailsResponseData.to_json() - -# convert the object into a dict -peer_details_response_data_dict = peer_details_response_data_instance.to_dict() -# create an instance of PeerDetailsResponseData from a dict -peer_details_response_data_form_dict = peer_details_response_data.from_dict(peer_details_response_data_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/PeerOptions.md b/openapi/docs/PeerOptions.md deleted file mode 100644 index 1d1d9a2..0000000 --- a/openapi/docs/PeerOptions.md +++ /dev/null @@ -1,29 +0,0 @@ -# PeerOptions - -Peer-specific options - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enable_simulcast** | **bool** | Enables the peer to use simulcast | [optional] [default to True] - -## Example - -```python -from openapi_client.models.peer_options import PeerOptions - -# TODO update the JSON string below -json = "{}" -# create an instance of PeerOptions from a JSON string -peer_options_instance = PeerOptions.from_json(json) -# print the JSON string representation of the object -print PeerOptions.to_json() - -# convert the object into a dict -peer_options_dict = peer_options_instance.to_dict() -# create an instance of PeerOptions from a dict -peer_options_form_dict = peer_options.from_dict(peer_options_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/PeerOptionsWebRTC.md b/openapi/docs/PeerOptionsWebRTC.md deleted file mode 100644 index bebb22e..0000000 --- a/openapi/docs/PeerOptionsWebRTC.md +++ /dev/null @@ -1,29 +0,0 @@ -# PeerOptionsWebRTC - -Options specific to the WebRTC peer - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enable_simulcast** | **bool** | Enables the peer to use simulcast | [optional] [default to True] - -## Example - -```python -from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC - -# TODO update the JSON string below -json = "{}" -# create an instance of PeerOptionsWebRTC from a JSON string -peer_options_web_rtc_instance = PeerOptionsWebRTC.from_json(json) -# print the JSON string representation of the object -print PeerOptionsWebRTC.to_json() - -# convert the object into a dict -peer_options_web_rtc_dict = peer_options_web_rtc_instance.to_dict() -# create an instance of PeerOptionsWebRTC from a dict -peer_options_web_rtc_form_dict = peer_options_web_rtc.from_dict(peer_options_web_rtc_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/PeerStatus.md b/openapi/docs/PeerStatus.md deleted file mode 100644 index 951877e..0000000 --- a/openapi/docs/PeerStatus.md +++ /dev/null @@ -1,11 +0,0 @@ -# PeerStatus - -Informs about the peer status - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/Room.md b/openapi/docs/Room.md deleted file mode 100644 index 6a1c3c1..0000000 --- a/openapi/docs/Room.md +++ /dev/null @@ -1,32 +0,0 @@ -# Room - -Description of the room state - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**components** | [**List[Component]**](Component.md) | | -**config** | [**RoomConfig**](RoomConfig.md) | | -**id** | **str** | Room ID | -**peers** | [**List[Peer]**](Peer.md) | | - -## Example - -```python -from openapi_client.models.room import Room - -# TODO update the JSON string below -json = "{}" -# create an instance of Room from a JSON string -room_instance = Room.from_json(json) -# print the JSON string representation of the object -print Room.to_json() - -# convert the object into a dict -room_dict = room_instance.to_dict() -# create an instance of Room from a dict -room_form_dict = room.from_dict(room_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/RoomApi.md b/openapi/docs/RoomApi.md deleted file mode 100644 index 8aed42f..0000000 --- a/openapi/docs/RoomApi.md +++ /dev/null @@ -1,632 +0,0 @@ -# openapi_client.RoomApi - -All URIs are relative to *http://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**add_component**](RoomApi.md#add_component) | **POST** /room/{room_id}/component | Creates the component and adds it to the room -[**add_peer**](RoomApi.md#add_peer) | **POST** /room/{room_id}/peer | Create peer -[**create_room**](RoomApi.md#create_room) | **POST** /room | Creates a room -[**delete_component**](RoomApi.md#delete_component) | **DELETE** /room/{room_id}/component/{id} | Delete the component from the room -[**delete_peer**](RoomApi.md#delete_peer) | **DELETE** /room/{room_id}/peer/{id} | Delete peer -[**delete_room**](RoomApi.md#delete_room) | **DELETE** /room/{room_id} | Delete the room -[**get_all_rooms**](RoomApi.md#get_all_rooms) | **GET** /room | Show information about all rooms -[**get_room**](RoomApi.md#get_room) | **GET** /room/{room_id} | Shows information about the room - - -# **add_component** -> ComponentDetailsResponse add_component(room_id, add_component_request=add_component_request) - -Creates the component and adds it to the room - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.add_component_request import AddComponentRequest -from openapi_client.models.component_details_response import ComponentDetailsResponse -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room ID - add_component_request = openapi_client.AddComponentRequest() # AddComponentRequest | Component config (optional) - - try: - # Creates the component and adds it to the room - api_response = api_instance.add_component(room_id, add_component_request=add_component_request) - print("The response of RoomApi->add_component:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling RoomApi->add_component: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room ID | - **add_component_request** | [**AddComponentRequest**](AddComponentRequest.md)| Component config | [optional] - -### Return type - -[**ComponentDetailsResponse**](ComponentDetailsResponse.md) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**201** | Successfully added component | - | -**400** | Invalid request | - | -**401** | Unauthorized | - | -**404** | Room doesn't exist | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **add_peer** -> PeerDetailsResponse add_peer(room_id, add_peer_request=add_peer_request) - -Create peer - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.add_peer_request import AddPeerRequest -from openapi_client.models.peer_details_response import PeerDetailsResponse -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room id - add_peer_request = openapi_client.AddPeerRequest() # AddPeerRequest | Peer specification (optional) - - try: - # Create peer - api_response = api_instance.add_peer(room_id, add_peer_request=add_peer_request) - print("The response of RoomApi->add_peer:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling RoomApi->add_peer: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room id | - **add_peer_request** | [**AddPeerRequest**](AddPeerRequest.md)| Peer specification | [optional] - -### Return type - -[**PeerDetailsResponse**](PeerDetailsResponse.md) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**201** | Peer successfully created | - | -**400** | Invalid request body structure | - | -**401** | Unauthorized | - | -**404** | Room doesn't exist | - | -**503** | Peer limit has been reached | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_room** -> RoomCreateDetailsResponse create_room(room_config=room_config) - -Creates a room - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.room_config import RoomConfig -from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_config = openapi_client.RoomConfig() # RoomConfig | Room configuration (optional) - - try: - # Creates a room - api_response = api_instance.create_room(room_config=room_config) - print("The response of RoomApi->create_room:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling RoomApi->create_room: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_config** | [**RoomConfig**](RoomConfig.md)| Room configuration | [optional] - -### Return type - -[**RoomCreateDetailsResponse**](RoomCreateDetailsResponse.md) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**201** | Room successfully created | - | -**400** | Invalid request structure | - | -**401** | Unauthorized | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_component** -> delete_component(room_id, id) - -Delete the component from the room - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room ID - id = 'id_example' # str | Component ID - - try: - # Delete the component from the room - api_instance.delete_component(room_id, id) - except Exception as e: - print("Exception when calling RoomApi->delete_component: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room ID | - **id** | **str**| Component ID | - -### Return type - -void (empty response body) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**204** | Successfully deleted | - | -**401** | Unauthorized | - | -**404** | Either component or the room doesn't exist | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_peer** -> delete_peer(room_id, id) - -Delete peer - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room ID - id = 'id_example' # str | Peer id - - try: - # Delete peer - api_instance.delete_peer(room_id, id) - except Exception as e: - print("Exception when calling RoomApi->delete_peer: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room ID | - **id** | **str**| Peer id | - -### Return type - -void (empty response body) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**204** | Peer successfully deleted | - | -**401** | Unauthorized | - | -**404** | Room ID or Peer ID references a resource that doesn't exist | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_room** -> delete_room(room_id) - -Delete the room - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room id - - try: - # Delete the room - api_instance.delete_room(room_id) - except Exception as e: - print("Exception when calling RoomApi->delete_room: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room id | - -### Return type - -void (empty response body) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**204** | Successfully deleted room | - | -**401** | Unauthorized | - | -**404** | Room doesn't exist | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_all_rooms** -> RoomsListingResponse get_all_rooms() - -Show information about all rooms - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.rooms_listing_response import RoomsListingResponse -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - - try: - # Show information about all rooms - api_response = api_instance.get_all_rooms() - print("The response of RoomApi->get_all_rooms:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling RoomApi->get_all_rooms: %s\n" % e) -``` - - - -### Parameters -This endpoint does not need any parameter. - -### Return type - -[**RoomsListingResponse**](RoomsListingResponse.md) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | -**401** | Unauthorized | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_room** -> RoomDetailsResponse get_room(room_id) - -Shows information about the room - -### Example - -* Bearer Authentication (authorization): -```python -import time -import os -import openapi_client -from openapi_client.models.room_details_response import RoomDetailsResponse -from openapi_client.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to http://localhost -# See configuration.py for a list of all supported configuration parameters. -configuration = openapi_client.Configuration( - host = "http://localhost" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization: authorization -configuration = openapi_client.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) - -# Enter a context with an instance of the API client -with openapi_client.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = openapi_client.RoomApi(api_client) - room_id = 'room_id_example' # str | Room ID - - try: - # Shows information about the room - api_response = api_instance.get_room(room_id) - print("The response of RoomApi->get_room:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling RoomApi->get_room: %s\n" % e) -``` - - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **room_id** | **str**| Room ID | - -### Return type - -[**RoomDetailsResponse**](RoomDetailsResponse.md) - -### Authorization - -[authorization](../README.md#authorization) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | -**401** | Unauthorized | - | -**404** | Room doesn't exist | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/openapi/docs/RoomConfig.md b/openapi/docs/RoomConfig.md deleted file mode 100644 index deaa81c..0000000 --- a/openapi/docs/RoomConfig.md +++ /dev/null @@ -1,30 +0,0 @@ -# RoomConfig - -Room configuration - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**max_peers** | **int** | Maximum amount of peers allowed into the room | [optional] -**video_codec** | **str** | Enforces video codec for each peer in the room | [optional] - -## Example - -```python -from openapi_client.models.room_config import RoomConfig - -# TODO update the JSON string below -json = "{}" -# create an instance of RoomConfig from a JSON string -room_config_instance = RoomConfig.from_json(json) -# print the JSON string representation of the object -print RoomConfig.to_json() - -# convert the object into a dict -room_config_dict = room_config_instance.to_dict() -# create an instance of RoomConfig from a dict -room_config_form_dict = room_config.from_dict(room_config_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/RoomCreateDetailsResponse.md b/openapi/docs/RoomCreateDetailsResponse.md deleted file mode 100644 index a7fb5fc..0000000 --- a/openapi/docs/RoomCreateDetailsResponse.md +++ /dev/null @@ -1,29 +0,0 @@ -# RoomCreateDetailsResponse - -Response containing room details - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**data** | [**RoomCreateDetailsResponseData**](RoomCreateDetailsResponseData.md) | | - -## Example - -```python -from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse - -# TODO update the JSON string below -json = "{}" -# create an instance of RoomCreateDetailsResponse from a JSON string -room_create_details_response_instance = RoomCreateDetailsResponse.from_json(json) -# print the JSON string representation of the object -print RoomCreateDetailsResponse.to_json() - -# convert the object into a dict -room_create_details_response_dict = room_create_details_response_instance.to_dict() -# create an instance of RoomCreateDetailsResponse from a dict -room_create_details_response_form_dict = room_create_details_response.from_dict(room_create_details_response_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/RoomCreateDetailsResponseData.md b/openapi/docs/RoomCreateDetailsResponseData.md deleted file mode 100644 index 402523f..0000000 --- a/openapi/docs/RoomCreateDetailsResponseData.md +++ /dev/null @@ -1,29 +0,0 @@ -# RoomCreateDetailsResponseData - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**jellyfish_address** | **str** | Jellyfish instance address where the room was created. This might be different than the address of Jellyfish where the request was sent only when running a cluster of Jellyfishes. | -**room** | [**Room**](Room.md) | | - -## Example - -```python -from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData - -# TODO update the JSON string below -json = "{}" -# create an instance of RoomCreateDetailsResponseData from a JSON string -room_create_details_response_data_instance = RoomCreateDetailsResponseData.from_json(json) -# print the JSON string representation of the object -print RoomCreateDetailsResponseData.to_json() - -# convert the object into a dict -room_create_details_response_data_dict = room_create_details_response_data_instance.to_dict() -# create an instance of RoomCreateDetailsResponseData from a dict -room_create_details_response_data_form_dict = room_create_details_response_data.from_dict(room_create_details_response_data_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/RoomDetailsResponse.md b/openapi/docs/RoomDetailsResponse.md deleted file mode 100644 index 785f8ba..0000000 --- a/openapi/docs/RoomDetailsResponse.md +++ /dev/null @@ -1,29 +0,0 @@ -# RoomDetailsResponse - -Response containing room details - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**data** | [**Room**](Room.md) | | - -## Example - -```python -from openapi_client.models.room_details_response import RoomDetailsResponse - -# TODO update the JSON string below -json = "{}" -# create an instance of RoomDetailsResponse from a JSON string -room_details_response_instance = RoomDetailsResponse.from_json(json) -# print the JSON string representation of the object -print RoomDetailsResponse.to_json() - -# convert the object into a dict -room_details_response_dict = room_details_response_instance.to_dict() -# create an instance of RoomDetailsResponse from a dict -room_details_response_form_dict = room_details_response.from_dict(room_details_response_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/docs/RoomsListingResponse.md b/openapi/docs/RoomsListingResponse.md deleted file mode 100644 index 6ad2695..0000000 --- a/openapi/docs/RoomsListingResponse.md +++ /dev/null @@ -1,29 +0,0 @@ -# RoomsListingResponse - -Response containing list of all rooms - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**data** | [**List[Room]**](Room.md) | | - -## Example - -```python -from openapi_client.models.rooms_listing_response import RoomsListingResponse - -# TODO update the JSON string below -json = "{}" -# create an instance of RoomsListingResponse from a JSON string -rooms_listing_response_instance = RoomsListingResponse.from_json(json) -# print the JSON string representation of the object -print RoomsListingResponse.to_json() - -# convert the object into a dict -rooms_listing_response_dict = rooms_listing_response_instance.to_dict() -# create an instance of RoomsListingResponse from a dict -rooms_listing_response_form_dict = rooms_listing_response.from_dict(rooms_listing_response_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/openapi/git_push.sh b/openapi/git_push.sh deleted file mode 100644 index f53a75d..0000000 --- a/openapi/git_push.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/openapi/setup.cfg b/openapi/setup.cfg deleted file mode 100644 index 11433ee..0000000 --- a/openapi/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length=99 diff --git a/openapi/test-requirements.txt b/openapi/test-requirements.txt deleted file mode 100644 index 3a0d0b9..0000000 --- a/openapi/test-requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -pytest~=7.1.3 -pytest-cov>=2.8.1 -pytest-randomly>=3.12.0 diff --git a/openapi/test/__init__.py b/openapi/test/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/openapi/test/test_add_component_request.py b/openapi/test/test_add_component_request.py deleted file mode 100644 index c55bc83..0000000 --- a/openapi/test/test_add_component_request.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.add_component_request import AddComponentRequest # noqa: E501 -from openapi_client.rest import ApiException - -class TestAddComponentRequest(unittest.TestCase): - """AddComponentRequest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test AddComponentRequest - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `AddComponentRequest` - """ - model = openapi_client.models.add_component_request.AddComponentRequest() # noqa: E501 - if include_optional : - return AddComponentRequest( - options = openapi_client.models.component_options.ComponentOptions(), - type = 'hls' - ) - else : - return AddComponentRequest( - type = 'hls', - ) - """ - - def testAddComponentRequest(self): - """Test AddComponentRequest""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_add_peer_request.py b/openapi/test/test_add_peer_request.py deleted file mode 100644 index 0540f60..0000000 --- a/openapi/test/test_add_peer_request.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.add_peer_request import AddPeerRequest # noqa: E501 -from openapi_client.rest import ApiException - -class TestAddPeerRequest(unittest.TestCase): - """AddPeerRequest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test AddPeerRequest - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `AddPeerRequest` - """ - model = openapi_client.models.add_peer_request.AddPeerRequest() # noqa: E501 - if include_optional : - return AddPeerRequest( - options = openapi_client.models.peer_options.PeerOptions(), - type = 'webrtc' - ) - else : - return AddPeerRequest( - options = openapi_client.models.peer_options.PeerOptions(), - type = 'webrtc', - ) - """ - - def testAddPeerRequest(self): - """Test AddPeerRequest""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_component.py b/openapi/test/test_component.py deleted file mode 100644 index 324fff9..0000000 --- a/openapi/test/test_component.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.component import Component # noqa: E501 -from openapi_client.rest import ApiException - -class TestComponent(unittest.TestCase): - """Component unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test Component - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `Component` - """ - model = openapi_client.models.component.Component() # noqa: E501 - if include_optional : - return Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls' - ) - else : - return Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', - ) - """ - - def testComponent(self): - """Test Component""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_component_details_response.py b/openapi/test/test_component_details_response.py deleted file mode 100644 index c405839..0000000 --- a/openapi/test/test_component_details_response.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.component_details_response import ComponentDetailsResponse # noqa: E501 -from openapi_client.rest import ApiException - -class TestComponentDetailsResponse(unittest.TestCase): - """ComponentDetailsResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ComponentDetailsResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `ComponentDetailsResponse` - """ - model = openapi_client.models.component_details_response.ComponentDetailsResponse() # noqa: E501 - if include_optional : - return ComponentDetailsResponse( - data = openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ) - else : - return ComponentDetailsResponse( - data = openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ), - ) - """ - - def testComponentDetailsResponse(self): - """Test ComponentDetailsResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_component_metadata.py b/openapi/test/test_component_metadata.py deleted file mode 100644 index 44a90c4..0000000 --- a/openapi/test/test_component_metadata.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.component_metadata import ComponentMetadata # noqa: E501 -from openapi_client.rest import ApiException - -class TestComponentMetadata(unittest.TestCase): - """ComponentMetadata unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ComponentMetadata - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `ComponentMetadata` - """ - model = openapi_client.models.component_metadata.ComponentMetadata() # noqa: E501 - if include_optional : - return ComponentMetadata( - playable = True - ) - else : - return ComponentMetadata( - ) - """ - - def testComponentMetadata(self): - """Test ComponentMetadata""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_component_options.py b/openapi/test/test_component_options.py deleted file mode 100644 index 80b250f..0000000 --- a/openapi/test/test_component_options.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.component_options import ComponentOptions # noqa: E501 -from openapi_client.rest import ApiException - -class TestComponentOptions(unittest.TestCase): - """ComponentOptions unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ComponentOptions - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `ComponentOptions` - """ - model = openapi_client.models.component_options.ComponentOptions() # noqa: E501 - if include_optional : - return ComponentOptions( - keep_alive_interval = 0, - pierce_nat = True, - reconnect_delay = 0, - rtp_port = 1, - source_uri = 'rtsp://localhost:554/stream' - ) - else : - return ComponentOptions( - source_uri = 'rtsp://localhost:554/stream', - ) - """ - - def testComponentOptions(self): - """Test ComponentOptions""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_component_options_rtsp.py b/openapi/test/test_component_options_rtsp.py deleted file mode 100644 index 60ec8f4..0000000 --- a/openapi/test/test_component_options_rtsp.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.component_options_rtsp import ComponentOptionsRTSP # noqa: E501 -from openapi_client.rest import ApiException - -class TestComponentOptionsRTSP(unittest.TestCase): - """ComponentOptionsRTSP unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ComponentOptionsRTSP - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `ComponentOptionsRTSP` - """ - model = openapi_client.models.component_options_rtsp.ComponentOptionsRTSP() # noqa: E501 - if include_optional : - return ComponentOptionsRTSP( - keep_alive_interval = 0, - pierce_nat = True, - reconnect_delay = 0, - rtp_port = 1, - source_uri = 'rtsp://localhost:554/stream' - ) - else : - return ComponentOptionsRTSP( - source_uri = 'rtsp://localhost:554/stream', - ) - """ - - def testComponentOptionsRTSP(self): - """Test ComponentOptionsRTSP""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_default_api.py b/openapi/test/test_default_api.py deleted file mode 100644 index 2ca2031..0000000 --- a/openapi/test/test_default_api.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest - -import openapi_client -from openapi_client.api.default_api import DefaultApi # noqa: E501 -from openapi_client.rest import ApiException - - -class TestDefaultApi(unittest.TestCase): - """DefaultApi unit test stubs""" - - def setUp(self): - self.api = openapi_client.api.default_api.DefaultApi() # noqa: E501 - - def tearDown(self): - pass - - def test_jellyfish_web_hls_controller_index(self): - """Test case for jellyfish_web_hls_controller_index - - Send file # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_error.py b/openapi/test/test_error.py deleted file mode 100644 index 7dccfca..0000000 --- a/openapi/test/test_error.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.error import Error # noqa: E501 -from openapi_client.rest import ApiException - -class TestError(unittest.TestCase): - """Error unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test Error - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `Error` - """ - model = openapi_client.models.error.Error() # noqa: E501 - if include_optional : - return Error( - errors = 'Token has expired' - ) - else : - return Error( - errors = 'Token has expired', - ) - """ - - def testError(self): - """Test Error""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_hls_skip.py b/openapi/test/test_hls_skip.py deleted file mode 100644 index 7beafc5..0000000 --- a/openapi/test/test_hls_skip.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.hls_skip import HlsSkip # noqa: E501 -from openapi_client.rest import ApiException - -class TestHlsSkip(unittest.TestCase): - """HlsSkip unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testHlsSkip(self): - """Test HlsSkip""" - # inst = HlsSkip() - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer.py b/openapi/test/test_peer.py deleted file mode 100644 index 7b77c18..0000000 --- a/openapi/test/test_peer.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer import Peer # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeer(unittest.TestCase): - """Peer unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test Peer - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `Peer` - """ - model = openapi_client.models.peer.Peer() # noqa: E501 - if include_optional : - return Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc' - ) - else : - return Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', - ) - """ - - def testPeer(self): - """Test Peer""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer_details_response.py b/openapi/test/test_peer_details_response.py deleted file mode 100644 index c3cbb36..0000000 --- a/openapi/test/test_peer_details_response.py +++ /dev/null @@ -1,65 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer_details_response import PeerDetailsResponse # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeerDetailsResponse(unittest.TestCase): - """PeerDetailsResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test PeerDetailsResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `PeerDetailsResponse` - """ - model = openapi_client.models.peer_details_response.PeerDetailsResponse() # noqa: E501 - if include_optional : - return PeerDetailsResponse( - data = openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( - peer = openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ), - token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', ) - ) - else : - return PeerDetailsResponse( - data = openapi_client.models.peer_details_response_data.PeerDetailsResponse_data( - peer = openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ), - token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', ), - ) - """ - - def testPeerDetailsResponse(self): - """Test PeerDetailsResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer_details_response_data.py b/openapi/test/test_peer_details_response_data.py deleted file mode 100644 index 55ab37e..0000000 --- a/openapi/test/test_peer_details_response_data.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer_details_response_data import PeerDetailsResponseData # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeerDetailsResponseData(unittest.TestCase): - """PeerDetailsResponseData unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test PeerDetailsResponseData - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `PeerDetailsResponseData` - """ - model = openapi_client.models.peer_details_response_data.PeerDetailsResponseData() # noqa: E501 - if include_optional : - return PeerDetailsResponseData( - peer = openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ), - token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242' - ) - else : - return PeerDetailsResponseData( - peer = openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ), - token = '5cdac726-57a3-4ecb-b1d5-72a3d62ec242', - ) - """ - - def testPeerDetailsResponseData(self): - """Test PeerDetailsResponseData""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer_options.py b/openapi/test/test_peer_options.py deleted file mode 100644 index 9031995..0000000 --- a/openapi/test/test_peer_options.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer_options import PeerOptions # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeerOptions(unittest.TestCase): - """PeerOptions unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test PeerOptions - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `PeerOptions` - """ - model = openapi_client.models.peer_options.PeerOptions() # noqa: E501 - if include_optional : - return PeerOptions( - enable_simulcast = True - ) - else : - return PeerOptions( - ) - """ - - def testPeerOptions(self): - """Test PeerOptions""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer_options_web_rtc.py b/openapi/test/test_peer_options_web_rtc.py deleted file mode 100644 index 2f4b1b6..0000000 --- a/openapi/test/test_peer_options_web_rtc.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer_options_web_rtc import PeerOptionsWebRTC # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeerOptionsWebRTC(unittest.TestCase): - """PeerOptionsWebRTC unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test PeerOptionsWebRTC - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `PeerOptionsWebRTC` - """ - model = openapi_client.models.peer_options_web_rtc.PeerOptionsWebRTC() # noqa: E501 - if include_optional : - return PeerOptionsWebRTC( - enable_simulcast = True - ) - else : - return PeerOptionsWebRTC( - ) - """ - - def testPeerOptionsWebRTC(self): - """Test PeerOptionsWebRTC""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_peer_status.py b/openapi/test/test_peer_status.py deleted file mode 100644 index b2d16f2..0000000 --- a/openapi/test/test_peer_status.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.peer_status import PeerStatus # noqa: E501 -from openapi_client.rest import ApiException - -class TestPeerStatus(unittest.TestCase): - """PeerStatus unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testPeerStatus(self): - """Test PeerStatus""" - # inst = PeerStatus() - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room.py b/openapi/test/test_room.py deleted file mode 100644 index 902ce53..0000000 --- a/openapi/test/test_room.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.room import Room # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoom(unittest.TestCase): - """Room unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test Room - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `Room` - """ - model = openapi_client.models.room.Room() # noqa: E501 - if include_optional : - return Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ] - ) - else : - return Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], - ) - """ - - def testRoom(self): - """Test Room""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room_api.py b/openapi/test/test_room_api.py deleted file mode 100644 index 0bf6684..0000000 --- a/openapi/test/test_room_api.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest - -import openapi_client -from openapi_client.api.room_api import RoomApi # noqa: E501 -from openapi_client.rest import ApiException - - -class TestRoomApi(unittest.TestCase): - """RoomApi unit test stubs""" - - def setUp(self): - self.api = openapi_client.api.room_api.RoomApi() # noqa: E501 - - def tearDown(self): - pass - - def test_add_component(self): - """Test case for add_component - - Creates the component and adds it to the room # noqa: E501 - """ - pass - - def test_add_peer(self): - """Test case for add_peer - - Create peer # noqa: E501 - """ - pass - - def test_create_room(self): - """Test case for create_room - - Creates a room # noqa: E501 - """ - pass - - def test_delete_component(self): - """Test case for delete_component - - Delete the component from the room # noqa: E501 - """ - pass - - def test_delete_peer(self): - """Test case for delete_peer - - Delete peer # noqa: E501 - """ - pass - - def test_delete_room(self): - """Test case for delete_room - - Delete the room # noqa: E501 - """ - pass - - def test_get_all_rooms(self): - """Test case for get_all_rooms - - Show information about all rooms # noqa: E501 - """ - pass - - def test_get_room(self): - """Test case for get_room - - Shows information about the room # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room_config.py b/openapi/test/test_room_config.py deleted file mode 100644 index bb02f27..0000000 --- a/openapi/test/test_room_config.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.room_config import RoomConfig # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoomConfig(unittest.TestCase): - """RoomConfig unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test RoomConfig - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `RoomConfig` - """ - model = openapi_client.models.room_config.RoomConfig() # noqa: E501 - if include_optional : - return RoomConfig( - max_peers = 10, - video_codec = 'h264' - ) - else : - return RoomConfig( - ) - """ - - def testRoomConfig(self): - """Test RoomConfig""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room_create_details_response.py b/openapi/test/test_room_create_details_response.py deleted file mode 100644 index e4b5184..0000000 --- a/openapi/test/test_room_create_details_response.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.room_create_details_response import RoomCreateDetailsResponse # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoomCreateDetailsResponse(unittest.TestCase): - """RoomCreateDetailsResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test RoomCreateDetailsResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `RoomCreateDetailsResponse` - """ - model = openapi_client.models.room_create_details_response.RoomCreateDetailsResponse() # noqa: E501 - if include_optional : - return RoomCreateDetailsResponse( - data = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( - jellyfish_address = 'jellyfish1:5003', - room = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ), ) - ) - else : - return RoomCreateDetailsResponse( - data = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponse_data( - jellyfish_address = 'jellyfish1:5003', - room = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ), ), - ) - """ - - def testRoomCreateDetailsResponse(self): - """Test RoomCreateDetailsResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room_create_details_response_data.py b/openapi/test/test_room_create_details_response_data.py deleted file mode 100644 index e8281a3..0000000 --- a/openapi/test/test_room_create_details_response_data.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.room_create_details_response_data import RoomCreateDetailsResponseData # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoomCreateDetailsResponseData(unittest.TestCase): - """RoomCreateDetailsResponseData unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test RoomCreateDetailsResponseData - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `RoomCreateDetailsResponseData` - """ - model = openapi_client.models.room_create_details_response_data.RoomCreateDetailsResponseData() # noqa: E501 - if include_optional : - return RoomCreateDetailsResponseData( - jellyfish_address = 'jellyfish1:5003', - room = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ) - ) - else : - return RoomCreateDetailsResponseData( - jellyfish_address = 'jellyfish1:5003', - room = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ), - ) - """ - - def testRoomCreateDetailsResponseData(self): - """Test RoomCreateDetailsResponseData""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_room_details_response.py b/openapi/test/test_room_details_response.py deleted file mode 100644 index 8af5861..0000000 --- a/openapi/test/test_room_details_response.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.room_details_response import RoomDetailsResponse # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoomDetailsResponse(unittest.TestCase): - """RoomDetailsResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test RoomDetailsResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `RoomDetailsResponse` - """ - model = openapi_client.models.room_details_response.RoomDetailsResponse() # noqa: E501 - if include_optional : - return RoomDetailsResponse( - data = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ) - ) - else : - return RoomDetailsResponse( - data = openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ), - ) - """ - - def testRoomDetailsResponse(self): - """Test RoomDetailsResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/test/test_rooms_listing_response.py b/openapi/test/test_rooms_listing_response.py deleted file mode 100644 index 55b52ad..0000000 --- a/openapi/test/test_rooms_listing_response.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import unittest -import datetime - -import openapi_client -from openapi_client.models.rooms_listing_response import RoomsListingResponse # noqa: E501 -from openapi_client.rest import ApiException - -class TestRoomsListingResponse(unittest.TestCase): - """RoomsListingResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test RoomsListingResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `RoomsListingResponse` - """ - model = openapi_client.models.rooms_listing_response.RoomsListingResponse() # noqa: E501 - if include_optional : - return RoomsListingResponse( - data = [ - openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ) - ] - ) - else : - return RoomsListingResponse( - data = [ - openapi_client.models.room.Room( - components = [ - openapi_client.models.component.Component( - id = 'component-1', - metadata = openapi_client.models.component_metadata.ComponentMetadata( - playable = True, ), - type = 'hls', ) - ], - config = openapi_client.models.room_config.RoomConfig( - max_peers = 10, - video_codec = 'h264', ), - id = 'room-1', - peers = [ - openapi_client.models.peer.Peer( - id = 'peer-1', - status = 'disconnected', - type = 'webrtc', ) - ], ) - ], - ) - """ - - def testRoomsListingResponse(self): - """Test RoomsListingResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/openapi/tox.ini b/openapi/tox.ini deleted file mode 100644 index 1a9028b..0000000 --- a/openapi/tox.ini +++ /dev/null @@ -1,9 +0,0 @@ -[tox] -envlist = py3 - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - -commands= - pytest --cov=openapi_client diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e69de29..0000000 From b4a7a8988860513d1c7d6e23f5028e546ec81eec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 7 Sep 2023 16:29:24 +0200 Subject: [PATCH 15/20] Remove templates --- generate_client.sh | 2 +- templates/README.mustache | 59 -- templates/README_onlypackage.mustache | 44 -- templates/__init__.mustache | 0 templates/__init__api.mustache | 5 - templates/__init__model.mustache | 11 - templates/__init__package.mustache | 35 - templates/api.mustache | 311 -------- templates/api_client.mustache | 783 --------------------- templates/api_doc.mustache | 74 -- templates/api_doc_example.mustache | 38 - templates/api_response.mustache | 25 - templates/api_test.mustache | 35 - templates/asyncio/rest.mustache | 241 ------- templates/common_README.mustache | 85 --- templates/configuration.mustache | 615 ---------------- templates/exceptions.mustache | 156 ---- templates/git_push.sh.mustache | 57 -- templates/github-workflow.mustache | 38 - templates/gitignore.mustache | 66 -- templates/gitlab-ci.mustache | 25 - templates/model.mustache | 14 - templates/model_anyof.mustache | 180 ----- templates/model_doc.mustache | 33 - templates/model_enum.mustache | 36 - templates/model_generic.mustache | 361 ---------- templates/model_oneof.mustache | 206 ------ templates/model_test.mustache | 62 -- templates/partial_header.mustache | 19 - templates/py.typed.mustache | 0 templates/pyproject.mustache | 40 -- templates/python_doc_auth_partial.mustache | 108 --- templates/requirements.mustache | 8 - templates/rest.mustache | 293 -------- templates/setup.mustache | 56 -- templates/setup_cfg.mustache | 2 - templates/signing.mustache | 403 ----------- templates/test-requirements.mustache | 6 - templates/tornado/rest.mustache | 223 ------ templates/tox.mustache | 9 - templates/travis.mustache | 17 - 41 files changed, 1 insertion(+), 4780 deletions(-) delete mode 100644 templates/README.mustache delete mode 100644 templates/README_onlypackage.mustache delete mode 100644 templates/__init__.mustache delete mode 100644 templates/__init__api.mustache delete mode 100644 templates/__init__model.mustache delete mode 100644 templates/__init__package.mustache delete mode 100644 templates/api.mustache delete mode 100644 templates/api_client.mustache delete mode 100644 templates/api_doc.mustache delete mode 100644 templates/api_doc_example.mustache delete mode 100644 templates/api_response.mustache delete mode 100644 templates/api_test.mustache delete mode 100644 templates/asyncio/rest.mustache delete mode 100644 templates/common_README.mustache delete mode 100644 templates/configuration.mustache delete mode 100644 templates/exceptions.mustache delete mode 100644 templates/git_push.sh.mustache delete mode 100644 templates/github-workflow.mustache delete mode 100644 templates/gitignore.mustache delete mode 100644 templates/gitlab-ci.mustache delete mode 100644 templates/model.mustache delete mode 100644 templates/model_anyof.mustache delete mode 100644 templates/model_doc.mustache delete mode 100644 templates/model_enum.mustache delete mode 100644 templates/model_generic.mustache delete mode 100644 templates/model_oneof.mustache delete mode 100644 templates/model_test.mustache delete mode 100644 templates/partial_header.mustache delete mode 100644 templates/py.typed.mustache delete mode 100644 templates/pyproject.mustache delete mode 100644 templates/python_doc_auth_partial.mustache delete mode 100644 templates/requirements.mustache delete mode 100644 templates/rest.mustache delete mode 100644 templates/setup.mustache delete mode 100644 templates/setup_cfg.mustache delete mode 100644 templates/signing.mustache delete mode 100644 templates/test-requirements.mustache delete mode 100644 templates/tornado/rest.mustache delete mode 100644 templates/tox.mustache delete mode 100644 templates/travis.mustache diff --git a/generate_client.sh b/generate_client.sh index 6112a91..e42fc67 100755 --- a/generate_client.sh +++ b/generate_client.sh @@ -6,4 +6,4 @@ openapi-generator-cli generate \ --package-name openapi_client \ --global-property apis,models,modelTests=false,supportingFiles -rm -rf openapi/{docs,test,.github,.openapi-generator,.gitignore,.gitlab-ci.yml,.travis.yml,.openapi-generator-ignore,git_push.sh,README.md,setup.cfg,test-requirements.txt,tox.ini} \ No newline at end of file +rm -rf openapi/{docs,test,.github,.openapi-generator,.gitignore,.gitlab-ci.yml,.travis.yml,.openapi-generator-ignore,git_push.sh,README.md,setup.cfg,test-requirements.txt,tox.ini} diff --git a/templates/README.mustache b/templates/README.mustache deleted file mode 100644 index 201df14..0000000 --- a/templates/README.mustache +++ /dev/null @@ -1,59 +0,0 @@ -# {{{projectName}}} -{{#appDescriptionWithNewLines}} -{{{.}}} -{{/appDescriptionWithNewLines}} - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: {{appVersion}} -- Package version: {{packageVersion}} -{{^hideGenerationTimestamp}} -- Build date: {{generatedDate}} -{{/hideGenerationTimestamp}} -- Build package: {{generatorClass}} -{{#infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/infoUrl}} - -## Requirements. - -Python {{{generatorLanguageVersion}}} - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`) - -Then import the package: -```python -import {{{packageName}}} -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import {{{packageName}}} -``` - -### Tests - -Execute `pytest` to run the tests. - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -{{> common_README }} diff --git a/templates/README_onlypackage.mustache b/templates/README_onlypackage.mustache deleted file mode 100644 index d04bc05..0000000 --- a/templates/README_onlypackage.mustache +++ /dev/null @@ -1,44 +0,0 @@ -# {{{projectName}}} -{{#appDescription}} -{{{.}}} -{{/appDescription}} - -The `{{packageName}}` package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: {{appVersion}} -- Package version: {{packageVersion}} -{{^hideGenerationTimestamp}} -- Build date: {{generatedDate}} -{{/hideGenerationTimestamp}} -- Build package: {{generatorClass}} -{{#infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/infoUrl}} - -## Requirements. - -Python {{{generatorLanguageVersion}}} - -## Installation & Usage - -This python library package is generated without supporting files like setup.py or requirements files - -To be able to use it, you will need these dependencies in your own package that uses this library: - -* urllib3 >= 1.25.3 -* python-dateutil -{{#asyncio}} -* aiohttp -{{/asyncio}} -{{#tornado}} -* tornado>=4.2,<5 -{{/tornado}} -* pydantic -* aenum - -## Getting Started - -In your own code, to use this library to connect and interact with {{{projectName}}}, -you can run the following: - -{{> common_README }} diff --git a/templates/__init__.mustache b/templates/__init__.mustache deleted file mode 100644 index e69de29..0000000 diff --git a/templates/__init__api.mustache b/templates/__init__api.mustache deleted file mode 100644 index 8870835..0000000 --- a/templates/__init__api.mustache +++ /dev/null @@ -1,5 +0,0 @@ -# flake8: noqa - -# import apis into api package -{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classFilename}} import {{classname}} -{{/apis}}{{/apiInfo}} diff --git a/templates/__init__model.mustache b/templates/__init__model.mustache deleted file mode 100644 index 0e1b55e..0000000 --- a/templates/__init__model.mustache +++ /dev/null @@ -1,11 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -{{>partial_header}} - -# import models into model package -{{#models}} -{{#model}} -from {{modelPackage}}.{{classFilename}} import {{classname}} -{{/model}} -{{/models}} diff --git a/templates/__init__package.mustache b/templates/__init__package.mustache deleted file mode 100644 index 7985e6e..0000000 --- a/templates/__init__package.mustache +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -{{>partial_header}} - -__version__ = "{{packageVersion}}" - -# import apis into sdk package -{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classFilename}} import {{classname}} -{{/apis}}{{/apiInfo}} -# import ApiClient -from {{packageName}}.api_response import ApiResponse -from {{packageName}}.api_client import ApiClient -from {{packageName}}.configuration import Configuration -from {{packageName}}.exceptions import OpenApiException -from {{packageName}}.exceptions import ApiTypeError -from {{packageName}}.exceptions import ApiValueError -from {{packageName}}.exceptions import ApiKeyError -from {{packageName}}.exceptions import ApiAttributeError -from {{packageName}}.exceptions import ApiException -{{#hasHttpSignatureMethods}} -from {{packageName}}.signing import HttpSigningConfiguration -{{/hasHttpSignatureMethods}} - -# import models into sdk package -{{#models}} -{{#model}} -from {{modelPackage}}.{{classFilename}} import {{classname}} -{{/model}} -{{/models}} -{{#recursionLimit}} - -__import__('sys').setrecursionlimit({{{.}}}) -{{/recursionLimit}} diff --git a/templates/api.mustache b/templates/api.mustache deleted file mode 100644 index 913e0db..0000000 --- a/templates/api.mustache +++ /dev/null @@ -1,311 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import re # noqa: F401 -import io -import warnings - -from pydantic import validate_arguments, ValidationError -from typing_extensions import Annotated{{#asyncio}} -from typing import overload, Optional, Union, Awaitable{{/asyncio}} - -{{#imports}} -{{import}} -{{/imports}} - -from {{packageName}}.api_client import ApiClient -from {{packageName}}.api_response import ApiResponse -from {{packageName}}.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -{{#operations}} -class {{classname}}(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client -{{#operation}} - -{{#asyncio}} - @overload - async def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501 - ... - - @overload - def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}async_req: Optional[bool]=True, **kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501 - ... - -{{/asyncio}} - @validate_arguments - def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{{returnType}}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501 - """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 - -{{#notes}} - {{{.}}} # noqa: E501 -{{/notes}} - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) - >>> result = thread.get() - -{{#allParams}} - :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} - :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} -{{/allParams}} - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: {{returnType}}{{^returnType}}None{{/returnType}} - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the {{operationId}}_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") -{{#asyncio}} - if async_req is not None: - kwargs['async_req'] = async_req -{{/asyncio}} - return self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501 - - @validate_arguments - def {{operationId}}_with_http_info(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> ApiResponse: # noqa: E501 - """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 - -{{#notes}} - {{{.}}} # noqa: E501 -{{/notes}} - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) - >>> result = thread.get() - -{{#allParams}} - :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} - :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} -{{/allParams}} - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: {{#returnType}}tuple({{.}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}} - """ - - {{#isDeprecated}} - warnings.warn("{{{httpMethod}}} {{{path}}} is deprecated.", DeprecationWarning) - - {{/isDeprecated}} - {{#servers.0}} - _hosts = [ -{{#servers}} - '{{{url}}}'{{^-last}},{{/-last}} -{{/servers}} - ] - _host = _hosts[0] - if kwargs.get('_host_index'): - _host_index = int(kwargs.get('_host_index')) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" - % len(_host) - ) - _host = _hosts[_host_index] - {{/servers.0}} - _params = locals() - - _all_params = [ -{{#allParams}} - '{{paramName}}'{{^-last}},{{/-last}} -{{/allParams}} - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params{{#servers.0}} and _key != "_host_index"{{/servers.0}}: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method {{operationId}}" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} -{{#pathParams}} - if _params['{{paramName}}']: - _path_params['{{baseName}}'] = _params['{{paramName}}'] - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - -{{/pathParams}} - - # process the query parameters - _query_params = [] -{{#queryParams}} - if _params.get('{{paramName}}') is not None: # noqa: E501 - {{#isDateTime}} - if isinstance(_params['{{paramName}}'], datetime): - _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.datetime_format))) - else: - _query_params.append(('{{baseName}}', _params['{{paramName}}'])) - {{/isDateTime}} - {{^isDateTime}} - {{#isDate}} - if isinstance(_params['{{paramName}}'], date): - _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.date_format))) - else: - _query_params.append(('{{baseName}}', _params['{{paramName}}'])) - {{/isDate}} - {{^isDate}} - _query_params.append(('{{baseName}}', _params['{{paramName}}']{{#isEnumRef}}.value{{/isEnumRef}})) - {{/isDate}} - {{/isDateTime}} - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - -{{/queryParams}} - # process the header parameters - _header_params = dict(_params.get('_headers', {})) -{{#headerParams}} - if _params['{{paramName}}']: - _header_params['{{baseName}}'] = _params['{{paramName}}'] - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - -{{/headerParams}} - # process the form parameters - _form_params = [] - _files = {} -{{#formParams}} - if _params['{{paramName}}']: - {{^isFile}} - _form_params.append(('{{{baseName}}}', _params['{{paramName}}'])) - {{/isFile}} - {{#isFile}} - _files['{{{baseName}}}'] = _params['{{paramName}}'] - {{/isFile}} - {{#isArray}} - _collection_formats['{{{baseName}}}'] = '{{collectionFormat}}' - {{/isArray}} - -{{/formParams}} - # process the body parameter - _body_params = None -{{#bodyParam}} - if _params['{{paramName}}'] is not None: - _body_params = _params['{{paramName}}'] - {{#isBinary}} - # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file - {{/isBinary}} - -{{/bodyParam}} - {{#hasProduces}} - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - [{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501 - - {{/hasProduces}} - {{#hasConsumes}} - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - {{/hasConsumes}} - # authentication setting - _auth_settings = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501 - - {{#returnType}} - {{#responses}} - {{#-first}} - _response_types_map = { - {{/-first}} - {{^isWildcard}} - '{{code}}': {{#dataType}}"{{.}}"{{/dataType}}{{^dataType}}None{{/dataType}}, - {{/isWildcard}} - {{#-last}} - } - {{/-last}} - {{/responses}} - {{/returnType}} - {{^returnType}} - _response_types_map = {} - {{/returnType}} - - return self.api_client.call_api( - '{{{path}}}', '{{httpMethod}}', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - {{#servers.0}} - _host=_host, - {{/servers.0}} - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) -{{/operation}} -{{/operations}} diff --git a/templates/api_client.mustache b/templates/api_client.mustache deleted file mode 100644 index 95fef88..0000000 --- a/templates/api_client.mustache +++ /dev/null @@ -1,783 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import atexit -import datetime -from dateutil.parser import parse -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -from urllib.parse import quote -{{#tornado}} -import tornado.gen -{{/tornado}} - -from {{packageName}}.configuration import Configuration -from {{packageName}}.api_response import ApiResponse -import {{modelPackage}} -from {{packageName}} import rest -from {{packageName}}.exceptions import ApiValueError, ApiException - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - PRIMITIVE_TYPES = (float, bool, bytes, str, int) - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int, # TODO remove as only py3 is supported? - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - _pool = None - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): - # use default configuration if none is provided - if configuration is None: - configuration = Configuration.get_default() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = '{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}' - self.client_side_validation = configuration.client_side_validation - - {{#asyncio}} - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_value, traceback): - await self.close() - {{/asyncio}} - {{^asyncio}} - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - {{/asyncio}} - - {{#asyncio}}async {{/asyncio}}def close(self): - {{#asyncio}} - await self.rest_client.close() - {{/asyncio}} - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - - _default = None - - @classmethod - def get_default(cls): - """Return new instance of ApiClient. - - This method returns newly created, based on default constructor, - object of ApiClient class or returns a copy of default - ApiClient. - - :return: The ApiClient object. - """ - if cls._default is None: - cls._default = ApiClient() - return cls._default - - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. - - It stores default ApiClient. - - :param default: object of ApiClient. - """ - cls._default = default - - {{#tornado}} - @tornado.gen.coroutine - {{/tornado}} - {{#asyncio}}async {{/asyncio}}def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - post_params.extend(self.files_parameters(files)) - - # auth setting - self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) - url += "?" + url_query - - try: - # perform request and return response - response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request( - method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') - raise e - - self.last_response = response_data - - return_data = None # assuming derialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - -{{^tornado}} - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) -{{/tornado}} -{{#tornado}} - if _return_http_data_only: - raise tornado.gen.Return(return_data) - else: - raise tornado.gen.Return(ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data)) -{{/tornado}} - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = obj.to_dict() - - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in data.items()} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr({{modelPackage}}, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_types_map, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host, - _request_auth) - - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, _request_auth)) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def parameters_to_url_query(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: URL query string (e.g. a=Hello%20World&b=123) - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) - if isinstance(v, bool): - v = str(v).lower() - if isinstance(v, dict): - v = json.dumps(v) - - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) - else: - new_params.append((k, quote(str(v)))) - - return "&".join(["=".join(item) for item in new_params]) - - def files_parameters(self, files=None): - """Builds form parameters. - - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if files: - for k, v in files.items(): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - for accept in accepts: - if re.search('json', accept, re.IGNORECASE): - return accept - - return accepts[0] - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return None - - for content_type in content_types: - if re.search('json', content_type, re.IGNORECASE): - return content_type - - return content_types[0] - - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param request_auth: if set, the provided settings will - override the token in the configuration. - """ - if not auth_settings: - return - - if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): - """Updates the request parameters based on a single auth_setting - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param auth_setting: auth settings for the endpoint - """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - {{#hasHttpSignatureMethods}} - else: - # The HTTP signature scheme requires multiple HTTP headers - # that are calculated dynamically. - signing_info = self.configuration.signing_info - auth_headers = signing_info.get_http_signature_headers( - resource_path, method, headers, body, queries) - headers.update(auth_headers) - {{/hasHttpSignatureMethods}} - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return an original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datetime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) - ) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - return klass.from_dict(data) diff --git a/templates/api_doc.mustache b/templates/api_doc.mustache deleted file mode 100644 index 4a1d364..0000000 --- a/templates/api_doc.mustache +++ /dev/null @@ -1,74 +0,0 @@ -# {{packageName}}.{{classname}}{{#description}} -{{.}}{{/description}} - -All URIs are relative to *{{basePath}}* - -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} -{{/operation}}{{/operations}} - -{{#operations}} -{{#operation}} -# **{{{operationId}}}** -> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}={{{paramName}}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) - -{{{summary}}}{{#notes}} - -{{{.}}}{{/notes}} - -### Example - -{{#hasAuthMethods}} -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -* Basic Authentication ({{name}}): -{{/isBasicBasic}} -{{#isBasicBearer}} -* Bearer{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} Authentication ({{name}}): -{{/isBasicBearer}} -{{/isBasic}} -{{#isApiKey}} -* Api Key Authentication ({{name}}): -{{/isApiKey }} -{{#isOAuth}} -* OAuth Authentication ({{name}}): -{{/isOAuth }} -{{/authMethods}} -{{/hasAuthMethods}} -{{> api_doc_example }} - -### Parameters -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} -Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} -{{/allParams}} - -### Return type - -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} - -### Authorization - -{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} - -### HTTP request headers - - - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} - -{{#responses.0}} -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -{{#responses}} -**{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}} | -{{/responses}} -{{/responses.0}} - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -{{/operation}} -{{/operations}} diff --git a/templates/api_doc_example.mustache b/templates/api_doc_example.mustache deleted file mode 100644 index 15fbe33..0000000 --- a/templates/api_doc_example.mustache +++ /dev/null @@ -1,38 +0,0 @@ -```python -import time -import os -import {{{packageName}}} -{{#vendorExtensions.x-py-example-import}} -{{{.}}} -{{/vendorExtensions.x-py-example-import}} -from {{{packageName}}}.rest import ApiException -from pprint import pprint - -{{> python_doc_auth_partial}} -# Enter a context with an instance of the API client -{{#asyncio}}async {{/asyncio}}with {{{packageName}}}.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = {{{packageName}}}.{{{classname}}}(api_client) - {{#allParams}} - {{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} - {{/allParams}} - - try: - {{#summary}} - # {{{.}}} - {{/summary}} - {{#returnType}}api_response = {{/returnType}}{{#asyncio}}await {{/asyncio}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) - {{#returnType}} - print("The response of {{classname}}->{{operationId}}:\n") - pprint(api_response) - {{/returnType}} - except Exception as e: - print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) -``` - -{{#vendorExtensions.x-py-postponed-example-imports.size}} -{{#vendorExtensions.x-py-postponed-example-imports}} -{{{.}}} -{{/vendorExtensions.x-py-postponed-example-imports}} -{{classname}}.update_forward_refs() -{{/vendorExtensions.x-py-postponed-example-imports.size}} \ No newline at end of file diff --git a/templates/api_response.mustache b/templates/api_response.mustache deleted file mode 100644 index d81c2ff..0000000 --- a/templates/api_response.mustache +++ /dev/null @@ -1,25 +0,0 @@ -"""API response object.""" - -from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr - -class ApiResponse: - """ - API response object - """ - - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") - - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None): - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data diff --git a/templates/api_test.mustache b/templates/api_test.mustache deleted file mode 100644 index c3bbe4b..0000000 --- a/templates/api_test.mustache +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import unittest - -import {{packageName}} -from {{apiPackage}}.{{classFilename}} import {{classname}} # noqa: E501 -from {{packageName}}.rest import ApiException - - -class {{#operations}}Test{{classname}}(unittest.TestCase): - """{{classname}} unit test stubs""" - - def setUp(self): - self.api = {{apiPackage}}.{{classFilename}}.{{classname}}() # noqa: E501 - - def tearDown(self): - pass - - {{#operation}} - def test_{{operationId}}(self): - """Test case for {{{operationId}}} - -{{#summary}} - {{{.}}} # noqa: E501 -{{/summary}} - """ - pass - - {{/operation}} -{{/operations}} - -if __name__ == '__main__': - unittest.main() diff --git a/templates/asyncio/rest.mustache b/templates/asyncio/rest.mustache deleted file mode 100644 index 98c811e..0000000 --- a/templates/asyncio/rest.mustache +++ /dev/null @@ -1,241 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import io -import json -import logging -import re -import ssl - -import aiohttp -from urllib.parse import urlencode, quote_plus - -from {{packageName}}.exceptions import ApiException, ApiValueError - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp, data): - self.aiohttp_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = data - - def getheaders(self): - """Returns a CIMultiDictProxy of the response headers.""" - return self.aiohttp_response.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.aiohttp_response.headers.get(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - - # maxsize is number of requests to host that are allowed in parallel - if maxsize is None: - maxsize = configuration.connection_pool_maxsize - - ssl_context = ssl.create_default_context(cafile=configuration.ssl_ca_cert) - if configuration.cert_file: - ssl_context.load_cert_chain( - configuration.cert_file, keyfile=configuration.key_file - ) - - if not configuration.verify_ssl: - ssl_context.check_hostname = False - ssl_context.verify_mode = ssl.CERT_NONE - - connector = aiohttp.TCPConnector( - limit=maxsize, - ssl=ssl_context - ) - - self.proxy = configuration.proxy - self.proxy_headers = configuration.proxy_headers - - # https pool manager - self.pool_manager = aiohttp.ClientSession( - connector=connector, - trust_env=True - ) - - async def close(self): - await self.pool_manager.close() - - async def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Execute request - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: this is a non-applicable field for - the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} - timeout = _request_timeout or 5 * 60 - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - - args = { - "method": method, - "url": url, - "timeout": timeout, - "headers": headers - } - - if self.proxy: - args["proxy"] = self.proxy - if self.proxy_headers: - args["proxy_headers"] = self.proxy_headers - - if query_params: - args["url"] += '?' + urlencode(query_params) - - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if re.search('json', headers['Content-Type'], re.IGNORECASE): - if body is not None: - body = json.dumps(body) - args["data"] = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - args["data"] = aiohttp.FormData(post_params) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by aiohttp - del headers['Content-Type'] - data = aiohttp.FormData() - for param in post_params: - k, v = param - if isinstance(v, tuple) and len(v) == 3: - data.add_field(k, - value=v[1], - filename=v[0], - content_type=v[2]) - else: - data.add_field(k, v) - args["data"] = data - - # Pass a `bytes` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form - elif isinstance(body, bytes): - args["data"] = body - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - - r = await self.pool_manager.request(**args) - if _preload_content: - - data = await r.read() - r = RESTResponse(r, data) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - async def get_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def head_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def options_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return (await self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def post_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return (await self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def patch_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) diff --git a/templates/common_README.mustache b/templates/common_README.mustache deleted file mode 100644 index 706d9b3..0000000 --- a/templates/common_README.mustache +++ /dev/null @@ -1,85 +0,0 @@ -```python -{{#apiInfo}}{{#apis}}{{#-last}}{{#hasHttpSignatureMethods}}import datetime{{/hasHttpSignatureMethods}}{{/-last}}{{/apis}}{{/apiInfo}} -import time -import {{{packageName}}} -from {{{packageName}}}.rest import ApiException -from pprint import pprint -{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -{{> python_doc_auth_partial}} - -# Enter a context with an instance of the API client -{{#asyncio}}async {{/asyncio}}with {{{packageName}}}.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = {{{packageName}}}.{{{classname}}}(api_client) - {{#allParams}} - {{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} - {{/allParams}} - - try: - {{#summary}} - # {{{.}}} - {{/summary}} - {{#returnType}}api_response = {{/returnType}}{{#asyncio}}await {{/asyncio}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) - {{#returnType}} - print("The response of {{classname}}->{{operationId}}:\n") - pprint(api_response) - {{/returnType}} - except ApiException as e: - print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) -{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} -``` - -## Documentation for API Endpoints - -All URIs are relative to *{{{basePath}}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - -## Documentation For Models - -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} - - -## Documentation For Authorization - -{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} -{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} -{{#authMethods}} - -### {{{name}}} - -{{#isApiKey}} -- **Type**: API key -- **API key parameter name**: {{{keyParamName}}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}} -{{#isBasicBasic}} -- **Type**: HTTP basic authentication -{{/isBasicBasic}} -{{#isBasicBearer}} -- **Type**: Bearer authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} -{{/isBasicBearer}} -{{#isHttpSignature}} -- **Type**: HTTP signature authentication -{{/isHttpSignature}} -{{/isBasic}} -{{#isOAuth}} -- **Type**: OAuth -- **Flow**: {{{flow}}} -- **Authorization URL**: {{{authorizationUrl}}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - **{{{scope}}}**: {{{description}}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} - -## Author - -{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} -{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/templates/configuration.mustache b/templates/configuration.mustache deleted file mode 100644 index ac51800..0000000 --- a/templates/configuration.mustache +++ /dev/null @@ -1,615 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import copy -import logging -{{^asyncio}} -import multiprocessing -{{/asyncio}} -import sys -import urllib3 - -import http.client as httplib -from {{packageName}}.exceptions import ApiValueError - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' -} - -class Configuration(object): - """This class contains various settings of the API client. - - :param host: Base url. - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer). - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication. - :param password: Password for HTTP basic authentication. - :param access_token: Access token. -{{#hasHttpSignatureMethods}} - :param signing_info: Configuration parameters for the HTTP signature security scheme. - Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration -{{/hasHttpSignatureMethods}} - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format. - -{{#hasAuthMethods}} - :Example: -{{#hasApiKeyMethods}} - - API Key Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - cookieAuth: # name for the security scheme - type: apiKey - in: cookie - name: JSESSIONID # cookie name - - You can programmatically set the cookie: - -conf = {{{packageName}}}.Configuration( - api_key={'cookieAuth': 'abc123'} - api_key_prefix={'cookieAuth': 'JSESSIONID'} -) - - The following cookie will be added to the HTTP request: - Cookie: JSESSIONID abc123 -{{/hasApiKeyMethods}} -{{#hasHttpBasicMethods}} - - HTTP Basic Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - http_basic_auth: - type: http - scheme: basic - - Configure API client with HTTP basic authentication: - -conf = {{{packageName}}}.Configuration( - username='the-user', - password='the-password', -) - -{{/hasHttpBasicMethods}} -{{#hasHttpSignatureMethods}} - - HTTP Signature Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - http_basic_auth: - type: http - scheme: signature - - Configure API client with HTTP signature authentication. Use the 'hs2019' signature scheme, - sign the HTTP requests with the RSA-SSA-PSS signature algorithm, and set the expiration time - of the signature to 5 minutes after the signature has been created. - Note you can use the constants defined in the {{{packageName}}}.signing module, and you can - also specify arbitrary HTTP headers to be included in the HTTP signature, except for the - 'Authorization' header, which is used to carry the signature. - - One may be tempted to sign all headers by default, but in practice it rarely works. - This is because explicit proxies, transparent proxies, TLS termination endpoints or - load balancers may add/modify/remove headers. Include the HTTP headers that you know - are not going to be modified in transit. - -conf = {{{packageName}}}.Configuration( - signing_info = {{{packageName}}}.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'rsa.pem', - signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, - signing_algorithm = {{{packageName}}}.signing.ALGORITHM_RSASSA_PSS, - signed_headers = [{{{packageName}}}.signing.HEADER_REQUEST_TARGET, - {{{packageName}}}.signing.HEADER_CREATED, - {{{packageName}}}.signing.HEADER_EXPIRES, - {{{packageName}}}.signing.HEADER_HOST, - {{{packageName}}}.signing.HEADER_DATE, - {{{packageName}}}.signing.HEADER_DIGEST, - 'Content-Type', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) -{{/hasHttpSignatureMethods}} -{{/hasAuthMethods}} - """ - - _default = None - - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - access_token=None, -{{#hasHttpSignatureMethods}} - signing_info=None, -{{/hasHttpSignatureMethods}} - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, - ): - """Constructor - """ - self._base_path = "{{{basePath}}}" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.access_token = access_token - """Access token - """ -{{#hasHttpSignatureMethods}} - if signing_info is not None: - signing_info.host = host - self.signing_info = signing_info - """The HTTP signing configuration - """ -{{/hasHttpSignatureMethods}} - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("{{packageName}}") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = ssl_ca_cert - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - self.tls_server_name = None - """SSL/TLS Server Name Indication (SNI) - Set this to the SNI value expected by the server. - """ - - {{#asyncio}} - self.connection_pool_maxsize = 100 - """This value is passed to the aiohttp to limit simultaneous connections. - Default values is 100, None means no-limit. - """ - {{/asyncio}} - {{^asyncio}} - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - {{/asyncio}} - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - self.socket_options = None - """Options to pass down to the underlying urllib3 socket - """ - - self.datetime_format = "{{{datetimeFormat}}}" - """datetime format - """ - - self.date_format = "{{{dateFormat}}}" - """date format - """ - - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name, value): - object.__setattr__(self, name, value) -{{#hasHttpSignatureMethods}} - if name == "signing_info" and value is not None: - # Ensure the host parameter from signing info is the same as - # Configuration.host. - value.host = self.host -{{/hasHttpSignatureMethods}} - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = default - - @classmethod - def get_default_copy(cls): - """Deprecated. Please use `get_default` instead. - - Deprecated. Please use `get_default` instead. - - :return: The configuration object. - """ - return cls.get_default() - - @classmethod - def get_default(cls): - """Return the default configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration. - - :return: The configuration object. - """ - if cls._default is None: - cls._default = Configuration() - return cls._default - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} -{{#authMethods}} -{{#isApiKey}} - if '{{name}}' in self.api_key{{#vendorExtensions.x-auth-id-alias}} or '{{.}}' in self.api_key{{/vendorExtensions.x-auth-id-alias}}: - auth['{{name}}'] = { - 'type': 'api_key', - 'in': {{#isKeyInCookie}}'cookie'{{/isKeyInCookie}}{{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, - 'key': '{{keyParamName}}', - 'value': self.get_api_key_with_prefix( - '{{name}}',{{#vendorExtensions.x-auth-id-alias}} - alias='{{.}}',{{/vendorExtensions.x-auth-id-alias}} - ), - } -{{/isApiKey}} -{{#isBasic}} - {{#isBasicBasic}} - if self.username is not None and self.password is not None: - auth['{{name}}'] = { - 'type': 'basic', - 'in': 'header', - 'key': 'Authorization', - 'value': self.get_basic_auth_token() - } - {{/isBasicBasic}} - {{#isBasicBearer}} - if self.access_token is not None: - auth['{{name}}'] = { - 'type': 'bearer', - 'in': 'header', - {{#bearerFormat}} - 'format': '{{{.}}}', - {{/bearerFormat}} - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - {{/isBasicBearer}} - {{#isHttpSignature}} - if self.signing_info is not None: - auth['{{name}}'] = { - 'type': 'http-signature', - 'in': 'header', - 'key': 'Authorization', - 'value': None # Signature headers are calculated for every HTTP request - } - {{/isHttpSignature}} -{{/isBasic}} -{{#isOAuth}} - if self.access_token is not None: - auth['{{name}}'] = { - 'type': 'oauth2', - 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } -{{/isOAuth}} -{{/authMethods}} - return auth - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: {{version}}\n"\ - "SDK Package Version: {{packageVersion}}".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - {{#servers}} - { - 'url': "{{{url}}}", - 'description': "{{{description}}}{{^description}}No description provided{{/description}}", - {{#variables}} - {{#-first}} - 'variables': { - {{/-first}} - '{{{name}}}': { - 'description': "{{{description}}}{{^description}}No description provided{{/description}}", - 'default_value': "{{{defaultValue}}}", - {{#enumValues}} - {{#-first}} - 'enum_values': [ - {{/-first}} - "{{{.}}}"{{^-last}},{{/-last}} - {{#-last}} - ] - {{/-last}} - {{/enumValues}} - }{{^-last}},{{/-last}} - {{#-last}} - } - {{/-last}} - {{/variables}} - }{{^-last}},{{/-last}} - {{/servers}} - ] - - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path - - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) - - url = server['url'] - - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) - - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) - - url = url.replace("{" + variable_name + "}", used_value) - - return url - - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None diff --git a/templates/exceptions.mustache b/templates/exceptions.mustache deleted file mode 100644 index baee900..0000000 --- a/templates/exceptions.mustache +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" - - -class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None): - """ Raises an exception for TypeErrors - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) - - -class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ - - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) - - -class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None): - """ - Raised when an attribute reference or assignment fails. - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiAttributeError, self).__init__(full_msg) - - -class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) - - -class ApiException(OpenApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message - -class BadRequestException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(BadRequestException, self).__init__(status, reason, http_resp) - -class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ServiceException, self).__init__(status, reason, http_resp) - - -def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, int): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result diff --git a/templates/git_push.sh.mustache b/templates/git_push.sh.mustache deleted file mode 100644 index 0e3776a..0000000 --- a/templates/git_push.sh.mustache +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="{{{gitHost}}}" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="{{{gitUserId}}}" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="{{{gitRepoId}}}" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="{{{releaseNote}}}" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/templates/github-workflow.mustache b/templates/github-workflow.mustache deleted file mode 100644 index a3aae3f..0000000 --- a/templates/github-workflow.mustache +++ /dev/null @@ -1,38 +0,0 @@ -# NOTE: This file is auto generated by OpenAPI Generator. -# URL: https://openapi-generator.tech -# -# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python - -name: {{packageName}} Python package -{{=<% %>=}} - -on: [push, pull_request] - -jobs: - build: - - runs-on: ubuntu-latest - strategy: - matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] - - steps: - - uses: actions/checkout@v3 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install flake8 pytest - if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - - name: Lint with flake8 - run: | - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - - name: Test with pytest - run: | - pytest diff --git a/templates/gitignore.mustache b/templates/gitignore.mustache deleted file mode 100644 index 43995bd..0000000 --- a/templates/gitignore.mustache +++ /dev/null @@ -1,66 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ -venv/ -.venv/ -.python-version -.pytest_cache - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -#Ipython Notebook -.ipynb_checkpoints diff --git a/templates/gitlab-ci.mustache b/templates/gitlab-ci.mustache deleted file mode 100644 index 0bb48fd..0000000 --- a/templates/gitlab-ci.mustache +++ /dev/null @@ -1,25 +0,0 @@ -# NOTE: This file is auto generated by OpenAPI Generator. -# URL: https://openapi-generator.tech -# -# ref: https://docs.gitlab.com/ee/ci/README.html -# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml - -stages: - - test - -.pytest: - stage: test - script: - - pip install -r requirements.txt - - pip install -r test-requirements.txt - - pytest --cov={{{packageName}}} - -pytest-3.7: - extends: .pytest - image: python:3.7-alpine -pytest-3.8: - extends: .pytest - image: python:3.8-alpine -pytest-3.9: - extends: .pytest - image: python:3.9-alpine \ No newline at end of file diff --git a/templates/model.mustache b/templates/model.mustache deleted file mode 100644 index 84792dd..0000000 --- a/templates/model.mustache +++ /dev/null @@ -1,14 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -{{#models}} -{{#model}} -{{#isEnum}} -{{>model_enum}} -{{/isEnum}} -{{^isEnum}} -{{#oneOf}}{{#-first}}{{>model_oneof}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>model_anyof}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>model_generic}}{{/anyOf}}{{/oneOf}} -{{/isEnum}} -{{/model}} -{{/models}} \ No newline at end of file diff --git a/templates/model_anyof.mustache b/templates/model_anyof.mustache deleted file mode 100644 index 74a007f..0000000 --- a/templates/model_anyof.mustache +++ /dev/null @@ -1,180 +0,0 @@ -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} -{{#vendorExtensions.x-py-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-model-imports}} -from typing import Union, Any, List, TYPE_CHECKING -from pydantic import StrictStr, Field - -{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] - -class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): - """ - {{{description}}}{{^description}}{{{classname}}}{{/description}} - """ - -{{#composedSchemas.anyOf}} - # data type: {{{dataType}}} - {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} -{{/composedSchemas.anyOf}} - if TYPE_CHECKING: - actual_instance: Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}] - else: - actual_instance: Any - any_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True -{{#discriminator}} - - discriminator_value_class_map = { -{{#children}} - '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} -{{/children}} - } -{{/discriminator}} - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - {{#isNullable}} - if v is None: - return v - - {{/isNullable}} - instance = {{{classname}}}.construct() - error_messages = [] - {{#composedSchemas.anyOf}} - # validate data type: {{{dataType}}} - {{#isContainer}} - try: - instance.{{vendorExtensions.x-py-name}} = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - try: - instance.{{vendorExtensions.x-py-name}} = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - if not isinstance(v, {{{dataType}}}): - error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") - else: - return v - - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.anyOf}} - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> {{{classname}}}: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> {{{classname}}}: - """Returns the object represented by the json string""" - instance = {{{classname}}}.construct() - {{#isNullable}} - if json_str is None: - return instance - - {{/isNullable}} - error_messages = [] - {{#composedSchemas.anyOf}} - {{#isContainer}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - # {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} - try: - instance.actual_instance = {{{dataType}}}.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.anyOf}} - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_dict() - else: - return json.dumps(self.actual_instance) - - def to_str(self) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict()) - -{{#vendorExtensions.x-py-postponed-model-imports.size}} -{{#vendorExtensions.x-py-postponed-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-postponed-model-imports}} -{{classname}}.update_forward_refs() -{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_doc.mustache b/templates/model_doc.mustache deleted file mode 100644 index dd54470..0000000 --- a/templates/model_doc.mustache +++ /dev/null @@ -1,33 +0,0 @@ -{{#models}}{{#model}}# {{classname}} - -{{#description}}{{&description}} -{{/description}} - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} -{{/vars}} - -{{^isEnum}} -## Example - -```python -from {{modelPackage}}.{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} import {{classname}} - -# TODO update the JSON string below -json = "{}" -# create an instance of {{classname}} from a JSON string -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance = {{classname}}.from_json(json) -# print the JSON string representation of the object -print {{classname}}.to_json() - -# convert the object into a dict -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict() -# create an instance of {{classname}} from a dict -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_form_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict) -``` -{{/isEnum}} -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - -{{/model}}{{/models}} diff --git a/templates/model_enum.mustache b/templates/model_enum.mustache deleted file mode 100644 index 83f0552..0000000 --- a/templates/model_enum.mustache +++ /dev/null @@ -1,36 +0,0 @@ -import json -import pprint -import re # noqa: F401 -from aenum import Enum, no_arg -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} - - -class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum): - """ - {{{description}}}{{^description}}{{{classname}}}{{/description}} - """ - - """ - allowed enum values - """ -{{#allowableValues}} - {{#enumVars}} - {{{name}}} = {{{value}}} - {{/enumVars}} - - @classmethod - def from_json(cls, json_str: str) -> {{{classname}}}: - """Create an instance of {{classname}} from a JSON string""" - return {{classname}}(json.loads(json_str)) - - {{#defaultValue}} - - # - @classmethod - def _missing_value_(cls, value): - if value is no_arg: - return cls.{{{.}}} - {{/defaultValue}} -{{/allowableValues}} diff --git a/templates/model_generic.mustache b/templates/model_generic.mustache deleted file mode 100644 index 1355ddb..0000000 --- a/templates/model_generic.mustache +++ /dev/null @@ -1,361 +0,0 @@ -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} -{{#vendorExtensions.x-py-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-model-imports}} - -class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): - """ - {{{description}}}{{^description}}{{{classname}}}{{/description}} - """ -{{#vars}} - {{name}}: {{{vendorExtensions.x-py-typing}}} -{{/vars}} -{{#isAdditionalPropertiesTrue}} - additional_properties: Dict[str, Any] = {} -{{/isAdditionalPropertiesTrue}} - __properties = [{{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}}] -{{#vars}} - {{#vendorExtensions.x-regex}} - - @validator('{{{name}}}') - def {{{name}}}_validate_regular_expression(cls, value): - """Validates the regular expression""" - {{^required}} - if value is None: - return value - - {{/required}} - {{#required}} - {{#isNullable}} - if value is None: - return value - - {{/isNullable}} - {{/required}} - if not re.match(r"{{{.}}}", value{{#vendorExtensions.x-modifiers}} ,re.{{{.}}}{{/vendorExtensions.x-modifiers}}): - raise ValueError(r"must validate the regular expression {{{vendorExtensions.x-pattern}}}") - return value - {{/vendorExtensions.x-regex}} - {{#isEnum}} - - @validator('{{{name}}}') - def {{{name}}}_validate_enum(cls, value): - """Validates the enum""" - {{^required}} - if value is None: - return value - - {{/required}} - {{#required}} - {{#isNullable}} - if value is None: - return value - - {{/isNullable}} - {{/required}} - {{#isArray}} - for i in value: - if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): - raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") - {{/isArray}} - {{^isArray}} - if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}): - raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") - {{/isArray}} - return value - {{/isEnum}} -{{/vars}} - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - -{{#hasChildren}} -{{#discriminator}} - # JSON field name that stores the object type - __discriminator_property_name = '{{discriminator.propertyBaseName}}' - - {{#mappedModels}} - {{#-first}} - # discriminator mappings - __discriminator_value_class_map = { - {{/-first}} - '{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}} - {{#-last}} - } - - @classmethod - def get_discriminator_value(cls, obj: dict) -> str: - """Returns the discriminator value (object type) of the data""" - discriminator_value = obj[cls.__discriminator_property_name] - if discriminator_value: - return cls.__discriminator_value_class_map.get(discriminator_value) - else: - return None - {{/-last}} - {{/mappedModels}} - -{{/discriminator}} -{{/hasChildren}} - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}: - """Create an instance of {{{classname}}} from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - {{#vendorExtensions.x-py-readonly}} - "{{{.}}}", - {{/vendorExtensions.x-py-readonly}} - {{#isAdditionalPropertiesTrue}} - "additional_properties" - {{/isAdditionalPropertiesTrue}} - }, - exclude_none=True) - {{#allVars}} - {{#isContainer}} - {{#isArray}} - {{#items.isArray}} - {{^items.items.isPrimitiveType}} - # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list of list) - _items = [] - if self.{{{name}}}: - for _item in self.{{{name}}}: - if _item: - _items.append( - [_inner_item.to_dict() for _inner_item in _item if _inner_item is not None] - ) - _dict['{{{baseName}}}'] = _items - {{/items.items.isPrimitiveType}} - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list) - _items = [] - if self.{{{name}}}: - for _item in self.{{{name}}}: - if _item: - _items.append(_item.to_dict()) - _dict['{{{baseName}}}'] = _items - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isArray}} - {{#isMap}} - {{#items.isArray}} - # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict of array) - _field_dict_of_array = {} - if self.{{{name}}}: - for _key in self.{{{name}}}: - if self.{{{name}}}[_key]: - _field_dict_of_array[_key] = [ - _item.to_dict() for _item in self.{{{name}}}[_key] - ] - _dict['{{{baseName}}}'] = _field_dict_of_array - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict) - _field_dict = {} - if self.{{{name}}}: - for _key in self.{{{name}}}: - if self.{{{name}}}[_key]: - _field_dict[_key] = self.{{{name}}}[_key].to_dict() - _dict['{{{baseName}}}'] = _field_dict - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isMap}} - {{/isContainer}} - {{^isContainer}} - {{^isPrimitiveType}} - {{^isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of {{{name}}} - if self.{{{name}}}: - _dict['{{{baseName}}}'] = self.{{{name}}}.to_dict() - {{/isEnumOrRef}} - {{/isPrimitiveType}} - {{/isContainer}} - {{/allVars}} - {{#isAdditionalPropertiesTrue}} - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - {{/isAdditionalPropertiesTrue}} - {{#allVars}} - {{#isNullable}} - # set to None if {{{name}}} (nullable) is None - # and __fields_set__ contains the field - if self.{{name}} is None and "{{{name}}}" in self.__fields_set__: - _dict['{{{baseName}}}'] = None - - {{/isNullable}} - {{/allVars}} - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}: - """Create an instance of {{{classname}}} from a dict""" - {{#hasChildren}} - {{#discriminator}} - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type: - klass = globals()[object_type] - return klass.from_dict(obj) - else: - raise ValueError("{{{classname}}} failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - {{/discriminator}} - {{/hasChildren}} - {{^hasChildren}} - if obj is None: - return None - - if not isinstance(obj, dict): - return {{{classname}}}.parse_obj(obj) - - {{#disallowAdditionalPropertiesIfNotPresent}} - {{^isAdditionalPropertiesTrue}} - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + obj) - - {{/isAdditionalPropertiesTrue}} - {{/disallowAdditionalPropertiesIfNotPresent}} - _obj = {{{classname}}}.parse_obj({ - {{#allVars}} - {{#isContainer}} - {{#isArray}} - {{#items.isArray}} - {{#items.items.isPrimitiveType}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.items.isPrimitiveType}} - {{^items.items.isPrimitiveType}} - "{{{name}}}": [ - [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("{{{baseName}}}") - ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/items.items.isPrimitiveType}} - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{#items.isEnumOrRef}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{^items.isEnumOrRef}} - "{{{name}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj.get("{{{baseName}}}")] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{#items.isPrimitiveType}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isArray}} - {{#isMap}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - {{#items.isContainer}} - {{#items.isMap}} - "{{{name}}}": dict( - (_k, dict( - (_ik, {{{items.items.dataType}}}.from_dict(_iv)) - for _ik, _iv in _v.items() - ) - if _v is not None - else None - ) - for _k, _v in obj.get("{{{baseName}}}").items() - ) - if obj.get("{{{baseName}}}") is not None - else None{{^-last}},{{/-last}} - {{/items.isMap}} - {{#items.isArray}} - "{{{name}}}": dict( - (_k, - [{{{items.items.dataType}}}.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("{{{baseName}}}").items() - ){{^-last}},{{/-last}} - {{/items.isArray}} - {{/items.isContainer}} - {{^items.isContainer}} - "{{{name}}}": dict( - (_k, {{{items.dataType}}}.from_dict(_v)) - for _k, _v in obj.get("{{{baseName}}}").items() - ) - if obj.get("{{{baseName}}}") is not None - else None{{^-last}},{{/-last}} - {{/items.isContainer}} - {{/items.isEnumOrRef}} - {{#items.isEnumOrRef}} - "{{{name}}}": dict((_k, _v) for _k, _v in obj.get("{{{baseName}}}").items()){{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{#items.isPrimitiveType}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isPrimitiveType}} - {{/isMap}} - {{/isContainer}} - {{^isContainer}} - {{^isPrimitiveType}} - {{^isEnumOrRef}} - "{{{name}}}": {{{dataType}}}.from_dict(obj.get("{{{baseName}}}")) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/isEnumOrRef}} - {{#isEnumOrRef}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/isEnumOrRef}} - {{/isPrimitiveType}} - {{#isPrimitiveType}} - {{#defaultValue}} - "{{{name}}}": obj.get("{{{baseName}}}") if obj.get("{{{baseName}}}") is not None else {{{defaultValue}}}{{^-last}},{{/-last}} - {{/defaultValue}} - {{^defaultValue}} - "{{{name}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/defaultValue}} - {{/isPrimitiveType}} - {{/isContainer}} - {{/allVars}} - }) - {{#isAdditionalPropertiesTrue}} - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - {{/isAdditionalPropertiesTrue}} - return _obj - {{/hasChildren}} - -{{#vendorExtensions.x-py-postponed-model-imports.size}} -{{#vendorExtensions.x-py-postponed-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-postponed-model-imports}} -{{classname}}.update_forward_refs() -{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_oneof.mustache b/templates/model_oneof.mustache deleted file mode 100644 index c7afad4..0000000 --- a/templates/model_oneof.mustache +++ /dev/null @@ -1,206 +0,0 @@ -from __future__ import annotations -from inspect import getfullargspec -import json -import pprint -import re # noqa: F401 -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} -{{#vendorExtensions.x-py-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-model-imports}} -from typing import Union, Any, List, TYPE_CHECKING -from pydantic import StrictStr, Field - -{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] - -class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): - """ - {{{description}}}{{^description}}{{{classname}}}{{/description}} - """ -{{#composedSchemas.oneOf}} - # data type: {{{dataType}}} - {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} -{{/composedSchemas.oneOf}} - if TYPE_CHECKING: - actual_instance: Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}] - else: - actual_instance: Any - one_of_schemas: List[str] = Field({{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS, const=True) - - class Config: - validate_assignment = True -{{#discriminator}} - - discriminator_value_class_map = { -{{#children}} - '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} -{{/children}} - } -{{/discriminator}} - - def __init__(self, *args, **kwargs): - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - {{#isNullable}} - if v is None: - return v - - {{/isNullable}} - instance = {{{classname}}}.construct() - error_messages = [] - match = 0 - {{#composedSchemas.oneOf}} - # validate data type: {{{dataType}}} - {{#isContainer}} - try: - instance.{{vendorExtensions.x-py-name}} = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - try: - instance.{{vendorExtensions.x-py-name}} = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - if not isinstance(v, {{{dataType}}}): - error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") - else: - match += 1 - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.oneOf}} - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - else: - return v - - @classmethod - def from_dict(cls, obj: dict) -> {{{classname}}}: - return cls.from_json(json.dumps(obj)) - - @classmethod - def from_json(cls, json_str: str) -> {{{classname}}}: - """Returns the object represented by the json string""" - instance = {{{classname}}}.construct() - {{#isNullable}} - if json_str is None: - return instance - - {{/isNullable}} - error_messages = [] - match = 0 - - {{#useOneOfDiscriminatorLookup}} - {{#discriminator}} - {{#mappedModels}} - {{#-first}} - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("{{{propertyBaseName}}}") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `{{{propertyBaseName}}}` in the input.") - - {{/-first}} - # check if data type is `{{{modelName}}}` - if _data_type == "{{{mappingName}}}": - instance.actual_instance = {{{modelName}}}.from_json(json_str) - return instance - - {{/mappedModels}} - {{/discriminator}} - {{/useOneOfDiscriminatorLookup}} - {{#composedSchemas.oneOf}} - {{#isContainer}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - instance.actual_instance = {{{dataType}}}.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.oneOf}} - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - else: - return instance - - def to_json(self) -> str: - """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> dict: - """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance - - def to_str(self) -> str: - """Returns the string representation of the actual instance""" - return pprint.pformat(self.dict()) - -{{#vendorExtensions.x-py-postponed-model-imports.size}} -{{#vendorExtensions.x-py-postponed-model-imports}} -{{{.}}} -{{/vendorExtensions.x-py-postponed-model-imports}} -{{classname}}.update_forward_refs() -{{/vendorExtensions.x-py-postponed-model-imports.size}} \ No newline at end of file diff --git a/templates/model_test.mustache b/templates/model_test.mustache deleted file mode 100644 index 93ebf99..0000000 --- a/templates/model_test.mustache +++ /dev/null @@ -1,62 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import unittest -import datetime - -{{#models}} -{{#model}} -import {{packageName}} -from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501 -from {{packageName}}.rest import ApiException - -class Test{{classname}}(unittest.TestCase): - """{{classname}} unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass -{{^isEnum}} - - def make_instance(self, include_optional): - """Test {{classname}} - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # uncomment below to create an instance of `{{{classname}}}` - """ - model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501 - if include_optional : - return {{classname}}( - {{#vars}} - {{name}} = {{{example}}}{{^example}}None{{/example}}{{^-last}}, {{/-last}} - {{/vars}} - ) - else : - return {{classname}}( - {{#vars}} - {{#required}} - {{name}} = {{{example}}}{{^example}}None{{/example}}, - {{/required}} - {{/vars}} - ) - """ -{{/isEnum}} - - def test{{classname}}(self): - """Test {{classname}}""" -{{^isEnum}} - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) -{{/isEnum}} -{{#isEnum}} - # inst = {{{classname}}}() -{{/isEnum}} -{{/model}} -{{/models}} - -if __name__ == '__main__': - unittest.main() diff --git a/templates/partial_header.mustache b/templates/partial_header.mustache deleted file mode 100644 index 50aa811..0000000 --- a/templates/partial_header.mustache +++ /dev/null @@ -1,19 +0,0 @@ -""" -{{#appName}} - {{{.}}} - -{{/appName}} -{{#appDescription}} - {{{.}}} - -{{/appDescription}} - {{#version}} - The version of the OpenAPI document: {{{.}}} - {{/version}} - {{#infoEmail}} - Contact: {{{.}}} - {{/infoEmail}} - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 diff --git a/templates/py.typed.mustache b/templates/py.typed.mustache deleted file mode 100644 index e69de29..0000000 diff --git a/templates/pyproject.mustache b/templates/pyproject.mustache deleted file mode 100644 index 75900ed..0000000 --- a/templates/pyproject.mustache +++ /dev/null @@ -1,40 +0,0 @@ -[tool.poetry] -name = "{{{packageName}}}" -version = "{{{packageVersion}}}" -description = "{{{appName}}}" -authors = ["{{infoName}}{{^infoName}}OpenAPI Generator Community{{/infoName}} <{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}>"] -license = "{{{licenseInfo}}}{{^licenseInfo}}NoLicense{{/licenseInfo}}" -readme = "README.md" -repository = "https://github.com/{{{gitUserId}}}/{{{gitRepoId}}}" -keywords = ["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"] -include = ["{{packageName}}/py.typed"] - -[tool.poetry.dependencies] -python = "^3.7" - -urllib3 = ">= 1.25.3" -python-dateutil = ">=2.8.2" -{{#asyncio}} -aiohttp = ">= 3.8.4" -{{/asyncio}} -{{#tornado}} -tornado = ">=4.2,<5" -{{/tornado}} -{{#hasHttpSignatureMethods}} -pem = ">= 19.3.0" -pycryptodome = ">= 3.9.0" -{{/hasHttpSignatureMethods}} -pydantic = "^1.10.5, <2" -aenum = ">=3.1.11" - -[tool.poetry.dev-dependencies] -pytest = ">=7.2.1" -tox = ">=3.9.0" -flake8 = ">=4.0.0" - -[build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" - -[tool.pylint.'MESSAGES CONTROL'] -extension-pkg-whitelist = "pydantic" diff --git a/templates/python_doc_auth_partial.mustache b/templates/python_doc_auth_partial.mustache deleted file mode 100644 index f478fe0..0000000 --- a/templates/python_doc_auth_partial.mustache +++ /dev/null @@ -1,108 +0,0 @@ -# Defining the host is optional and defaults to {{{basePath}}} -# See configuration.py for a list of all supported configuration parameters. -configuration = {{{packageName}}}.Configuration( - host = "{{{basePath}}}" -) - -{{#hasAuthMethods}} -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} - -# Configure HTTP basic authorization: {{{name}}} -configuration = {{{packageName}}}.Configuration( - username = os.environ["USERNAME"], - password = os.environ["PASSWORD"] -) -{{/isBasicBasic}} -{{#isBasicBearer}} - -# Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}} -configuration = {{{packageName}}}.Configuration( - access_token = os.environ["BEARER_TOKEN"] -) -{{/isBasicBearer}} -{{#isHttpSignature}} - -# Configure HTTP message signature: {{{name}}} -# The HTTP Signature Header mechanism that can be used by a client to -# authenticate the sender of a message and ensure that particular headers -# have not been modified in transit. -# -# You can specify the signing key-id, private key path, signing scheme, -# signing algorithm, list of signed headers and signature max validity. -# The 'key_id' parameter is an opaque string that the API server can use -# to lookup the client and validate the signature. -# The 'private_key_path' parameter should be the path to a file that -# contains a DER or base-64 encoded private key. -# The 'private_key_passphrase' parameter is optional. Set the passphrase -# if the private key is encrypted. -# The 'signed_headers' parameter is used to specify the list of -# HTTP headers included when generating the signature for the message. -# You can specify HTTP headers that you want to protect with a cryptographic -# signature. Note that proxies may add, modify or remove HTTP headers -# for legitimate reasons, so you should only add headers that you know -# will not be modified. For example, if you want to protect the HTTP request -# body, you can specify the Digest header. In that case, the client calculates -# the digest of the HTTP request body and includes the digest in the message -# signature. -# The 'signature_max_validity' parameter is optional. It is configured as a -# duration to express when the signature ceases to be valid. The client calculates -# the expiration date every time it generates the cryptographic signature -# of an HTTP request. The API server may have its own security policy -# that controls the maximum validity of the signature. The client max validity -# must be lower than the server max validity. -# The time on the client and server must be synchronized, otherwise the -# server may reject the client signature. -# -# The client must use a combination of private key, signing scheme, -# signing algorithm and hash algorithm that matches the security policy of -# the API server. -# -# See {{{packageName}}}.signing for a list of all supported parameters. -from {{{packageName}}} import signing -import datetime - -configuration = {{{packageName}}}.Configuration( - host = "{{{basePath}}}", - signing_info = {{{packageName}}}.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'private_key.pem', - private_key_passphrase = 'YOUR_PASSPHRASE', - signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, - signing_algorithm = {{{packageName}}}.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - hash_algorithm = {{{packageName}}}.signing.SCHEME_RSA_SHA256, - signed_headers = [ - {{{packageName}}}.signing.HEADER_REQUEST_TARGET, - {{{packageName}}}.signing.HEADER_CREATED, - {{{packageName}}}.signing.HEADER_EXPIRES, - {{{packageName}}}.signing.HEADER_HOST, - {{{packageName}}}.signing.HEADER_DATE, - {{{packageName}}}.signing.HEADER_DIGEST, - 'Content-Type', - 'Content-Length', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) -{{/isHttpSignature}} -{{/isBasic}} -{{#isApiKey}} - -# Configure API key authorization: {{{name}}} -configuration.api_key['{{{name}}}'] = os.environ["API_KEY"] - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['{{name}}'] = 'Bearer' -{{/isApiKey}} -{{#isOAuth}} - -configuration.access_token = os.environ["ACCESS_TOKEN"] -{{/isOAuth}} -{{/authMethods}} -{{/hasAuthMethods}} diff --git a/templates/requirements.mustache b/templates/requirements.mustache deleted file mode 100644 index bd4fe39..0000000 --- a/templates/requirements.mustache +++ /dev/null @@ -1,8 +0,0 @@ -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.25.3, < 2.1.0 -pydantic >= 1.10.5, < 2 -aenum >= 3.1.11 -{{#asyncio}} -aiohttp >= 3.0.0 -{{/asyncio}} diff --git a/templates/rest.mustache b/templates/rest.mustache deleted file mode 100644 index c8748d7..0000000 --- a/templates/rest.mustache +++ /dev/null @@ -1,293 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import io -import json -import logging -import re -import ssl - -from urllib.parse import urlencode, quote_plus -import urllib3 - -from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries - - if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name - - - if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - - # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str) or isinstance(body, bytes): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) diff --git a/templates/setup.mustache b/templates/setup.mustache deleted file mode 100644 index 538a8df..0000000 --- a/templates/setup.mustache +++ /dev/null @@ -1,56 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -from setuptools import setup, find_packages # noqa: H301 - -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools -NAME = "{{{projectName}}}" -VERSION = "{{packageVersion}}" -PYTHON_REQUIRES = ">=3.7" -{{#apiInfo}} -{{#apis}} -{{#-last}} -REQUIRES = [ - "urllib3 >= 1.25.3, < 2.1.0", - "python-dateutil", -{{#asyncio}} - "aiohttp >= 3.0.0", -{{/asyncio}} -{{#tornado}} - "tornado>=4.2,<5", -{{/tornado}} -{{#hasHttpSignatureMethods}} - "pem>=19.3.0", - "pycryptodome>=3.9.0", -{{/hasHttpSignatureMethods}} - "pydantic >= 1.10.5, < 2", - "aenum" -] - -setup( - name=NAME, - version=VERSION, - description="{{appName}}", - author="{{infoName}}{{^infoName}}OpenAPI Generator community{{/infoName}}", - author_email="{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}", - url="{{packageUrl}}", - keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"], - install_requires=REQUIRES, - packages=find_packages(exclude=["test", "tests"]), - include_package_data=True, - {{#licenseInfo}}license="{{.}}", - {{/licenseInfo}}long_description_content_type='text/markdown', - long_description="""\ - {{appDescription}} - """, # noqa: E501 - package_data={"{{{packageName}}}": ["py.typed"]}, -) -{{/-last}} -{{/apis}} -{{/apiInfo}} diff --git a/templates/setup_cfg.mustache b/templates/setup_cfg.mustache deleted file mode 100644 index 11433ee..0000000 --- a/templates/setup_cfg.mustache +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length=99 diff --git a/templates/signing.mustache b/templates/signing.mustache deleted file mode 100644 index 8dca7e2..0000000 --- a/templates/signing.mustache +++ /dev/null @@ -1,403 +0,0 @@ -{{>partial_header}} - -from base64 import b64encode -from Crypto.IO import PEM, PKCS8 -from Crypto.Hash import SHA256, SHA512 -from Crypto.PublicKey import RSA, ECC -from Crypto.Signature import PKCS1_v1_5, pss, DSS -from email.utils import formatdate -import json -import os -import re -from time import time -from urllib.parse import urlencode, urlparse - -# The constants below define a subset of HTTP headers that can be included in the -# HTTP signature scheme. Additional headers may be included in the signature. - -# The '(request-target)' header is a calculated field that includes the HTTP verb, -# the URL path and the URL query. -HEADER_REQUEST_TARGET = '(request-target)' -# The time when the HTTP signature was generated. -HEADER_CREATED = '(created)' -# The time when the HTTP signature expires. The API server should reject HTTP requests -# that have expired. -HEADER_EXPIRES = '(expires)' -# The 'Host' header. -HEADER_HOST = 'Host' -# The 'Date' header. -HEADER_DATE = 'Date' -# When the 'Digest' header is included in the HTTP signature, the client automatically -# computes the digest of the HTTP request body, per RFC 3230. -HEADER_DIGEST = 'Digest' -# The 'Authorization' header is automatically generated by the client. It includes -# the list of signed headers and a base64-encoded signature. -HEADER_AUTHORIZATION = 'Authorization' - -# The constants below define the cryptographic schemes for the HTTP signature scheme. -SCHEME_HS2019 = 'hs2019' -SCHEME_RSA_SHA256 = 'rsa-sha256' -SCHEME_RSA_SHA512 = 'rsa-sha512' - -# The constants below define the signature algorithms that can be used for the HTTP -# signature scheme. -ALGORITHM_RSASSA_PSS = 'RSASSA-PSS' -ALGORITHM_RSASSA_PKCS1v15 = 'RSASSA-PKCS1-v1_5' - -ALGORITHM_ECDSA_MODE_FIPS_186_3 = 'fips-186-3' -ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 = 'deterministic-rfc6979' -ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS = { - ALGORITHM_ECDSA_MODE_FIPS_186_3, - ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 -} - -# The cryptographic hash algorithm for the message signature. -HASH_SHA256 = 'sha256' -HASH_SHA512 = 'sha512' - - -class HttpSigningConfiguration(object): - """The configuration parameters for the HTTP signature security scheme. - The HTTP signature security scheme is used to sign HTTP requests with a private key - which is in possession of the API client. - An 'Authorization' header is calculated by creating a hash of select headers, - and optionally the body of the HTTP request, then signing the hash value using - a private key. The 'Authorization' header is added to outbound HTTP requests. - - :param key_id: A string value specifying the identifier of the cryptographic key, - when signing HTTP requests. - :param signing_scheme: A string value specifying the signature scheme, when - signing HTTP requests. - Supported value are hs2019, rsa-sha256, rsa-sha512. - Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are - available for server-side applications that only support the older - HTTP signature algorithms. - :param private_key_path: A string value specifying the path of the file containing - a private key. The private key is used to sign HTTP requests. - :param private_key_passphrase: A string value specifying the passphrase to decrypt - the private key. - :param signed_headers: A list of strings. Each value is the name of a HTTP header - that must be included in the HTTP signature calculation. - The two special signature headers '(request-target)' and '(created)' SHOULD be - included in SignedHeaders. - The '(created)' header expresses when the signature was created. - The '(request-target)' header is a concatenation of the lowercased :method, an - ASCII space, and the :path pseudo-headers. - When signed_headers is not specified, the client defaults to a single value, - '(created)', in the list of HTTP headers. - When SignedHeaders contains the 'Digest' value, the client performs the - following operations: - 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. - 2. Set the 'Digest' header in the request body. - 3. Include the 'Digest' header and value in the HTTP signature. - :param signing_algorithm: A string value specifying the signature algorithm, when - signing HTTP requests. - Supported values are: - 1. For RSA keys: RSASSA-PSS, RSASSA-PKCS1-v1_5. - 2. For ECDSA keys: fips-186-3, deterministic-rfc6979. - If None, the signing algorithm is inferred from the private key. - The default signing algorithm for RSA keys is RSASSA-PSS. - The default signing algorithm for ECDSA keys is fips-186-3. - :param hash_algorithm: The hash algorithm for the signature. Supported values are - sha256 and sha512. - If the signing_scheme is rsa-sha256, the hash algorithm must be set - to None or sha256. - If the signing_scheme is rsa-sha512, the hash algorithm must be set - to None or sha512. - :param signature_max_validity: The signature max validity, expressed as - a datetime.timedelta value. It must be a positive value. - """ - def __init__(self, key_id, signing_scheme, private_key_path, - private_key_passphrase=None, - signed_headers=None, - signing_algorithm=None, - hash_algorithm=None, - signature_max_validity=None): - self.key_id = key_id - if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: - raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) - self.signing_scheme = signing_scheme - if not os.path.exists(private_key_path): - raise Exception("Private key file does not exist") - self.private_key_path = private_key_path - self.private_key_passphrase = private_key_passphrase - self.signing_algorithm = signing_algorithm - self.hash_algorithm = hash_algorithm - if signing_scheme == SCHEME_RSA_SHA256: - if self.hash_algorithm is None: - self.hash_algorithm = HASH_SHA256 - elif self.hash_algorithm != HASH_SHA256: - raise Exception("Hash algorithm must be sha256 when security scheme is %s" % - SCHEME_RSA_SHA256) - elif signing_scheme == SCHEME_RSA_SHA512: - if self.hash_algorithm is None: - self.hash_algorithm = HASH_SHA512 - elif self.hash_algorithm != HASH_SHA512: - raise Exception("Hash algorithm must be sha512 when security scheme is %s" % - SCHEME_RSA_SHA512) - elif signing_scheme == SCHEME_HS2019: - if self.hash_algorithm is None: - self.hash_algorithm = HASH_SHA256 - elif self.hash_algorithm not in {HASH_SHA256, HASH_SHA512}: - raise Exception("Invalid hash algorithm") - if signature_max_validity is not None and signature_max_validity.total_seconds() < 0: - raise Exception("The signature max validity must be a positive value") - self.signature_max_validity = signature_max_validity - # If the user has not provided any signed_headers, the default must be set to '(created)', - # as specified in the 'HTTP signature' standard. - if signed_headers is None or len(signed_headers) == 0: - signed_headers = [HEADER_CREATED] - if self.signature_max_validity is None and HEADER_EXPIRES in signed_headers: - raise Exception( - "Signature max validity must be set when " - "'(expires)' signature parameter is specified") - if len(signed_headers) != len(set(signed_headers)): - raise Exception("Cannot have duplicates in the signed_headers parameter") - if HEADER_AUTHORIZATION in signed_headers: - raise Exception("'Authorization' header cannot be included in signed headers") - self.signed_headers = signed_headers - self.private_key = None - """The private key used to sign HTTP requests. - Initialized when the PEM-encoded private key is loaded from a file. - """ - self.host = None - """The host name, optionally followed by a colon and TCP port number. - """ - self._load_private_key() - - def get_http_signature_headers(self, resource_path, method, headers, body, query_params): - """Create a cryptographic message signature for the HTTP request and add the signed headers. - - :param resource_path : A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method, e.g. GET, POST. - :param headers: A dict containing the HTTP request headers. - :param body: The object representing the HTTP request body. - :param query_params: A string representing the HTTP request query parameters. - :return: A dict of HTTP headers that must be added to the outbound HTTP request. - """ - if method is None: - raise Exception("HTTP method must be set") - if resource_path is None: - raise Exception("Resource path must be set") - - signed_headers_list, request_headers_dict = self._get_signed_header_info( - resource_path, method, headers, body, query_params) - - header_items = [ - "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] - string_to_sign = "\n".join(header_items) - - digest, digest_prefix = self._get_message_digest(string_to_sign.encode()) - b64_signed_msg = self._sign_digest(digest) - - request_headers_dict[HEADER_AUTHORIZATION] = self._get_authorization_header( - signed_headers_list, b64_signed_msg) - - return request_headers_dict - - def get_public_key(self): - """Returns the public key object associated with the private key. - """ - pubkey = None - if isinstance(self.private_key, RSA.RsaKey): - pubkey = self.private_key.publickey() - elif isinstance(self.private_key, ECC.EccKey): - pubkey = self.private_key.public_key() - return pubkey - - def _load_private_key(self): - """Load the private key used to sign HTTP requests. - The private key is used to sign HTTP requests as defined in - https://datatracker.ietf.org/doc/draft-cavage-http-signatures/. - """ - if self.private_key is not None: - return - with open(self.private_key_path, 'r') as f: - pem_data = f.read() - # Verify PEM Pre-Encapsulation Boundary - r = re.compile(r"\s*-----BEGIN (.*)-----\s+") - m = r.match(pem_data) - if not m: - raise ValueError("Not a valid PEM pre boundary") - pem_header = m.group(1) - if pem_header == 'RSA PRIVATE KEY': - self.private_key = RSA.importKey(pem_data, self.private_key_passphrase) - elif pem_header == 'EC PRIVATE KEY': - self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) - elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: - # Key is in PKCS8 format, which is capable of holding many different - # types of private keys, not just EC keys. - (key_binary, pem_header, is_encrypted) = \ - PEM.decode(pem_data, self.private_key_passphrase) - (oid, privkey, params) = \ - PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) - if oid == '1.2.840.10045.2.1': - self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) - else: - raise Exception("Unsupported key: {0}. OID: {1}".format(pem_header, oid)) - else: - raise Exception("Unsupported key: {0}".format(pem_header)) - # Validate the specified signature algorithm is compatible with the private key. - if self.signing_algorithm is not None: - supported_algs = None - if isinstance(self.private_key, RSA.RsaKey): - supported_algs = {ALGORITHM_RSASSA_PSS, ALGORITHM_RSASSA_PKCS1v15} - elif isinstance(self.private_key, ECC.EccKey): - supported_algs = ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS - if supported_algs is not None and self.signing_algorithm not in supported_algs: - raise Exception( - "Signing algorithm {0} is not compatible with private key".format( - self.signing_algorithm)) - - def _get_signed_header_info(self, resource_path, method, headers, body, query_params): - """Build the HTTP headers (name, value) that need to be included in - the HTTP signature scheme. - - :param resource_path : A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method, e.g. GET, POST. - :param headers: A dict containing the HTTP request headers. - :param body: The object (e.g. a dict) representing the HTTP request body. - :param query_params: A string representing the HTTP request query parameters. - :return: A tuple containing two dict objects: - The first dict contains the HTTP headers that are used to calculate - the HTTP signature. - The second dict contains the HTTP headers that must be added to - the outbound HTTP request. - """ - - if body is None: - body = '' - else: - body = body.to_json() - - # Build the '(request-target)' HTTP signature parameter. - target_host = urlparse(self.host).netloc - target_path = urlparse(self.host).path - request_target = method.lower() + " " + target_path + resource_path - if query_params: - request_target += "?" + urlencode(query_params) - - # Get UNIX time, e.g. seconds since epoch, not including leap seconds. - now = time() - # Format date per RFC 7231 section-7.1.1.2. An example is: - # Date: Wed, 21 Oct 2015 07:28:00 GMT - cdate = formatdate(timeval=now, localtime=False, usegmt=True) - # The '(created)' value MUST be a Unix timestamp integer value. - # Subsecond precision is not supported. - created = int(now) - if self.signature_max_validity is not None: - expires = now + self.signature_max_validity.total_seconds() - - signed_headers_list = [] - request_headers_dict = {} - for hdr_key in self.signed_headers: - hdr_key = hdr_key.lower() - if hdr_key == HEADER_REQUEST_TARGET: - value = request_target - elif hdr_key == HEADER_CREATED: - value = '{0}'.format(created) - elif hdr_key == HEADER_EXPIRES: - value = '{0}'.format(expires) - elif hdr_key == HEADER_DATE.lower(): - value = cdate - request_headers_dict[HEADER_DATE] = '{0}'.format(cdate) - elif hdr_key == HEADER_DIGEST.lower(): - request_body = body.encode() - body_digest, digest_prefix = self._get_message_digest(request_body) - b64_body_digest = b64encode(body_digest.digest()) - value = digest_prefix + b64_body_digest.decode('ascii') - request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( - digest_prefix, b64_body_digest.decode('ascii')) - elif hdr_key == HEADER_HOST.lower(): - value = target_host - request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) - else: - value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) - if value is None: - raise Exception( - "Cannot sign HTTP request. " - "Request does not contain the '{0}' header".format(hdr_key)) - signed_headers_list.append((hdr_key, value)) - - return signed_headers_list, request_headers_dict - - def _get_message_digest(self, data): - """Calculates and returns a cryptographic digest of a specified HTTP request. - - :param data: The string representation of the date to be hashed with a cryptographic hash. - :return: A tuple of (digest, prefix). - The digest is a hashing object that contains the cryptographic digest of - the HTTP request. - The prefix is a string that identifies the cryptographic hash. It is used - to generate the 'Digest' header as specified in RFC 3230. - """ - if self.hash_algorithm == HASH_SHA512: - digest = SHA512.new() - prefix = 'SHA-512=' - elif self.hash_algorithm == HASH_SHA256: - digest = SHA256.new() - prefix = 'SHA-256=' - else: - raise Exception("Unsupported hash algorithm: {0}".format(self.hash_algorithm)) - digest.update(data) - return digest, prefix - - def _sign_digest(self, digest): - """Signs a message digest with a private key specified in the signing_info. - - :param digest: A hashing object that contains the cryptographic digest of the HTTP request. - :return: A base-64 string representing the cryptographic signature of the input digest. - """ - sig_alg = self.signing_algorithm - if isinstance(self.private_key, RSA.RsaKey): - if sig_alg is None or sig_alg == ALGORITHM_RSASSA_PSS: - # RSASSA-PSS in Section 8.1 of RFC8017. - signature = pss.new(self.private_key).sign(digest) - elif sig_alg == ALGORITHM_RSASSA_PKCS1v15: - # RSASSA-PKCS1-v1_5 in Section 8.2 of RFC8017. - signature = PKCS1_v1_5.new(self.private_key).sign(digest) - else: - raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) - elif isinstance(self.private_key, ECC.EccKey): - if sig_alg is None: - sig_alg = ALGORITHM_ECDSA_MODE_FIPS_186_3 - if sig_alg in ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS: - # draft-ietf-httpbis-message-signatures-00 does not specify the ECDSA encoding. - # Issue: https://github.com/w3c-ccg/http-signatures/issues/107 - signature = DSS.new(key=self.private_key, mode=sig_alg, - encoding='der').sign(digest) - else: - raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) - else: - raise Exception("Unsupported private key: {0}".format(type(self.private_key))) - return b64encode(signature) - - def _get_authorization_header(self, signed_headers, signed_msg): - """Calculates and returns the value of the 'Authorization' header when signing HTTP requests. - - :param signed_headers : A list of tuples. Each value is the name of a HTTP header that - must be included in the HTTP signature calculation. - :param signed_msg: A base-64 encoded string representation of the signature. - :return: The string value of the 'Authorization' header, representing the signature - of the HTTP request. - """ - created_ts = None - expires_ts = None - for k, v in signed_headers: - if k == HEADER_CREATED: - created_ts = v - elif k == HEADER_EXPIRES: - expires_ts = v - lower_keys = [k.lower() for k, v in signed_headers] - headers_value = " ".join(lower_keys) - - auth_str = "Signature keyId=\"{0}\",algorithm=\"{1}\",".format( - self.key_id, self.signing_scheme) - if created_ts is not None: - auth_str = auth_str + "created={0},".format(created_ts) - if expires_ts is not None: - auth_str = auth_str + "expires={0},".format(expires_ts) - auth_str = auth_str + "headers=\"{0}\",signature=\"{1}\"".format( - headers_value, signed_msg.decode('ascii')) - - return auth_str diff --git a/templates/test-requirements.mustache b/templates/test-requirements.mustache deleted file mode 100644 index ca8eb27..0000000 --- a/templates/test-requirements.mustache +++ /dev/null @@ -1,6 +0,0 @@ -pytest~=7.1.3 -pytest-cov>=2.8.1 -pytest-randomly>=3.12.0 -{{#hasHttpSignatureMethods}} -pycryptodome>=3.9.0 -{{/hasHttpSignatureMethods}} \ No newline at end of file diff --git a/templates/tornado/rest.mustache b/templates/tornado/rest.mustache deleted file mode 100644 index 59f14ff..0000000 --- a/templates/tornado/rest.mustache +++ /dev/null @@ -1,223 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import io -import json -import logging -import re - -from urllib.parse import urlencode, quote_plus -import tornado -import tornado.gen -from tornado import httpclient -from urllib3.filepost import encode_multipart_formdata - -from {{packageName}}.exceptions import ApiException, ApiValueError - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.tornado_response = resp - self.status = resp.code - self.reason = resp.reason - - if resp.body: - self.data = resp.body - else: - self.data = None - - def getheaders(self): - """Returns a CIMultiDictProxy of the response headers.""" - return self.tornado_response.headers - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.tornado_response.headers.get(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=4): - # maxsize is number of requests to host that are allowed in parallel - - self.ca_certs = configuration.ssl_ca_cert - self.client_key = configuration.key_file - self.client_cert = configuration.cert_file - - self.proxy_port = self.proxy_host = None - - # https pool manager - if configuration.proxy: - self.proxy_port = 80 - self.proxy_host = configuration.proxy - - self.pool_manager = httpclient.AsyncHTTPClient() - - @tornado.gen.coroutine - def request(self, method, url, query_params=None, headers=None, body=None, - post_params=None, _preload_content=True, - _request_timeout=None): - """Execute Request - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: this is a non-applicable field for - the AiohttpClient. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - request = httpclient.HTTPRequest(url) - request.allow_nonstandard_methods = True - request.ca_certs = self.ca_certs - request.client_key = self.client_key - request.client_cert = self.client_cert - request.proxy_host = self.proxy_host - request.proxy_port = self.proxy_port - request.method = method - if headers: - request.headers = headers - if 'Content-Type' not in headers: - request.headers['Content-Type'] = 'application/json' - request.request_timeout = _request_timeout or 5 * 60 - - post_params = post_params or {} - - if query_params: - request.url += '?' + urlencode(query_params) - - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if re.search('json', headers['Content-Type'], re.IGNORECASE): - if body: - body = json.dumps(body) - request.body = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - request.body = urlencode(post_params) - elif headers['Content-Type'] == 'multipart/form-data': - multipart = encode_multipart_formdata(post_params) - request.body, headers['Content-Type'] = multipart - # Pass a `bytes` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form - elif isinstance(body, bytes): - request.body = body - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - - r = yield self.pool_manager.fetch(request, raise_error=False) - - if _preload_content: - - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - raise tornado.gen.Return(r) - - @tornado.gen.coroutine - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - result = yield self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - result = yield self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - result = yield self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) diff --git a/templates/tox.mustache b/templates/tox.mustache deleted file mode 100644 index 9d717c3..0000000 --- a/templates/tox.mustache +++ /dev/null @@ -1,9 +0,0 @@ -[tox] -envlist = py3 - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - -commands= - pytest --cov={{{packageName}}} diff --git a/templates/travis.mustache b/templates/travis.mustache deleted file mode 100644 index 53cb57e..0000000 --- a/templates/travis.mustache +++ /dev/null @@ -1,17 +0,0 @@ -# ref: https://docs.travis-ci.com/user/languages/python -language: python -python: - - "3.7" - - "3.8" - - "3.9" - - "3.10" - - "3.11" - # uncomment the following if needed - #- "3.11-dev" # 3.11 development branch - #- "nightly" # nightly build -# command to install dependencies -install: - - "pip install -r requirements.txt" - - "pip install -r test-requirements.txt" -# command to run tests -script: pytest --cov={{{packageName}}} From 7753e8f00b5544e356cce69fe79fd5c67f8c48d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Thu, 7 Sep 2023 16:52:59 +0200 Subject: [PATCH 16/20] Remove project files --- jellyfish/pyproject.toml | 26 -------------------- jellyfish/setup.py | 52 ---------------------------------------- 2 files changed, 78 deletions(-) delete mode 100644 jellyfish/pyproject.toml delete mode 100644 jellyfish/setup.py diff --git a/jellyfish/pyproject.toml b/jellyfish/pyproject.toml deleted file mode 100644 index 1891fd8..0000000 --- a/jellyfish/pyproject.toml +++ /dev/null @@ -1,26 +0,0 @@ -[tool.poetry] -name = "jellyfish-server-sdk" -version = "0.1.0" -description = "Python server SDK for Jellyfish Media Server" -authors = ["Membrane Team https://github.com/membraneframework"] -license = "Apache 2.0" -readme = "README.md" -repository = "https://github.com/jellyfish-dev/python-server-sdk" - - -[tool.poetry.dependencies] -python = "^3.7" - -urllib3 = ">= 1.25.3" -python-dateutil = ">=2.8.2" -pydantic = "^1.10.5, <2" -aenum = ">=3.1.11" - -[tool.poetry.dev-dependencies] -pytest = ">=7.2.1" -tox = ">=3.9.0" -flake8 = ">=4.0.0" - -[build-system] -requires = ["setuptools ~= 68.1"] -build-backend = "setuptools.build_meta" diff --git a/jellyfish/setup.py b/jellyfish/setup.py deleted file mode 100644 index 76e8ff9..0000000 --- a/jellyfish/setup.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding: utf-8 - -# pylint: disable=locally-disabled, line-too-long - -""" - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: 0.2.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" - - -from setuptools import setup, find_packages # noqa: H301 - -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools -NAME = "jellyfish-server-sdk" -VERSION = "0.1.0" -PYTHON_REQUIRES = ">=3.7" -REQUIRES = [ - "urllib3 >= 1.25.3, < 2.1.0", - "python-dateutil", - "pydantic >= 1.10.5, < 2", - "aenum" -] - -setup( - name=NAME, - version=VERSION, - description="Jellyfish Media Server", - author="Jellyfish team", - author_email="team@openapitools.org", - url="", - keywords=["OpenAPI", "OpenAPI-Generator", "Jellyfish Media Server"], - install_requires=REQUIRES, - packages=find_packages(exclude=["test", "tests"]), - include_package_data=True, - license="Apache 2.0", - long_description_content_type='text/markdown', - long_description="""\ - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - """, # noqa: E501 - package_data={"jellyfish_openapi_client": ["py.typed"]}, -) From 3d60abb52f204f9833683b592d4381decd9caf71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Fri, 8 Sep 2023 14:53:47 +0200 Subject: [PATCH 17/20] options check --- generate_client.sh | 2 ++ jellyfish/room_api.py | 2 +- tests/__init__.py | 0 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 tests/__init__.py diff --git a/generate_client.sh b/generate_client.sh index e42fc67..eb79e94 100755 --- a/generate_client.sh +++ b/generate_client.sh @@ -1,3 +1,5 @@ +#!/bin/bash + rm -rf openapi openapi-generator-cli generate \ -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/openapi-generator-compatibility/openapi.yaml \ diff --git a/jellyfish/room_api.py b/jellyfish/room_api.py index 23e335d..29edb2a 100644 --- a/jellyfish/room_api.py +++ b/jellyfish/room_api.py @@ -60,7 +60,7 @@ def delete_peer(self, room_id: str, peer_id: str) -> None: def add_component(self, room_id: str, component_type: str, options=None) -> Component: """Creates component in the room""" - if options: + if options is not None: options = ComponentOptions(options) request = AddComponentRequest(type=component_type, options=options) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 From e1ada1cdb00fcaeae04286e13062db4b4c8b09ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Fri, 8 Sep 2023 15:15:27 +0200 Subject: [PATCH 18/20] Custom partial_header template --- generate_client.sh | 3 ++- openapi/openapi_client/__init__.py | 4 +--- openapi/openapi_client/api/default_api.py | 4 +--- openapi/openapi_client/api/room_api.py | 4 +--- openapi/openapi_client/api_client.py | 4 +--- openapi/openapi_client/configuration.py | 4 +--- openapi/openapi_client/exceptions.py | 4 +--- openapi/openapi_client/models/__init__.py | 4 +--- .../models/add_component_request.py | 4 +--- .../openapi_client/models/add_peer_request.py | 4 +--- openapi/openapi_client/models/component.py | 4 +--- .../models/component_details_response.py | 4 +--- .../openapi_client/models/component_metadata.py | 4 +--- .../openapi_client/models/component_options.py | 4 +--- .../models/component_options_rtsp.py | 4 +--- openapi/openapi_client/models/error.py | 4 +--- openapi/openapi_client/models/hls_skip.py | 4 +--- openapi/openapi_client/models/peer.py | 4 +--- .../models/peer_details_response.py | 4 +--- .../models/peer_details_response_data.py | 4 +--- openapi/openapi_client/models/peer_options.py | 4 +--- .../models/peer_options_web_rtc.py | 4 +--- openapi/openapi_client/models/peer_status.py | 4 +--- openapi/openapi_client/models/room.py | 4 +--- openapi/openapi_client/models/room_config.py | 4 +--- .../models/room_create_details_response.py | 4 +--- .../models/room_create_details_response_data.py | 4 +--- .../models/room_details_response.py | 4 +--- .../models/rooms_listing_response.py | 4 +--- openapi/openapi_client/rest.py | 4 +--- openapi/setup.py | 4 +--- templates/partial_header.mustache | 17 +++++++++++++++++ 32 files changed, 49 insertions(+), 91 deletions(-) create mode 100644 templates/partial_header.mustache diff --git a/generate_client.sh b/generate_client.sh index eb79e94..567bae2 100755 --- a/generate_client.sh +++ b/generate_client.sh @@ -2,9 +2,10 @@ rm -rf openapi openapi-generator-cli generate \ - -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/openapi-generator-compatibility/openapi.yaml \ + -i https://raw.githubusercontent.com/jellyfish-dev/jellyfish/main/openapi.yaml \ -g python \ -o openapi \ + -t templates \ --package-name openapi_client \ --global-property apis,models,modelTests=false,supportingFiles diff --git a/openapi/openapi_client/__init__.py b/openapi/openapi_client/__init__.py index d6a545c..364c81d 100644 --- a/openapi/openapi_client/__init__.py +++ b/openapi/openapi_client/__init__.py @@ -3,9 +3,7 @@ # flake8: noqa """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/api/default_api.py b/openapi/openapi_client/api/default_api.py index a5828b4..69af7ab 100644 --- a/openapi/openapi_client/api/default_api.py +++ b/openapi/openapi_client/api/default_api.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/api/room_api.py b/openapi/openapi_client/api/room_api.py index c779e2a..c259df0 100644 --- a/openapi/openapi_client/api/room_api.py +++ b/openapi/openapi_client/api/room_api.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/api_client.py b/openapi/openapi_client/api_client.py index cb105e1..fa1f57e 100644 --- a/openapi/openapi_client/api_client.py +++ b/openapi/openapi_client/api_client.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/configuration.py b/openapi/openapi_client/configuration.py index fd876d5..460d58a 100644 --- a/openapi/openapi_client/configuration.py +++ b/openapi/openapi_client/configuration.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/exceptions.py b/openapi/openapi_client/exceptions.py index c62a6ba..0ff8add 100644 --- a/openapi/openapi_client/exceptions.py +++ b/openapi/openapi_client/exceptions.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/__init__.py b/openapi/openapi_client/models/__init__.py index df259e8..e78a2e7 100644 --- a/openapi/openapi_client/models/__init__.py +++ b/openapi/openapi_client/models/__init__.py @@ -2,9 +2,7 @@ # flake8: noqa """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/add_component_request.py b/openapi/openapi_client/models/add_component_request.py index 1723ea0..c01f06f 100644 --- a/openapi/openapi_client/models/add_component_request.py +++ b/openapi/openapi_client/models/add_component_request.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/add_peer_request.py b/openapi/openapi_client/models/add_peer_request.py index d649fdf..cfc41f0 100644 --- a/openapi/openapi_client/models/add_peer_request.py +++ b/openapi/openapi_client/models/add_peer_request.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/component.py b/openapi/openapi_client/models/component.py index 18e0d34..2be82d4 100644 --- a/openapi/openapi_client/models/component.py +++ b/openapi/openapi_client/models/component.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/component_details_response.py b/openapi/openapi_client/models/component_details_response.py index d3ec75f..5792ba3 100644 --- a/openapi/openapi_client/models/component_details_response.py +++ b/openapi/openapi_client/models/component_details_response.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/component_metadata.py b/openapi/openapi_client/models/component_metadata.py index 20f80b9..7721513 100644 --- a/openapi/openapi_client/models/component_metadata.py +++ b/openapi/openapi_client/models/component_metadata.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/component_options.py b/openapi/openapi_client/models/component_options.py index 7501ebc..f90137c 100644 --- a/openapi/openapi_client/models/component_options.py +++ b/openapi/openapi_client/models/component_options.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/component_options_rtsp.py b/openapi/openapi_client/models/component_options_rtsp.py index d2bf321..a42ec20 100644 --- a/openapi/openapi_client/models/component_options_rtsp.py +++ b/openapi/openapi_client/models/component_options_rtsp.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/error.py b/openapi/openapi_client/models/error.py index 5635824..31975e8 100644 --- a/openapi/openapi_client/models/error.py +++ b/openapi/openapi_client/models/error.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/hls_skip.py b/openapi/openapi_client/models/hls_skip.py index aea7ae3..9d51496 100644 --- a/openapi/openapi_client/models/hls_skip.py +++ b/openapi/openapi_client/models/hls_skip.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer.py b/openapi/openapi_client/models/peer.py index 9e0cbac..df15742 100644 --- a/openapi/openapi_client/models/peer.py +++ b/openapi/openapi_client/models/peer.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer_details_response.py b/openapi/openapi_client/models/peer_details_response.py index e7e779f..6629ce1 100644 --- a/openapi/openapi_client/models/peer_details_response.py +++ b/openapi/openapi_client/models/peer_details_response.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer_details_response_data.py b/openapi/openapi_client/models/peer_details_response_data.py index 0bdbab3..98bff6c 100644 --- a/openapi/openapi_client/models/peer_details_response_data.py +++ b/openapi/openapi_client/models/peer_details_response_data.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer_options.py b/openapi/openapi_client/models/peer_options.py index c12fb8d..2bd9c3c 100644 --- a/openapi/openapi_client/models/peer_options.py +++ b/openapi/openapi_client/models/peer_options.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer_options_web_rtc.py b/openapi/openapi_client/models/peer_options_web_rtc.py index 0f9d99b..e51f45f 100644 --- a/openapi/openapi_client/models/peer_options_web_rtc.py +++ b/openapi/openapi_client/models/peer_options_web_rtc.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/peer_status.py b/openapi/openapi_client/models/peer_status.py index e9441bc..fc9fc11 100644 --- a/openapi/openapi_client/models/peer_status.py +++ b/openapi/openapi_client/models/peer_status.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/room.py b/openapi/openapi_client/models/room.py index 00a498a..1ec5cb6 100644 --- a/openapi/openapi_client/models/room.py +++ b/openapi/openapi_client/models/room.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/room_config.py b/openapi/openapi_client/models/room_config.py index b1edda1..bc00f7e 100644 --- a/openapi/openapi_client/models/room_config.py +++ b/openapi/openapi_client/models/room_config.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/room_create_details_response.py b/openapi/openapi_client/models/room_create_details_response.py index d700a62..a351cb4 100644 --- a/openapi/openapi_client/models/room_create_details_response.py +++ b/openapi/openapi_client/models/room_create_details_response.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/room_create_details_response_data.py b/openapi/openapi_client/models/room_create_details_response_data.py index 5c8f34d..a439102 100644 --- a/openapi/openapi_client/models/room_create_details_response_data.py +++ b/openapi/openapi_client/models/room_create_details_response_data.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/room_details_response.py b/openapi/openapi_client/models/room_details_response.py index 9c13cb6..7b7b91f 100644 --- a/openapi/openapi_client/models/room_details_response.py +++ b/openapi/openapi_client/models/room_details_response.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/models/rooms_listing_response.py b/openapi/openapi_client/models/rooms_listing_response.py index 9f83026..ce557f5 100644 --- a/openapi/openapi_client/models/rooms_listing_response.py +++ b/openapi/openapi_client/models/rooms_listing_response.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/openapi_client/rest.py b/openapi/openapi_client/rest.py index bd9c595..3d683b2 100644 --- a/openapi/openapi_client/rest.py +++ b/openapi/openapi_client/rest.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/openapi/setup.py b/openapi/setup.py index d7d8399..cedca17 100644 --- a/openapi/setup.py +++ b/openapi/setup.py @@ -1,9 +1,7 @@ # coding: utf-8 """ - Jellyfish Media Server - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + Python API wrapper for Jellyfish Media Server The version of the OpenAPI document: 0.2.0 Generated by OpenAPI Generator (https://openapi-generator.tech) diff --git a/templates/partial_header.mustache b/templates/partial_header.mustache new file mode 100644 index 0000000..5857428 --- /dev/null +++ b/templates/partial_header.mustache @@ -0,0 +1,17 @@ +""" +{{#appName}} +{{/appName}} +{{#appDescription}} + Python API wrapper for Jellyfish Media Server + +{{/appDescription}} + {{#version}} + The version of the OpenAPI document: {{{.}}} + {{/version}} + {{#infoEmail}} + Contact: {{{.}}} + {{/infoEmail}} + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 From fff4168ebb16a95469f89bec821b97dda9a64c63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Mon, 11 Sep 2023 11:23:29 +0200 Subject: [PATCH 19/20] Fix docker test --- docker-compose-test.yaml | 10 +++++++--- tests/test_room_api.py | 5 ++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docker-compose-test.yaml b/docker-compose-test.yaml index 6ddeb76..87b3a97 100644 --- a/docker-compose-test.yaml +++ b/docker-compose-test.yaml @@ -7,13 +7,13 @@ services: restart: on-failure healthcheck: test: > - curl --fail -H "authorization: Bearer development" http://localhost:5002/room || exit 1 + curl --fail -H "authorization: Bearer development" http://jellyfish:5002/room || exit 1 interval: 3s retries: 2 timeout: 2s start_period: 30s environment: - VIRTUAL_HOST: "localhost" + VIRTUAL_HOST: "jellyfish" USE_INTEGRATED_TURN: "true" INTEGRATED_TURN_IP: "${INTEGRATED_TURN_IP:-127.0.0.1}" INTEGRATED_TURN_LISTEN_IP: "0.0.0.0" @@ -26,10 +26,14 @@ services: - "5002:5002" - "49999:49999" - "50000-50050:50000-50050/udp" + networks: + - network test: image: python:3.7-alpine3.18 - command: sh -c "cd app/ && pip install -r requirements.txt && pytest" + command: sh -c "cd app/ && pip install -r requirements.txt && pytest tests/test_room_api.py::TestAuthentication" + environment: + - DOCKER_TEST=TRUE volumes: - .:/app networks: diff --git a/tests/test_room_api.py b/tests/test_room_api.py index f31595d..0f62ab7 100644 --- a/tests/test_room_api.py +++ b/tests/test_room_api.py @@ -4,6 +4,8 @@ Tests room api """ +import os + import pytest from jellyfish import RoomApi, RoomConfig @@ -15,7 +17,8 @@ from jellyfish import UnauthorizedException, NotFoundException, BadRequestException -SERVER_ADDRESS = "http://localhost:5002" +HOST = 'jellyfish' if os.getenv('DOCKER_TEST') == 'TRUE' else 'localhost' +SERVER_ADDRESS = f'http://{HOST}:5002' SERVER_API_TOKEN = "development" MAX_PEERS = 10 From a24a085ec7a2b06efebc1bdfc0e5d830dfd3dc81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Ro=C5=BCnawski?= Date: Mon, 11 Sep 2023 11:27:54 +0200 Subject: [PATCH 20/20] Add all tests in docker test --- docker-compose-test.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose-test.yaml b/docker-compose-test.yaml index 87b3a97..9dcc268 100644 --- a/docker-compose-test.yaml +++ b/docker-compose-test.yaml @@ -31,7 +31,7 @@ services: test: image: python:3.7-alpine3.18 - command: sh -c "cd app/ && pip install -r requirements.txt && pytest tests/test_room_api.py::TestAuthentication" + command: sh -c "cd app/ && pip install -r requirements.txt && pytest" environment: - DOCKER_TEST=TRUE volumes: