Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29b9753aa3 | ||
|
|
c88e6d359c | ||
|
|
ed1059bf8c |
No files matched your search
@@ -55,3 +55,6 @@ dedup_cache.db
|
||||
dedup_cache.db-journal
|
||||
catalog_cache.db
|
||||
catalog_cache.db-journal
|
||||
|
||||
# Log persistente (rotating file)
|
||||
logs/
|
||||
@@ -136,7 +136,40 @@ class Api:
|
||||
pass
|
||||
|
||||
def _log(self, view: str, msg: str) -> None:
|
||||
# Emit alla UI + mirror sul file di log persistente
|
||||
self._emit("log", {"view": view, "msg": msg})
|
||||
try:
|
||||
import logging
|
||||
logging.getLogger(f"ui.{view}").info(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Log persistente
|
||||
# ------------------------------------------------------------------
|
||||
def get_log_file_path(self) -> str:
|
||||
"""Ritorna il path del file di log corrente (per apertura da UI)."""
|
||||
try:
|
||||
from core.applog import log_file_path
|
||||
return str(log_file_path())
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
def open_log_folder(self) -> dict:
|
||||
"""Apre la cartella dei log nel file manager del sistema."""
|
||||
try:
|
||||
from core.applog import log_file_path
|
||||
import subprocess
|
||||
folder = log_file_path().parent
|
||||
if sys.platform == "darwin":
|
||||
subprocess.Popen(["open", str(folder)])
|
||||
elif sys.platform == "win32":
|
||||
os.startfile(str(folder)) # type: ignore[attr-defined]
|
||||
else:
|
||||
subprocess.Popen(["xdg-open", str(folder)])
|
||||
return {"ok": True, "path": str(folder)}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Bootstrap
|
||||
|
||||
+10
-8
@@ -39,21 +39,23 @@ def log(msg):
|
||||
# 1. Scarica yt-dlp standalone
|
||||
# =========================================================================
|
||||
def download_ytdlp():
|
||||
"""Scarica il binario standalone di yt-dlp per macOS."""
|
||||
"""Scarica il binario standalone di yt-dlp per macOS.
|
||||
|
||||
Usa il NIGHTLY channel invece dello stable perche' YouTube rompe le
|
||||
API ogni 1-2 settimane e la stable resta indietro di 3-4 settimane
|
||||
tipicamente. La nightly esce quasi ogni giorno con i fix.
|
||||
Sempre re-download: garantisce che ogni build imbarca yt-dlp fresco.
|
||||
"""
|
||||
arch = platform.machine() # arm64 o x86_64
|
||||
if arch == "arm64":
|
||||
url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"
|
||||
url = "https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download/yt-dlp_macos"
|
||||
else:
|
||||
url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos_legacy"
|
||||
url = "https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download/yt-dlp_macos_legacy"
|
||||
|
||||
dest = BUNDLE_DIR / "yt-dlp"
|
||||
if dest.exists():
|
||||
log(f"yt-dlp gia presente: {dest}")
|
||||
return dest
|
||||
|
||||
log(f"Scarico yt-dlp da {url} ...")
|
||||
BUNDLE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
log(f"Scarico yt-dlp nightly da {url} ...")
|
||||
# Usa curl perche urllib di Python 3.8 ha problemi SSL su macOS
|
||||
subprocess.run(
|
||||
["curl", "-L", "-o", str(dest), url],
|
||||
|
||||
+4
-6
@@ -29,7 +29,7 @@ BUILD_DIR = ROOT / "build"
|
||||
DIST_DIR = ROOT / "dist"
|
||||
BUNDLE_DIR = ROOT / "bundle_bin"
|
||||
|
||||
YTDLP_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"
|
||||
YTDLP_URL = "https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download/yt-dlp.exe"
|
||||
FFMPEG_URL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
|
||||
FPCALC_URL = ("https://github.com/acoustid/chromaprint/releases/download/"
|
||||
"v1.5.1/chromaprint-fpcalc-1.5.1-windows-x86_64.zip")
|
||||
@@ -43,13 +43,11 @@ def log(msg):
|
||||
# 1. Scarica yt-dlp.exe
|
||||
# =========================================================================
|
||||
def download_ytdlp():
|
||||
"""Scarica sempre il nightly fresco: la stable resta indietro di
|
||||
3-4 settimane rispetto alle rotture API YouTube."""
|
||||
dest = BUNDLE_DIR / "yt-dlp.exe"
|
||||
if dest.exists():
|
||||
log(f"yt-dlp.exe gia presente: {dest}")
|
||||
return dest
|
||||
|
||||
log(f"Scarico yt-dlp.exe ...")
|
||||
BUNDLE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
log(f"Scarico yt-dlp.exe nightly ...")
|
||||
urllib.request.urlretrieve(YTDLP_URL, dest)
|
||||
log(f"yt-dlp.exe scaricato ({dest.stat().st_size // 1024 // 1024} MB)")
|
||||
return dest
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
"""Setup logging persistente su file rotante.
|
||||
|
||||
Chiamato in `main.py` prima di qualsiasi import pesante. Il file di log
|
||||
vive in:
|
||||
- macOS: ~/Library/Application Support/MusicTools/logs/app.log
|
||||
- Windows: %APPDATA%/MusicTools/logs/app.log
|
||||
- Dev: <project_root>/logs/app.log
|
||||
|
||||
Rotazione: 1 file al giorno, mantiene gli ultimi 7. Cattura anche stdout
|
||||
e stderr per non perdere `print()` o traceback che l'app windowed
|
||||
altrimenti scarterebbe.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
_setup_done = False
|
||||
|
||||
|
||||
def _logs_dir() -> Path:
|
||||
"""Directory dei log — parallela a config.json."""
|
||||
if getattr(sys, "frozen", False):
|
||||
if sys.platform == "win32":
|
||||
base = Path(os.environ.get("APPDATA", Path.home()))
|
||||
else:
|
||||
base = Path.home() / "Library" / "Application Support"
|
||||
d = base / "MusicTools" / "logs"
|
||||
else:
|
||||
d = Path(__file__).resolve().parent.parent / "logs"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def log_file_path() -> Path:
|
||||
return _logs_dir() / "app.log"
|
||||
|
||||
|
||||
def _install_excepthook() -> None:
|
||||
"""Cattura ogni uncaught exception dentro il file di log.
|
||||
NON tocca sys.stdout/stderr (romperebbe WebKit)."""
|
||||
import traceback
|
||||
logger = logging.getLogger("uncaught")
|
||||
_orig = sys.excepthook
|
||||
|
||||
def _hook(exc_type, exc_value, tb):
|
||||
try:
|
||||
logger.error(
|
||||
"Uncaught: %s: %s\n%s",
|
||||
exc_type.__name__,
|
||||
exc_value,
|
||||
"".join(traceback.format_exception(exc_type, exc_value, tb)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
_orig(exc_type, exc_value, tb)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.excepthook = _hook
|
||||
|
||||
# Anche per exception in threading (Python 3.8+)
|
||||
try:
|
||||
_orig_thread = threading_excepthook = getattr(__import__("threading"), "excepthook", None)
|
||||
|
||||
def _thread_hook(args):
|
||||
try:
|
||||
logger.error(
|
||||
"Thread uncaught: %s: %s\n%s",
|
||||
args.exc_type.__name__,
|
||||
args.exc_value,
|
||||
"".join(traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if _orig_thread:
|
||||
try:
|
||||
_orig_thread(args)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if threading_excepthook is not None:
|
||||
__import__("threading").excepthook = _thread_hook
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def setup() -> Path:
|
||||
"""Configura il logger root — NON tocca stdout/stderr per non rompere
|
||||
WebKit (segfault). Cattura traceback via sys.excepthook + logger.
|
||||
"""
|
||||
global _setup_done
|
||||
path = log_file_path()
|
||||
if _setup_done:
|
||||
return path
|
||||
_setup_done = True
|
||||
|
||||
root = logging.getLogger()
|
||||
root.setLevel(logging.INFO)
|
||||
|
||||
fmt = logging.Formatter(
|
||||
fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
# File handler con rotazione giornaliera (max 7 file = 7 giorni)
|
||||
fh = logging.handlers.TimedRotatingFileHandler(
|
||||
str(path),
|
||||
when="midnight",
|
||||
backupCount=7,
|
||||
encoding="utf-8",
|
||||
utc=False,
|
||||
)
|
||||
fh.setFormatter(fmt)
|
||||
fh.setLevel(logging.INFO)
|
||||
root.addHandler(fh)
|
||||
|
||||
# Se in dev, mantieni anche console (utile durante lavoro)
|
||||
if not getattr(sys, "frozen", False):
|
||||
ch = logging.StreamHandler(sys.__stderr__)
|
||||
ch.setFormatter(fmt)
|
||||
ch.setLevel(logging.INFO)
|
||||
root.addHandler(ch)
|
||||
|
||||
_install_excepthook()
|
||||
|
||||
root.info(f"MusicTools log start — file: {path}")
|
||||
return path
|
||||
+1
-1
@@ -5,7 +5,7 @@ import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
VERSION = "v1.11.0"
|
||||
VERSION = "v1.11.3"
|
||||
|
||||
|
||||
APP_NAME = "MusicTools"
|
||||
|
||||
+18
-1
@@ -247,6 +247,7 @@ def download_playlist(
|
||||
**subprocess_flags(),
|
||||
)
|
||||
|
||||
last_lines: list = [] # buffer per capire l'errore se exit != 0
|
||||
for line in _current_process.stdout:
|
||||
if is_stopped():
|
||||
_current_process.terminate()
|
||||
@@ -254,6 +255,13 @@ def download_playlist(
|
||||
progress_callback(i, total, query, "stopped", 0)
|
||||
return
|
||||
|
||||
# Tieni le ultime 10 righe non-progress per il report d'errore
|
||||
stripped = line.strip()
|
||||
if stripped and not re.match(r"^\[download\]\s+\d", stripped):
|
||||
last_lines.append(stripped)
|
||||
if len(last_lines) > 10:
|
||||
last_lines.pop(0)
|
||||
|
||||
# Parse progress da output yt-dlp
|
||||
pct_match = re.search(r"(\d+(?:\.\d+)?)%", line)
|
||||
if pct_match and progress_callback:
|
||||
@@ -278,8 +286,17 @@ def download_playlist(
|
||||
if progress_callback:
|
||||
progress_callback(i, total, query, "done", 100)
|
||||
else:
|
||||
# Estrai la vera causa da last_lines: cerca la riga ERROR di yt-dlp
|
||||
err_hint = ""
|
||||
for l in reversed(last_lines):
|
||||
if "ERROR" in l or "error" in l:
|
||||
err_hint = l[:220]
|
||||
break
|
||||
if not err_hint and last_lines:
|
||||
err_hint = last_lines[-1][:220]
|
||||
detail = f" — {err_hint}" if err_hint else ""
|
||||
if progress_callback:
|
||||
progress_callback(i, total, query, f"error: yt-dlp exit {return_code}", 0)
|
||||
progress_callback(i, total, query, f"error: yt-dlp exit {return_code}{detail}", 0)
|
||||
|
||||
except Exception as e:
|
||||
with _process_lock:
|
||||
|
||||
@@ -4,6 +4,17 @@ import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ============================================================
|
||||
# Logging persistente su file (rotazione giornaliera, 7 giorni).
|
||||
# Chiamato SUBITO cosi' ogni traceback o print da qui in poi
|
||||
# finisce nel file, anche in modalita' windowed.
|
||||
# ============================================================
|
||||
try:
|
||||
from core.applog import setup as _setup_log
|
||||
_setup_log()
|
||||
except Exception as _e:
|
||||
print(f"[bootstrap] log setup failed: {_e}")
|
||||
|
||||
# ============================================================
|
||||
# Fix SSL CA bundle: quando l'app e' frozen (PyInstaller) i moduli
|
||||
# ssl e requests non trovano nessun CA bundle di default -> tutte
|
||||
|
||||
@@ -151,6 +151,9 @@ button, input, select, textarea { font-family: inherit; font-size: inherit; }
|
||||
flex-direction: column;
|
||||
padding: 24px 12px;
|
||||
border-right: 1px solid var(--border);
|
||||
height: 100vh;
|
||||
min-height: 0; /* consente ai flex children di rimpicciolirsi sotto il contenuto */
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.brand {
|
||||
@@ -192,7 +195,17 @@ button, input, select, textarea { font-family: inherit; font-size: inherit; }
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
flex: 1;
|
||||
min-height: 0; /* per far funzionare overflow su flex child */
|
||||
overflow-y: auto; /* scrolla se ci sono troppi tab e la finestra è corta */
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.nav::-webkit-scrollbar { width: 6px; }
|
||||
.nav::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-input);
|
||||
border-radius: 3px;
|
||||
}
|
||||
.nav::-webkit-scrollbar-thumb:hover { background: var(--bg-input-hover); }
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
|
||||
@@ -598,6 +598,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="section-label">Log</h2>
|
||||
<div class="card">
|
||||
<div class="field">
|
||||
<label class="field-label">Cartella dei log</label>
|
||||
<div class="row">
|
||||
<div class="path-display" id="logPathDisplay" style="flex:1;">—</div>
|
||||
<button class="btn btn-ghost pill btn-sm" id="openLogFolderBtn">📁 Apri cartella</button>
|
||||
</div>
|
||||
<div class="hint">
|
||||
<span class="hint-ico">ⓘ</span>
|
||||
<div>
|
||||
L'app scrive un log giornaliero (<code>app.log</code>) con rotazione automatica (7 giorni).
|
||||
Utile per debug: incluide stdout, stderr, log delle tab e traceback.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="section-label">Aspetto</h2>
|
||||
<div class="card">
|
||||
<div class="field">
|
||||
|
||||
@@ -490,6 +490,12 @@ async function init() {
|
||||
if ($("#cookiesBrowserSelect")) $("#cookiesBrowserSelect").value = state.config.cookies_browser || "";
|
||||
$("#outputInput").value = state.config.output_dir || "";
|
||||
$("#themeSelect").value = state.config.theme || "dark";
|
||||
// Popola path del log corrente
|
||||
if ($("#logPathDisplay")) {
|
||||
window.pywebview.api.get_log_file_path().then((p) => {
|
||||
if (p) $("#logPathDisplay").textContent = p;
|
||||
}).catch(() => {});
|
||||
}
|
||||
applyTheme(state.config.theme);
|
||||
|
||||
// Download tab — usa output_dir come default
|
||||
@@ -1284,6 +1290,15 @@ $("#browseCookiesBtn").addEventListener("click", async () => {
|
||||
if (path) $("#cookiesInput").value = path;
|
||||
});
|
||||
|
||||
$("#openLogFolderBtn")?.addEventListener("click", async () => {
|
||||
try {
|
||||
const r = await window.pywebview.api.open_log_folder();
|
||||
if (!r || !r.ok) toast("Impossibile aprire la cartella: " + (r?.error || "errore"), "error");
|
||||
} catch (e) {
|
||||
toast("Errore: " + e, "error");
|
||||
}
|
||||
});
|
||||
|
||||
$("#browseOutputBtn").addEventListener("click", async () => {
|
||||
const path = await window.pywebview.api.browse_directory();
|
||||
if (path) $("#outputInput").value = path;
|
||||
|
||||
Reference in new issue
Block a user