v0.18.0: paste a link, get the song

File > Import from URL... runs trav's `song` helper (yt-dlp --extract-audio
--audio-format mp3) from inside the app. Everything at the link downloads to
a private temp dir and is imported as each song lands. "and add to current
playlist?" puts the batch above the selected song, else at the end of the
playing playlist, else at the end of the shown one, in the link's order.
Each song goes straight into Identify Track. With no AcoustID key, the
proposal comes from the filename alone.

Album art now opens on a single click, in a window shaped like the cover
and as big as the screen allows.

Also fixed the dev fixture's play journal, which crashed startup (wrong
shape) and would have been ignored anyway (wrong keys). The loader now
skips a journal it can't read instead of aborting.

Claude-Session: https://claude.ai/code/session_01R5m9mXFPHNro78BdD69mG2
This commit is contained in:
2026-09-10 23:44:45 -05:00
parent 3d19b0de0a
commit d335e9144b
13 changed files with 1179 additions and 33 deletions
+200 -14
View File
@@ -9,7 +9,7 @@ from PyQt6.QtWidgets import (
from PyQt6.QtCore import Qt, QEvent, QTimer
from PyQt6.QtGui import QAction, QKeySequence
from lintunes import device_sync, mpris, music_folder, tagging, theme
from lintunes import device_sync, mpris, music_folder, tagging, theme, url_import
from lintunes.andtunes import layout as andtunes_layout
from lintunes.andtunes import sync as andtunes_sync
from lintunes.art_search import AlbumArtFetcher
@@ -29,6 +29,7 @@ from lintunes.gui.sidebar import SidebarPanel
from lintunes.gui.library_view import LibraryView
from lintunes.gui.playlist_view import PlaylistView
from lintunes.gui.transport import TransportBar
from lintunes.gui.url_import_dialog import UrlImportDialog
from lintunes.gui.info_dialog import InfoDialog
from lintunes.gui.music_folder_dialog import MusicFolderDialog
from lintunes.gui.preferences_dialog import PreferencesDialog
@@ -170,6 +171,17 @@ class MainWindow(QMainWindow):
self._identify_queue = []
self._identify_total = 0
self._identifier = None
# True from the first lookup until the queue drains, so tracks queued
# mid-run (Import from URL) wait their turn instead of starting a
# second lookup alongside.
self._identify_running = False
# Import from URL: also shares the status-bar progress widgets.
self._url_worker = None
self._url_target = None # url_import.ImportTarget, or None
self._url_inserted = 0 # songs added to the target so far
self._url_imported = 0
self._url_identify = True # False after "Stop Identifying"
self._url_note = ""
# Separate instance from the playback inhibitor: pausing music
# mid-sync must not drop the sync's hold. Logout flag included so
# GNOME's shutdown/restart dialog names the transfer as the blocker.
@@ -298,9 +310,12 @@ class MainWindow(QMainWindow):
file_menu.addSeparator()
self._add_action(file_menu, "Add Files to Library…", "Ctrl+O",
self._open_files_dialog)
self._url_import_action = self._add_action(
file_menu, "Import from URL…", "", self._import_from_url)
self._export_action = self._add_action(
file_menu, "Export Playlist…", "", self._export_playlist)
file_menu.aboutToShow.connect(self._refresh_export_action)
file_menu.aboutToShow.connect(self._refresh_url_import_action)
file_menu.addSeparator()
self._add_action(file_menu, "Quit", "Ctrl+Q", self.close)
@@ -488,12 +503,15 @@ class MainWindow(QMainWindow):
def _busy_worker(self):
"""The transfer currently owning the status-bar progress widgets."""
for worker in (self._sync_worker, self._andtunes_worker,
self._export_worker):
self._export_worker, self._url_worker):
if worker is not None and worker.busy():
return worker
return None
def _confirm_cancel_sync(self):
if self._url_worker is not None and self._url_worker.busy():
self._confirm_cancel_url_import()
return
if self._export_worker is not None and self._export_worker.busy():
self._confirm_cancel_export()
return
@@ -1005,8 +1023,7 @@ class MainWindow(QMainWindow):
if paths:
self.import_files([Path(p) for p in paths])
def import_files(self, paths, playlist_pid: str = "",
position: int | None = None):
def _ensure_music_dir(self) -> Path | None:
music_dir = self._music_import_dir()
if music_dir is None:
# Ask rather than guess — better one question than music copied
@@ -1017,6 +1034,12 @@ class MainWindow(QMainWindow):
self.statusBar().showMessage(
"Choose where to keep your music first — Edit ▸ Preferences.",
8000)
return music_dir
def import_files(self, paths, playlist_pid: str = "",
position: int | None = None) -> list:
music_dir = self._ensure_music_dir()
if music_dir is None:
return []
self.statusBar().showMessage(f"Importing {len(paths)} item(s)…")
imported = file_importer.import_paths(
@@ -1025,10 +1048,136 @@ class MainWindow(QMainWindow):
self.statusBar().showMessage(f"Imported {len(imported)} track(s)", 5000)
if imported:
self._library_view.reload()
return imported
def _import_files_to_playlist(self, paths, pid, position=None):
self.import_files([Path(p) for p in paths], pid, position)
# ---- importing from a link (trav's `song` helper, in-process) ----
def _refresh_url_import_action(self):
"""One transfer owns the status-bar progress widgets at a time."""
self._url_import_action.setEnabled(self._busy_worker() is None)
def _url_import_target(self):
shown, row = "", None
if self._content.currentWidget() is self._playlist_view:
shown = self._playlist_view.playlist_id
rows = self._playlist_view.table.selected_source_rows()
row = rows[0] if rows else None
return url_import.resolve_target(
self._manager.library, shown, row, self._now_playing_context)
def _import_from_url(self):
if self._busy_worker() is not None:
return
missing = [name for name, ok in (
("yt-dlp", url_import.ytdlp_available()),
("ffmpeg", exporter.web_support.ffmpeg_available())) if not ok]
if missing:
QMessageBox.warning(
self, "Import from URL",
f"Importing from a link needs {' and '.join(missing)}, "
f"which {'is' if len(missing) == 1 else 'are'} not "
f"installed.\n\n"
"yt-dlp: pip install --user yt-dlp (or your distro's "
"package)\nffmpeg: your distro's “ffmpeg” package")
return
target = self._url_import_target()
dialog = UrlImportDialog(target.description if target else None, self)
if not dialog.exec():
return
if self._ensure_music_dir() is None:
return
self._url_target = target if dialog.add_to_playlist() else None
self._url_inserted = 0
self._url_imported = 0
self._url_identify = True
problem = self._identify_setup_problem()
self._url_note = (f"tags proposed from filenames only ({problem})"
if problem else "")
worker = url_import.UrlImportWorker(dialog.url(), self)
worker.item_started.connect(self._on_url_item_started)
worker.progress.connect(self._sync_progress.setValue)
worker.downloaded.connect(self._on_url_downloaded)
worker.finished.connect(self._on_url_finished)
worker.failed.connect(self._on_url_failed)
self._url_worker = worker
self._sync_label.setText("Downloading…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
worker.start()
def _on_url_item_started(self, index: int, count: int, title: str):
short = title if len(title) <= 40 else title[:39] + "…"
where = f"{index} of {count} · " if count > 1 else ""
self._sync_label.setText(f"Downloading {where}{short}")
self._sync_progress.setValue(0)
def _on_url_downloaded(self, path: str):
"""One song is off the network: file it and identify it now, so the
first dialog can be up while the rest are still downloading."""
target = self._url_target
pid, position = "", None
if target is not None and target.pid in self._manager.library.playlists:
pid = target.pid
if target.position is not None:
# Each song goes after the ones already added, so the batch
# keeps the link's order, all of it above the selected song.
position = target.position + self._url_inserted
imported = self.import_files([Path(path)], pid, position)
if pid:
self._url_inserted += len(imported)
self._url_imported += len(imported)
if imported and self._url_identify:
self._enqueue_identify(imported)
def _finish_url_import(self):
if self._url_worker is not None:
self._url_worker.cleanup()
self._hide_sync_widgets()
def _on_url_finished(self, summary: dict):
self._finish_url_import()
count = self._url_imported
if summary["cancelled"]:
msg = f"Import cancelled — {count} song(s) imported"
else:
msg = f"Imported {count} song(s) from the link"
target = self._url_target
playlist = (self._manager.library.playlists.get(target.pid)
if target is not None else None)
if playlist is not None and count:
msg += f" into “{playlist.name}”"
if summary["errors"]:
msg += f" · {len(summary['errors'])} couldn't be downloaded"
if self._url_note and count and self._url_identify:
msg += f" · {self._url_note}"
self.statusBar().showMessage(msg, 12000)
def _on_url_failed(self, message: str):
self._finish_url_import()
QMessageBox.warning(self, "Import from URL",
f"Couldn't import from that link:\n\n{message}")
def _confirm_cancel_url_import(self):
box = QMessageBox(self)
box.setWindowTitle("Stop downloading")
box.setText("Stop downloading from the link?\n"
"Songs already imported stay in your library.")
stop = box.addButton("Stop Downloading",
QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton("Keep Downloading",
QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
if box.clickedButton() is stop and self._url_worker is not None:
self._url_worker.cancel()
# ---- deleting tracks ----
def _delete_tracks(self, track_ids: list[int], delete_files: bool):
@@ -1229,14 +1378,37 @@ class MainWindow(QMainWindow):
f"Skipped {skipped} track(s) with no file to fingerprint", 6000)
if not tracks:
return
self._identify_queue = tracks
self._identify_total = len(tracks)
self._identify_next(api_key)
self._enqueue_identify(tracks)
def _identify_next(self, api_key: str):
def _identify_setup_problem(self) -> str:
"""Why an AcoustID lookup can't run on this machine, or ''."""
if not fpcalc_available():
return "fpcalc isn't installed"
if not self._prefs.acoustid.get("api_key", "").strip():
return "no AcoustID key in Preferences"
return ""
def _enqueue_identify(self, tracks: list):
"""Queue tracks for Identify and start the queue if it's idle. An
Import from URL adds songs one at a time while an earlier one is still
behind its dialog, so the queue can grow mid-run."""
if not self._identify_running:
self._identify_queue = []
self._identify_total = 0
self._identify_queue.extend(tracks)
self._identify_total += len(tracks)
if not self._identify_running:
self._identify_next()
def _identify_next(self):
if not self._identify_queue:
self._identify_running = False
return
self._identify_running = True
track = self._identify_queue.pop(0)
if track.track_id not in self._manager.library.tracks:
self._identify_next() # deleted while it waited its turn
return
done = self._identify_total - len(self._identify_queue)
counter = (f" ({done} of {self._identify_total})"
if self._identify_total > 1 else "")
@@ -1246,10 +1418,14 @@ class MainWindow(QMainWindow):
# source) outlives this method.
self._identifier = TrackIdentifier()
self._identifier.finished.connect(
lambda result, t=track, k=api_key: self._on_identified(t, k, result))
self._identifier.identify(track, api_key)
lambda result, t=track: self._on_identified(t, result))
# Read fresh for every track. With no key (only an Import from URL
# gets this far without one) the identifier proposes from the
# filename alone.
self._identifier.identify(
track, self._prefs.acoustid.get("api_key", "").strip())
def _on_identified(self, track, api_key: str, result: dict):
def _on_identified(self, track, result: dict):
if "error" in result:
self.statusBar().showMessage(
f"Couldn't identify “{track.name}”: {result['error']}", 6000)
@@ -1273,9 +1449,13 @@ class MainWindow(QMainWindow):
f"Updated tags for “{track.name}”", 5000)
elif dialog.cancel_all:
self._identify_queue.clear()
self._identify_running = False
# Also covers songs a URL import has yet to download: they
# still import, they just don't get a dialog each.
self._url_identify = False
self.statusBar().clearMessage()
return
self._identify_next(api_key)
self._identify_next()
# ---- relocating a moved/renamed file ----
@@ -1418,8 +1598,11 @@ class MainWindow(QMainWindow):
def closeEvent(self, event):
# Quitting mid-transfer abandons a partial file on the device (it
# self-heals next sync, but silently) — make it a deliberate choice.
if self._busy_worker() is not None and self._busy_worker() is not (
self._export_worker):
# A link import has nothing half-written on a device to warn about:
# it is simply stopped below.
busy = self._busy_worker()
if busy is not None and busy not in (self._export_worker,
self._url_worker):
box = QMessageBox(self)
box.setWindowTitle("Sync in progress")
box.setText(
@@ -1435,6 +1618,9 @@ class MainWindow(QMainWindow):
if box.clickedButton() is not quit_button:
event.ignore()
return
if self._url_worker is not None:
self._url_worker.cancel()
self._url_worker.cleanup()
self._inhibitor.release()
self._sync_inhibitor.release()
# Before the player: this stops the device and kills the HTTP server it