Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add playback state #2

Merged
merged 2 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 80 additions & 1 deletion poetry.lock

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

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ packages = [
python = "^3.11"
aiohttp = ">=3.0.0"
yarl = ">=1.6.0"
mashumaro = "^3.11"
orjson = "^3.9.10"

[tool.poetry.group.dev.dependencies]
aresponses = "2.1.6"
Expand Down
17 changes: 17 additions & 0 deletions src/spotifyaio/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""Asynchronous Python client for Spotify."""
from .exceptions import (
SpotifyAuthenticationFailedError,
SpotifyConnectionError,
SpotifyError,
)
from .models import Device, PlaybackState
from .spotify import SpotifyClient

__all__ = [
"Device",
"SpotifyError",
"SpotifyConnectionError",
"SpotifyAuthenticationFailedError",
"SpotifyClient",
"PlaybackState",
]
13 changes: 13 additions & 0 deletions src/spotifyaio/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Asynchronous Python client for Spotify."""


class SpotifyError(Exception):
"""Generic exception."""


class SpotifyConnectionError(SpotifyError):
"""Spotify connection exception."""


class SpotifyAuthenticationFailedError(SpotifyError):
"""Spotify authentication failed exception."""
25 changes: 25 additions & 0 deletions src/spotifyaio/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Models for Spotify."""
from dataclasses import dataclass, field

from mashumaro import field_options
from mashumaro.mixins.orjson import DataClassORJSONMixin


@dataclass
class Device(DataClassORJSONMixin):
"""Device model."""

device_id: str = field(metadata=field_options(alias="id"))
is_active: bool
is_private_session: bool
name: str
supports_volume: bool
device_type: str = field(metadata=field_options(alias="type"))
volume_percent: int


@dataclass
class PlaybackState(DataClassORJSONMixin):
"""Playback state model."""

device: Device
113 changes: 113 additions & 0 deletions src/spotifyaio/spotify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Spotify client for handling connections with Spotify."""
from __future__ import annotations

import asyncio
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Awaitable, Callable, Self

from aiohttp import ClientSession
from aiohttp.hdrs import METH_GET
from yarl import URL

from spotifyaio.exceptions import SpotifyConnectionError, SpotifyError
from spotifyaio.models import PlaybackState


@dataclass
class SpotifyClient:
"""Main class for handling connections with Spotify."""

session: ClientSession | None = None
request_timeout: int = 10
api_host: str = "api.spotify.com"
_token: str | None = None
_close_session: bool = False
refresh_token_function: Callable[[], Awaitable[str]] | None = None

async def refresh_token(self) -> None:
"""Refresh token with provided function."""
if self.refresh_token_function:
self._token = await self.refresh_token_function()

def authenticate(self, token: str) -> None:
"""Authenticate the user with a token."""
self._token = token

async def _request(
self,
uri: str,
*,
data: dict[str, Any] | None = None,
) -> str:
"""Handle a request to Spotify."""
version = metadata.version(__package__)
url = URL.build(
scheme="https",
host=self.api_host,
port=443,
).joinpath(uri)

await self.refresh_token()

headers = {
"User-Agent": f"AioSpotify/{version}",
"Accept": "application/json, text/plain, */*",
"Authorization": f"Bearer {self._token}",
}

if self.session is None:
self.session = ClientSession()
self._close_session = True

try:
async with asyncio.timeout(self.request_timeout):
response = await self.session.request(
METH_GET,
url,
headers=headers,
data=data,
)
except asyncio.TimeoutError as exception:
msg = "Timeout occurred while connecting to Spotify"
raise SpotifyConnectionError(msg) from exception

content_type = response.headers.get("Content-Type", "")

if "application/json" not in content_type:
text = await response.text()
msg = "Unexpected response from Spotify"
raise SpotifyError(
msg,
{"Content-Type": content_type, "response": text},
)

return await response.text()

async def get_playback(self) -> PlaybackState:
"""Get devices."""
response = await self._request("v1/me/player")
return PlaybackState.from_json(response)

async def close(self) -> None:
"""Close open client session."""
if self.session and self._close_session:
await self.session.close()

async def __aenter__(self) -> Self:
"""Async enter.

Returns
-------
The SpotifyClient object.
"""
return self

async def __aexit__(self, *_exc_info: object) -> None:
"""Async exit.

Args:
----
_exc_info: Exec type.
"""
await self.close()
8 changes: 8 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""Asynchronous Python client for Spotify."""
from pathlib import Path


def load_fixture(filename: str) -> str:
"""Load a fixture."""
path = Path(__package__) / "fixtures" / filename
return path.read_text(encoding="utf-8")
14 changes: 14 additions & 0 deletions tests/__snapshots__/test_playback.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# serializer version: 1
# name: test_get_devices
dict({
'device': dict({
'device_id': '21dac6b0e0a1f181870fdc9749b2656466557687',
'device_type': 'Computer',
'is_active': True,
'is_private_session': False,
'name': 'DESKTOP-BKC5SIK',
'supports_volume': True,
'volume_percent': 69,
}),
})
# ---
12 changes: 12 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Asynchronous Python client for Spotify."""
import pytest

from syrupy import SnapshotAssertion

from .syrupy import SpotifySnapshotExtension


@pytest.fixture(name="snapshot")
def snapshot_assertion(snapshot: SnapshotAssertion) -> SnapshotAssertion:
"""Return snapshot assertion fixture with the Spotify extension."""
return snapshot.use_extension(SpotifySnapshotExtension)
3 changes: 3 additions & 0 deletions tests/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Constants for tests."""

SPOTIFY_URL = "api.spotify.com"
Loading