Skip to content

Commit 0a4490a

Browse files
authored
Add method to save audiobooks (#478)
1 parent a54d669 commit 0a4490a

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

src/spotifyaio/spotify.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,17 @@ async def get_saved_audiobooks(self) -> list[SimplifiedAudiobook]:
306306
response = await self._get("v1/me/audiobooks", params=params)
307307
return SavedAudiobookResponse.from_json(response).items
308308

309-
# Save an audiobook
309+
async def save_audiobooks(self, audiobook_ids: list[str]) -> None:
310+
"""Save audiobooks."""
311+
if not audiobook_ids:
312+
return
313+
if len(audiobook_ids) > 50:
314+
msg = "Maximum of 50 audiobooks can be saved at once"
315+
raise ValueError(msg)
316+
params: dict[str, Any] = {
317+
"ids": ",".join([get_identifier(i) for i in audiobook_ids])
318+
}
319+
await self._put("v1/me/audiobooks", params=params)
310320

311321
# Remove an audiobook
312322

tests/test_spotify.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1458,6 +1458,47 @@ async def test_get_saved_audiobooks(
14581458
)
14591459

14601460

1461+
async def test_save_audiobooks(
1462+
responses: aioresponses,
1463+
authenticated_client: SpotifyClient,
1464+
) -> None:
1465+
"""Test saving an audiobook."""
1466+
responses.put(
1467+
f"{SPOTIFY_URL}/v1/me/audiobooks?ids=0TnOYISbd1XYRBk9myaseg",
1468+
status=200,
1469+
body="",
1470+
)
1471+
await authenticated_client.save_audiobooks(["0TnOYISbd1XYRBk9myaseg"])
1472+
responses.assert_called_once_with(
1473+
f"{SPOTIFY_URL}/v1/me/audiobooks",
1474+
METH_PUT,
1475+
headers=HEADERS,
1476+
params={"ids": "0TnOYISbd1XYRBk9myaseg"},
1477+
json=None,
1478+
)
1479+
1480+
1481+
async def test_save_no_audiobooks(
1482+
responses: aioresponses,
1483+
authenticated_client: SpotifyClient,
1484+
) -> None:
1485+
"""Test saving no audiobooks."""
1486+
await authenticated_client.save_audiobooks([])
1487+
responses.assert_not_called() # type: ignore[no-untyped-call]
1488+
1489+
1490+
async def test_save_too_many_audiobooks(
1491+
responses: aioresponses,
1492+
authenticated_client: SpotifyClient,
1493+
) -> None:
1494+
"""Test saving too many audiobooks."""
1495+
with pytest.raises(
1496+
ValueError, match="Maximum of 50 audiobooks can be saved at once"
1497+
):
1498+
await authenticated_client.save_audiobooks(["abc"] * 51)
1499+
responses.assert_not_called() # type: ignore[no-untyped-call]
1500+
1501+
14611502
async def test_get_show_episodes(
14621503
responses: aioresponses,
14631504
snapshot: SnapshotAssertion,

0 commit comments

Comments
 (0)