delarte/src/delarte/api.py
Barbagus 58b0ba30a3 Refactor api module and Rendition* model
Split `api` functionalities in smaller parts
- fetch API JSON object `fetch_api_object()`
- read the config object `read_config_player_object()`
Move that "pipeline" in `__init__.py`

Remove `code` field `Rendition` and replace it with some track rendition
models that are build from parsing the `code` from ArteTV. Also move the
`protocol` from the `RenditionSource` to the `Rendition` model itself...
who knows how we might handle it in the future.
2023-02-16 20:11:45 +01:00

49 lines
1.3 KiB
Python

# License: GNU AGPL v3: http://www.gnu.org/licenses/
# This file is part of `delarte` (https://git.afpy.org/fcode/delarte.git)
"""Provide ArteTV JSON API utilities."""
import json
from .error import HTTPError, UnexpectedAPIResponse
MIME_TYPE = "application/vnd.api+json; charset=utf-8"
def fetch_api_object(http, url):
"""Fetch an API object."""
r = http.request("GET", url)
HTTPError.raise_for_status(r)
mime_type = r.getheader("content-type")
if mime_type != MIME_TYPE:
raise UnexpectedAPIResponse("MIME_TYPE", url, MIME_TYPE, mime_type)
return json.loads(r.data.decode("utf-8"))
def read_config_player_object(obj):
"""Return program ID and streams information from config player object."""
try:
if obj["data"]["type"] != "ConfigPlayer":
raise UnexpectedAPIResponse("OBJECT_TYPE")
attributes = obj["data"]["attributes"]
program_id = attributes["metadata"]["providerId"]
streams = [
(
s["versions"][0]["eStat"]["ml5"],
s["versions"][0]["label"],
s["protocol"],
s["url"],
)
for s in attributes["streams"]
]
return program_id, streams
except (KeyError, IndexError, ValueError) as e:
raise UnexpectedAPIResponse("SCHEMA") from e