diff --git a/vrobbler/apps/scrobbles/imap.py b/vrobbler/apps/scrobbles/imap.py index 20b1f97..e52a9bf 100644 --- a/vrobbler/apps/scrobbles/imap.py +++ b/vrobbler/apps/scrobbles/imap.py @@ -2,7 +2,6 @@ import json import imaplib import email from email.header import decode_header -from django.core.files.base import ContentFile from profiles.models import UserProfile from scrobbles.models import Scrobble from scrobbles.scrobblers import email_scrobble_board_game @@ -11,11 +10,12 @@ import logging logger = logging.getLogger(__name__) -def process_scrobbles_from_imap() -> list[Scrobble] | None: +def process_scrobbles_from_imap() -> list[Scrobble]: """For all user profiles with IMAP creds, check inbox for scrobbleable email attachments.""" scrobbles_created: list[Scrobble] = [] active_profiles = UserProfile.objects.filter(imap_auto_import=True) + logger.info("Starting import of scrobbles from IMAP", extra={"active_profiles": active_profiles}) for profile in active_profiles: logger.info( "Importing scrobbles from IMAP for user", @@ -62,18 +62,16 @@ def process_scrobbles_from_imap() -> list[Scrobble] | None: # Try parsing JSON if applicable parsed_json = {} if filename.lower().endswith(".bgsplay"): + # TODO Pull this out into a parse_pgsplay function try: parsed_json = json.loads( file_data.decode("utf-8") ) except Exception as e: - # You might want to log this - print( - f"Failed to parse JSON from {filename}: {e}" - ) + logger.error("Failed to parse JSON file", extra={"filename": filename, "error": e}) if not parsed_json: - logger.info("No JSON found in BG Stats file") + logger.info("No JSON found in BG Stats file", extra={"filename": filename}) continue scrobble = email_scrobble_board_game( @@ -91,3 +89,4 @@ def process_scrobbles_from_imap() -> list[Scrobble] | None: ) return scrobbles_created logger.info(f"No new scrobbles found in IMAP folders") + return [] diff --git a/vrobbler/apps/scrobbles/management/commands/import_from_imap.py b/vrobbler/apps/scrobbles/management/commands/import_from_imap.py new file mode 100644 index 0000000..7da97e4 --- /dev/null +++ b/vrobbler/apps/scrobbles/management/commands/import_from_imap.py @@ -0,0 +1,15 @@ +from django.core.management.base import BaseCommand +from vrobbler.apps.scrobbles.imap import process_scrobbles_from_imap + + +class Command(BaseCommand): + def add_arguments(self, parser): + parser.add_argument( + "--restart", + action="store_true", + help="Restart failed imports", + ) + + def handle(self, *args, **options): + count = len(process_scrobbles_from_imap()) + print(f"Started {count} IMAP imports")