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:
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(

View File

@ -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

View File

@ -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"<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(
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()

View File

@ -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()")

View File

@ -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)