Skip to content

Commit

Permalink
Applying linters
Browse files Browse the repository at this point in the history
  • Loading branch information
rsonke-maxxton committed Nov 17, 2024
1 parent f83f1bc commit be8c9c8
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = false
insert_final_newline = false
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
MANIFEST
24 changes: 24 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-json
- id: check-added-large-files
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
name: isort (python)
args: ["--profile", "black"]
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
- repo: https://github.com/PyCQA/flake8
rev: 7.1.1
hooks:
- id: flake8
args: ["--max-line-length=160"]
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ poetry run python -m unittest discover -s tests
```



## Data Structures

For a very short and simplified example of the complete library JSON that the API provides, see [example.json](./example.json). Below you will find the fields of each main topic.
Expand Down Expand Up @@ -129,6 +128,3 @@ For a very short and simplified example of the complete library JSON that the AP
"artist_id": 2
}
```
```
Made changes.
7 changes: 6 additions & 1 deletion ibroadcastaio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
"""Provide a package for ibroadcastaio."""
from .client import IBroadcastClient

from .client import IBroadcastClient

__all__ = [
"IBroadcastClient",
]
85 changes: 63 additions & 22 deletions ibroadcastaio/client.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import json
from aiohttp import ClientSession
from typing import Any, AsyncGenerator
import logging

from ibroadcastaio.const import BASE_API_URL, BASE_LIBRARY_URL, REFERER, STATUS_API, VERSION
from aiohttp import ClientSession

from ibroadcastaio.const import (
BASE_API_URL,
BASE_LIBRARY_URL,
REFERER,
STATUS_API,
VERSION,
)


class IBroadcastClient:
"""iBroadcast API Client to use the API in an async manner"""

_user_id = None
_token = None

Expand All @@ -22,7 +30,7 @@ def __init__(self, http_session: ClientSession) -> None:
self.http_session = http_session

async def login(self, username: str, password: str) -> dict[str, Any]:
data={
data = {
"mode": "status",
"email_address": username,
"password": password,
Expand All @@ -31,7 +39,9 @@ async def login(self, username: str, password: str) -> dict[str, Any]:
"supported_types": False,
}

status = await self.__post(f"{BASE_API_URL}{STATUS_API}", { "content_type": "application/json" }, data)
status = await self.__post(
f"{BASE_API_URL}{STATUS_API}", {"content_type": "application/json"}, data
)
if "user" not in status:
raise ValueError("Invalid credentials")

Expand All @@ -57,16 +67,40 @@ async def refresh_library(self):
For now we fetch the complete librady and split it into in memory class members.
Later, we remove this step and rewrite methods such as _get_albums(album_id) to directly fetch it from the API.
"""
library = await self.__post(f"{BASE_LIBRARY_URL}", { "content_type": "application/json" }, data)

self._albums = {album['album_id']: album async for album in self.__jsonToDict(library['library']['albums'], 'album_id')}
self._artists = {artist['artist_id']: artist async for artist in self.__jsonToDict(library['library']['artists'], 'artist_id')}
self._playlists = {playlist['playlist_id']: playlist async for playlist in self.__jsonToDict(library['library']['playlists'], 'playlist_id')}
self._tags = {tag['tag_id']: tag async for tag in self.__jsonToDict(library['library']['tags'], 'tag_id')}
self._tracks = {track['track_id']: track async for track in self.__jsonToDict(library['library']['tracks'], 'track_id')}

self._settings = library['settings']
library = await self.__post(
f"{BASE_LIBRARY_URL}", {"content_type": "application/json"}, data
)

self._albums = {
album["album_id"]: album
async for album in self.__jsonToDict(
library["library"]["albums"], "album_id"
)
}
self._artists = {
artist["artist_id"]: artist
async for artist in self.__jsonToDict(
library["library"]["artists"], "artist_id"
)
}
self._playlists = {
playlist["playlist_id"]: playlist
async for playlist in self.__jsonToDict(
library["library"]["playlists"], "playlist_id"
)
}
self._tags = {
tag["tag_id"]: tag
async for tag in self.__jsonToDict(library["library"]["tags"], "tag_id")
}
self._tracks = {
track["track_id"]: track
async for track in self.__jsonToDict(
library["library"]["tracks"], "track_id"
)
}

self._settings = library["settings"]

async def get_settings(self):
self._check_library_loaded()
Expand All @@ -76,13 +110,20 @@ async def get_album(self, album_id: int):
self._check_library_loaded()
return self._albums.get(album_id)


async def __post(self, url: str, headers: dict[str, Any] | None = None, data: dict[str, Any] | None = None):
async with self.http_session.post(url=url, data=json.dumps(data), headers=headers) as response:
async def __post(
self,
url: str,
headers: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
):
async with self.http_session.post(
url=url, data=json.dumps(data), headers=headers
) as response:
return await response.json()


async def __jsonToDict(self, data: list[dict[str, Any]], main_key: str) -> AsyncGenerator[dict[str, Any], None]:
async def __jsonToDict(
self, data: list[dict[str, Any]], main_key: str
) -> AsyncGenerator[dict[str, Any], None]:
"""
Convert the library json into python dicts. See the readme for all fields.
Expand Down Expand Up @@ -138,10 +179,10 @@ async def __jsonToDict(self, data: list[dict[str, Any]], main_key: str) -> Async
}
}
"""
if not 'map' in data or type(data['map']) is not dict:
if "map" not in data or type(data["map"]) is not dict:
return

keymap = {v: k for (k, v) in data['map'].items() if not isinstance(v, dict)}
keymap = {v: k for (k, v) in data["map"].items() if not isinstance(v, dict)}

for key, value in data.items():
if type(value) is list:
Expand All @@ -152,4 +193,4 @@ async def __jsonToDict(self, data: list[dict[str, Any]], main_key: str) -> Async
def _check_library_loaded(self):
"""Check if the library is loaded"""
if self._settings is None:
raise ValueError("Library not loaded. Please call refresh_library first.")
raise ValueError("Library not loaded. Please call refresh_library first.")
2 changes: 1 addition & 1 deletion ibroadcastaio/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
STATUS_API = "/s/JSON/status"

REFERER = "ibroadcastaio-client"
VERSION = "0.1.0"
VERSION = "0.1.0"
122 changes: 121 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ pylint = "^3.3.1"

[tool.poetry.dev-dependencies]
pytest = "^6.2.4"
black = "^24.10.0"
isort = "^5.13.2"
flake8 = "^7.1.1"

[tool.poetry.scripts]
example = "example:main"
Expand Down
2 changes: 1 addition & 1 deletion tests/example.json
Original file line number Diff line number Diff line change
Expand Up @@ -534,4 +534,4 @@
"sessionkey": "",
"user": ""
}
}
}
Loading

0 comments on commit be8c9c8

Please sign in to comment.