234 lines
9.2 KiB
Python
234 lines
9.2 KiB
Python
"""Apple Music links for File ▸ Import from URL… (Round 130).
|
|
|
|
Spotify's twin (``spotify_link``): Apple won't hand over audio either, but
|
|
it will say what a link is, without a key or a login, and each song is then
|
|
found on YouTube by artist, title and length exactly as a Spotify song is.
|
|
The songs come back as ``spotify_link.SpotifyTrack``s, so the probe, the
|
|
checklist, the YouTube search and the tagging are all Spotify's own.
|
|
|
|
Where the list comes from depends on the link (measured November 2026):
|
|
|
|
- **An album or a song** — the public iTunes Lookup API
|
|
(``itunes.apple.com/lookup``), which is documented and stable: track and
|
|
disc numbers, the album's name, each song's length.
|
|
- **A playlist** — has no keyless API, but its ``music.apple.com`` page
|
|
carries every song as JSON in a ``serialized-server-data`` script: title,
|
|
artist, album and length per song, and the playlist's name. All of them,
|
|
not a first page: a 143-song playlist's page held all 143.
|
|
|
|
Shaped like ``spotify_link``: pure helpers first (tested against canned
|
|
JSON), then the network calls.
|
|
"""
|
|
import json
|
|
import re
|
|
from urllib.parse import parse_qs, urlsplit
|
|
|
|
import requests
|
|
|
|
from lintunes.spotify_link import USER_AGENT, SpotifyTrack
|
|
|
|
TIMEOUT = 20
|
|
LOOKUP_URL = "https://itunes.apple.com/lookup"
|
|
PLAYLIST_URL = "https://music.apple.com/{storefront}/playlist/{id}"
|
|
|
|
_HOSTS = ("music.apple.com", "geo.music.apple.com", "embed.music.apple.com",
|
|
"itunes.apple.com")
|
|
|
|
_SERVER_DATA = re.compile(
|
|
r'<script[^>]*id="serialized-server-data"[^>]*>\s*(.*?)\s*</script>',
|
|
re.DOTALL)
|
|
|
|
|
|
class AppleMusicError(Exception):
|
|
pass
|
|
|
|
|
|
def apple_source(text: str) -> tuple[str, str, str] | None:
|
|
"""(kind, id, storefront) for an Apple Music song, album or playlist
|
|
link, else None. kind is "song", "album" or "playlist"; an album link
|
|
with ``?i=<song id>`` (what Share Song copies) is that one song."""
|
|
text = (text or "").strip()
|
|
try:
|
|
parts = urlsplit(text)
|
|
except ValueError:
|
|
return None
|
|
if parts.scheme not in ("http", "https") or \
|
|
(parts.hostname or "").lower() not in _HOSTS:
|
|
return None
|
|
segments = [s for s in parts.path.split("/") if s]
|
|
storefront = "us"
|
|
if segments and re.fullmatch(r"[a-z]{2}", segments[0]):
|
|
storefront = segments.pop(0)
|
|
if len(segments) < 2:
|
|
return None
|
|
kind, source_id = segments[0], segments[-1]
|
|
song = (parse_qs(parts.query).get("i") or [""])[0]
|
|
if kind == "album":
|
|
if song.isdigit():
|
|
return "song", song, storefront
|
|
m = re.fullmatch(r"(?:id)?(\d+)", source_id)
|
|
return ("album", m.group(1), storefront) if m else None
|
|
if kind == "song":
|
|
m = re.fullmatch(r"(?:id)?(\d+)", source_id)
|
|
return ("song", m.group(1), storefront) if m else None
|
|
if kind == "playlist" and source_id.startswith("pl."):
|
|
return "playlist", source_id, storefront
|
|
return None
|
|
|
|
|
|
def _seconds(ms) -> int | None:
|
|
try:
|
|
return round(float(ms) / 1000) or None
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def parse_lookup(data: dict, kind: str) -> tuple[str, list[SpotifyTrack]]:
|
|
"""An iTunes Lookup answer → (the album's or song's name, its songs).
|
|
An album's songs are numbered as on the album; a lone song too, since
|
|
the lookup knows where it sits."""
|
|
results = (data or {}).get("results") or []
|
|
songs = [r for r in results
|
|
if r.get("wrapperType") == "track" and r.get("trackName")]
|
|
if not songs:
|
|
raise AppleMusicError("Apple Music has no songs at that link (it may "
|
|
"be private, deleted, or not in that country)")
|
|
songs.sort(key=lambda r: (r.get("discNumber") or 0,
|
|
r.get("trackNumber") or 0))
|
|
collection = next((r for r in results
|
|
if r.get("wrapperType") == "collection"), None)
|
|
discs = max((r.get("discCount") or 0) for r in songs)
|
|
tracks = [SpotifyTrack(
|
|
id=str(r.get("trackId") or n), title=r["trackName"],
|
|
artist=r.get("artistName") or "",
|
|
album=r.get("collectionName") or "",
|
|
duration=_seconds(r.get("trackTimeMillis")),
|
|
track_number=r.get("trackNumber") or 0,
|
|
track_count=r.get("trackCount") or 0,
|
|
disc_number=(r.get("discNumber") or 0) if discs > 1 else 0,
|
|
disc_count=discs if discs > 1 else 0)
|
|
for n, r in enumerate(songs, 1)]
|
|
if kind == "song":
|
|
return tracks[0].title, tracks[:1]
|
|
name = (collection or {}).get("collectionName") or tracks[0].album
|
|
return name or "Apple Music", tracks
|
|
|
|
|
|
def _link_title(item: dict, key: str) -> str:
|
|
links = item.get(key) or []
|
|
return (links[0].get("title") or "") if links else ""
|
|
|
|
|
|
def parse_playlist_page(html: str) -> tuple[str, list[SpotifyTrack]]:
|
|
"""A ``music.apple.com`` playlist page → (its name, its songs in order).
|
|
Raises AppleMusicError when the page isn't shaped the way it was in
|
|
November 2026."""
|
|
m = _SERVER_DATA.search(html or "")
|
|
if not m:
|
|
raise AppleMusicError("Apple Music's page didn't have the song list "
|
|
"in it (Apple may have changed its page "
|
|
"format)")
|
|
try:
|
|
data = json.loads(m.group(1))
|
|
sections = data["data"][0]["data"]["sections"]
|
|
except (ValueError, KeyError, IndexError, TypeError) as e:
|
|
raise AppleMusicError(f"Apple Music's song list couldn't be read: "
|
|
f"{e}")
|
|
name = ""
|
|
tracks: list[SpotifyTrack] = []
|
|
for section in sections:
|
|
kind = section.get("itemKind")
|
|
items = section.get("items") or []
|
|
if kind == "containerDetailHeaderLockup" and items and not name:
|
|
name = items[0].get("title") or ""
|
|
elif kind == "trackLockup":
|
|
for n, item in enumerate(items, 1):
|
|
title = item.get("title")
|
|
if not title:
|
|
continue
|
|
ident = ((item.get("contentDescriptor") or {})
|
|
.get("identifiers") or {}).get("storeAdamID")
|
|
tracks.append(SpotifyTrack(
|
|
id=str(ident or n), title=title,
|
|
artist=(item.get("artistName")
|
|
or _link_title(item, "subtitleLinks")),
|
|
album=_link_title(item, "tertiaryLinks"),
|
|
duration=_seconds(item.get("duration"))))
|
|
if not tracks:
|
|
raise AppleMusicError("Apple Music's page had no songs in it")
|
|
return name or "Apple Music", tracks
|
|
|
|
|
|
# The size a cover is asked for. Apple's artwork URLs are templates and
|
|
# scale server-side to whatever is asked.
|
|
COVER_SIZE = 1200
|
|
|
|
|
|
def _artwork(template: str) -> str:
|
|
if not template:
|
|
return ""
|
|
return (template.replace("{w}", str(COVER_SIZE))
|
|
.replace("{h}", str(COVER_SIZE)).replace("{f}", "jpg"))
|
|
|
|
|
|
def playlist_cover_url(html: str) -> str:
|
|
"""A playlist page's cover image URL, or "" when it has none."""
|
|
m = _SERVER_DATA.search(html or "")
|
|
try:
|
|
sections = json.loads(m.group(1))["data"][0]["data"]["sections"]
|
|
except (AttributeError, ValueError, KeyError, IndexError, TypeError):
|
|
return ""
|
|
for section in sections:
|
|
if section.get("itemKind") == "containerDetailHeaderLockup":
|
|
for item in section.get("items") or []:
|
|
url = (((item.get("artwork") or {}).get("dictionary") or {})
|
|
.get("url"))
|
|
if url:
|
|
return _artwork(url)
|
|
return ""
|
|
|
|
|
|
def lookup_cover_url(data: dict) -> str:
|
|
"""An iTunes Lookup answer's cover, at ``COVER_SIZE``, or ""."""
|
|
for r in (data or {}).get("results") or []:
|
|
url = r.get("artworkUrl100") or ""
|
|
if url and "100x100" in url:
|
|
return url.replace("100x100", f"{COVER_SIZE}x{COVER_SIZE}")
|
|
return ""
|
|
|
|
|
|
# ---- network ----
|
|
|
|
def _get(url: str, **params) -> requests.Response:
|
|
try:
|
|
return requests.get(url, params=params or None, timeout=TIMEOUT,
|
|
headers={"User-Agent": USER_AGENT})
|
|
except requests.RequestException as e:
|
|
raise AppleMusicError(f"couldn't reach Apple Music: {e}")
|
|
|
|
|
|
def fetch(kind: str, source_id: str,
|
|
storefront: str = "us") -> tuple[str, list[SpotifyTrack], str]:
|
|
"""→ (the link's name, its songs, its cover image URL or "")."""
|
|
if kind == "playlist":
|
|
resp = _get(PLAYLIST_URL.format(storefront=storefront, id=source_id))
|
|
if resp.status_code == 404:
|
|
raise AppleMusicError("Apple Music has no playlist with that "
|
|
"link (it may be private or deleted)")
|
|
if not resp.ok:
|
|
raise AppleMusicError(f"Apple Music answered {resp.status_code}")
|
|
return (*parse_playlist_page(resp.text),
|
|
playlist_cover_url(resp.text))
|
|
params = {"id": source_id, "country": storefront}
|
|
if kind == "album":
|
|
params["entity"] = "song"
|
|
params["limit"] = 200 # the default 50 cuts a box set short
|
|
resp = _get(LOOKUP_URL, **params)
|
|
if not resp.ok:
|
|
raise AppleMusicError(f"Apple Music answered {resp.status_code}")
|
|
try:
|
|
data = resp.json()
|
|
except ValueError as e:
|
|
raise AppleMusicError(f"Apple Music's answer couldn't be read: {e}")
|
|
return (*parse_lookup(data, kind), lookup_cover_url(data))
|