Quellcode durchsuchen

[scrobbles] Simplify notifications and add to books

Colin Powell vor 7 Monaten
Ursprung
Commit
56c000154c

+ 2 - 0
vrobbler/apps/books/koreader.py

@@ -9,6 +9,7 @@ import requests
 from books.constants import BOOKS_TITLES_TO_IGNORE
 from django.apps import apps
 from django.contrib.auth import get_user_model
+from scrobbles.utils import send_notifications_for_scrobble
 from stream_sqlite import stream_sqlite
 from webdav.client import get_webdav_client
 
@@ -441,6 +442,7 @@ def process_koreader_sqlite_file(file_path, user_id) -> list:
     created = []
     if new_scrobbles:
         created = Scrobble.objects.bulk_create(new_scrobbles)
+        send_notifications_for_scrobble(created.last().id)
         fix_long_play_stats_for_scrobbles(created)
         logger.info(
             f"Created {len(created)} scrobbles",

+ 8 - 28
vrobbler/apps/scrobbles/models.py

@@ -7,7 +7,6 @@ from uuid import uuid4
 
 import pendulum
 import pytz
-import requests
 from beers.models import Beer
 from boardgames.models import BoardGame
 from books.koreader import process_koreader_sqlite_file
@@ -28,7 +27,6 @@ from moods.models import Mood
 from music.lastfm import LastFM
 from music.models import Artist, Track
 from podcasts.models import PodcastEpisode
-from profiles.models import UserProfile
 from profiles.utils import (
     end_of_day,
     end_of_month,
@@ -38,9 +36,13 @@ from profiles.utils import (
     start_of_week,
 )
 from scrobbles import dataclasses as logdata
-from scrobbles.constants import LONG_PLAY_MEDIA
+from scrobbles.constants import LONG_PLAY_MEDIA, MEDIA_END_PADDING_SECONDS
 from scrobbles.stats import build_charts
-from scrobbles.utils import media_class_to_foreign_key
+from scrobbles.utils import (
+    get_file_md5_hash,
+    media_class_to_foreign_key,
+    send_notifications_for_scrobble,
+)
 from sports.models import SportEvent
 from tasks.models import Task
 from trails.models import Trail
@@ -49,9 +51,6 @@ from videogames.models import VideoGame
 from videos.models import Series, Video
 from webpages.models import WebPage
 
-from vrobbler.apps.scrobbles.constants import MEDIA_END_PADDING_SECONDS
-from vrobbler.apps.scrobbles.utils import get_file_md5_hash
-
 logger = logging.getLogger(__name__)
 User = get_user_model()
 BNULL = {"blank": True, "null": True}
@@ -1197,27 +1196,8 @@ class Scrobble(TimeStampedModel):
         cls,
         scrobble_data: dict,
     ) -> "Scrobble":
-        scrobble = cls.objects.create(
-            **scrobble_data,
-        )
-        profile = UserProfile.objects.filter(
-            user_id=scrobble_data["user_id"]
-        ).first()
-        if profile and profile.ntfy_enabled and profile.ntfy_url:
-            # TODO allow prority and tags to be configured in the profile
-            notify_str = f"{scrobble.media_obj}"
-            if scrobble.log and scrobble.log.get("description"):
-                notify_str += f" - {scrobble.log.get('description')}"
-            requests.post(
-                profile.ntfy_url,
-                data=notify_str.encode(encoding="utf-8"),
-                headers={
-                    "Title": scrobble.media_obj.strings.verb,
-                    "Priority": scrobble.media_obj.strings.priority,
-                    "Tags": scrobble.media_obj.strings.tags,
-                },
-            )
-
+        scrobble = cls.objects.create(**scrobble_data)
+        send_notifications_for_scrobble(scrobble.id)
         return scrobble
 
     def stop(self, force_finish=False) -> None:

+ 23 - 1
vrobbler/apps/scrobbles/utils.py

@@ -4,7 +4,7 @@ import re
 from datetime import datetime, timedelta, tzinfo
 
 import pytz
-from books.koreader import fetch_file_from_webdav
+import requests
 from django.apps import apps
 from django.contrib.auth import get_user_model
 from django.db import models
@@ -188,6 +188,7 @@ def delete_zombie_scrobbles(dry_run=True):
 def import_from_webdav_for_all_users(restart=False):
     """Grab a list of all users with WebDAV enabled and kickoff imports for them"""
     from scrobbles.models import KoReaderImport
+    from books.koreader import fetch_file_from_webdav
 
     # LastFmImport = apps.get_model("scrobbles", "LastFMImport")
     webdav_enabled_user_ids = UserProfile.objects.filter(
@@ -289,3 +290,24 @@ def deduplicate_tracks():
             other.scrobble_set.update(track=first)
             print("deleting ", other.id, " - ", other)
             other.delete()
+
+
+def send_notifications_for_scrobble(scrobble_id):
+    from scrobbles.models import Scrobble
+
+    scrobble = Scrobble.objects.get(id=scrobble_id)
+    profile = scrobble.user.profile
+    if profile and profile.ntfy_enabled and profile.ntfy_url:
+        # TODO allow prority and tags to be configured in the profile
+        notify_str = f"{scrobble.media_obj}"
+        if scrobble.log and scrobble.log.get("description"):
+            notify_str += f" - {scrobble.log.get('description')}"
+        requests.post(
+            profile.ntfy_url,
+            data=notify_str.encode(encoding="utf-8"),
+            headers={
+                "Title": scrobble.media_obj.strings.verb,
+                "Priority": scrobble.media_obj.strings.priority,
+                "Tags": scrobble.media_obj.strings.tags,
+            },
+        )