[music] Reorganize importer and fix lookups

This commit is contained in:
2025-07-25 10:20:49 -04:00
parent e8e989bb63
commit edf9fbd9c1
10 changed files with 742 additions and 347 deletions

View File

@ -1,23 +1,21 @@
import codecs
import csv
import logging
from datetime import datetime, timedelta
import pytz
import requests
from django.contrib.auth import get_user_model
from music.models import Track
from scrobbles.constants import AsTsvColumn
from scrobbles.models import Scrobble
from scrobbles.utils import timestamp_user_tz_to_utc
logger = logging.getLogger(__name__)
def process_audioscrobbler_tsv_file(file_path, user_id, user_tz=None):
def import_audioscrobbler_tsv_file(file_path, user_id):
"""Takes a path to a file of TSV data and imports it as past scrobbles"""
new_scrobbles = []
if not user_tz:
user_tz = pytz.utc
user = get_user_model().objects.get(id=user_id)
is_os_file = "https://" not in file_path
@ -44,11 +42,13 @@ def process_audioscrobbler_tsv_file(file_path, user_id, user_tz=None):
)
continue
album_name = row[AsTsvColumn["ALBUM_NAME"].value]
track = Track.find_or_create(
title=row[AsTsvColumn["TRACK_NAME"].value],
musicbrainz_id=row[AsTsvColumn["MB_ID"].value],
artist_name=row[AsTsvColumn["ARTIST_NAME"].value],
album_name=row[AsTsvColumn["ALBUM_NAME"].value],
album_name=album_name,
run_time_seconds=int(row[AsTsvColumn["RUN_TIME_SECONDS"].value]),
enrich=True,
)
# TODO Set all this up as constants
@ -62,22 +62,26 @@ def process_audioscrobbler_tsv_file(file_path, user_id, user_tz=None):
)
continue
timestamp = timestamp_user_tz_to_utc(
int(row[AsTsvColumn["TIMESTAMP"].value]), user_tz
timestamp = user.profile.get_timestamp_with_tz(
datetime.fromtimestamp(int(row[AsTsvColumn["TIMESTAMP"].value]))
)
stop_timestamp = timestamp + timedelta(seconds=track.run_time_seconds)
new_scrobble = Scrobble(
user_id=user_id,
user=user,
timestamp=timestamp,
stop_timestamp=stop_timestamp,
source=source,
log={"rockbox_info": rockbox_info},
log={"rockbox_info": rockbox_info, "album_name": album_name},
playback_position_seconds=track.run_time_seconds,
track=track,
played_to_completion=True,
in_progress=False,
media_type=Scrobble.MediaType.TRACK,
timezone=timestamp.tzinfo.name,
)
existing = Scrobble.objects.filter(
timestamp=timestamp, track=track
timestamp=timestamp, track=track, user=user
).first()
if existing:
logger.debug(f"Skipping existing scrobble {new_scrobble}")