"""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]