Move cron jobs to musicmuster.py

This commit is contained in:
Keith Edmunds 2022-04-18 14:53:57 +01:00
parent 70287d15a6
commit fd0d3e6e1f
5 changed files with 54 additions and 28 deletions

View File

@ -46,6 +46,7 @@ elif MM_ENV == 'DEVELOPMENT':
else: else:
raise ValueError(f"Unknown MusicMuster environment: {MM_ENV=}") raise ValueError(f"Unknown MusicMuster environment: {MM_ENV=}")
DEBUG(f"Using {dbname} database", True)
MYSQL_CONNECT = f"mysql+mysqldb://{dbuser}:{dbpw}@{dbhost}/{dbname}" MYSQL_CONNECT = f"mysql+mysqldb://{dbuser}:{dbpw}@{dbhost}/{dbname}"
engine = sqlalchemy.create_engine( engine = sqlalchemy.create_engine(

View File

@ -59,7 +59,7 @@ def log_uncaught_exceptions(ex_cls, ex, tb):
sys.excepthook = log_uncaught_exceptions 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, Outupt a log message at level DEBUG. If force_stderr is True,
output this message to stderr regardless of default stderr level output this message to stderr regardless of default stderr level

View File

@ -129,8 +129,8 @@ class Notes(Base):
row: int = Column(Integer, nullable=False) row: int = Column(Integer, nullable=False)
note: str = Column(String(256), index=False) note: str = Column(String(256), index=False)
def __init__( def __init__(self, session: Session, playlist_id: int,
self, session: Session, playlist_id: int, row: int, text: str) -> None: row: int, text: str) -> None:
"""Create note""" """Create note"""
DEBUG(f"Notes.__init__({playlist_id=}, {row=}, {text=})") DEBUG(f"Notes.__init__({playlist_id=}, {row=}, {text=})")
@ -257,11 +257,6 @@ class Playlists(Base):
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Playlists(id={self.id}, name={self.name}>" return f"<Playlists(id={self.id}, name={self.name}>"
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( def add_track(
self, session: Session, track_id: int, self, session: Session, track_id: int,
row: Optional[int] = None) -> None: row: Optional[int] = None) -> None:
@ -652,5 +647,6 @@ class Tracks(Base):
session.add(self) session.add(self)
session.flush() session.flush()
def update_path(self, newpath: str) -> None: def update_path(self, session, newpath: str) -> None:
self.path = newpath self.path = newpath
session.commit()

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import argparse
import os.path import os.path
import psutil import psutil
import sys 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.dlg_SelectPlaylist_ui import Ui_dlgSelectPlaylist
from ui.downloadcsv_ui import Ui_DateSelect from ui.downloadcsv_ui import Ui_DateSelect
from ui.main_window_ui import Ui_MainWindow 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: class TrackData:
@ -1074,11 +1075,34 @@ class SelectPlaylistDialog(QDialog):
if __name__ == "__main__": if __name__ == "__main__":
try: p = argparse.ArgumentParser()
Base.metadata.create_all(dbconfig.engine) # Only allow at most one option to be specified
app = QApplication(sys.argv) group = p.add_mutually_exclusive_group()
win = Window() group.add_argument('-u', '--update',
win.show() action="store_true", dest="update",
sys.exit(app.exec()) default=False, help="Update database")
except Exception: # group.add_argument('-f', '--full-update',
EXCEPTION("Unhandled Exception caught by musicmuster.main()") # 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()")

View File

@ -5,6 +5,7 @@ import os
import shutil import shutil
import tempfile import tempfile
import helpers
from config import Config from config import Config
from helpers import ( from helpers import (
fade_point, fade_point,
@ -250,24 +251,26 @@ def update_db(session):
# database: # database:
for path in list(os_paths - db_paths): 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? # is filename in database?
track = Tracks.get_by_filename(session, os.path.basename(path)) track = Tracks.get_by_filename(session, os.path.basename(path))
if not track: if not track:
messages.append(f"Track missing from database: {path}") messages.append(f"{path} missing from database: {path}")
else: else:
# Check track info matches found track # 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: 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: else:
create_track_from_file(session, path) create_track_from_file(session, path)
# Refresh database paths # Refresh database paths
db_paths = set(Tracks.get_all_paths(session)) 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): for path in list(db_paths - os_paths):
# Manage tracks listed in database but where path is invalid # Manage tracks listed in database but where path is invalid
DEBUG(f"Invalid {path=} in database", True)
track = Tracks.get_by_path(session, path) track = Tracks.get_by_path(session, path)
messages.append(f"Remove from database: {path=} {track=}") messages.append(f"Remove from database: {path=} {track=}")
@ -279,12 +282,14 @@ def update_db(session):
f"File removed: {track.title=}, {track.artist=}, " f"File removed: {track.title=}, {track.artist=}, "
f"{track.path=}" f"{track.path=}"
) )
for playlist in [a.playlist for a in track.playlists]: for playlist_track in track.playlists:
# Create note row = playlist_track.row
Notes(session, playlist.id, pt.row, note_txt)
# TODO: this needs to call playlist.add_note() now
# Remove playlist entry # 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 # Remove Track entry pointing to invalid path
Tracks.remove_by_path(session, path) Tracks.remove_by_path(session, path)