Prettify lastfm provider

This commit is contained in:
Dima Gerasimov 2019-11-13 22:32:50 +00:00
parent d242874fa3
commit 494902a9f1

View file

@ -1,37 +1,59 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from functools import lru_cache from functools import lru_cache
from typing import Dict, List, NamedTuple from typing import NamedTuple, Dict, Any
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
import os
import json import json
import pytz import pytz
_PATH = Path("/L/backups/lastfm") from my_configuration import paths
# TODO Json type?
# TODO memoised properties?
# TODO lazy mode and eager mode?
# lazy is a bit nicer in terms of more flexibility and less processing?
# eager is a bit more explicit for error handling
class Scrobble(NamedTuple): class Scrobble(NamedTuple):
dt: datetime raw: Dict[str, Any]
track: str
@property
def dt(self) -> datetime:
ts = int(self.raw['date'])
return datetime.fromtimestamp(ts, tz=pytz.utc)
@property
def artist(self) -> str:
return self.raw['artist']
@property
def name(self) -> str:
return self.raw['name']
@property
def track(self) -> str:
return f'{self.artist}{self.name}'
# TODO __repr__, __str__
# TODO could also be nice to make generic? maybe even depending on eagerness
# TODO memoise...? # TODO memoise...?
# TODO watch out, if we keep the app running it might expire # TODO watch out, if we keep the app running it might expire
def _iter_scrobbles(): def _iter_scrobbles():
last = max(_PATH.glob('*.json')) last = max(Path(paths.lastfm.export_path).glob('*.json'))
# TODO mm, no timezone? wonder if it's UTC... # TODO mm, no timezone? hopefuly it's UTC
j = json.loads(last.read_text()) j = json.loads(last.read_text())
for d in j: for raw in j:
ts = int(d['date']) yield Scrobble(raw=raw)
dt = datetime.fromtimestamp(ts, tz=pytz.utc)
track = f"{d['artist']}{d['name']}"
yield Scrobble(dt, track)
@lru_cache(1) @lru_cache(1)
def get_scrobbles(): def get_scrobbles():
# TODO assert sorted?
return list(_iter_scrobbles()) return list(_iter_scrobbles())