[scrobbles] Fixes dedup utility, adding a transaction

Deleting tracks needs to be in a transaction so we don't try to delete a
track that may still have scrobbles associated with it.
This commit is contained in:
2025-03-29 13:49:54 -04:00
parent 99da9b62bf
commit 3208a32ffe

View File

@ -2,12 +2,12 @@ import hashlib
import logging import logging
import re import re
from datetime import datetime, timedelta, tzinfo from datetime import datetime, timedelta, tzinfo
from sqlite3 import IntegrityError
import pytz import pytz
import requests
from django.apps import apps from django.apps import apps
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.db import models from django.db import models, transcation
from django.utils import timezone from django.utils import timezone
from profiles.models import UserProfile from profiles.models import UserProfile
from profiles.utils import now_user_timezone from profiles.utils import now_user_timezone
@ -271,7 +271,6 @@ def get_file_md5_hash(file_path: str) -> str:
file_hash.update(chunk) file_hash.update(chunk)
return file_hash.hexdigest() return file_hash.hexdigest()
def deduplicate_tracks(commit=False) -> int: def deduplicate_tracks(commit=False) -> int:
from music.models import Track from music.models import Track
@ -288,9 +287,13 @@ def deduplicate_tracks(commit=False) -> int:
for other in tracks.exclude(id=first.id): for other in tracks.exclude(id=first.id):
print("moving scrobbles for ", other.id, " to ", first.id) print("moving scrobbles for ", other.id, " to ", first.id)
if commit: if commit:
other.scrobble_set.update(track=first) with transaction.atomic():
print("deleting ", other.id, " - ", other) other.scrobble_set.update(track=first)
other.delete() print("deleting ", other.id, " - ", other)
try:
other.delete()
except IntegrityError as e:
print("could not delete ", other.id, f": IntegrityError {e}")
return len(dups) return len(dups)