46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
"""
|
|
Music metadata search via the iTunes Search API.
|
|
Free, no auth, returns track info + album art URLs.
|
|
"""
|
|
|
|
import httpx
|
|
from typing import Any
|
|
|
|
ITUNES_URL = "https://itunes.apple.com/search"
|
|
|
|
|
|
async def search_music(query: str, limit: int = 10) -> list[dict[str, Any]]:
|
|
params = {
|
|
"term": query,
|
|
"media": "music",
|
|
"entity": "song",
|
|
"limit": limit,
|
|
}
|
|
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
response = await client.get(ITUNES_URL, params=params)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
|
|
results = []
|
|
for item in data.get("results", []):
|
|
# Upgrade artwork URL to 600x600 (iTunes returns 100x100 by default)
|
|
art_url = item.get("artworkUrl100", "")
|
|
if art_url:
|
|
art_url = art_url.replace("100x100bb", "600x600bb")
|
|
|
|
results.append({
|
|
"trackId": item.get("trackId"),
|
|
"trackName": item.get("trackName", ""),
|
|
"artistName": item.get("artistName", ""),
|
|
"collectionName": item.get("collectionName", ""),
|
|
"trackNumber": item.get("trackNumber"),
|
|
"discNumber": item.get("discNumber"),
|
|
"releaseDate": item.get("releaseDate", "")[:4], # just the year
|
|
"genre": item.get("primaryGenreName", ""),
|
|
"artworkUrl": art_url,
|
|
"previewUrl": item.get("previewUrl", ""),
|
|
})
|
|
|
|
return results
|