Mixonomer/music/tasks/refresh_lastfm_stats.py

49 lines
1.6 KiB
Python
Raw Normal View History

2019-10-19 20:35:37 +01:00
from google.cloud import firestore
import logging
from datetime import datetime
import music.db.database as database
from spotfm.maths.counter import Counter
from spotframework.model.uri import Uri
db = firestore.Client()
logger = logging.getLogger(__name__)
def refresh_lastfm_stats(username, playlist_name):
logger.info(f'refreshing {playlist_name} stats for {username}')
fmnet = database.get_authed_lastfm_network(username=username)
spotnet = database.get_authed_spotify_network(username=username)
counter = Counter(fmnet=fmnet, spotnet=spotnet)
database_ref = database.get_user_playlist_ref_by_username(user=username, playlist=playlist_name)
playlist_dict = database_ref.get().to_dict()
2019-10-20 16:32:10 +01:00
spotify_playlist = spotnet.get_playlist(uri=Uri(playlist_dict['uri']))
track_count = counter.count_playlist(playlist=spotify_playlist)
album_count = counter.count_playlist(playlist=spotify_playlist, query_album=True)
artist_count = counter.count_playlist(playlist=spotify_playlist, query_artist=True)
2019-10-19 20:35:37 +01:00
user_count = fmnet.get_user_scrobble_count()
2019-10-20 16:32:10 +01:00
percent = round((track_count * 100) / user_count, 2)
album_percent = round((album_count * 100) / user_count, 2)
artist_percent = round((artist_count * 100) / user_count, 2)
2019-10-19 20:35:37 +01:00
database_ref.update({
2019-10-20 16:32:10 +01:00
'lastfm_stat_count': track_count,
'lastfm_stat_album_count': album_count,
'lastfm_stat_artist_count': artist_count,
2019-10-19 20:35:37 +01:00
'lastfm_stat_percent': percent,
2019-10-20 16:32:10 +01:00
'lastfm_stat_album_percent': album_percent,
'lastfm_stat_artist_percent': artist_percent,
2019-10-19 20:35:37 +01:00
'lastfm_stat_last_refresh': datetime.utcnow()
})