"""Round 130: Apple Music links in File ▸ Import from URL. Spotify's path with another reader: an Apple Music song, album or playlist is listed (iTunes Lookup API for albums and songs, the playlist page's ``serialized-server-data`` JSON for playlists), each song is found on YouTube by artist, title and length, and a named list offers a playlist of the same name. No network here: the answers are canned. """ import json import time import pytest from lintunes import apple_music_link, spotify_link, url_import from lintunes.apple_music_link import ( AppleMusicError, apple_source, parse_lookup, parse_playlist_page, ) from lintunes.gui.url_import_dialog import UrlImportDialog PLAYLIST_URL = "https://music.apple.com/us/playlist/2026-10/pl.u-zPyLmjRtEZ54PZ" def _lockup(adam_id, title, artist, album, ms): return {"title": title, "artistName": artist, "duration": ms, "trackNumber": None, "subtitleLinks": [{"title": artist}], "tertiaryLinks": [{"title": album}], "contentDescriptor": {"kind": "song", "identifiers": {"storeAdamID": adam_id}}} def _page(name, lockups) -> str: data = {"data": [{"intent": {}, "data": {"sections": [ {"itemKind": "containerDetailHeaderLockup", "items": [{"title": name, "trackCount": len(lockups)}]}, {"itemKind": "trackLockup", "items": lockups}, {"itemKind": "bubbleLockup", "items": [{"title": "Some Artist"}]}, ]}}]} return ('") PLAYLIST = _page("2026-10", [ _lockup("617854252", "Tomorrow's Girls", "Donald Fagen", "Kamakiriad", 377680), _lockup("1452872926", "Zou bisou bisou", "Gillian Hills", "Twistin' the Rock", 136000), ]) ALBUM = {"resultCount": 4, "results": [ {"wrapperType": "collection", "collectionName": "Double"}, # Out of order on purpose, and two discs. {"wrapperType": "track", "trackId": 3, "trackName": "Three", "artistName": "A", "collectionName": "Double", "trackTimeMillis": 3000, "trackNumber": 1, "trackCount": 1, "discNumber": 2, "discCount": 2}, {"wrapperType": "track", "trackId": 2, "trackName": "Two", "artistName": "A", "collectionName": "Double", "trackTimeMillis": 2000, "trackNumber": 2, "trackCount": 2, "discNumber": 1, "discCount": 2}, {"wrapperType": "track", "trackId": 1, "trackName": "One", "artistName": "A", "collectionName": "Double", "trackTimeMillis": 1000, "trackNumber": 1, "trackCount": 2, "discNumber": 1, "discCount": 2}, ]} SONG = {"resultCount": 1, "results": [ {"wrapperType": "track", "trackId": 617854252, "trackName": "Tomorrow's Girls", "artistName": "Donald Fagen", "collectionName": "Kamakiriad", "trackTimeMillis": 377680, "trackNumber": 5, "trackCount": 8, "discNumber": 1, "discCount": 1}]} # -------------------------------------------------------------------------- # A. links @pytest.mark.parametrize("text, source", [ (PLAYLIST_URL, ("playlist", "pl.u-zPyLmjRtEZ54PZ", "us")), ("https://music.apple.com/gb/playlist/pl.f4d106fed2bd41149aaacabb233eb5eb", ("playlist", "pl.f4d106fed2bd41149aaacabb233eb5eb", "gb")), ("https://music.apple.com/us/album/kamakiriad/617853627", ("album", "617853627", "us")), ("https://music.apple.com/us/album/tomorrows-girls/617853627" "?i=617854252", ("song", "617854252", "us")), ("https://music.apple.com/us/song/tomorrows-girls/617854252", ("song", "617854252", "us")), ("https://geo.music.apple.com/album/x/id617853627", ("album", "617853627", "us")), ("https://music.apple.com/us/artist/donald-fagen/155517", None), ("https://music.apple.com/library/playlist/p.abc", None), ("https://example.com/us/album/x/1", None), ("not a link", None), ]) def test_apple_source(text, source): assert apple_source(text) == source def test_link_kind(): assert url_import.link_kind(PLAYLIST_URL) == "apple" assert url_import.looks_like_url(PLAYLIST_URL) # -------------------------------------------------------------------------- # B. reading the songs def test_a_playlist_page_names_its_songs_with_albums_and_lengths(): name, tracks = parse_playlist_page(PLAYLIST) assert name == "2026-10" assert [(t.id, t.artist, t.title, t.album, t.duration, t.track_number) for t in tracks] == [ ("617854252", "Donald Fagen", "Tomorrow's Girls", "Kamakiriad", 378, 0), ("1452872926", "Gillian Hills", "Zou bisou bisou", "Twistin' the Rock", 136, 0)] @pytest.mark.parametrize("html", [ "nothing", '', _page("Empty", []), ]) def test_a_changed_page_says_so(html): with pytest.raises(AppleMusicError): parse_playlist_page(html) def test_an_album_is_in_disc_and_track_order_and_numbered(): name, tracks = parse_lookup(ALBUM, "album") assert name == "Double" assert [(t.title, t.disc_number, t.track_number) for t in tracks] == [ ("One", 1, 1), ("Two", 1, 2), ("Three", 2, 1)] assert spotify_link.tag_fields(tracks[2]) == { "name": "Three", "artist": "A", "album": "Double", "track_number": 1, "track_count": 1, "disc_number": 2, "disc_count": 2} def test_a_song_is_one_song_and_one_disc_gets_no_disc_tag(): name, tracks = parse_lookup(SONG, "song") assert name == "Tomorrow's Girls" and len(tracks) == 1 assert "disc_number" not in spotify_link.tag_fields(tracks[0]) assert tracks[0].track_number == 5 def test_nothing_found_says_so(): with pytest.raises(AppleMusicError): parse_lookup({"resultCount": 0, "results": []}, "album") # -------------------------------------------------------------------------- # C. the dialog def _pump(qapp, until, timeout=10.0): deadline = time.monotonic() + timeout while not until() and time.monotonic() < deadline: qapp.processEvents() time.sleep(0.01) assert until(), "timed out waiting" @pytest.fixture def canned(monkeypatch): def fetch(kind, _id, _storefront="us"): if kind == "playlist": return parse_playlist_page(PLAYLIST) return parse_lookup(SONG if kind == "song" else ALBUM, kind) monkeypatch.setattr(apple_music_link, "fetch", fetch) def _dialog(qapp, url): qapp.clipboard().setText(url) dialog = UrlImportDialog(None) assert dialog.url() == url return dialog def test_a_playlist_is_a_checklist_offering_a_playlist_of_its_name( qapp, canned): dialog = _dialog(qapp, PLAYLIST_URL) dialog._on_import() _pump(qapp, lambda: dialog._probe is None) assert dialog._picking and dialog._list.count() == 2 assert "Apple Music link has 2 songs" in dialog._status.text() assert not dialog._make.isHidden() assert dialog._make_name.text() == "2026-10" dialog._make.setChecked(True) dialog._on_import() assert dialog.new_playlist_name() == "2026-10" assert [t.title for t in dialog.spotify_tracks()] == [ "Tomorrow's Girls", "Zou bisou bisou"] def test_an_apple_song_goes_straight_through(qapp, canned): dialog = _dialog(qapp, "https://music.apple.com/us/song/x/617854252") dialog._on_import() _pump(qapp, lambda: dialog.result() == dialog.DialogCode.Accepted) assert [t.artist for t in dialog.spotify_tracks()] == ["Donald Fagen"] assert dialog.new_playlist_name() == "" # -------------------------------------------------------------------------- # D. the playlist's cover (kept, not shown yet) from lintunes import playlist_art # noqa: E402 from tests.test_round109 import _import, _named, fake, window # noqa: E402,F401 JPEG = b"\xff\xd8\xff\xe0" + b"\0" * 32 PNG = b"\x89PNG\r\n\x1a\n" + b"\0" * 32 def test_cover_urls_are_read_off_every_kind_of_answer(): page = PLAYLIST.replace( '"trackCount": 2}', '"trackCount": 2, "artwork": {"dictionary": ' '{"url": "https://is1-ssl.mzstatic.com/x/{w}x{h}bb.{f}"}}}') assert apple_music_link.playlist_cover_url(page) == ( "https://is1-ssl.mzstatic.com/x/1200x1200bb.jpg") assert apple_music_link.playlist_cover_url(PLAYLIST) == "" assert apple_music_link.lookup_cover_url({"results": [ {"artworkUrl100": "https://a/b/100x100bb.jpg"}]}) == ( "https://a/b/1200x1200bb.jpg") embed = ('") assert spotify_link.cover_url(embed) == "https://i.scdn.co/big" assert spotify_link.cover_url("") == "" def test_a_cover_is_kept_per_playlist_and_replaced(tmp_path): assert playlist_art.find(tmp_path, "ABCD1234") is None playlist_art.save(tmp_path, "ABCD1234", JPEG) assert playlist_art.find(tmp_path, "ABCD1234").name == "ABCD1234.jpg" playlist_art.save(tmp_path, "ABCD1234", PNG) # png replaces jpg assert playlist_art.find(tmp_path, "ABCD1234").name == "ABCD1234.png" assert sorted(p.name for p in (tmp_path / "playlist_art").iterdir()) == [ "ABCD1234.png"] with pytest.raises(ValueError): playlist_art.save(tmp_path, "ABCD1234", b"not an image") with pytest.raises(ValueError): playlist_art.save(tmp_path, "../x", JPEG) def test_the_probe_passes_the_cover_on_for_a_new_playlist(qapp, monkeypatch): monkeypatch.setattr(apple_music_link, "fetch", lambda *a: ( *parse_playlist_page(PLAYLIST), "https://img/cover.jpg")) dialog = _dialog(qapp, PLAYLIST_URL) dialog._on_import() _pump(qapp, lambda: dialog._probe is None) dialog._on_import() assert dialog.new_playlist_cover() == "" # not ticked: no cover dialog._make.setChecked(True) assert dialog.new_playlist_cover() == "https://img/cover.jpg" def test_the_new_playlist_gets_its_cover(window, qapp, fake, mp3_file, monkeypatch): monkeypatch.setenv("FAKE_YTDLP_AUDIO", str(mp3_file)) monkeypatch.setattr(playlist_art, "download", lambda url: JPEG) saved = [] real_save = playlist_art.save monkeypatch.setattr(playlist_art, "save", lambda *a: saved.append(real_save(*a))) manager = window._manager _import(window, qapp, monkeypatch, ["aaa", "bbb"], cover="https://img/c") [playlist] = _named(manager, "Road Trip") _pump(qapp, lambda: saved) assert playlist_art.find(manager.data_dir, playlist.persistent_id) \ == saved[0] # -------------------------------------------------------------------------- # E. the now-playing words: side by side when they fit, stacked when not def test_title_beside_artist_over_album_when_there_is_room(qapp): from lintunes.gui.transport import NowPlayingText from PyQt6.QtWidgets import QWidget holder = QWidget() # a window would get a title bar holder.resize(1000, 100) text = NowPlayingText(holder) holder.show() text.set_song("Tomorrow's Girls", "Donald Fagen", "Kamakiriad") text.resize(900, 50) text.arrange() assert text.side assert text.title.geometry().right() < text.artist.geometry().left() assert text.artist.geometry().left() == text.album.geometry().left() assert text.artist.geometry().bottom() < text.album.geometry().top() assert (text.artist.text(), text.album.text()) == ("Donald Fagen", "Kamakiriad") from PyQt6.QtGui import QFontMetrics big = text.title.font().pixelSize() assert big > QFontMetrics(text._title_font).height() # it grew text.resize(QFontMetrics(text._title_font).horizontalAdvance( "Tomorrow's Girls") + 20, 50) # too narrow: the stack assert not text.side and text.album.isHidden() assert text.artist.text().startswith("Donald Fagen") # maybe elided assert text.title.geometry().bottom() < text.artist.geometry().top() text.resize(600, 50) text.set_lines("DJ mode", "x") text.set_song("Tomorrow's Girls", "Donald Fagen", "Kamakiriad") assert text.side def test_fixed_lines_and_a_bare_title_always_stack(qapp): from lintunes.gui.transport import NowPlayingText from PyQt6.QtWidgets import QWidget holder = QWidget() # a window would get a title bar holder.resize(1000, 100) text = NowPlayingText(holder) holder.show() text.resize(900, 50) text.set_lines("DJ mode", "Drag songs onto the records") assert not text.side and text.artist.text() == "Drag songs onto the records" text.set_song("Untitled", "", "") assert not text.side and text.artist.text() == "" text.set_song("Song", "", "Album only") assert text.side and not text.album.isHidden() and text.artist.isHidden() # -------------------------------------------------------------------------- # F. songs the library already has: unticked, but still in the playlist from lintunes.library_match import LibraryMatcher # noqa: E402 from lintunes.models.track import Track # noqa: E402 def _t(tid, artist, name, seconds=200): return Track(track_id=tid, artist=artist, name=name, total_time=seconds * 1000) def test_the_matcher_finds_the_same_song_and_not_another_take(): m = LibraryMatcher([ _t(1, "Donald Fagen", "Tomorrow's Girls (Remastered)", 378), _t(2, "Tate McRae", "Housewife", 209), _t(3, "Some Band", "Song", 200), _t(4, "Some Band", "Song", 320), ]) assert m.find("Donald Fagen", "Tomorrow's Girls", 378).track_id == 1 # Apple's "A & B" artist still shares a word with the library's. assert m.find("Tate McRae & Julia Michaels", "Housewife", 209).track_id == 2 assert m.find("Some Band", "Song", 318).track_id == 4 # closest length assert m.find("Some Band", "Song", 260) is None # neither take assert m.find("Other Band", "Housewife", 209) is None assert m.find("Donald Fagen", "Tomorrow's Girls", None).track_id == 1 def test_owned_songs_are_unticked_and_still_listed_in_order(qapp, canned): owned = [_t(7, "Donald Fagen", "Tomorrow's Girls", 378)] qapp.clipboard().setText(PLAYLIST_URL) dialog = UrlImportDialog(None, library_tracks=lambda: owned) dialog._on_import() _pump(qapp, lambda: dialog._probe is None) first, second = dialog._list.item(0), dialog._list.item(1) assert "already in your library" in first.text() assert first.checkState() == first.checkState().Unchecked assert second.checkState() == second.checkState().Checked assert "1 is already in your library" in dialog._status.text() assert dialog._ok.text() == "Import 1 Song" dialog._make.setChecked(True) dialog._on_import() assert [t.title for t in dialog.spotify_tracks()] == ["Zou bisou bisou"] assert dialog.link_rows() == [ {"key": "617854252", "owned": 7, "download": False}, {"key": "1452872926", "owned": None, "download": True}] def test_all_owned_offers_to_add_them(qapp, canned): owned = [_t(7, "Donald Fagen", "Tomorrow's Girls", 378), _t(8, "Gillian Hills", "Zou bisou bisou", 136)] qapp.clipboard().setText(PLAYLIST_URL) dialog = UrlImportDialog(None, library_tracks=lambda: owned) dialog._on_import() _pump(qapp, lambda: dialog._probe is None) assert dialog._ok.text() == "Add 2 Songs From Library" assert dialog._ok.isEnabled() def test_the_playlist_comes_out_in_the_links_order(window, qapp): """Owned songs go in as soon as everything before them is placed; a download holds back what follows it; a failed one is skipped.""" manager = window._manager for tid, name in ((1, "Have A"), (2, "Have B"), (3, "Got C"), (4, "Got E")): manager.add_track(_t(tid, "X", name)) window._url_target = None window._url_inserted = 0 window._url_new_name, window._url_new_pid = "From Apple", "" window._url_new_cover = "" window._url_rows = [ {"key": "a", "owned": 1, "download": False}, {"key": "c", "owned": None, "download": True}, {"key": "b", "owned": 2, "download": False}, {"key": "d", "owned": None, "download": True}, # will fail {"key": "e", "owned": None, "download": True}, ] window._url_placed = 0 window._place_url_rows() [playlist] = _named(manager, "From Apple") assert playlist.track_ids == [1] # c holds the rest back window._url_row_done("e", 4) # lands early: waits assert playlist.track_ids == [1] window._url_row_done("c", 3) assert playlist.track_ids == [1, 3, 2] # d still downloading window._on_url_item_failed("d") assert playlist.track_ids == [1, 3, 2, 4] # -------------------------------------------------------------------------- # G. the playlist's cover in the art panel while nothing plays def test_the_shown_playlists_cover_shows_while_nothing_plays(window, qapp, tmp_path): from PyQt6.QtGui import QColor, QImage manager = window._manager playlist = manager.create_playlist("Covered") image = QImage(8, 8, QImage.Format.Format_RGB32) image.fill(QColor("red")) png = tmp_path / "c.png" image.save(str(png)) playlist_art.save(manager.data_dir, playlist.persistent_id, png.read_bytes()) art = window._sidebar.art window._show_playlist(playlist.persistent_id) assert art.showing_playlist_art() and art.has_art() assert art._title() == "Covered" manager.add_track(_t(9, "X", "Playing")) art.set_track(manager.library.tracks[9]) # a song: its art wins assert not art.showing_playlist_art() art.set_track(None) assert art.showing_playlist_art() window._show_library() # no playlist shown assert not art.showing_playlist_art() and not art.has_art() # -------------------------------------------------------------------------- # H. names Syncthing would rename: written in NFC, and followed if renamed import os # noqa: E402 import shutil # noqa: E402 import unicodedata # noqa: E402 from lintunes.importers import file_importer # noqa: E402 from lintunes.library_manager import LibraryManager # noqa: E402 from lintunes.models import Library # noqa: E402 # "বাড়ি" as YouTube spells it: U+09DC, which NFC writes as U+09A1 U+09BC. RAW = "বাড়ি" NFC = unicodedata.normalize("NFC", RAW) def test_the_raw_name_is_not_nfc(): assert RAW != NFC def _manager(tmp_path): media = tmp_path / "media" (media / "Music").mkdir(parents=True) return LibraryManager(Library(music_folder=str(media)), tmp_path / "data") def test_an_import_is_named_in_nfc(tmp_path, mp3_file, qapp): src = tmp_path / "dl" / f"{RAW} [abc].mp3" src.parent.mkdir() shutil.copy(mp3_file, src) manager = _manager(tmp_path) track = file_importer.import_file(src, manager.organize_root(), manager) assert os.path.basename(track.location) == f"{NFC} [abc].mp3" assert os.path.exists(track.location) def test_a_file_syncthing_renamed_is_followed(tmp_path, mp3_file, qapp): manager = _manager(tmp_path) folder = manager.organize_root() / "Unknown Artist" / "Unknown Album" folder.mkdir(parents=True) raw = folder / f"{RAW}.mp3" shutil.copy(mp3_file, raw) track = Track(track_id=1, name=RAW, location=str(raw)) manager.add_track(track) os.rename(raw, folder / f"{NFC}.mp3") # what Syncthing does manager.edit_track_fields(1, {"artist": "Someone", "album": "Bhandari"}) assert os.path.exists(track.location) assert track.location.endswith(f"Someone/Bhandari/{NFC}.mp3") from lintunes import tagging assert tagging.read_tags(track.location)["artist"] == "Someone" def test_a_missing_file_with_no_nfc_twin_stays_missing(tmp_path, qapp): manager = _manager(tmp_path) track = Track(track_id=1, name="x", location=str(tmp_path / "gone.mp3")) manager.add_track(track) assert not manager.repair_location(track) assert track.location == str(tmp_path / "gone.mp3") # -------------------------------------------------------------------------- # I. playlist Get Info: created, last played, imported from, cover from lintunes.models.playlist import Playlist # noqa: E402 from lintunes.storage.playlist_plays import PlaylistPlays # noqa: E402 def test_created_and_source_round_trip_and_are_set_on_creation(tmp_path, qapp): p = Playlist(name="P", persistent_id="AB", date_created="2026-11-17T00:00:00+00:00", source_url="https://music.apple.com/x") back = Playlist.from_dict(p.to_dict()) assert (back.date_created, back.source_url) == (p.date_created, p.source_url) assert "source_url" not in Playlist(name="Q").to_dict() # nothing extra manager = _manager(tmp_path) made = manager.create_playlist("New", source_url="https://x/y") assert made.date_created and made.source_url == "https://x/y" assert manager.create_folder("F").date_created def test_last_played_is_the_newest_stamp_of_any_machine(tmp_path): mine = PlaylistPlays(tmp_path, "aaa") other = PlaylistPlays(tmp_path, "bbb") assert mine.record("P1", "2026-11-01T10:00:00+00:00") assert not mine.record("P1", "2026-11-01T10:00:30+00:00") # < a minute assert other.record("P1", "2026-11-02T09:00:00+00:00") assert mine.last_played("P1") == "2026-11-02T09:00:00+00:00" assert mine.last_played("P2") is None # Each machine writes only its own file. assert sorted(p.name for p in (tmp_path / "playlist_plays").iterdir()) \ == ["aaa.json", "bbb.json"] def test_playing_from_a_playlist_stamps_it(window, qapp): manager = window._manager playlist = manager.create_playlist("Played") manager.add_track(_t(5, "X", "Song")) window._now_playing_context = f"playlist:{playlist.persistent_id}" window._on_track_changed(manager.library.tracks[5]) assert manager.playlist_last_played(playlist.persistent_id) assert manager.playlist_last_played("nope") is None def test_the_dialog_reports_name_and_cover_changes(qapp): from lintunes.gui.playlist_info_dialog import PlaylistInfoDialog playlist = Playlist(name="Mix", persistent_id="AB", source_url="https://music.apple.com/us/playlist/x/pl.1") dialog = PlaylistInfoDialog(playlist, [_t(1, "A", "B", 200)], art=JPEG) assert dialog.new_name() == "" and dialog.art_change() is None dialog._name.setText("Mix 2") dialog._on_remove() assert dialog.new_name() == "Mix 2" and dialog.art_change() == b"" dialog._on_art_staged(PNG, "image/png") assert dialog.art_change() == PNG def test_get_info_ok_renames_and_sets_the_cover(window, qapp, monkeypatch, tmp_path): from lintunes.gui import main_window as mw from PyQt6.QtGui import QColor, QImage manager = window._manager playlist = manager.create_playlist("Old") image = QImage(4, 4, QImage.Format.Format_RGB32) image.fill(QColor("blue")) bmp = tmp_path / "c.bmp" # not JPEG/PNG: re-encoded image.save(str(bmp)) class _Dialog: def __init__(self, *a, **kw): pass def exec(self): return True def new_name(self): return "New Name" def art_change(self): return bmp.read_bytes() monkeypatch.setattr(mw, "PlaylistInfoDialog", _Dialog) window._playlist_info(playlist.persistent_id) assert playlist.name == "New Name" saved = playlist_art.find(manager.data_dir, playlist.persistent_id) assert saved.suffix == ".png" _Dialog.art_change = lambda self: b"" window._playlist_info(playlist.persistent_id) assert playlist_art.find(manager.data_dir, playlist.persistent_id) is None