Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
223 lines
7.3 KiB
Python
223 lines
7.3 KiB
Python
"""Paths, settings and small shared helpers."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
import traceback
|
|
from pathlib import Path
|
|
|
|
from PyQt6.QtCore import QObject, QRunnable, QSettings, QThreadPool, pyqtSignal
|
|
|
|
APP_NAME = "Mulberry"
|
|
APP_ID = "mulberry"
|
|
VERSION = "1.1.0"
|
|
USER_AGENT = f"{APP_NAME}/{VERSION} ( https://github.com/BeamStarTech/Mulberry )"
|
|
|
|
IS_WIN = sys.platform == "win32"
|
|
IS_MAC = sys.platform == "darwin"
|
|
IS_LINUX = not IS_WIN and not IS_MAC
|
|
FROZEN = bool(getattr(sys, "frozen", False))
|
|
# folder holding bundled extras (libmpv dll, assets) in a PyInstaller build
|
|
BUNDLE_DIR = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent.parent))
|
|
|
|
|
|
def _xdg(var: str, default: str) -> Path:
|
|
return Path(os.environ.get(var) or os.path.expanduser(default))
|
|
|
|
|
|
if IS_WIN:
|
|
_roaming = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
|
|
_local = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
|
|
CONFIG_DIR = _roaming / APP_NAME
|
|
DATA_DIR = _local / APP_NAME
|
|
CACHE_DIR = _local / APP_NAME / "cache"
|
|
elif IS_MAC:
|
|
_sup = Path.home() / "Library" / "Application Support" / APP_NAME
|
|
CONFIG_DIR, DATA_DIR = _sup, _sup
|
|
CACHE_DIR = Path.home() / "Library" / "Caches" / APP_NAME
|
|
else:
|
|
CONFIG_DIR = _xdg("XDG_CONFIG_HOME", "~/.config") / APP_ID
|
|
DATA_DIR = _xdg("XDG_DATA_HOME", "~/.local/share") / APP_ID
|
|
CACHE_DIR = _xdg("XDG_CACHE_HOME", "~/.cache") / APP_ID
|
|
COVER_DIR = DATA_DIR / "covers"
|
|
THUMB_DIR = CACHE_DIR / "thumbs"
|
|
DB_PATH = DATA_DIR / "library.db"
|
|
SCROBBLE_CACHE = DATA_DIR / "scrobble_cache.json"
|
|
|
|
for _d in (CONFIG_DIR, DATA_DIR, CACHE_DIR, COVER_DIR, THUMB_DIR):
|
|
_d.mkdir(parents=True, exist_ok=True)
|
|
|
|
AUDIO_EXTS = {
|
|
"mp3", "mp2", "mp1", "flac", "ogg", "oga", "opus", "spx", "m4a", "m4b", "mp4", "aac",
|
|
"alac", "wav", "wave", "aif", "aiff", "aifc", "wma", "asf", "ape", "wv", "mpc", "mp+",
|
|
"tta", "ofr", "ofs", "tak", "dsf", "dff", "mka", "webm", "ac3", "eac3", "dts", "amr",
|
|
"au", "snd", "caf", "w64", "rf64", "mod", "xm", "it", "s3m", "mtm", "umx", "669",
|
|
"med", "okt", "far", "stm", "ult", "psm", "mptm", "spc", "vgm", "vgz", "gym", "nsf",
|
|
"sid", "mid", "midi", "kar", "3gp", "m4r", "aa", "aax", "voc", "mlp", "thd", "truehd",
|
|
}
|
|
PLAYLIST_EXTS = {"m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"}
|
|
|
|
|
|
class Settings:
|
|
"""Thin typed wrapper around QSettings with defaults."""
|
|
|
|
DEFAULTS = {
|
|
"library/folders": [],
|
|
"library/scan_on_start": True,
|
|
"library/grouping": "albumartist_album",
|
|
"playback/backend": "auto", # auto (mpv on Linux, Qt on Windows) | mpv | qt
|
|
"playback/device": "",
|
|
"playback/volume": 70,
|
|
"playback/replaygain": "off", # off | track | album
|
|
"playback/rg_preamp": 0.0,
|
|
"playback/gapless": True,
|
|
"playback/eq_enabled": False,
|
|
"playback/eq_bands": [0.0] * 10,
|
|
"playback/eq_preamp": 0.0,
|
|
"playback/repeat": "off", # off | track | playlist
|
|
"playback/shuffle": False,
|
|
"playback/resume": True,
|
|
"appearance/color_source": "kde", # kde (= follow system) | album | custom
|
|
"appearance/mode": "kde", # kde | dark | light
|
|
"appearance/custom_color": "#9a7fd1",
|
|
"appearance/hero": "full", # full | compact | hidden
|
|
"appearance/playlist_art_bg": True,
|
|
"appearance/visualizer": True,
|
|
"appearance/analyzer": True,
|
|
"appearance/font": "",
|
|
"appearance/notifications": True,
|
|
"appearance/tray": True,
|
|
"lastfm/enabled": False,
|
|
"lastfm/api_key": "",
|
|
"lastfm/use_own_key": False,
|
|
"lastfm/api_secret": "",
|
|
"lastfm/session": "",
|
|
"lastfm/user": "",
|
|
"listenbrainz/enabled": False,
|
|
"listenbrainz/token": "",
|
|
"online/auto_lyrics": True,
|
|
"lyrics/source": "auto", # auto | lrclib | netease | local | embedded
|
|
"lyrics/plain": False,
|
|
"appearance/floating_shape": True,
|
|
"online/auto_covers": True,
|
|
"online/save_covers_to_folder": False,
|
|
"online/acoustid_key": "",
|
|
"cd/device": "",
|
|
"cd/rip_format": "flac",
|
|
"cd/rip_quality": 5,
|
|
"cd/rip_dir": str(Path.home() / "Music"),
|
|
"cd/rip_pattern": "{albumartist}/{album}/{track:02d} - {title}",
|
|
}
|
|
|
|
def __init__(self):
|
|
self.q = QSettings(str(CONFIG_DIR / "mulberry.conf"), QSettings.Format.IniFormat)
|
|
|
|
def get(self, key: str, default=None):
|
|
d = self.DEFAULTS.get(key, default)
|
|
v = self.q.value(key, d)
|
|
if v is None:
|
|
return d
|
|
if isinstance(d, bool):
|
|
return v if isinstance(v, bool) else str(v).lower() in ("1", "true", "yes")
|
|
if isinstance(d, int) and not isinstance(d, bool):
|
|
try:
|
|
return int(v)
|
|
except (TypeError, ValueError):
|
|
return d
|
|
if isinstance(d, float):
|
|
try:
|
|
return float(v)
|
|
except (TypeError, ValueError):
|
|
return d
|
|
if isinstance(d, list):
|
|
if isinstance(v, str):
|
|
v = [v] if v else []
|
|
if d and isinstance(d[0], float):
|
|
try:
|
|
return [float(x) for x in v]
|
|
except (TypeError, ValueError):
|
|
return d
|
|
return list(v)
|
|
return v
|
|
|
|
def set(self, key: str, value):
|
|
self.q.setValue(key, value)
|
|
|
|
def raw(self):
|
|
return self.q
|
|
|
|
|
|
settings = Settings()
|
|
|
|
|
|
# ---------------------------------------------------------------- async helper
|
|
class _Signals(QObject):
|
|
done = pyqtSignal(object)
|
|
failed = pyqtSignal(str)
|
|
|
|
|
|
class _Job(QRunnable):
|
|
def __init__(self, fn, args, kwargs):
|
|
super().__init__()
|
|
self.fn, self.args, self.kwargs = fn, args, kwargs
|
|
self.sig = _Signals()
|
|
self.setAutoDelete(True)
|
|
|
|
def run(self):
|
|
try:
|
|
res = self.fn(*self.args, **self.kwargs)
|
|
except Exception as e: # noqa: BLE001
|
|
import urllib.error
|
|
if not isinstance(e, (urllib.error.URLError, TimeoutError, OSError, RuntimeError)):
|
|
traceback.print_exc()
|
|
try:
|
|
self.sig.failed.emit(str(e) or e.__class__.__name__)
|
|
except RuntimeError:
|
|
pass
|
|
return
|
|
try:
|
|
self.sig.done.emit(res)
|
|
except RuntimeError:
|
|
pass
|
|
|
|
|
|
_jobs: set = set()
|
|
_pool = QThreadPool()
|
|
_pool.setMaxThreadCount(6)
|
|
|
|
|
|
def run_async(fn, *args, on_done=None, on_error=None, **kwargs):
|
|
"""Run fn in a worker thread; deliver result/error on the GUI thread."""
|
|
job = _Job(fn, args, kwargs)
|
|
sig = job.sig
|
|
_jobs.add(sig)
|
|
|
|
def _finish(res):
|
|
_jobs.discard(sig)
|
|
if on_done:
|
|
on_done(res)
|
|
|
|
def _fail(msg):
|
|
_jobs.discard(sig)
|
|
if on_error:
|
|
on_error(msg)
|
|
|
|
sig.done.connect(_finish)
|
|
sig.failed.connect(_fail)
|
|
_pool.start(job)
|
|
return sig
|
|
|
|
|
|
def fmt_time(sec: float | int | None, force_hours=False) -> str:
|
|
if sec is None or sec < 0:
|
|
return "--:--"
|
|
sec = int(sec)
|
|
h, rem = divmod(sec, 3600)
|
|
m, s = divmod(rem, 60)
|
|
if h or force_hours:
|
|
return f"{h}:{m:02d}:{s:02d}"
|
|
return f"{m}:{s:02d}"
|
|
|
|
|
|
def is_audio_file(path: str) -> bool:
|
|
return Path(path).suffix.lower().lstrip(".") in AUDIO_EXTS
|