75 lines
1.9 KiB
Python
75 lines
1.9 KiB
Python
import logging
|
|
|
|
from django.db.models.signals import post_delete, post_save
|
|
from django.dispatch import receiver
|
|
from django.utils import timezone
|
|
|
|
from scrobbles.models import Scrobble
|
|
from scrobbles.tasks import CHARTABLE_MEDIA_TYPES, SCROBBLES_WITHOUT_CHARTS, update_charts_for_timestamp
|
|
from scrobbles.utils import tokenize_title_to_tags
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@receiver(post_save, sender=Scrobble)
|
|
def update_charts_on_scrobble_complete(sender, instance, **kwargs):
|
|
if not instance.played_to_completion:
|
|
return
|
|
|
|
if instance.timestamp is None:
|
|
return
|
|
|
|
if instance.media_type.lower() in SCROBBLES_WITHOUT_CHARTS:
|
|
return
|
|
|
|
if instance.media_type.lower() not in CHARTABLE_MEDIA_TYPES:
|
|
return
|
|
|
|
_update_charts_for_timestamp(instance.user, instance.timestamp)
|
|
|
|
|
|
@receiver(post_delete, sender=Scrobble)
|
|
def update_charts_on_scrobble_delete(sender, instance, **kwargs):
|
|
if instance.timestamp is None:
|
|
return
|
|
|
|
if instance.media_type.lower() in SCROBBLES_WITHOUT_CHARTS:
|
|
return
|
|
|
|
if instance.media_type.lower() not in CHARTABLE_MEDIA_TYPES:
|
|
return
|
|
|
|
_update_charts_for_timestamp(instance.user, instance.timestamp)
|
|
|
|
|
|
def _update_charts_for_timestamp(user, ts):
|
|
if ts is None:
|
|
return
|
|
|
|
if timezone.is_naive(ts):
|
|
ts = timezone.make_aware(ts)
|
|
|
|
year = ts.year
|
|
month = ts.month
|
|
week = ts.isocalendar()[1]
|
|
day = ts.day
|
|
|
|
update_charts_for_timestamp.delay(user.id, year, month, day, week)
|
|
|
|
|
|
@receiver(post_save, sender=Scrobble)
|
|
def add_tags_from_task_title(sender, instance, **kwargs):
|
|
if instance.media_type != Scrobble.MediaType.TASK:
|
|
return
|
|
|
|
title = instance.logdata.title
|
|
if not title:
|
|
return
|
|
|
|
new_tags = tokenize_title_to_tags(title)
|
|
existing_tags = {t.name for t in instance.tags.all()}
|
|
|
|
for tag in new_tags:
|
|
if tag not in existing_tags:
|
|
instance.tags.add(tag)
|