From 4a32baac3a282411ef909f536189d7fac8f09997 Mon Sep 17 00:00:00 2001 From: trav Date: Fri, 23 Oct 2026 01:47:41 -0700 Subject: [PATCH] v0.78.0: importing a playlist link can make a new playlist of the same name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Once a YouTube, SoundCloud or Spotify link turns out to be a named list, Import from URL offers "Make a new playlist of these songs, named …" (off unless ticked, the name editable). yt-dlp's listing now prints each entry's playlist_title; Spotify's probe hands over the album's or playlist's name. The playlist is made when the first song lands, so a link that downloads nothing leaves no empty playlist, and the songs go in in the link's order. Undoing "New Playlist" takes it all back in one step. --- CLAUDE.md | 7 + lintunes/__init__.py | 2 +- lintunes/gui/main_window.py | 22 +++ lintunes/gui/url_import_dialog.py | 47 ++++++- lintunes/url_import.py | 29 +++- tests/test_round109.py | 219 ++++++++++++++++++++++++++++++ tests/test_round49.py | 2 + tests/test_round75.py | 4 + tests/test_round76.py | 2 + 9 files changed, 327 insertions(+), 7 deletions(-) create mode 100644 tests/test_round109.py diff --git a/CLAUDE.md b/CLAUDE.md index f82464b..886c61a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -745,6 +745,13 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal get `gui/url_import_progress.py`, a non-modal per-song list (Hide keeps downloading; clicking the status-bar line reopens it). `LTSTART` carries the id, and `ERROR: [site] : …` lines become `item_failed`. + **A named list can become a playlist** (Round 109): the probe also + prints `LTLIST %(playlist_title|)s` (Spotify's probe emits the album's + or playlist's name), and the dialog then offers "Make a new playlist of + these songs, named [it]", off unless ticked. `MainWindow` makes the + playlist when the *first* song lands (nothing downloaded → no empty + playlist) and adds each song with `undoable=False`, so undoing "New + Playlist" is the one step that takes it all back. **A Spotify link** (Round 76, `spotify_link.py`, ported from trav's `spotify-youtube` script) can't be downloaded, but Spotify's public embed page (`open.spotify.com/embed//`, a `__NEXT_DATA__` diff --git a/lintunes/__init__.py b/lintunes/__init__.py index bae84c3..70c7ad3 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.77.1" +__version__ = "0.78.0" diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 544eb37..79b3ff6 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -287,6 +287,11 @@ class MainWindow(QMainWindow): self._bpm_results: dict[int, int] = {} self._url_target = None # url_import.ImportTarget, or None self._url_inserted = 0 # songs added to the target so far + # "Make a new playlist of these songs": its name until the first + # song lands, then the playlist's pid (made then, so a link that + # downloads nothing leaves no empty playlist behind). + self._url_new_name = "" + self._url_new_pid = "" self._url_imported = 0 self._url_identify = True # False after "Stop Identifying" self._url_note = "" @@ -1828,6 +1833,8 @@ class MainWindow(QMainWindow): chosen = dialog.chosen_entries() self._url_target = target if dialog.add_to_playlist() else None self._url_inserted = 0 + self._url_new_name = dialog.new_playlist_name() + self._url_new_pid = "" self._url_imported = 0 self._url_identify = True problem = self._identify_setup_problem() @@ -1921,6 +1928,8 @@ class MainWindow(QMainWindow): imported = self.import_files([Path(path)], pid, position) if pid: self._url_inserted += len(imported) + if imported and (self._url_new_name or self._url_new_pid): + self._add_to_new_url_playlist(imported) self._url_imported += len(imported) if self._url_progress is not None: self._url_progress.landed(bool(imported)) @@ -1930,6 +1939,19 @@ class MainWindow(QMainWindow): else: self._enqueue_identify(imported) + def _add_to_new_url_playlist(self, tracks): + """Into the link's own new playlist, in the order the songs land + (the link's order). One undo step: undoing "New Playlist" takes + it away with everything in it.""" + if self._url_new_pid not in self._manager.library.playlists: + if not self._url_new_name: + return # it was made, then deleted mid-import + playlist = self._manager.create_playlist(self._url_new_name) + self._url_new_pid = playlist.persistent_id + self._url_new_name = "" + self._manager.add_tracks_to_playlist( + self._url_new_pid, [t.track_id for t in tracks], undoable=False) + def _finish_url_import(self): if self._url_worker is not None: self._url_worker.cleanup() diff --git a/lintunes/gui/url_import_dialog.py b/lintunes/gui/url_import_dialog.py index ecf6276..189df29 100644 --- a/lintunes/gui/url_import_dialog.py +++ b/lintunes/gui/url_import_dialog.py @@ -23,6 +23,11 @@ A Spotify link (Round 76) is listed the same way, from Spotify's own page (``url_import.SpotifyProbe``): a track goes straight through, an album or playlist is a checklist with everything ticked. The caller reads the chosen songs from ``spotify_tracks()`` and finds each one on YouTube. + +A list that has a name (a YouTube or SoundCloud playlist, a Spotify album +or playlist) offers to make a new playlist of the same name holding every +song imported (``new_playlist_name()``). Off unless ticked; the name can be +edited first. """ from urllib.parse import parse_qs, urlsplit @@ -75,6 +80,7 @@ class UrlImportDialog(QDialog): self._single = None # the one entry of a one-song link self._seen: set[str] = set() # ids already listed (a Mix loops) self._just_song = False # "Just This Song" was pressed + self._list_name = "" # what the link's list is called self.cookies_used = None # a browser the probe needed layout = QVBoxLayout(self) @@ -132,6 +138,20 @@ class UrlImportDialog(QDialog): else: self._add.setChecked(True) + # Shown once the link turns out to be a named list. + self._make_row = QHBoxLayout() + self._make = QCheckBox("Make a new playlist of these songs, named") + self._make_name = QLineEdit() + self._make_name.setEnabled(False) + self._make.toggled.connect(self._make_name.setEnabled) + self._make.toggled.connect(self._update_ok) + self._make_name.textChanged.connect(self._update_ok) + self._make_row.addWidget(self._make) + self._make_row.addWidget(self._make_name, 1) + for widget in (self._make, self._make_name): + widget.hide() + layout.addLayout(self._make_row) + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) self._ok = buttons.button(QDialogButtonBox.StandardButton.Ok) @@ -157,6 +177,13 @@ class UrlImportDialog(QDialog): def add_to_playlist(self) -> bool: return self._add.isEnabled() and self._add.isChecked() + def new_playlist_name(self) -> str: + """The name for a new playlist of the imported songs ("" for none).""" + if (not self._picking or not self._list_name or self._just_song + or not self._make.isChecked()): + return "" + return self._make_name.text().strip() + def download_urls(self) -> list[str]: """What to hand yt-dlp: the ticked songs' own pages, the linked song alone, or the link itself — never a list link the user didn't see.""" @@ -193,7 +220,9 @@ class UrlImportDialog(QDialog): if self._picking: n = self._checked_count() self._ok.setText(f"Import {n} Song{'' if n == 1 else 's'}") - self._ok.setEnabled(n > 0) + self._ok.setEnabled(n > 0 and not ( + self._make.isChecked() + and not self._make_name.text().strip())) elif self._probe is not None: self._ok.setEnabled(False) else: @@ -215,6 +244,7 @@ class UrlImportDialog(QDialog): self._entries = [] self._seen = set() self._single = None + self._list_name = "" self._url.setEnabled(False) self._just.setVisible(bool(self._linked)) spotify = self._kind == "spotify" @@ -227,6 +257,7 @@ class UrlImportDialog(QDialog): probe = (SpotifyProbe if spotify else PlaylistProbe)( url, cookies_browser=self._cookies) probe.entry.connect(self._on_entry) + probe.named.connect(self._on_named) probe.finished.connect(self._on_probe_finished) probe.failed.connect(self._on_probe_failed) probe.cookies_used.connect(self._on_cookies_used) @@ -259,11 +290,25 @@ class UrlImportDialog(QDialog): self._add_row(entry) self._status.setText(self._count_text(listing=True)) + def _on_named(self, name: str): + if self.sender() is not self._probe: + return + self._list_name = name + self._make_name.setText(name) + if self._picking: + self._show_make() + + def _show_make(self): + self._make.show() + self._make_name.show() + def _show_picker(self): self._picking = True self._list.show() self._all.show() self._none.show() + if self._list_name: + self._show_make() self.resize(max(self.width(), 560), max(self.height(), 520)) def _add_row(self, entry: dict): diff --git a/lintunes/url_import.py b/lintunes/url_import.py index 5c2b60b..211ba68 100644 --- a/lintunes/url_import.py +++ b/lintunes/url_import.py @@ -71,6 +71,9 @@ ENTRY = "LTENTRY" # a postprocessor starting or finishing (ExtractAudio = the mp3 conversion). HIT = "LTHIT" POSTPROCESS = "LTPP" +# The name of the list an ENTRY came from (empty for a lone song), printed +# beside every entry — "make a new playlist with these songs" is named by it. +LISTNAME = "LTLIST" # What YouTube says when it wants a signed-in browser. Matched on a fragment @@ -189,6 +192,7 @@ def build_probe_command(url: str, a different order every time it's listed.""" return [ "yt-dlp", "--flat-playlist", *_cookie_args(cookies_browser), + "--print", f"{LISTNAME} %(playlist_title|)s", "--print", f"{ENTRY} %(id)s\t%(duration|)s\t%(webpage_url|)s\t%(title)s", "--", url, @@ -232,7 +236,8 @@ def parse_line(line: str): """One line of yt-dlp output → ("start", i, n, id, title) | ("file", path) | ("progress", percent) | ("entry", {id, duration, url, title}) | ("hit", {id, duration, views, url, channel, title}) | - ("postprocess", name, status) | None for everything else.""" + ("postprocess", name, status) | ("list", name) | None for everything + else.""" line = line.rstrip("\r\n") if line.startswith(START + " "): parts = line[len(START) + 1:].split("\t", 3) @@ -253,6 +258,9 @@ def parse_line(line: str): return ("hit", {"id": parts[0], "duration": _duration(parts[1]), "views": _int(parts[2], 0), "url": parts[3], "channel": parts[4], "title": parts[5]}) + if line.startswith(LISTNAME + " "): + name = line[len(LISTNAME) + 1:].strip() + return ("list", name) if name and name != "NA" else None if line.startswith(POSTPROCESS + " "): parts = line[len(POSTPROCESS) + 1:].split() if len(parts) != 2: @@ -479,17 +487,20 @@ class PlaylistProbe(_YtdlpRun): ``entry`` streams each song as yt-dlp finds it ({id, duration, url, title}); a long Mix takes a while to list, and the dialog fills as it - goes. ``finished`` carries how many were found (cancelled or not); - ``failed`` means none were. + goes. ``named`` carries the list's own name, once, if it has one. + ``finished`` carries how many were found (cancelled or not); ``failed`` + means none were. """ entry = pyqtSignal(dict) + named = pyqtSignal(str) finished = pyqtSignal(int) def __init__(self, url: str, parent=None, *, cookies_browser: str | None = None): super().__init__(parent, cookies_browser=cookies_browser) self._url = url + self._named = False def start(self): if not self._busy: @@ -499,7 +510,12 @@ class PlaylistProbe(_YtdlpRun): return build_probe_command(self._url, cookies_browser) def _on_parsed(self, parsed): - if parsed[0] != "entry" or self._cancel.is_set(): + if self._cancel.is_set(): + return False + if parsed[0] == "list" and not self._named: + self._named = True + self.named.emit(parsed[1]) + if parsed[0] != "entry": return False self.entry.emit(parsed[1]) return True @@ -603,6 +619,7 @@ class SpotifyProbe(QObject): ``SpotifyTrack`` under ``"spotify"``. One request, no yt-dlp.""" entry = pyqtSignal(dict) + named = pyqtSignal(str) # the album's or playlist's name finished = pyqtSignal(int) failed = pyqtSignal(str) cookies_used = pyqtSignal(str) # never: Spotify needs no cookies @@ -627,11 +644,13 @@ class SpotifyProbe(QObject): def _run(self): try: kind, source_id = spotify_link.spotify_source(self._url) - _name, tracks = spotify_link.fetch(kind, source_id) + name, tracks = spotify_link.fetch(kind, source_id) except Exception as e: self._busy = False self.failed.emit(str(e)) return + if kind != "track": + self.named.emit(name) count = 0 for track in tracks: if self._cancel.is_set(): diff --git a/tests/test_round109.py b/tests/test_round109.py new file mode 100644 index 0000000..ca82b9f --- /dev/null +++ b/tests/test_round109.py @@ -0,0 +1,219 @@ +"""Round 109 — importing a playlist link can make a playlist of it. + +A YouTube or SoundCloud playlist, or a Spotify album or playlist, has a +name. Once the link turns out to be a list, the import dialog offers +"Make a new playlist of these songs, named [its name]" (off unless ticked, +the name editable). The playlist is made when the first song lands, so a +link that downloads nothing leaves no empty playlist, and the songs go in +in the link's order. + +yt-dlp itself is never run: round 75's fake, taught to print the list name. +""" +import os +import stat +import sys + +import pytest + +from lintunes import spotify_link, url_import +from lintunes.gui.url_import_dialog import UrlImportDialog +from lintunes.library_manager import LibraryManager +from lintunes.models import Library +from lintunes.preferences import Preferences +from lintunes.spotify_link import SpotifyTrack +from tests.test_round75 import FAKE_YTDLP, MIX, _pump + +PLAYLIST = "https://www.youtube.com/playlist?list=PLx" + +# Every listed entry is preceded by the name of its list, as yt-dlp's +# "%(playlist_title|)s" prints it ("" for a lone song). +FAKE_WITH_NAME = FAKE_YTDLP.replace( + ' print(f"LTENTRY {vid}', + ' print("LTLIST " + os.environ.get("FAKE_LISTNAME", ""), ' + 'flush=True)\n print(f"LTENTRY {vid}') + + +@pytest.fixture +def fake(tmp_path, monkeypatch): + assert FAKE_WITH_NAME != FAKE_YTDLP + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + script = bin_dir / "yt-dlp" + script.write_text(FAKE_WITH_NAME.replace("/usr/bin/env python3", + sys.executable)) + script.chmod(script.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_YTDLP_LOG", str(tmp_path / "argv.log")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + monkeypatch.setenv("FAKE_LISTNAME", "Road Trip") + + +def _dialog(qapp, url): + qapp.clipboard().setText(url) + return UrlImportDialog("Adds to the end of “Chill”") + + +# -------------------------------------------------------------------------- +# A. the name, from yt-dlp and from Spotify + + +def test_list_name_lines(): + assert url_import.parse_line("LTLIST Road Trip\n") == ("list", "Road Trip") + assert url_import.parse_line("LTLIST \n") is None # a lone song + assert url_import.parse_line("LTLIST NA\n") is None + assert "LTLIST %(playlist_title|)s" in url_import.build_probe_command( + PLAYLIST) + + +def test_the_probe_names_its_list_once(qapp, fake): + probe = url_import.PlaylistProbe(PLAYLIST) + names, done = [], [] + probe.named.connect(names.append) + probe.finished.connect(done.append) + probe.start() + _pump(qapp, lambda: done) + assert names == ["Road Trip"] + + +@pytest.mark.parametrize("link, named", [ + ("https://open.spotify.com/album/abc", ["Fresh Album"]), + ("https://open.spotify.com/track/abc", []), +]) +def test_spotify_names_albums_and_playlists(qapp, monkeypatch, link, named): + monkeypatch.setattr(spotify_link, "fetch", lambda kind, sid: ( + "Fresh Album", [SpotifyTrack(id="1", title="One", artist="A")])) + probe = url_import.SpotifyProbe(link) + names, done = [], [] + probe.named.connect(names.append) + probe.finished.connect(done.append) + probe.start() + _pump(qapp, lambda: done) + assert names == named + + +# -------------------------------------------------------------------------- +# B. the dialog + + +def test_a_named_list_offers_a_new_playlist(qapp, fake): + dialog = _dialog(qapp, PLAYLIST) + assert not dialog._make.isVisibleTo(dialog) + dialog._on_import() + _pump(qapp, lambda: dialog._probe is None) + assert dialog._make.isVisibleTo(dialog) + assert dialog._make_name.text() == "Road Trip" + assert not dialog._make.isChecked() # off unless ticked + assert dialog.new_playlist_name() == "" + + dialog._make.setChecked(True) + assert dialog.new_playlist_name() == "Road Trip" + dialog._make_name.setText("") + assert not dialog._ok.isEnabled() # a playlist needs a name + dialog._make_name.setText(" Summer ") + assert dialog._ok.isEnabled() + dialog._on_import() + assert dialog.new_playlist_name() == "Summer" + + +def test_no_name_no_offer(qapp, fake, monkeypatch): + monkeypatch.setenv("FAKE_LISTNAME", "") + dialog = _dialog(qapp, PLAYLIST) + dialog._on_import() + _pump(qapp, lambda: dialog._probe is None) + assert dialog._picking + assert not dialog._make.isVisibleTo(dialog) + dialog._make.setChecked(True) + assert dialog.new_playlist_name() == "" + + +def test_just_this_song_makes_no_playlist(qapp, fake): + dialog = _dialog(qapp, MIX) + dialog._on_import() + _pump(qapp, lambda: dialog._probe is None) + dialog._make.setChecked(True) + dialog._just.click() + assert dialog.new_playlist_name() == "" + + +# -------------------------------------------------------------------------- +# C. through the window + + +@pytest.fixture +def window(qapp, tmp_path, fake, monkeypatch): + from lintunes.gui.main_window import MainWindow + library = Library(music_folder=str(tmp_path / "media")) + (tmp_path / "media").mkdir() + manager = LibraryManager(library, tmp_path / "data") + win = MainWindow(manager, Preferences(tmp_path / "data")) + monkeypatch.setattr(win, "_enqueue_identify", lambda tracks: None) + monkeypatch.setattr(win, "_show_batch_review", lambda analysis: None) + yield win + if win._url_batch is not None: + win._url_batch.cancel() + win.close() + + +def _import(window, qapp, monkeypatch, ids, name="Road Trip"): + from lintunes.gui import main_window as mw + chosen = [{"id": i, "title": f"Song {i}", + "url": f"https://www.youtube.com/watch?v={i}"} for i in ids] + + class _Dialog: + cookies_used = None + def __init__(self, *a, **kw): + pass + def exec(self): + return True + def add_to_playlist(self): + return False + def new_playlist_name(self): + return name + def chosen_entries(self): + return chosen + def spotify_tracks(self): + return [] + def download_urls(self): + return [c["url"] for c in chosen] + monkeypatch.setattr(mw, "UrlImportDialog", _Dialog) + window._import_from_url() + worker = window._url_worker + _pump(qapp, lambda: worker.temp_dir is None) + + +def _named(manager, name): + return [p for p in manager.library.playlists.values() if p.name == name] + + +def test_the_new_playlist_holds_every_song_in_order(window, qapp, fake, + mp3_file, monkeypatch): + monkeypatch.setenv("FAKE_YTDLP_AUDIO", str(mp3_file)) + manager = window._manager + _import(window, qapp, monkeypatch, ["ccc", "bad1", "aaa"]) + [playlist] = _named(manager, "Road Trip") + titles = [manager.library.tracks[t].name for t in playlist.track_ids] + assert titles == ["Song ccc [ccc]", "Song aaa [aaa]"] # not the failed one + + manager.undo_stack.undo() # one step takes it all away + assert _named(manager, "Road Trip") == [] + assert len(manager.library.tracks) == 2 # the songs stay imported + + +def test_nothing_downloaded_makes_no_playlist(window, qapp, fake, mp3_file, + monkeypatch): + from lintunes.gui import main_window as mw + warned = [] + monkeypatch.setattr(mw.QMessageBox, "warning", + lambda *a, **kw: warned.append(a)) + monkeypatch.setenv("FAKE_YTDLP_AUDIO", str(mp3_file)) + _import(window, qapp, monkeypatch, ["bad1", "bad2"]) + _pump(qapp, lambda: warned) # "Couldn't import from that link" + assert _named(window._manager, "Road Trip") == [] + + +def test_unticked_makes_no_playlist(window, qapp, fake, mp3_file, + monkeypatch): + monkeypatch.setenv("FAKE_YTDLP_AUDIO", str(mp3_file)) + before = set(window._manager.library.playlists) + _import(window, qapp, monkeypatch, ["aaa", "bbb"], name="") + assert set(window._manager.library.playlists) == before diff --git a/tests/test_round49.py b/tests/test_round49.py index b4fcef4..d71b87b 100644 --- a/tests/test_round49.py +++ b/tests/test_round49.py @@ -347,6 +347,8 @@ class TestWindow: return "https://x.test/list" def add_to_playlist(self): return True + def new_playlist_name(self): + return "" monkeypatch.setattr(mw, "UrlImportDialog", _Dialog) window._show_playlist("a") diff --git a/tests/test_round75.py b/tests/test_round75.py index bbbb901..e5ee88e 100644 --- a/tests/test_round75.py +++ b/tests/test_round75.py @@ -363,6 +363,8 @@ def test_only_the_chosen_songs_download(window, qapp, fake, mp3_file, return MIX def add_to_playlist(self): return False + def new_playlist_name(self): + return "" def chosen_entries(self): return chosen def spotify_tracks(self): @@ -409,6 +411,8 @@ def test_one_song_gets_no_progress_window(window, qapp, fake, mp3_file, return "https://www.youtube.com/watch?v=aaa" def add_to_playlist(self): return False + def new_playlist_name(self): + return "" def chosen_entries(self): return [] def spotify_tracks(self): diff --git a/tests/test_round76.py b/tests/test_round76.py index 9bc054b..6d5742c 100644 --- a/tests/test_round76.py +++ b/tests/test_round76.py @@ -347,6 +347,8 @@ def test_spotify_songs_import_tagged_and_go_to_identify(window, qapp, fake, return True def add_to_playlist(self): return False + def new_playlist_name(self): + return "" def chosen_entries(self): return chosen def spotify_tracks(self):