diff --git a/CHANGELOG.md b/CHANGELOG.md index 4edcd05..faebd30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ installed optional packages; verify the headless-backend failure explicitly. - Keep the v2.1.2 GitHub tag as a historical failed publishing attempt. Its tagged workflow failed before uploading to PyPI; v2.1.3 supersedes it. +- Fix `get_album` failing with `AlbumDetails.pre_release_end_date_time: value + does not match str | None`: Spotify returns `preReleaseEndDateTime` as an + `{isoString, precision}` object, now decoded as `ReleaseDate`. Album search + hits shared the same field and were silently skipped; they decode too. + `ReleaseDate` now lives in `spotapi.models.catalogue.common`. ## 2.1.2 - 2026-11-22 (GitHub tag; PyPI publication blocked) diff --git a/examples/README.md b/examples/README.md index d220d03..ceb2ff2 100644 --- a/examples/README.md +++ b/examples/README.md @@ -13,6 +13,7 @@ authenticated session. | What you're building | Example | Notes | |---|---|---| | First public search | [public_search.py](public_search.py) | Typed results and predictable field names | +| Album lookup with pre-release end date | [album_lookup.py](album_lookup.py) | Prints name, pre-release end date and track count for one album | | CSV audit of a large public playlist | [playlist_audit.py](playlist_audit.py) | Keeps duplicate occurrences and unavailable entries; bounded to 10,000 | | Playlist overlap analysis | [overlap.py](overlap.py) | Compare shared tracks without editing either playlist | | Artist and recording credits | [credit_trail.py](credit_trail.py) | Inspect contributors and related metadata | diff --git a/examples/album_lookup.py b/examples/album_lookup.py new file mode 100644 index 0000000..4fcd3ee --- /dev/null +++ b/examples/album_lookup.py @@ -0,0 +1,18 @@ +"""Look up an album and print its pre-release end date and track count.""" + +import asyncio + +from spotapi import Public + + +async def main() -> None: + album = await Public.get_album("spotify:album:3LUcDBe7DZDExhHbZEQchk") + end = album.pre_release_end_date_time + + print(album.name) + print("Pre-release end:", end.iso_string if end else None, end.precision if end else None) + print("Tracks:", album.tracks_v2.total_count if album.tracks_v2 else len(album.tracks)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/spotapi/models/catalogue/album.py b/spotapi/models/catalogue/album.py index 643c403..3d7918a 100644 --- a/spotapi/models/catalogue/album.py +++ b/spotapi/models/catalogue/album.py @@ -4,7 +4,7 @@ from dataclasses import dataclass, field -from .common import CoverArt, VisualIdentity +from .common import CoverArt, ReleaseDate, VisualIdentity __all__ = ("Album",) @@ -54,7 +54,7 @@ class Album: date: Date | None = None is_album_pre_release: bool | None = None playability: Playability | None = None - pre_release_end_date_time: str | None = None + pre_release_end_date_time: ReleaseDate | None = None type: str | None = None visual_identity: VisualIdentity | None = None diff --git a/spotapi/models/catalogue/album_details.py b/spotapi/models/catalogue/album_details.py index 8b15e6c..145ff7e 100644 --- a/spotapi/models/catalogue/album_details.py +++ b/spotapi/models/catalogue/album_details.py @@ -15,6 +15,7 @@ Playability as AlbumPlayability, ) from .common import ( + ReleaseDate, Sources, VisualIdentity, ) @@ -34,17 +35,6 @@ __all__ = ("AlbumDetails",) -@dataclass(slots=True) -class ReleaseDate: - iso_string: str - precision: str | None = None - - @property - def year(self) -> int: - """Return the available release year without inventing an unknown date.""" - return int(self.iso_string[:4]) - - @dataclass(slots=True) class ArtistSharingInfo: share_url: str | None = None @@ -200,7 +190,7 @@ class AlbumDetails: type: str | None = None visual_identity: VisualIdentity | None = None more_albums_by_artist: MoreAlbumsByArtist | None = None - pre_release_end_date_time: str | None = None + pre_release_end_date_time: ReleaseDate | None = None releases: AlbumReleases | None = None watch_feed_entrypoint: dict[str, Any] | None = None diff --git a/spotapi/models/catalogue/common.py b/spotapi/models/catalogue/common.py index a294a58..6d45d21 100644 --- a/spotapi/models/catalogue/common.py +++ b/spotapi/models/catalogue/common.py @@ -1,4 +1,4 @@ -"""Shared artwork and color dataclasses.""" +"""Shared artwork, color and release-date dataclasses.""" from __future__ import annotations @@ -11,12 +11,26 @@ "CoverArt", "ExtractedColorSet", "ExtractedColors", + "ReleaseDate", "Sources", "SquareCoverImage", "VisualIdentity", ) +@dataclass(slots=True) +class ReleaseDate: + """A Spotify timestamp: an ISO 8601 string and its precision (e.g. ``DAY``).""" + + iso_string: str + precision: str | None = None + + @property + def year(self) -> int: + """Return the available release year without inventing an unknown date.""" + return int(self.iso_string[:4]) + + @dataclass(slots=True) class Sources: """One artwork URL with optional pixel dimensions; no image data is fetched.""" diff --git a/spotapi/models/catalogue/entities.py b/spotapi/models/catalogue/entities.py index 2446b2f..b30adac 100644 --- a/spotapi/models/catalogue/entities.py +++ b/spotapi/models/catalogue/entities.py @@ -4,8 +4,7 @@ from dataclasses import dataclass, field -from .album_details import ReleaseDate -from .common import CoverArt +from .common import CoverArt, ReleaseDate from .podcast import Publisher from .podcast_episode import EpisodePodcastReference from .track import Duration diff --git a/spotapi/models/catalogue/podcast_episode.py b/spotapi/models/catalogue/podcast_episode.py index 236918d..3a3cdd4 100644 --- a/spotapi/models/catalogue/podcast_episode.py +++ b/spotapi/models/catalogue/podcast_episode.py @@ -4,8 +4,7 @@ from dataclasses import dataclass, field -from .album_details import ReleaseDate -from .common import Sources, VisualIdentity +from .common import ReleaseDate, Sources, VisualIdentity from .track import ContentRating, Duration from .track_details import SharingInfo diff --git a/tests/fixtures/catalogue/get_album_pre_release_end_date.json b/tests/fixtures/catalogue/get_album_pre_release_end_date.json new file mode 100644 index 0000000..7e82d65 --- /dev/null +++ b/tests/fixtures/catalogue/get_album_pre_release_end_date.json @@ -0,0 +1,116 @@ +{ + "albumUnion": { + "__typename": "Album", + "copyright": { + "items": [ + {"text": "2026 Prophecy Productions", "type": "C"}, + {"text": "2026 Prophecy Productions", "type": "P"} + ], + "totalCount": 2 + }, + "courtesyLine": "", + "date": {"isoString": "2026-02-20T00:00:00Z", "precision": "DAY"}, + "isPreRelease": false, + "label": "Prophecy Productions", + "name": "Aba Khan", + "playability": {"playable": true, "reason": "PLAYABLE"}, + "preReleaseEndDateTime": {"isoString": "2026-02-20T05:00:00Z", "precision": "MINUTE"}, + "saved": false, + "sharingInfo": { + "shareId": "k6pVxV-MSCGXR45wyOMiqQ", + "shareUrl": "https://open.spotify.com/album/3LUcDBe7DZDExhHbZEQchk?si=k6pVxV-MSCGXR45wyOMiqQ" + }, + "tracksV2": { + "items": [ + { + "track": { + "artists": { + "items": [ + { + "profile": {"name": "Nytt Land"}, + "uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp" + } + ] + }, + "associationsV3": { + "audioAssociations": {"totalCount": 0}, + "videoAssociations": {"totalCount": 0} + }, + "contentRating": {"label": "NONE"}, + "discNumber": 1, + "duration": {"totalMilliseconds": 142235}, + "mediaType": "AUDIO", + "name": "Aba Khan", + "playability": {"playable": true}, + "playcount": "15313", + "relinkingInformation": null, + "saved": false, + "trackNumber": 1, + "uri": "spotify:track:5GZeWg8JmrxO15G2KT6p9p" + }, + "uid": "4772f4dc743d57837fc3" + }, + { + "track": { + "artists": { + "items": [ + { + "profile": {"name": "Nytt Land"}, + "uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp" + } + ] + }, + "associationsV3": { + "audioAssociations": {"totalCount": 0}, + "videoAssociations": {"totalCount": 0} + }, + "contentRating": {"label": "NONE"}, + "discNumber": 1, + "duration": {"totalMilliseconds": 405882}, + "mediaType": "AUDIO", + "name": "Taiga", + "playability": {"playable": true}, + "playcount": "38060", + "relinkingInformation": null, + "saved": false, + "trackNumber": 2, + "uri": "spotify:track:3Gt2s4m4yw7NDPPFgJpf5O" + }, + "uid": "6c7375030f2f3c35a3b4" + } + ], + "totalCount": 8 + }, + "type": "ALBUM", + "uri": "spotify:album:3LUcDBe7DZDExhHbZEQchk", + "watchFeedEntrypoint": null, + "artists": { + "items": [ + { + "id": "6NQ701XGEJodDZ5lqVtrBp", + "profile": {"name": "Nytt Land"}, + "sharingInfo": { + "shareUrl": "https://open.spotify.com/artist/6NQ701XGEJodDZ5lqVtrBp?si=7Nf73ATjT6aRAASmy0QHFQ" + }, + "uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp" + } + ], + "totalCount": 1 + }, + "coverArt": { + "extractedColors": {"colorDark": {"hex": "#600810"}}, + "sources": [ + { + "height": 300, + "url": "https://i.scdn.co/image/ab67616d00001e02798cbc922f80394af87cef8c", + "width": 300 + } + ] + }, + "discs": { + "items": [{"number": 1, "tracks": {"totalCount": 8}}], + "totalCount": 1 + } + }, + "meV2": {"ianaTimezoneId": "America/New_York"} +} diff --git a/tests/test_album_pre_release.py b/tests/test_album_pre_release.py new file mode 100644 index 0000000..1f2ef53 --- /dev/null +++ b/tests/test_album_pre_release.py @@ -0,0 +1,103 @@ +"""Regression tests for ``preReleaseEndDateTime`` objects in album payloads. + +Spotify returns this field as ``{"isoString": ..., "precision": ...}`` even when +``isPreRelease`` is false. It once failed with ``getAlbum: failed to deserialize +AlbumDetails: AlbumDetails.pre_release_end_date_time: value does not match +str | None``. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from spotapi.datastruct import ObjectDict +from spotapi.models.catalogue import Album, AlbumDetails, from_dict +from spotapi.models.catalogue.common import ReleaseDate +from spotapi.operations import Operations +from spotapi.queries import Queries + +ALBUM_URI = "spotify:album:3LUcDBe7DZDExhHbZEQchk" +FIXTURE = Path(__file__).parent / "fixtures" / "catalogue" / "get_album_pre_release_end_date.json" + + +def _album_response() -> dict[str, Any]: + """Load the sanitized, trimmed getAlbum response for the Nytt Land album.""" + return json.loads(FIXTURE.read_text(encoding="utf-8")) + + +async def _get_album(response: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> AlbumDetails: + async def direct_query(self: Queries, uri: str, /, operation: Operations) -> ObjectDict: + assert (uri, operation) == (ALBUM_URI, Operations.GET_ALBUM) + + return ObjectDict(response) + + monkeypatch.setattr(Queries, "direct_query", direct_query) + + return await Queries().resource(ALBUM_URI, Operations.GET_ALBUM, AlbumDetails) + + +async def test_get_album_decodes_object_pre_release_end_date( + monkeypatch: pytest.MonkeyPatch, +) -> None: + album = await _get_album(_album_response(), monkeypatch) + + assert album.is_pre_release is False + assert album.pre_release_end_date_time == ReleaseDate( + iso_string="2026-02-20T05:00:00Z", precision="MINUTE" + ) + assert album.name == "Aba Khan" + assert [track.name for track in album.tracks] == ["Aba Khan", "Taiga"] + + +@pytest.mark.parametrize("precision", ["DAY", "MINUTE"]) +async def test_get_album_accepts_either_pre_release_precision( + precision: str, monkeypatch: pytest.MonkeyPatch +) -> None: + response = _album_response() + response["albumUnion"]["preReleaseEndDateTime"] = { + "isoString": "2026-02-20T00:00:00Z", + "precision": precision, + } + + album = await _get_album(response, monkeypatch) + + assert album.pre_release_end_date_time is not None + assert album.pre_release_end_date_time.precision == precision + assert album.pre_release_end_date_time.year == 2026 + + +@pytest.mark.parametrize("missing", [False, True]) +async def test_get_album_keeps_pre_release_end_date_optional( + missing: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + response = _album_response() + + if missing: + del response["albumUnion"]["preReleaseEndDateTime"] + else: + response["albumUnion"]["preReleaseEndDateTime"] = None + + album = await _get_album(response, monkeypatch) + + assert album.pre_release_end_date_time is None + + +def test_album_search_hit_decodes_object_pre_release_end_date() -> None: + """Search skips undecodable hits, so a mismatch would silently drop the album.""" + album = from_dict( + Album, + { + "name": "Aba Khan", + "uri": ALBUM_URI, + "isAlbumPreRelease": False, + "preReleaseEndDateTime": {"isoString": "2026-02-20T05:00:00Z", "precision": "MINUTE"}, + }, + ) + + assert album.pre_release_end_date_time == ReleaseDate( + iso_string="2026-02-20T05:00:00Z", precision="MINUTE" + )