From 494902a9f193039b66770b3a4f43639033732512 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 13 Nov 2019 22:32:50 +0000 Subject: [PATCH] Prettify lastfm provider --- my/lastfm/__init__.py | 48 +++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/my/lastfm/__init__.py b/my/lastfm/__init__.py index dc0a27f..cee03dc 100755 --- a/my/lastfm/__init__.py +++ b/my/lastfm/__init__.py @@ -1,37 +1,59 @@ #!/usr/bin/env python3 from functools import lru_cache -from typing import Dict, List, NamedTuple +from typing import NamedTuple, Dict, Any from datetime import datetime from pathlib import Path -import os import json 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): - dt: datetime - track: str + raw: Dict[str, Any] + + @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 watch out, if we keep the app running it might expire def _iter_scrobbles(): - last = max(_PATH.glob('*.json')) - # TODO mm, no timezone? wonder if it's UTC... + last = max(Path(paths.lastfm.export_path).glob('*.json')) + # TODO mm, no timezone? hopefuly it's UTC j = json.loads(last.read_text()) - for d in j: - ts = int(d['date']) - dt = datetime.fromtimestamp(ts, tz=pytz.utc) - track = f"{d['artist']} — {d['name']}" - yield Scrobble(dt, track) + for raw in j: + yield Scrobble(raw=raw) @lru_cache(1) def get_scrobbles(): + # TODO assert sorted? return list(_iter_scrobbles())