forked from trav/lintunes
Snapshot of the existing codebase before working through the TASKS.md backlog. Real library data (data/) and the iTunes import fixture (itunes-test-library/) are gitignored.
167 lines
4.8 KiB
Python
167 lines
4.8 KiB
Python
from dataclasses import dataclass, field
|
|
from typing import Optional
|
|
from datetime import datetime
|
|
from urllib.parse import unquote
|
|
|
|
|
|
# Mapping from iTunes XML key names to our field names
|
|
ITUNES_FIELD_MAP = {
|
|
"Track ID": "track_id",
|
|
"Name": "name",
|
|
"Artist": "artist",
|
|
"Album Artist": "album_artist",
|
|
"Album": "album",
|
|
"Genre": "genre",
|
|
"Kind": "kind",
|
|
"Size": "size",
|
|
"Total Time": "total_time",
|
|
"Disc Number": "disc_number",
|
|
"Disc Count": "disc_count",
|
|
"Track Number": "track_number",
|
|
"Track Count": "track_count",
|
|
"Year": "year",
|
|
"Date Modified": "date_modified",
|
|
"Date Added": "date_added",
|
|
"Bit Rate": "bit_rate",
|
|
"Sample Rate": "sample_rate",
|
|
"Play Count": "play_count",
|
|
"Play Date UTC": "play_date_utc",
|
|
"Skip Count": "skip_count",
|
|
"Skip Date": "skip_date",
|
|
"Rating": "rating",
|
|
"Album Rating": "album_rating",
|
|
"Album Rating Computed": "album_rating_computed",
|
|
"Loved": "loved",
|
|
"Composer": "composer",
|
|
"Grouping": "grouping",
|
|
"Comments": "comments",
|
|
"Sort Name": "sort_name",
|
|
"Sort Artist": "sort_artist",
|
|
"Sort Album Artist": "sort_album_artist",
|
|
"Sort Album": "sort_album",
|
|
"Sort Composer": "sort_composer",
|
|
"Work": "work",
|
|
"Movement Name": "movement_name",
|
|
"Movement Number": "movement_number",
|
|
"Movement Count": "movement_count",
|
|
"Persistent ID": "persistent_id",
|
|
"Track Type": "track_type",
|
|
"Compilation": "compilation",
|
|
"BPM": "bpm",
|
|
"Volume Adjustment": "volume_adjustment",
|
|
"Start Time": "start_time",
|
|
"Stop Time": "stop_time",
|
|
"Equalizer": "equalizer",
|
|
}
|
|
|
|
|
|
def _datetime_to_iso(dt):
|
|
if isinstance(dt, datetime):
|
|
return dt.isoformat()
|
|
return dt
|
|
|
|
|
|
def _iso_to_datetime(s):
|
|
if isinstance(s, str):
|
|
return datetime.fromisoformat(s)
|
|
return s
|
|
|
|
|
|
@dataclass
|
|
class Track:
|
|
track_id: int = 0
|
|
persistent_id: str = ""
|
|
name: str = ""
|
|
artist: str = ""
|
|
album_artist: str = ""
|
|
album: str = ""
|
|
genre: str = ""
|
|
composer: str = ""
|
|
grouping: str = ""
|
|
comments: str = ""
|
|
kind: str = ""
|
|
size: int = 0
|
|
total_time: int = 0 # milliseconds
|
|
disc_number: int = 0
|
|
disc_count: int = 0
|
|
track_number: int = 0
|
|
track_count: int = 0
|
|
year: int = 0
|
|
bpm: int = 0
|
|
bit_rate: int = 0
|
|
sample_rate: int = 0
|
|
play_count: int = 0
|
|
skip_count: int = 0
|
|
rating: int = 0
|
|
album_rating: int = 0
|
|
album_rating_computed: bool = False
|
|
loved: bool = False
|
|
compilation: bool = False
|
|
volume_adjustment: int = 0
|
|
start_time: int = 0
|
|
stop_time: int = 0
|
|
equalizer: str = ""
|
|
date_modified: Optional[str] = None # ISO 8601
|
|
date_added: Optional[str] = None
|
|
play_date_utc: Optional[str] = None
|
|
skip_date: Optional[str] = None
|
|
location: str = "" # Remapped local path
|
|
track_type: str = ""
|
|
sort_name: str = ""
|
|
sort_artist: str = ""
|
|
sort_album_artist: str = ""
|
|
sort_album: str = ""
|
|
sort_composer: str = ""
|
|
work: str = ""
|
|
movement_name: str = ""
|
|
movement_number: int = 0
|
|
movement_count: int = 0
|
|
|
|
def to_dict(self) -> dict:
|
|
d = {}
|
|
for f in self.__dataclass_fields__:
|
|
val = getattr(self, f)
|
|
if val != self.__dataclass_fields__[f].default:
|
|
d[f] = val
|
|
return d
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict) -> "Track":
|
|
known = {f.name for f in cls.__dataclass_fields__.values()}
|
|
return cls(**{k: v for k, v in d.items() if k in known})
|
|
|
|
@classmethod
|
|
def from_itunes_dict(cls, itunes_dict: dict, remap_location=None) -> "Track":
|
|
kwargs = {}
|
|
for itunes_key, our_key in ITUNES_FIELD_MAP.items():
|
|
if itunes_key in itunes_dict:
|
|
val = itunes_dict[itunes_key]
|
|
if isinstance(val, datetime):
|
|
val = val.isoformat()
|
|
kwargs[our_key] = val
|
|
|
|
# iTunes "computed" ratings are guesses, not the user's — drop them
|
|
if itunes_dict.get("Rating Computed"):
|
|
kwargs.pop("rating", None)
|
|
if itunes_dict.get("Album Rating Computed"):
|
|
kwargs.pop("album_rating", None)
|
|
kwargs.pop("album_rating_computed", None)
|
|
|
|
if "Location" in itunes_dict:
|
|
location = decode_location_url(itunes_dict["Location"])
|
|
if remap_location is not None:
|
|
location = remap_location(location)
|
|
kwargs["location"] = location
|
|
|
|
return cls(**kwargs)
|
|
|
|
|
|
def decode_location_url(url: str) -> str:
|
|
"""Decode an iTunes Location URL to a plain absolute path."""
|
|
location = unquote(url)
|
|
for prefix in ("file://localhost", "file://"):
|
|
if location.startswith(prefix):
|
|
location = location[len(prefix):]
|
|
break
|
|
return location
|