From fd0d3e6e1fa0b251b950d4c42b8bb96fe55003b3 Mon Sep 17 00:00:00 2001 From: Keith Edmunds Date: Mon, 18 Apr 2022 14:53:57 +0100 Subject: [PATCH] Move cron jobs to musicmuster.py --- app/dbconfig.py | 1 + app/log.py | 2 +- app/models.py | 12 ++++-------- app/musicmuster.py | 42 +++++++++++++++++++++++++++++++++--------- app/utilities.py | 25 +++++++++++++++---------- 5 files changed, 54 insertions(+), 28 deletions(-) diff --git a/app/dbconfig.py b/app/dbconfig.py index 7b133e3..6edec31 100644 --- a/app/dbconfig.py +++ b/app/dbconfig.py @@ -46,6 +46,7 @@ elif MM_ENV == 'DEVELOPMENT': else: raise ValueError(f"Unknown MusicMuster environment: {MM_ENV=}") +DEBUG(f"Using {dbname} database", True) MYSQL_CONNECT = f"mysql+mysqldb://{dbuser}:{dbpw}@{dbhost}/{dbname}" engine = sqlalchemy.create_engine( diff --git a/app/log.py b/app/log.py index 2db1129..bec254e 100644 --- a/app/log.py +++ b/app/log.py @@ -59,7 +59,7 @@ def log_uncaught_exceptions(ex_cls, ex, tb): sys.excepthook = log_uncaught_exceptions -def DEBUG(msg, force_stderr=False): +def DEBUG(msg, force_stderr=True): """ Outupt a log message at level DEBUG. If force_stderr is True, output this message to stderr regardless of default stderr level diff --git a/app/models.py b/app/models.py index ae88f55..b13c207 100644 --- a/app/models.py +++ b/app/models.py @@ -129,8 +129,8 @@ class Notes(Base): row: int = Column(Integer, nullable=False) note: str = Column(String(256), index=False) - def __init__( - self, session: Session, playlist_id: int, row: int, text: str) -> None: + def __init__(self, session: Session, playlist_id: int, + row: int, text: str) -> None: """Create note""" DEBUG(f"Notes.__init__({playlist_id=}, {row=}, {text=})") @@ -257,11 +257,6 @@ class Playlists(Base): def __repr__(self) -> str: return f"" - def add_note(self, session: Session, row: int, text: str) -> Notes: - """Add note to playlist at passed row""" - - return Notes(session, self.id, row, text) - def add_track( self, session: Session, track_id: int, row: Optional[int] = None) -> None: @@ -652,5 +647,6 @@ class Tracks(Base): session.add(self) session.flush() - def update_path(self, newpath: str) -> None: + def update_path(self, session, newpath: str) -> None: self.path = newpath + session.commit() diff --git a/app/musicmuster.py b/app/musicmuster.py index 6736de2..d94fa92 100755 --- a/app/musicmuster.py +++ b/app/musicmuster.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import argparse import os.path import psutil import sys @@ -39,7 +40,7 @@ from ui.dlg_search_database_ui import Ui_Dialog from ui.dlg_SelectPlaylist_ui import Ui_dlgSelectPlaylist from ui.downloadcsv_ui import Ui_DateSelect from ui.main_window_ui import Ui_MainWindow -from utilities import create_track_from_file +from utilities import create_track_from_file, update_db class TrackData: @@ -1074,11 +1075,34 @@ class SelectPlaylistDialog(QDialog): if __name__ == "__main__": - try: - Base.metadata.create_all(dbconfig.engine) - app = QApplication(sys.argv) - win = Window() - win.show() - sys.exit(app.exec()) - except Exception: - EXCEPTION("Unhandled Exception caught by musicmuster.main()") + p = argparse.ArgumentParser() + # Only allow at most one option to be specified + group = p.add_mutually_exclusive_group() + group.add_argument('-u', '--update', + action="store_true", dest="update", + default=False, help="Update database") + # group.add_argument('-f', '--full-update', + # action="store_true", dest="full_update", + # default=False, help="Update database") + # group.add_argument('-i', '--import', dest="fname", help="Input file") + args = p.parse_args() + + # Run as required + if args.update: + DEBUG("Updating database") + with Session() as session: + update_db(session) + # elif args.full_update: + # DEBUG("Full update of database") + # with Session() as session: + # full_update_db(session) + else: + # Normal run + try: + Base.metadata.create_all(dbconfig.engine) + app = QApplication(sys.argv) + win = Window() + win.show() + sys.exit(app.exec()) + except Exception: + EXCEPTION("Unhandled Exception caught by musicmuster.main()") diff --git a/app/utilities.py b/app/utilities.py index 83f6230..aa07602 100755 --- a/app/utilities.py +++ b/app/utilities.py @@ -5,6 +5,7 @@ import os import shutil import tempfile +import helpers from config import Config from helpers import ( fade_point, @@ -250,24 +251,26 @@ def update_db(session): # database: for path in list(os_paths - db_paths): - DEBUG(f"songdb.update_db: {path=} not in database") + DEBUG(f"utilities.update_db: {path=} not in database") # is filename in database? track = Tracks.get_by_filename(session, os.path.basename(path)) if not track: - messages.append(f"Track missing from database: {path}") + messages.append(f"{path} missing from database: {path}") else: # Check track info matches found track - t = get_music_info(path) + t = helpers.get_tags(path) if t['artist'] == track.artist and t['title'] == track.title: - track.update_path(path) + print(f">>> Update {path=} for {track.title=}") + track.update_path(session, path) else: create_track_from_file(session, path) # Refresh database paths db_paths = set(Tracks.get_all_paths(session)) - # Remote any tracks from database whose paths don't exist + # Remove any tracks from database whose paths don't exist for path in list(db_paths - os_paths): # Manage tracks listed in database but where path is invalid + DEBUG(f"Invalid {path=} in database", True) track = Tracks.get_by_path(session, path) messages.append(f"Remove from database: {path=} {track=}") @@ -279,12 +282,14 @@ def update_db(session): f"File removed: {track.title=}, {track.artist=}, " f"{track.path=}" ) - for playlist in [a.playlist for a in track.playlists]: - # Create note - Notes(session, playlist.id, pt.row, note_txt) - # TODO: this needs to call playlist.add_note() now + for playlist_track in track.playlists: + row = playlist_track.row # Remove playlist entry - playlist.remove_track(session, pt.row) + DEBUG(f"Remove {row=} from {playlist_track.playlist_id}", True) + playlist_track.playlist.remove_track(session, row) + # Create note + DEBUG(f"Add note at {row=} to {playlist_track.playlist_id=}", True) + Notes(session, playlist_track.playlist_id, row, note_txt) # Remove Track entry pointing to invalid path Tracks.remove_by_path(session, path)