mirror of
https://github.com/Dvorinka/swingmusic-extended.git
synced 2026-06-04 20:43:04 +00:00
e770606567
* Save to DB only unique trackhashes * Add check if track already exists in playlist * replace all paths with `pathlib.Path` * `architecture.md`: * add config folder layout `config.py`: * fix bug where `pathlib.Path` cannot be serialized `files.py`: * remove unused imports * update path concatenation to `pathlib.Path` * add config-folder creation `imgserver.py`: * fix serialisation bug `playlistlib.py`: * update path concatenation to `pathlib.Path` * update all `settings.Paths` usages to new singleton `Paths` class. * update all usages of `settings.Paths` * `files.py`: * rework assets copy function. * remove unused loop and unused `shutil.copy2` function `settings.py` * fix recursion exception in `Paths` * `settings.py`: * remove Singleton and `@property` todos from `Paths` * `__init__.py`: * remove now unused function `create_config_dir()` `setup.files`: * remove because merged into `settings.Paths()` for more central and clear flow how the base path gets decided `settings.py`: * add `copy_assets` function `start_swingmusic.py`: * add configurable settings.Paths class `__main__.py`: * update click to used correct default path * remove wrong commited egg files * remove change in the wrong branch * add forgotten `property` decorator update `get_files_and_dirs` to use pathlib where possible `config.py`: * update type annotation `folders.py`: * convert `pathlib` to posix path where needed for sub-functions `folderlib.py`: * rework `get_files_and_dirs` to use `pathlib` where possible `settings.py`: * add forgotten `@property` `start_swingmusic.py`: * remove second `log_startup_info()` * `artistlib.py`: * fix calling property `tagger.py`: * fix comparing elements in `pathlib.Path` * add support for repeating lyrics. * rework lyrics api and lib * update most path functions. add type-hint pathlib where needed * for serialization paths are converted to posix path * use `open` instead of `os.open` update `metaclass` with constant * fix initial config exception if empty file existed * update `userConfig` with `InitVar` to be excluded from `asdict` * remove `is_windows_slash()` rework path function to use pathlib * convert `pathlib.Path` to `str` for serialization * fixing bug with str + pathlib * `__main__.py`: * update click to use package version * remove now unused function `print_version` `filesystem.py`: * rework `CWD` to use importlib `pyproject.toml`: * disable namespace for `importlib.resources` to work correctly * update `lyrics.py`: * remove unused functions * simplify functions * fix bug where assets get created on root * remove unused code * update lyrics for clearer structure. * add support for unsynced lyrics * fix wrong return type in unsynced lyrics * update `/check` to use `send_lyrics` * prefer tags to duplicates * `lyrics.py`: * add docs to a function group * `logger.py`: * add logging config dict. * combine Logging into one file * add socket logger * add debug mode to logger * add JSONL formater * `logger.py`: * update config to directly use the formater. resolves circular import exception `__main__.py`: * add logger setup to main `start_swingmusic.py`: * add debug option to cli * `lyrics.py`: * add offset support * add `setuptools-scm` to get version from git * add support for docker build with scm * add support for docker build with scm need someone who can test the changes workflow * update all usage of `version.txt` to `metadata.version()` * 2x update all usage of `version.txt` to `metadata.version()` * update to no local_scheme version * provide fix for #331. convert `sql.Row` and `TrackTable` to dict before converting to dataclass. * fix `__main__.py`: * wrong import and uncommited changes * add debug and base_path parameter * fix logger pathlib * add client build workflow * set name * split client from build * try fixing builds * try another fix * try also another fix * try again something new * try again something new * change runner * fix failed run because of malformed runner * add wheel builds * remove systems from pure python build * add isolated pyinstaller build * artifacts with names * wrong wheel path * try fetch-depth for tag fetch * disable fail-fast. add wheel installation * add install system packages * add debug * fix wheel install fix pyinstaller spec file * try fix for pyinstaller * try another fix * build on release * add concrete release types * only run on released or pre-released * try release upload * reformat upload * fix needs tag * identifiable pyinstaller builds * compress client folder before uploading * update to src build * remove no more needed aarch64 build script rename pyinstaller assets to lowercase * remove unneeded code * fix: save to DB only unique track hashes * replace click with argparse * set concrete types in argparse * replace manuall path usages with pathlib * remove unused `configs.py` file * reformat `start_swingmusic.py` * fix empty set startup exception * optimizing static files serve function * fixing bug in optimisation of static files serve function * fix folder view bug * colorlib.py: * fix wrong type exception * remove singe use Index_everything class * update logging of populate.py * cleanup files * fix settings.py Paths copy function. Created folder on file. * add exist check to folder * remove unused `INFO` class * fix multiprocessing bug on windows * potential icon fix for pyinstaller fix multiple logging bug * fix argparse config path bug add jobs file * cleanup code fragments fix logging issue add notes to function * note that concurrent creates own sys.modules * refactor some lyrics plugin condition remove unused import from hashing * refactor taglib.py * update import statements to be static * playlistlib.py: * refactoring and more doc strings populate.py: * add poc bugfix settings.py: * add typehint * possible bugfix for multitreading globals * folder.py: * add check if provided path is absolute populate.py: * add bug note settings.py: * add possible error from Singleton implementation start_swingmusic.py: * correct spelling * pass resolved path to Paths tagger.py: * add logging * trying out fixes for multithreading * only upload results not metadata * fix build action again * folder.py: * strictly use pathlib where possible folderlib.py: * add missing docstring to function, who really need it. track.py: * refactor some code folder.py: * refactor some more code * Merge DBPath class and Paths class. Update all usages of DBPath folderslib.py: * fix bug with logging taglib.py: * add missing docstring settings.py: * merge classes * refactor * network.py: * add more docstring config.py: * update pathlib usage tools.py: * refactor * add docstrings * colorlib.py: * add docstring Refactor App builder into grouped config settings. * update assets access for migration * Update FUNDING.yml * Update FUNDING.yml * upgrade tinytag in requirements.txt * update readme * update license * update readme * Update README.md * Update README.md * cleanup requirements.txt remove unused import in audio_segment.py add entrypoint.sh for appimage support update pyproject.toml for optional dependencies add appimage to github workflow * fix invalid workflow file * AppImage build needs more research. Commenting for now * testing a new build workflow * add libev installation * update workflow to new optional dependencies * trying again another fix * finally fix all optional deps installation correctly * remove AppImage poc * albumslib.py: * add docstring folder.py: * add unix path fix update logger name to `__name__` * update build with docker update Dockerfile with git fix typo in lyrics.py add dynamic deps back * add log for static folder * add missing import * add some more todos * add support for AppImages even when it's not perfect. * quick bugfix for wrong appimage config path * fix uploading not finding AppImages builds aka wrong pattern * optimise docker build by using artifacts. Add client path option. change docstring to sphinx format * add todos * Now support AppImages for real: manually build AppImage as we are building a complex project. * fix missing dep in AppImage build * add full AppImage metadata * add missing image file. * only update swingmusic appimage not tool * add todo and fix AppImage build again. * Try fixing some path mixup in AppImage build * add debug tag to action * correct path to appimage folder * do not download tool before checkout * Another fix for path in appimage build * extend config files with more information * default client dir is now inside the config dir. TODOs updated. * default client dir is now inside the config dir. TODOs updated. Add priority todos. * Auto download client when client not found. Respects user provided dir. * rename `requests` submodule to `request` * poc for arm AppImage builds * try out another fix * fix typo in build.yml * add missing arch tag * fix uploading double names * unique naming * enable fallback version for project. * do not download client into readonly dir. * fix relative client download path. Client was resolved into parent of config. * remove client backup path as client is now downloadable * `Paths` checks if config folder exists and creates it if necessary. logger no more creates the config folder. `app_builder.py`: static route no more with '/client' * path are only created in MainProcess. fix gz file not found. * move assets into src and update usages accordingly * remove solved todos * Only upload artefacts if not draft/master aka only on tag * wrong type in assets copy * update log with correct priority * add debug statements and logging to Paths * remove debugging statement * remove double version tag from docker build * fork save release protection * fix typo * add fallback client dir for static builds. * update argparse to new param * add missing import pathlib * add sparse checkout as we do not need everything downloaded * add assets copy check * init logger bevor Paths * remove unused import * check if logdir exists and create if not * only add exec info to file * remove exception log from cli * move logging into main. Allows tools support again. * UserConfig now correctly uses _finished key. Bug where _finished was never written * double save serverId. update root_dir to trow no exception on init. remove debug param * clean up TODOs --------- Co-authored-by: skilletfun <skilletfun.laptew.sergey@yandex.ru> Co-authored-by: Mungai Njoroge <geoffreymungai45@gmail.com>
373 lines
11 KiB
Python
373 lines
11 KiB
Python
"""
|
|
This library contains the classes and functions related to the watchdog file watcher.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import time
|
|
|
|
from watchdog.events import PatternMatchingEventHandler
|
|
from watchdog.observers.api import BaseObserverSubclassCallable
|
|
from watchdog.observers import Observer
|
|
|
|
from swingmusic import settings
|
|
from swingmusic.config import UserConfig
|
|
from swingmusic.db.libdata import TrackTable
|
|
from swingmusic.db.userdata import LibDataTable
|
|
from swingmusic.lib.colorlib import process_color
|
|
from swingmusic.lib.tagger import create_albums, create_artists
|
|
from swingmusic.lib.taglib import extract_thumb, get_tags
|
|
from swingmusic.logger import log
|
|
from swingmusic.models import Artist, Track
|
|
from swingmusic.store.albums import AlbumStore
|
|
from swingmusic.store.artists import ArtistMapEntry, ArtistStore
|
|
from swingmusic.store.tracks import TrackStore
|
|
|
|
|
|
class Watcher:
|
|
"""
|
|
Contains the methods for initializing and starting watchdog.
|
|
"""
|
|
|
|
observers: list[BaseObserverSubclassCallable] = []
|
|
|
|
def __init__(self):
|
|
self.observer = Observer()
|
|
|
|
def run(self):
|
|
"""
|
|
Starts watchers for each dir in root_dirs
|
|
"""
|
|
|
|
trials = 0
|
|
|
|
while trials < 10:
|
|
try:
|
|
# dirs = sdb.get_root_dirs()
|
|
dirs = UserConfig().rootDirs
|
|
dirs = [rf"{d}" for d in dirs]
|
|
|
|
dir_map = [
|
|
{"original": d, "realpath": os.path.realpath(d)} for d in dirs
|
|
]
|
|
break
|
|
except sqlite3.OperationalError:
|
|
trials += 1
|
|
time.sleep(1)
|
|
else:
|
|
log.error(
|
|
"WatchDogError: Failed to start Watchdog. Waiting for database timed out!"
|
|
)
|
|
return
|
|
|
|
if len(dirs) == 0:
|
|
log.warning(
|
|
"WatchDogInfo: No root directories configured. Watchdog not started."
|
|
)
|
|
return
|
|
|
|
dir_map = [d for d in dir_map if d["realpath"] != d["original"]]
|
|
|
|
# if len(dirs) > 0 and dirs[0] == "$home":
|
|
# dirs = [settings.USER_HOME_DIR]
|
|
|
|
if any([d == "$home" for d in dirs]):
|
|
dirs = [settings.Paths().USER_HOME_DIR]
|
|
|
|
event_handler = Handler(root_dirs=dirs, dir_map=dir_map)
|
|
|
|
for _dir in dirs:
|
|
exists = os.path.exists(_dir)
|
|
|
|
if not exists:
|
|
log.error("WatchdogError: Directory not found: %s", _dir)
|
|
|
|
for _dir in dirs:
|
|
self.observer.schedule(
|
|
event_handler, os.path.realpath(_dir), recursive=True
|
|
)
|
|
self.observers.append(self.observer)
|
|
|
|
try:
|
|
self.observer.start()
|
|
log.info("Started watchdog")
|
|
except (FileNotFoundError, PermissionError):
|
|
log.error(
|
|
"WatchdogError: Failed to start watchdog, root directories could not be resolved."
|
|
)
|
|
return
|
|
except OSError as e:
|
|
log.error("Failed to start watchdog. %s", e)
|
|
return
|
|
|
|
try:
|
|
while True:
|
|
time.sleep(1)
|
|
except KeyboardInterrupt:
|
|
self.stop_all()
|
|
|
|
for obsv in self.observers:
|
|
obsv.join()
|
|
|
|
def stop_all(self):
|
|
"""
|
|
Unschedules and stops all existing watchers.
|
|
"""
|
|
log.info("Stopping all watchdog observers")
|
|
for obsv in self.observers:
|
|
obsv.unschedule_all()
|
|
obsv.stop()
|
|
|
|
def restart(self):
|
|
"""
|
|
Stops all existing watchers, refetches root_dirs from the db
|
|
and restarts the watchers.
|
|
"""
|
|
log.info("🔃 Restarting watchdog")
|
|
self.stop_all()
|
|
self.run()
|
|
|
|
|
|
def handle_color(albumhash: str):
|
|
entry = LibDataTable.find_one(albumhash, "album")
|
|
|
|
if entry and entry.color:
|
|
return
|
|
|
|
colors = process_color(albumhash, is_album=True)
|
|
|
|
if colors:
|
|
return
|
|
|
|
if entry is None:
|
|
LibDataTable.insert_one(
|
|
{"itemhash": albumhash, "color": colors[0], "itemtype": "album"}
|
|
)
|
|
else:
|
|
LibDataTable.update_one(albumhash, {"color": colors[0]})
|
|
|
|
return colors
|
|
|
|
|
|
def add_track(filepath: str) -> None:
|
|
"""
|
|
Processes the audio tags for a given file ands add them to the database and store.
|
|
|
|
Then creates the folder, album and artist objects for the added track and adds them to the store.
|
|
"""
|
|
|
|
TrackStore.remove_track_by_filepath(filepath)
|
|
|
|
config = UserConfig()
|
|
tags = get_tags(filepath, config)
|
|
|
|
# if the track is somehow invalid, return
|
|
if tags is None or tags["bitrate"] == 0 or tags["duration"] == 0:
|
|
return
|
|
|
|
TrackTable.insert_one(tags)
|
|
extract_thumb(filepath, tags["albumhash"] + ".webp", overwrite=True)
|
|
|
|
colors = handle_color(tags["albumhash"])
|
|
track = Track(**tags)
|
|
TrackStore.add_track(track)
|
|
|
|
# SECTION: Index album
|
|
albumentry = AlbumStore.albummap.get(track.albumhash)
|
|
|
|
if albumentry is None:
|
|
album, trackhashes = create_albums([track.trackhash])[0]
|
|
AlbumStore.index_new_album(album, trackhashes)
|
|
else:
|
|
trackhash_exists = track.trackhash in albumentry.trackhashes
|
|
|
|
if not trackhash_exists:
|
|
albumentry.trackhashes.add(track.trackhash)
|
|
albumentry.album.trackcount += 1
|
|
albumentry.set_color(colors[0]) if colors else None
|
|
|
|
# SECTION: Index artist
|
|
artists = create_artists(track.artisthashes)
|
|
|
|
for artist in artists:
|
|
ArtistStore.artistmap[artist[0].artisthash] = ArtistMapEntry(
|
|
artist=artist[0],
|
|
albumhashes=artist[1],
|
|
trackhashes=artist[2],
|
|
)
|
|
|
|
|
|
def remove_track(filepath: str) -> None:
|
|
"""
|
|
Removes a track from the music dict.
|
|
"""
|
|
try:
|
|
track = TrackStore.get_tracks_by_filepaths([filepath])[0]
|
|
except IndexError:
|
|
return
|
|
|
|
db.remove_tracks_by_filepaths(filepath)
|
|
TrackStore.remove_track_by_filepath(filepath)
|
|
|
|
empty_album = TrackStore.count_tracks_by_trackhash(track.albumhash) > 0
|
|
|
|
if empty_album:
|
|
AlbumStore.remove_album_by_hash(track.albumhash)
|
|
|
|
artists: list[Artist] = track.artists + track.albumartists # type: ignore
|
|
|
|
for artist in artists:
|
|
empty_artist = not ArtistStore.artist_has_tracks(artist.artisthash)
|
|
|
|
if empty_artist:
|
|
ArtistStore.remove_artist_by_hash(artist.artisthash)
|
|
|
|
|
|
class Handler(PatternMatchingEventHandler):
|
|
files_to_process = []
|
|
files_to_process_windows = []
|
|
file_sizes = {}
|
|
|
|
root_dirs = []
|
|
dir_map = []
|
|
|
|
def __init__(self, root_dirs: list[str], dir_map: dict[str:str]):
|
|
self.root_dirs = root_dirs
|
|
self.dir_map = dir_map
|
|
patterns = [f"*{f}" for f in settings.SUPPORTED_FILES]
|
|
|
|
PatternMatchingEventHandler.__init__(
|
|
self,
|
|
patterns=patterns,
|
|
ignore_directories=True,
|
|
)
|
|
|
|
def get_abs_path(self, path: str):
|
|
"""
|
|
Convert a realpath to a path relative to the matching root directory.
|
|
"""
|
|
for d in self.dir_map:
|
|
if d["realpath"] in path:
|
|
return path.replace(d["realpath"], d["original"])
|
|
|
|
return path
|
|
|
|
def on_created(self, event):
|
|
"""
|
|
Fired when a supported file is created.
|
|
"""
|
|
try:
|
|
self.file_sizes[event.src_path] = os.path.getsize(event.src_path)
|
|
except FileNotFoundError:
|
|
return
|
|
|
|
self.files_to_process.append(event.src_path)
|
|
self.files_to_process_windows.append(event.src_path)
|
|
|
|
def on_deleted(self, event):
|
|
"""
|
|
Fired when a delete event occurs on a supported file.
|
|
"""
|
|
path = self.get_abs_path(event.src_path)
|
|
remove_track(path)
|
|
|
|
def on_moved(self, event):
|
|
"""
|
|
Fired when a move event occurs on a supported file.
|
|
"""
|
|
trash = "share/Trash"
|
|
|
|
if trash in event.dest_path:
|
|
path = self.get_abs_path(event.src_path)
|
|
remove_track(path)
|
|
|
|
elif trash in event.src_path:
|
|
path = self.get_abs_path(event.dest_path)
|
|
add_track(path)
|
|
|
|
elif trash not in event.dest_path and trash not in event.src_path:
|
|
dest_path = self.get_abs_path(event.dest_path)
|
|
src_path = self.get_abs_path(event.src_path)
|
|
|
|
add_track(dest_path)
|
|
remove_track(src_path)
|
|
|
|
def on_closed(self, event):
|
|
"""
|
|
Fired when a created file is closed.
|
|
NOT FIRED IN WINDOWS
|
|
"""
|
|
try:
|
|
# Get initial file size
|
|
initial_size = os.path.getsize(event.src_path)
|
|
|
|
# Wait for 10 seconds
|
|
time.sleep(10)
|
|
|
|
# Check if file size has changed
|
|
current_size = os.path.getsize(event.src_path)
|
|
|
|
if current_size > 0 and current_size == initial_size:
|
|
path = self.get_abs_path(event.src_path)
|
|
add_track(path)
|
|
# Remove from processing list only after successful processing
|
|
self.files_to_process.remove(event.src_path)
|
|
else:
|
|
# File is still being modified or has been deleted
|
|
log.info(
|
|
f"File {event.src_path} is still being modified. Skipping processing for now."
|
|
)
|
|
except FileNotFoundError:
|
|
# file was closed and deleted.
|
|
log.info(f"File {event.src_path} was closed and deleted before processing.")
|
|
except ValueError:
|
|
# file was already removed from the list by another event handler.
|
|
log.info(
|
|
f"File {event.src_path} was already removed from the processing list."
|
|
)
|
|
|
|
def on_modified(self, event):
|
|
# this event handler is triggered twice on windows
|
|
# for copy events. We need to test how this behaves in
|
|
# Linux.
|
|
|
|
if event.src_path not in self.files_to_process_windows:
|
|
return
|
|
|
|
# Check if file write operation is complete
|
|
try:
|
|
current_size = os.path.getsize(event.src_path)
|
|
except FileNotFoundError:
|
|
# File was deleted or moved
|
|
return
|
|
|
|
previous_size = self.file_sizes.get(event.src_path, -1)
|
|
|
|
if current_size == previous_size:
|
|
# Wait for a short duration to ensure the file write operation is complete
|
|
time.sleep(10)
|
|
|
|
# Check the file size again
|
|
try:
|
|
current_size = os.path.getsize(event.src_path)
|
|
except FileNotFoundError:
|
|
# File was deleted or moved
|
|
return
|
|
|
|
if current_size == previous_size:
|
|
try:
|
|
os.rename(event.src_path, event.src_path)
|
|
path = self.get_abs_path(event.src_path)
|
|
remove_track(path)
|
|
add_track(path)
|
|
self.files_to_process_windows.remove(event.src_path)
|
|
del self.file_sizes[event.src_path]
|
|
except OSError:
|
|
# File is locked
|
|
pass
|
|
return
|
|
|
|
# Update the file size for the next iteration
|
|
self.file_sizes[event.src_path] = current_size
|