fuck it we ball
This commit is contained in:
commit
04c969c041
10 files changed
+1087
No files matched your search
@@ -0,0 +1,12 @@
|
||||
.env
|
||||
.git
|
||||
.gitignore
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
__pycache__
|
||||
.pytest_cache
|
||||
cache.db
|
||||
tests.py
|
||||
README.md
|
||||
.claude
|
||||
.idea
|
||||
@@ -0,0 +1,5 @@
|
||||
.env
|
||||
__pycache__/
|
||||
cache.db
|
||||
.pytest_cache/
|
||||
.idea/
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
FROM python:3.14-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["python", "main.py"]
|
||||
@@ -0,0 +1,38 @@
|
||||
# catch
|
||||
|
||||
catch.sistav.com — converts track and album links between Spotify, Tidal
|
||||
and Apple Music. Tracks match by ISRC, albums by barcode.
|
||||
|
||||
## Run
|
||||
|
||||
`.env`:
|
||||
|
||||
```
|
||||
SPOTIFY_CLIENT_ID=...
|
||||
SPOTIFY_CLIENT_SECRET=...
|
||||
TIDAL_CLIENT_ID=...
|
||||
TIDAL_CLIENT_SECRET=...
|
||||
```
|
||||
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
docker build -t catch .
|
||||
docker run -d --env-file .env -p 8000:8000 catch
|
||||
```
|
||||
|
||||
Optional env vars (defaults in `convert.py` and `main.py`): COUNTRY_CODE,
|
||||
PORT, CACHE_DB, CACHE_SIZE, RATE_LIMIT_PER_MINUTE, MAX_LINK_LENGTH,
|
||||
HTTP_TIMEOUT, HTTP_RETRIES, SEARCH_LIMIT, TIDAL_MAX_PAGES,
|
||||
DURATION_TOLERANCE, MAX_ALTERNATIVES.
|
||||
|
||||
## Test
|
||||
|
||||
```
|
||||
pytest tests.py
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
|
||||
_lock = threading.Lock()
|
||||
_conn = None
|
||||
_size = 1000
|
||||
|
||||
|
||||
def init(path, size):
|
||||
global _conn, _size
|
||||
_size = size
|
||||
_conn = sqlite3.connect(path, check_same_thread=False)
|
||||
_conn.execute("CREATE TABLE IF NOT EXISTS cache ("
|
||||
"key TEXT PRIMARY KEY, value TEXT, created REAL)")
|
||||
_conn.commit()
|
||||
|
||||
|
||||
def get(key):
|
||||
with _lock:
|
||||
row = _conn.execute("SELECT value FROM cache WHERE key = ?",
|
||||
(key,)).fetchone()
|
||||
return json.loads(row[0]) if row else None
|
||||
|
||||
|
||||
def put(keys, value):
|
||||
now = time.time()
|
||||
payload = json.dumps(value)
|
||||
with _lock:
|
||||
for key in keys:
|
||||
_conn.execute("INSERT OR REPLACE INTO cache "
|
||||
"(key, value, created) VALUES (?, ?, ?)",
|
||||
(key, payload, now))
|
||||
_conn.execute("DELETE FROM cache WHERE key NOT IN "
|
||||
"(SELECT key FROM cache ORDER BY created DESC LIMIT ?)",
|
||||
(_size,))
|
||||
_conn.commit()
|
||||
+641
@@ -0,0 +1,641 @@
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
|
||||
COUNTRY_CODE = os.environ.get("COUNTRY_CODE", "US")
|
||||
MAX_ALTERNATIVES = int(os.environ.get("MAX_ALTERNATIVES", "3"))
|
||||
HTTP_TIMEOUT = float(os.environ.get("HTTP_TIMEOUT", "15"))
|
||||
HTTP_RETRIES = int(os.environ.get("HTTP_RETRIES", "4"))
|
||||
SEARCH_LIMIT = int(os.environ.get("SEARCH_LIMIT", "10"))
|
||||
TIDAL_MAX_PAGES = int(os.environ.get("TIDAL_MAX_PAGES", "5"))
|
||||
DURATION_TOLERANCE = int(os.environ.get("DURATION_TOLERANCE", "3"))
|
||||
|
||||
SERVICES = ("spotify", "tidal", "apple")
|
||||
|
||||
SHORT_LINK_HOSTS = {"spotify.link", "spotify.app.link"}
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
session = requests.Session()
|
||||
|
||||
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
|
||||
SPOTIFY_API = "https://api.spotify.com/v1"
|
||||
TIDAL_TOKEN_URL = "https://auth.tidal.com/v1/oauth2/token"
|
||||
TIDAL_API = "https://openapi.tidal.com/v2"
|
||||
ITUNES_API = "https://itunes.apple.com"
|
||||
|
||||
MAX_ALTERNATIVES = 3
|
||||
|
||||
_QUALIFIER = re.compile(
|
||||
r"\s*[(\[][^)\]]*(deluxe|edition|remaster|anniversary|expanded|bonus"
|
||||
r"|version|reissue|re-issue|special)[^)\]]*[)\]]", re.I)
|
||||
|
||||
|
||||
def http_json(url, headers=None, form_data=None):
|
||||
for attempt in range(HTTP_RETRIES + 1):
|
||||
if form_data:
|
||||
resp = session.post(url, data=form_data, headers=headers,
|
||||
timeout=HTTP_TIMEOUT)
|
||||
else:
|
||||
resp = session.get(url, headers=headers, timeout=HTTP_TIMEOUT)
|
||||
if resp.status_code == 429 and attempt < HTTP_RETRIES:
|
||||
retry_after = resp.headers.get("Retry-After")
|
||||
wait = float(retry_after) if retry_after \
|
||||
and retry_after.isdigit() else 1.5 ** attempt
|
||||
time.sleep(min(wait, HTTP_TIMEOUT))
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def client_credentials_token(token_url, client_id, client_secret):
|
||||
basic = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
|
||||
data = http_json(token_url,
|
||||
headers={"Authorization": f"Basic {basic}"},
|
||||
form_data={"grant_type": "client_credentials"})
|
||||
return data["access_token"], data.get("expires_in", 3600)
|
||||
|
||||
|
||||
def get_tokens():
|
||||
keys = ("SPOTIFY_CLIENT_ID", "SPOTIFY_CLIENT_SECRET",
|
||||
"TIDAL_CLIENT_ID", "TIDAL_CLIENT_SECRET")
|
||||
missing = [k for k in keys if not os.environ.get(k)]
|
||||
if missing:
|
||||
raise RuntimeError("Missing credentials: " + ", ".join(missing))
|
||||
spotify, spotify_ttl = client_credentials_token(
|
||||
SPOTIFY_TOKEN_URL, os.environ["SPOTIFY_CLIENT_ID"],
|
||||
os.environ["SPOTIFY_CLIENT_SECRET"])
|
||||
tidal, tidal_ttl = client_credentials_token(
|
||||
TIDAL_TOKEN_URL, os.environ["TIDAL_CLIENT_ID"],
|
||||
os.environ["TIDAL_CLIENT_SECRET"])
|
||||
return {"spotify": spotify, "tidal": tidal,
|
||||
"expires_at": time.time() + min(spotify_ttl, tidal_ttl) - 60}
|
||||
|
||||
|
||||
def iso8601_duration_to_seconds(value):
|
||||
match = re.fullmatch(
|
||||
r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?", value or "")
|
||||
if not match:
|
||||
return None
|
||||
hours, minutes, seconds = (float(g) if g else 0 for g in match.groups())
|
||||
return int(hours * 3600 + minutes * 60 + seconds)
|
||||
|
||||
|
||||
def titles_match(a, b):
|
||||
a, b = (a or "").casefold().strip(), (b or "").casefold().strip()
|
||||
return bool(a) and bool(b) and (a in b or b in a)
|
||||
|
||||
|
||||
def artist_matches(name, want_artists):
|
||||
return any(titles_match(name, w) for w in want_artists)
|
||||
|
||||
|
||||
def core_title(title):
|
||||
return _QUALIFIER.sub("", title or "").casefold().strip()
|
||||
|
||||
|
||||
def album_match_key(album_title, want):
|
||||
core = core_title(album_title)
|
||||
same_core = bool(core) and core == core_title(want.get("album"))
|
||||
return same_core, titles_match(album_title, want.get("album"))
|
||||
|
||||
|
||||
def year_of(date_string):
|
||||
match = re.match(r"(\d{4})", date_string or "")
|
||||
return int(match.group(1)) if match else 9999
|
||||
|
||||
|
||||
def duration_close(seconds, want):
|
||||
return (seconds is not None and want.get("duration_s") is not None
|
||||
and abs(seconds - want["duration_s"]) <= DURATION_TOLERANCE)
|
||||
|
||||
|
||||
def rank(scored):
|
||||
scored.sort(key=lambda pair: pair[0], reverse=True)
|
||||
seen, out = set(), []
|
||||
for _, entry in scored:
|
||||
if entry["url"] and entry["url"] not in seen:
|
||||
seen.add(entry["url"])
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def as_match(ranked):
|
||||
if not ranked:
|
||||
return None
|
||||
best, alts = ranked[0], ranked[1:1 + MAX_ALTERNATIVES]
|
||||
return {"url": best["url"], "art": best.get("art"),
|
||||
"alts": [{"url": a["url"], "note": a.get("note")} for a in alts]}
|
||||
|
||||
|
||||
def parse_link(link):
|
||||
link = link.strip()
|
||||
|
||||
uri = re.match(r"spotify:(track|album):([A-Za-z0-9]{22})", link)
|
||||
if uri:
|
||||
return "spotify", uri.group(1), uri.group(2)
|
||||
|
||||
parsed = urllib.parse.urlparse(link if "://" in link else "https://" + link)
|
||||
host = parsed.hostname or ""
|
||||
|
||||
if host in SHORT_LINK_HOSTS:
|
||||
resp = session.get(link, headers={"User-Agent": "Mozilla/5.0"},
|
||||
timeout=HTTP_TIMEOUT)
|
||||
parsed = urllib.parse.urlparse(resp.url)
|
||||
host = parsed.hostname or ""
|
||||
|
||||
if "spotify" in host:
|
||||
match = re.search(r"/(track|album)/([A-Za-z0-9]{22})", parsed.path)
|
||||
if match:
|
||||
return "spotify", match.group(1), match.group(2)
|
||||
elif "tidal" in host:
|
||||
match = re.search(r"/track/(\d+)", parsed.path)
|
||||
if match:
|
||||
return "tidal", "track", match.group(1)
|
||||
match = re.search(r"/album/(\d+)", parsed.path)
|
||||
if match:
|
||||
return "tidal", "album", match.group(1)
|
||||
elif "apple" in host or "itunes" in host:
|
||||
track_param = urllib.parse.parse_qs(parsed.query).get("i", [""])[0]
|
||||
if track_param.isdigit():
|
||||
return "apple", "track", track_param
|
||||
match = re.search(r"/song/(?:[^/]+/)?(?:id)?(\d+)", parsed.path)
|
||||
if match:
|
||||
return "apple", "track", match.group(1)
|
||||
match = re.search(r"/album/(?:[^/]+/)?(?:id)?(\d+)", parsed.path)
|
||||
if match:
|
||||
return "apple", "album", match.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def sp_get(path_and_query, token):
|
||||
return http_json(f"{SPOTIFY_API}{path_and_query}",
|
||||
headers={"Authorization": f"Bearer {token}"})
|
||||
|
||||
|
||||
def sp_art(album):
|
||||
images = album.get("images") or []
|
||||
if not images:
|
||||
return None
|
||||
return images[1]["url"] if len(images) > 1 else images[0]["url"]
|
||||
|
||||
|
||||
def sp_track(track_id, token):
|
||||
d = sp_get(f"/tracks/{track_id}", token)
|
||||
return {"title": d["name"], "artists": [a["name"] for a in d["artists"]],
|
||||
"duration_s": round(d["duration_ms"] / 1000),
|
||||
"album": d["album"]["name"],
|
||||
"isrc": d.get("external_ids", {}).get("isrc"),
|
||||
"url": d["external_urls"]["spotify"],
|
||||
"art": sp_art(d["album"])}
|
||||
|
||||
|
||||
def sp_album(album_id, token):
|
||||
d = sp_get(f"/albums/{album_id}", token)
|
||||
return {"title": d["name"], "artists": [a["name"] for a in d["artists"]],
|
||||
"upc": d.get("external_ids", {}).get("upc"),
|
||||
"total_tracks": d.get("total_tracks"),
|
||||
"release_date": d.get("release_date"),
|
||||
"url": d["external_urls"]["spotify"],
|
||||
"art": sp_art(d)}
|
||||
|
||||
|
||||
def sp_search(query, item_type, token):
|
||||
q = urllib.parse.urlencode({"q": query, "type": item_type,
|
||||
"limit": SEARCH_LIMIT})
|
||||
d = sp_get(f"/search?{q}", token)
|
||||
return d[item_type + "s"]["items"]
|
||||
|
||||
|
||||
def score_spotify_tracks(candidates, want, strict):
|
||||
scored = []
|
||||
for item in candidates:
|
||||
if strict:
|
||||
if want["artists"] and not any(
|
||||
artist_matches(a["name"], want["artists"])
|
||||
for a in item["artists"]):
|
||||
continue
|
||||
if not titles_match(item["name"], want["title"]):
|
||||
continue
|
||||
album = item.get("album") or {}
|
||||
is_album = (album.get("album_type") == "album"
|
||||
and not any((a.get("name") or "").casefold()
|
||||
== "various artists"
|
||||
for a in album.get("artists", [])))
|
||||
key = (*album_match_key(album.get("name"), want),
|
||||
duration_close(round(item["duration_ms"] / 1000), want),
|
||||
is_album,
|
||||
item.get("popularity") or 0,
|
||||
-year_of(album.get("release_date")))
|
||||
note = f"{album.get('name')} ({year_of(album.get('release_date'))})"
|
||||
scored.append((key, {"url": item["external_urls"]["spotify"],
|
||||
"note": note, "art": sp_art(album)}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def score_spotify_albums(candidates, want, strict):
|
||||
scored = []
|
||||
for item in candidates:
|
||||
if strict:
|
||||
if want["artists"] and not any(
|
||||
artist_matches(a["name"], want["artists"])
|
||||
for a in item["artists"]):
|
||||
continue
|
||||
if not titles_match(item["name"], want["title"]):
|
||||
continue
|
||||
key = (item.get("release_date") == want.get("release_date"),
|
||||
item.get("total_tracks") == want.get("total_tracks"),
|
||||
(item["name"] or "").casefold()
|
||||
== (want["title"] or "").casefold(),
|
||||
-year_of(item.get("release_date")))
|
||||
note = f"{item['name']} ({year_of(item.get('release_date'))})"
|
||||
scored.append((key, {"url": item["external_urls"]["spotify"],
|
||||
"note": note, "art": sp_art(item)}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def find_spotify_track(want, tokens):
|
||||
token = tokens["spotify"]
|
||||
if want.get("isrc"):
|
||||
candidates = sp_search(f"isrc:{want['isrc']}", "track", token)
|
||||
ranked = (score_spotify_tracks(candidates, want, strict=True)
|
||||
or score_spotify_tracks(candidates, want, strict=False))
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
candidates = sp_search(
|
||||
f"track:{want['title']} artist:{want['artists'][0]}",
|
||||
"track", token)
|
||||
return as_match(score_spotify_tracks(candidates, want, strict=True))
|
||||
return None
|
||||
|
||||
|
||||
def find_spotify_album(want, tokens):
|
||||
token = tokens["spotify"]
|
||||
if want.get("upc"):
|
||||
candidates = sp_search(f"upc:{want['upc']}", "album", token)
|
||||
ranked = score_spotify_albums(candidates, want, strict=False)
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
candidates = sp_search(
|
||||
f"album:{want['title']} artist:{want['artists'][0]}",
|
||||
"album", token)
|
||||
return as_match(score_spotify_albums(candidates, want, strict=True))
|
||||
return None
|
||||
|
||||
|
||||
def td_get(path_and_query, token):
|
||||
return http_json(f"{TIDAL_API}{path_and_query}",
|
||||
headers={"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.api+json"})
|
||||
|
||||
|
||||
def td_get_paged(path_and_query, token):
|
||||
data, included = [], []
|
||||
url = path_and_query
|
||||
for _ in range(TIDAL_MAX_PAGES):
|
||||
res = td_get(url, token)
|
||||
data += res.get("data", [])
|
||||
included += res.get("included", [])
|
||||
next_link = (res.get("links") or {}).get("next")
|
||||
if not next_link:
|
||||
break
|
||||
url = next_link
|
||||
return data, included
|
||||
|
||||
|
||||
def td_share_link(item, kind):
|
||||
for link in item.get("attributes", {}).get("externalLinks", []):
|
||||
if link.get("meta", {}).get("type") == "TIDAL_SHARING":
|
||||
return link["href"]
|
||||
return f"https://tidal.com/browse/{kind}/{item['id']}"
|
||||
|
||||
|
||||
def td_item(kind, item_id, token):
|
||||
include = "artists,albums" if kind == "track" else "artists"
|
||||
res = td_get(
|
||||
f"/{kind}s/{item_id}?countryCode={COUNTRY_CODE}&include={include}",
|
||||
token)
|
||||
attrs = res["data"]["attributes"]
|
||||
artists = [i["attributes"]["name"] for i in res.get("included", [])
|
||||
if i["type"] == "artists"]
|
||||
common = {"title": attrs.get("title"), "artists": artists,
|
||||
"url": td_share_link(res["data"], kind)}
|
||||
if kind == "track":
|
||||
albums = [i["attributes"].get("title") for i in res.get("included", [])
|
||||
if i["type"] == "albums"]
|
||||
common.update(isrc=attrs.get("isrc"),
|
||||
duration_s=iso8601_duration_to_seconds(attrs.get("duration")),
|
||||
album=albums[0] if albums else None)
|
||||
else:
|
||||
common.update(upc=attrs.get("barcodeId"),
|
||||
total_tracks=attrs.get("numberOfItems"),
|
||||
release_date=attrs.get("releaseDate"))
|
||||
return common
|
||||
|
||||
|
||||
def td_tracks_by_isrc(isrc, token):
|
||||
q = urllib.parse.urlencode({"countryCode": COUNTRY_CODE,
|
||||
"filter[isrc]": isrc, "include": "albums"})
|
||||
data, included = td_get_paged(f"/tracks?{q}", token)
|
||||
album_attrs = {i["id"]: i["attributes"] for i in included
|
||||
if i["type"] == "albums"}
|
||||
pairs = []
|
||||
for item in data:
|
||||
rel = item.get("relationships", {}).get("albums", {}).get("data", [])
|
||||
pairs.append((item, [album_attrs[r["id"]] for r in rel
|
||||
if r["id"] in album_attrs]))
|
||||
return pairs
|
||||
|
||||
|
||||
def td_albums_by_barcode(upc, token):
|
||||
q = urllib.parse.urlencode({"countryCode": COUNTRY_CODE,
|
||||
"filter[barcodeId]": upc})
|
||||
data, _ = td_get_paged(f"/albums?{q}", token)
|
||||
return data
|
||||
|
||||
|
||||
def td_search(text, kind, token):
|
||||
quoted = urllib.parse.quote(text, safe="")
|
||||
res = td_get(
|
||||
f"/searchResults/{quoted}?countryCode={COUNTRY_CODE}&include={kind}s",
|
||||
token)
|
||||
return [i for i in res.get("included", []) if i["type"] == f"{kind}s"]
|
||||
|
||||
|
||||
def td_streamable(attrs):
|
||||
availability = attrs.get("availability")
|
||||
return availability is None or "STREAM" in availability
|
||||
|
||||
|
||||
def score_tidal_tracks(candidates, want, require_title_match):
|
||||
scored = []
|
||||
for item, albums in candidates:
|
||||
attrs = item.get("attributes", {})
|
||||
if not td_streamable(attrs):
|
||||
continue
|
||||
if require_title_match and not titles_match(attrs.get("title"),
|
||||
want["title"]):
|
||||
continue
|
||||
album_keys = [album_match_key(a.get("title"), want) for a in albums]
|
||||
is_album = any(a.get("type") == "ALBUM" for a in albums)
|
||||
album_pop = max((a.get("popularity") or 0 for a in albums), default=0)
|
||||
duration = iso8601_duration_to_seconds(attrs.get("duration"))
|
||||
key = (*max(album_keys, default=(False, False)),
|
||||
duration_close(duration, want),
|
||||
is_album,
|
||||
album_pop,
|
||||
attrs.get("popularity") or 0,
|
||||
-min((year_of(a.get("releaseDate")) for a in albums),
|
||||
default=9999))
|
||||
if albums:
|
||||
note = (f"{albums[0].get('title')}"
|
||||
f" ({year_of(albums[0].get('releaseDate'))})")
|
||||
else:
|
||||
note = attrs.get("title")
|
||||
scored.append((key, {"url": td_share_link(item, "track"),
|
||||
"note": note}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def score_tidal_albums(candidates, want, require_title_match):
|
||||
scored = []
|
||||
for item in candidates:
|
||||
attrs = item.get("attributes", {})
|
||||
if not td_streamable(attrs):
|
||||
continue
|
||||
if require_title_match and not titles_match(attrs.get("title"),
|
||||
want["title"]):
|
||||
continue
|
||||
key = (attrs.get("releaseDate") == want.get("release_date"),
|
||||
attrs.get("numberOfItems") == want.get("total_tracks"),
|
||||
(attrs.get("title") or "").casefold()
|
||||
== (want["title"] or "").casefold(),
|
||||
attrs.get("popularity") or 0)
|
||||
note = f"{attrs.get('title')} ({year_of(attrs.get('releaseDate'))})"
|
||||
scored.append((key, {"url": td_share_link(item, "album"),
|
||||
"note": note}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def find_tidal_track(want, tokens):
|
||||
token = tokens["tidal"]
|
||||
if want.get("isrc"):
|
||||
candidates = td_tracks_by_isrc(want["isrc"], token)
|
||||
ranked = score_tidal_tracks(candidates, want,
|
||||
require_title_match=False)
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
candidates = [(item, []) for item in td_search(
|
||||
f"{want['title']} {want['artists'][0]}", "track", token)]
|
||||
return as_match(score_tidal_tracks(candidates, want,
|
||||
require_title_match=True))
|
||||
return None
|
||||
|
||||
|
||||
def find_tidal_album(want, tokens):
|
||||
token = tokens["tidal"]
|
||||
if want.get("upc"):
|
||||
candidates = td_albums_by_barcode(want["upc"], token)
|
||||
ranked = score_tidal_albums(candidates, want,
|
||||
require_title_match=False)
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
candidates = td_search(
|
||||
f"{want['title']} {want['artists'][0]}", "album", token)
|
||||
return as_match(score_tidal_albums(candidates, want,
|
||||
require_title_match=True))
|
||||
return None
|
||||
|
||||
|
||||
def itunes_get(path_and_query):
|
||||
return http_json(f"{ITUNES_API}{path_and_query}",
|
||||
headers={"User-Agent": "Mozilla/5.0"})
|
||||
|
||||
|
||||
def ap_art(result):
|
||||
art = result.get("artworkUrl100")
|
||||
return art.replace("100x100", "300x300") if art else None
|
||||
|
||||
|
||||
def ap_track(track_id):
|
||||
res = itunes_get(f"/lookup?id={track_id}&country={COUNTRY_CODE}")
|
||||
d = next((r for r in res.get("results", [])
|
||||
if r.get("wrapperType") == "track"), None)
|
||||
if d is None:
|
||||
raise ValueError(f"Apple Music track {track_id} not found")
|
||||
return {"title": d["trackName"], "artists": [d.get("artistName")],
|
||||
"duration_s": round((d.get("trackTimeMillis") or 0) / 1000) or None,
|
||||
"album": d.get("collectionName"),
|
||||
"isrc": None,
|
||||
"url": d.get("trackViewUrl"), "art": ap_art(d)}
|
||||
|
||||
|
||||
def ap_album(album_id):
|
||||
res = itunes_get(f"/lookup?id={album_id}&country={COUNTRY_CODE}")
|
||||
d = next((r for r in res.get("results", [])
|
||||
if r.get("wrapperType") == "collection"), None)
|
||||
if d is None:
|
||||
raise ValueError(f"Apple Music album {album_id} not found")
|
||||
return {"title": d["collectionName"], "artists": [d.get("artistName")],
|
||||
"upc": None,
|
||||
"total_tracks": d.get("trackCount"),
|
||||
"release_date": (d.get("releaseDate") or "")[:10] or None,
|
||||
"url": d.get("collectionViewUrl"), "art": ap_art(d)}
|
||||
|
||||
|
||||
def score_apple_tracks(candidates, want, strict):
|
||||
scored = []
|
||||
for item in candidates:
|
||||
if item.get("wrapperType") != "track" or not item.get("trackViewUrl"):
|
||||
continue
|
||||
if strict:
|
||||
if want["artists"] and not artist_matches(
|
||||
item.get("artistName"), want["artists"]):
|
||||
continue
|
||||
if not titles_match(item.get("trackName"), want["title"]):
|
||||
continue
|
||||
collection_artist = (item.get("collectionArtistName")
|
||||
or item.get("artistName") or "")
|
||||
duration = round((item.get("trackTimeMillis") or 0) / 1000) or None
|
||||
key = (*album_match_key(item.get("collectionName"), want),
|
||||
duration_close(duration, want),
|
||||
collection_artist.casefold() != "various artists",
|
||||
-year_of(item.get("releaseDate")))
|
||||
note = (f"{item.get('collectionName')}"
|
||||
f" ({year_of(item.get('releaseDate'))})")
|
||||
scored.append((key, {"url": item["trackViewUrl"], "note": note,
|
||||
"art": ap_art(item)}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def score_apple_albums(candidates, want, strict):
|
||||
scored = []
|
||||
for item in candidates:
|
||||
if item.get("wrapperType") != "collection" \
|
||||
or not item.get("collectionViewUrl"):
|
||||
continue
|
||||
if strict:
|
||||
if want["artists"] and not artist_matches(
|
||||
item.get("artistName"), want["artists"]):
|
||||
continue
|
||||
if not titles_match(item.get("collectionName"), want["title"]):
|
||||
continue
|
||||
key = (item.get("trackCount") == want.get("total_tracks"),
|
||||
(item.get("collectionName") or "").casefold()
|
||||
== (want["title"] or "").casefold(),
|
||||
-year_of(item.get("releaseDate")))
|
||||
note = (f"{item.get('collectionName')}"
|
||||
f" ({year_of(item.get('releaseDate'))})")
|
||||
scored.append((key, {"url": item["collectionViewUrl"], "note": note,
|
||||
"art": ap_art(item)}))
|
||||
return rank(scored)
|
||||
|
||||
|
||||
def find_apple_track(want, tokens):
|
||||
if want.get("isrc"):
|
||||
res = itunes_get(f"/lookup?isrc={urllib.parse.quote(want['isrc'])}"
|
||||
f"&entity=song&country={COUNTRY_CODE}")
|
||||
candidates = res.get("results", [])
|
||||
ranked = (score_apple_tracks(candidates, want, strict=True)
|
||||
or score_apple_tracks(candidates, want, strict=False))
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
term = urllib.parse.quote(f"{want['title']} {want['artists'][0]}")
|
||||
res = itunes_get(f"/search?term={term}&media=music&entity=song"
|
||||
f"&limit={SEARCH_LIMIT}&country={COUNTRY_CODE}")
|
||||
return as_match(score_apple_tracks(res.get("results", []), want,
|
||||
strict=True))
|
||||
return None
|
||||
|
||||
|
||||
def find_apple_album(want, tokens):
|
||||
if want.get("upc"):
|
||||
res = itunes_get(f"/lookup?upc={urllib.parse.quote(want['upc'])}"
|
||||
f"&entity=album&country={COUNTRY_CODE}")
|
||||
ranked = score_apple_albums(res.get("results", []), want,
|
||||
strict=False)
|
||||
if ranked:
|
||||
return as_match(ranked)
|
||||
if want["artists"]:
|
||||
term = urllib.parse.quote(f"{want['title']} {want['artists'][0]}")
|
||||
res = itunes_get(f"/search?term={term}&media=music&entity=album"
|
||||
f"&limit={SEARCH_LIMIT}&country={COUNTRY_CODE}")
|
||||
return as_match(score_apple_albums(res.get("results", []), want,
|
||||
strict=True))
|
||||
return None
|
||||
|
||||
|
||||
def fetch_source(service, kind, item_id, tokens):
|
||||
if service == "spotify":
|
||||
if kind == "track":
|
||||
return sp_track(item_id, tokens["spotify"])
|
||||
return sp_album(item_id, tokens["spotify"])
|
||||
if service == "tidal":
|
||||
return td_item(kind, item_id, tokens["tidal"])
|
||||
if kind == "track":
|
||||
return ap_track(item_id)
|
||||
return ap_album(item_id)
|
||||
|
||||
|
||||
def find_match(service, kind, want, tokens):
|
||||
if service == "spotify":
|
||||
if kind == "track":
|
||||
return find_spotify_track(want, tokens)
|
||||
return find_spotify_album(want, tokens)
|
||||
if service == "tidal":
|
||||
if kind == "track":
|
||||
return find_tidal_track(want, tokens)
|
||||
return find_tidal_album(want, tokens)
|
||||
if kind == "track":
|
||||
return find_apple_track(want, tokens)
|
||||
return find_apple_album(want, tokens)
|
||||
|
||||
|
||||
def convert(link, tokens):
|
||||
parsed = parse_link(link)
|
||||
if not parsed:
|
||||
return None, ("Could not recognize that link. Paste a Spotify, "
|
||||
"Tidal or Apple Music track/album link.")
|
||||
service, kind, item_id = parsed
|
||||
|
||||
want = fetch_source(service, kind, item_id, tokens)
|
||||
links = {service: {"url": want["url"], "alts": []}}
|
||||
art = want.get("art")
|
||||
for other in SERVICES:
|
||||
if other == service:
|
||||
continue
|
||||
try:
|
||||
match = find_match(other, kind, want, tokens)
|
||||
except (requests.RequestException, ValueError) as e:
|
||||
log.warning("%s lookup failed for %s: %s", other, link, e)
|
||||
match = None
|
||||
links[other] = match
|
||||
if match and not art:
|
||||
art = match.get("art")
|
||||
|
||||
label = f"{want['title']} - {', '.join(a for a in want['artists'] if a)}"
|
||||
if kind == "album":
|
||||
label += " [album]"
|
||||
return {"label": label, "kind": kind, "source": service, "art": art,
|
||||
"links": links}, None
|
||||
|
||||
|
||||
def handle(link, tokens):
|
||||
try:
|
||||
return convert(link, tokens)
|
||||
except requests.HTTPError as e:
|
||||
return None, (f"API error {e.response.status_code}: "
|
||||
f"{e.response.text[:200]}")
|
||||
except requests.RequestException as e:
|
||||
return None, f"Network error: {e}"
|
||||
except ValueError as e:
|
||||
return None, str(e)
|
||||
@@ -0,0 +1,139 @@
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
import requests
|
||||
from flask import Flask, render_template, request
|
||||
from waitress import serve
|
||||
|
||||
import cache
|
||||
import convert
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
PORT = int(os.environ.get("PORT", "8000"))
|
||||
CACHE_DB = os.environ.get("CACHE_DB", "cache.db")
|
||||
CACHE_SIZE = int(os.environ.get("CACHE_SIZE", "1000"))
|
||||
RATE_LIMIT_PER_MINUTE = int(os.environ.get("RATE_LIMIT_PER_MINUTE", "20"))
|
||||
MAX_LINK_LENGTH = int(os.environ.get("MAX_LINK_LENGTH", "500"))
|
||||
MAX_TRACKED_IPS = 10000
|
||||
RATE_WINDOW_SECONDS = 60
|
||||
|
||||
AUTOPLAY = {"spotify": "autoplay_ok=1", "tidal": "play=true"}
|
||||
|
||||
cache.init(CACHE_DB, CACHE_SIZE)
|
||||
|
||||
token_cache = {"tokens": None}
|
||||
token_lock = threading.Lock()
|
||||
ip_hits = {}
|
||||
rate_lock = threading.Lock()
|
||||
|
||||
|
||||
def tokens():
|
||||
with token_lock:
|
||||
current = token_cache["tokens"]
|
||||
if not current or time.time() > current["expires_at"]:
|
||||
token_cache["tokens"] = convert.get_tokens()
|
||||
return token_cache["tokens"]
|
||||
|
||||
|
||||
def rate_limited(ip):
|
||||
now = time.time()
|
||||
with rate_lock:
|
||||
if len(ip_hits) > MAX_TRACKED_IPS:
|
||||
ip_hits.clear()
|
||||
hits = ip_hits.setdefault(ip, [])
|
||||
while hits and hits[0] < now - RATE_WINDOW_SECONDS:
|
||||
hits.pop(0)
|
||||
if len(hits) >= RATE_LIMIT_PER_MINUTE:
|
||||
return True
|
||||
hits.append(now)
|
||||
return False
|
||||
|
||||
|
||||
def client_ip():
|
||||
cf = request.headers.get("CF-Connecting-IP", "")
|
||||
if cf:
|
||||
return cf
|
||||
forwarded = request.headers.get("X-Forwarded-For", "")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
return request.remote_addr or "unknown"
|
||||
|
||||
|
||||
def with_autoplay(service, url):
|
||||
param = AUTOPLAY.get(service)
|
||||
if not param:
|
||||
return url
|
||||
return url + ("&" if "?" in url else "?") + param
|
||||
|
||||
|
||||
def lookup(link):
|
||||
try:
|
||||
parsed = convert.parse_link(link)
|
||||
except requests.RequestException:
|
||||
parsed = None
|
||||
if not parsed:
|
||||
return None, ("Could not recognize that link. Paste a Spotify, "
|
||||
"Tidal or Apple Music track/album link.")
|
||||
key = ":".join(parsed)
|
||||
result = cache.get(key)
|
||||
if result:
|
||||
return result, None
|
||||
result, error = convert.handle(link, tokens())
|
||||
if result:
|
||||
keys = {key}
|
||||
for match in result["links"].values():
|
||||
if not match:
|
||||
continue
|
||||
urls = [match.get("url")] + [a["url"] for a in match.get("alts", [])]
|
||||
for url in urls:
|
||||
url_parsed = convert.parse_link(url) if url else None
|
||||
if url_parsed:
|
||||
keys.add(":".join(url_parsed))
|
||||
cache.put(keys, result)
|
||||
return result, error
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
link = request.args.get("link", "").strip()[:MAX_LINK_LENGTH]
|
||||
result = error = None
|
||||
rows = []
|
||||
if link:
|
||||
if rate_limited(client_ip()):
|
||||
error = "Too many requests. Wait a minute and try again."
|
||||
else:
|
||||
result, error = lookup(link)
|
||||
if result:
|
||||
for service in convert.SERVICES:
|
||||
match = result["links"].get(service)
|
||||
if not match:
|
||||
rows.append({"service": service, "url": None})
|
||||
continue
|
||||
rows.append({
|
||||
"service": service,
|
||||
"url": match["url"],
|
||||
"play_url": with_autoplay(service, match["url"]),
|
||||
"alts": [{"url": a["url"],
|
||||
"play_url": with_autoplay(service, a["url"]),
|
||||
"note": a["note"]}
|
||||
for a in match["alts"]],
|
||||
})
|
||||
return render_template("index.html", link=link, error=error,
|
||||
result=result, rows=rows)
|
||||
|
||||
|
||||
@app.route("/health")
|
||||
def health():
|
||||
return "ok"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
serve(app, host="0.0.0.0", port=PORT)
|
||||
@@ -0,0 +1,5 @@
|
||||
flask
|
||||
requests
|
||||
python-dotenv
|
||||
waitress
|
||||
pytest
|
||||
@@ -0,0 +1,85 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>catch.sistav.com</title>
|
||||
<style>
|
||||
body { max-width: 44em; margin: 1.5em auto; padding: 0 1em;
|
||||
font: 18px/1.5 Georgia, "Times New Roman", serif;
|
||||
background: #faf9f5; color: #222; }
|
||||
h1 { margin: .5em 0; }
|
||||
input[type=url] { width: 100%; font-size: 1em; padding: .5em;
|
||||
box-sizing: border-box; border: 1px solid #999;
|
||||
background: #fff; }
|
||||
button { font-size: .95em; padding: .35em 1.1em; cursor: pointer; }
|
||||
a { overflow-wrap: anywhere; }
|
||||
hr { border: 0; border-top: 1px solid #ccc; margin: 1.5em 0; }
|
||||
.art { float: right; width: 160px; height: 160px; margin: 0 0 1em 1em;
|
||||
border: 1px solid #ccc; }
|
||||
.label { font-size: 1.15em; font-weight: bold; }
|
||||
.error { color: #b00; }
|
||||
.row { margin: 1.25em 0; }
|
||||
.alt { margin: .6em 0 .6em 1.5em; }
|
||||
.note { color: #666; }
|
||||
summary { cursor: pointer; color: #444; }
|
||||
@media (max-width: 600px) { .art { width: 112px; height: 112px; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>catch</h1>
|
||||
|
||||
<form method="get">
|
||||
<input type="url" name="link" placeholder="spotify / tidal / apple music link" value="{{ link }}" autofocus>
|
||||
<button>convert</button>
|
||||
</form>
|
||||
|
||||
{% if error %}
|
||||
<hr>
|
||||
<p class="error">{{ error }}</p>
|
||||
{% elif result %}
|
||||
<hr>
|
||||
{% if result.art %}<img class="art" src="{{ result.art }}" alt="">{% endif %}
|
||||
<p class="label">{{ result.label }}</p>
|
||||
{% for row in rows %}
|
||||
<div class="row">
|
||||
<b>{{ row.service }}</b><br>
|
||||
{% if row.url %}
|
||||
<a href="{{ row.play_url }}">{{ row.url }}</a>
|
||||
<button data-copy="{{ row.play_url }}">copy</button>
|
||||
{% if row.alts %}
|
||||
<details>
|
||||
<summary>not the right one?</summary>
|
||||
{% for alt in row.alts %}
|
||||
<div class="alt">
|
||||
<a href="{{ alt.play_url }}">{{ alt.url }}</a>
|
||||
<button data-copy="{{ alt.play_url }}">copy</button>
|
||||
<span class="note">{{ alt.note }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</details>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
no match
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<p><button data-copy-page>share</button></p>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
document.addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-copy], [data-copy-page]");
|
||||
if (!btn) return;
|
||||
const text = btn.hasAttribute("data-copy-page") ? location.href : btn.dataset.copy;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const old = btn.textContent;
|
||||
btn.textContent = "copied!";
|
||||
setTimeout(() => { btn.textContent = old; }, 1500);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,114 @@
|
||||
from dotenv import load_dotenv
|
||||
|
||||
import convert
|
||||
|
||||
load_dotenv()
|
||||
|
||||
_tokens = None
|
||||
|
||||
|
||||
def tokens():
|
||||
global _tokens
|
||||
if _tokens is None:
|
||||
_tokens = convert.get_tokens()
|
||||
return _tokens
|
||||
|
||||
|
||||
def ids(url):
|
||||
return convert.parse_link(url)
|
||||
|
||||
|
||||
def converted(link, service):
|
||||
result, error = convert.convert(link, tokens())
|
||||
assert error is None, f"{link}: {error}"
|
||||
match = result["links"].get(service)
|
||||
assert match, f"no {service} match for {link}"
|
||||
return match["url"]
|
||||
|
||||
|
||||
PARSE_CASES = [
|
||||
("https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=abc",
|
||||
("spotify", "track", "0VjIjW4GlUZAMYd2vXMi3b")),
|
||||
("https://open.spotify.com/intl-de/track/0VjIjW4GlUZAMYd2vXMi3b",
|
||||
("spotify", "track", "0VjIjW4GlUZAMYd2vXMi3b")),
|
||||
("spotify:track:7qiZfU4dY1lWllzX7mPBI3",
|
||||
("spotify", "track", "7qiZfU4dY1lWllzX7mPBI3")),
|
||||
("https://open.spotify.com/album/4yP0hdKOZPNshxUOjY0cZj",
|
||||
("spotify", "album", "4yP0hdKOZPNshxUOjY0cZj")),
|
||||
("https://tidal.com/browse/track/82130",
|
||||
("tidal", "track", "82130")),
|
||||
("https://tidal.com/track/15180969/u",
|
||||
("tidal", "track", "15180969")),
|
||||
("https://listen.tidal.com/track/77646170",
|
||||
("tidal", "track", "77646170")),
|
||||
("https://tidal.com/album/430416913/track/430416934",
|
||||
("tidal", "track", "430416934")),
|
||||
("https://tidal.com/browse/album/136204266",
|
||||
("tidal", "album", "136204266")),
|
||||
("https://music.apple.com/us/album/after-hours/1499378108?i=1499378615",
|
||||
("apple", "track", "1499378615")),
|
||||
("https://music.apple.com/us/song/blinding-lights/1499378615",
|
||||
("apple", "track", "1499378615")),
|
||||
("https://music.apple.com/us/album/after-hours/1499378108",
|
||||
("apple", "album", "1499378108")),
|
||||
("not a link at all", None),
|
||||
("https://example.com/track/123", None),
|
||||
]
|
||||
|
||||
PAIRS = [
|
||||
("https://open.spotify.com/track/41sGGCCoHI2GLV9qadX80A",
|
||||
"https://tidal.com/track/107549626/u"),
|
||||
("https://open.spotify.com/track/10Nmj3JCNoMeBQ87uw5j8k",
|
||||
"https://tidal.com/browse/track/309896"),
|
||||
("https://open.spotify.com/track/6ztstiyZL6FXzh4aG46ZPD",
|
||||
"https://tidal.com/track/15180969/u"),
|
||||
("https://open.spotify.com/track/7INi4pMPG4IE0Smx5y4KVf",
|
||||
"https://tidal.com/browse/track/82130"),
|
||||
("https://open.spotify.com/track/42et6fnHCw1HIPSrdPprMl",
|
||||
"https://tidal.com/browse/track/74455861"),
|
||||
("https://open.spotify.com/album/4yP0hdKOZPNshxUOjY0cZj",
|
||||
"https://tidal.com/browse/album/134858516"),
|
||||
("https://open.spotify.com/album/5OrhhWHH015Al0f85fzFIC",
|
||||
"https://tidal.com/browse/album/136204266"),
|
||||
]
|
||||
|
||||
ONE_WAY = [
|
||||
("https://tidal.com/album/430416913/track/430416934", "spotify",
|
||||
"https://open.spotify.com/track/42et6fnHCw1HIPSrdPprMl"),
|
||||
]
|
||||
|
||||
APPLE_ROUND_TRIPS = [
|
||||
"https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b",
|
||||
"https://open.spotify.com/album/4yP0hdKOZPNshxUOjY0cZj",
|
||||
]
|
||||
|
||||
|
||||
def test_parse_links():
|
||||
for link, expected in PARSE_CASES:
|
||||
assert convert.parse_link(link) == expected, link
|
||||
|
||||
|
||||
def test_pairs_match_both_ways():
|
||||
for spotify, tidal in PAIRS:
|
||||
assert ids(converted(spotify, "tidal")) == ids(tidal), spotify
|
||||
assert ids(converted(tidal, "spotify")) == ids(spotify), tidal
|
||||
|
||||
|
||||
def test_one_way_matches():
|
||||
for source, service, expected in ONE_WAY:
|
||||
assert ids(converted(source, service)) == ids(expected), source
|
||||
|
||||
|
||||
def test_apple_round_trips():
|
||||
for link in APPLE_ROUND_TRIPS:
|
||||
apple = converted(link, "apple")
|
||||
assert ids(converted(apple, "spotify")) == ids(link), link
|
||||
|
||||
|
||||
def test_result_shape():
|
||||
result, error = convert.convert(
|
||||
"https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b", tokens())
|
||||
assert error is None
|
||||
assert result["art"]
|
||||
for service in convert.SERVICES:
|
||||
assert result["links"].get(service), service
|
||||
Reference in new issue
Block a user