Mulberry/mulberry/playlist.py
Claude a0b83cd4e3
Mulberry 1.2.1: CD fixes, web links, lyrics priority, portable playlists
- Fix crash after CD ripping (running QThread was destroyed)
- Audio CDs always use mpv (bundled on Windows) even when Qt is the main engine
  — fixes 'several tracks failed to play' on Windows
- YouTube/SoundCloud/Bandcamp links resolved with bundled yt-dlp
- Lyrics: Auto prefers synced from any source (LRCLIB > NetEase > embedded >
  local); explicit choices no longer fall back; NetEase uses cloudsearch
  (search/get/web is encrypted outside China)
- Playlist export uses absolute paths by default; import remaps paths from
  other machines/OSes via the library
- HTTPS: certificate fallback (system bundles, certifi) for packaged builds;
  cover search shows real errors, more fallbacks, Last.fm covers
- MusicBrainz: retry without album, cleaner album artist, async genre
- CI self-tests require bundled libmpv (Windows), yt-dlp and TLS certs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-10 00:45:03 -05:00

722 lines
26 KiB
Python

"""Playlist models (multi-tab), queue, shuffle/repeat logic and undo."""
from __future__ import annotations
import json
import os
import random
import time
import urllib.parse
from PyQt6.QtCore import (QAbstractTableModel, QMimeData, QModelIndex, QObject, Qt, QTimer,
QUrl, pyqtSignal)
from PyQt6.QtGui import QFont, QUndoCommand, QUndoStack
from . import library as L
from .config import fmt_time, settings
from .song import Song
ROWS_MIME = "application/x-mulberry-rows"
SONGS_MIME = "application/x-mulberry-songs"
# key, header, default visible, width
COLUMNS = [
("track", "#", True, 44),
("title", "Title", True, 240),
("artist", "Artist", True, 170),
("album", "Album", True, 220),
("albumartist", "Album artist", False, 150),
("year", "Year", False, 56),
("genre", "Genre", False, 110),
("composer", "Composer", False, 120),
("disc", "Disc", False, 44),
("length", "Length", True, 64),
("bitrate", "Bitrate", False, 70),
("samplerate", "Sample rate", False, 86),
("bitdepth", "Bit depth", False, 64),
("filetype", "File type", True, 84),
("filesize", "Size", False, 74),
("playcount", "Plays", False, 54),
("skipcount", "Skips", False, 54),
("lastplayed", "Last played", False, 120),
("rating", "Rating", False, 96),
("added", "Date added", False, 110),
("source", "Source", True, 64),
("url", "Path", False, 300),
]
COL_KEYS = [c[0] for c in COLUMNS]
COL = {k: i for i, k in enumerate(COL_KEYS)}
def _size(n):
for unit in ("B", "KB", "MB", "GB"):
if n < 1024:
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} TB"
def _date(ts):
return time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) if ts else ""
class _Snapshot(QUndoCommand):
def __init__(self, model, before, after, text):
super().__init__(text)
self.model, self.before, self.after = model, before, after
self._first = True
def redo(self):
if self._first:
self._first = False
return
self.model._set_songs(list(self.after))
def undo(self):
self.model._set_songs(list(self.before))
class PlaylistModel(QAbstractTableModel):
changed = pyqtSignal() # content changed (for persistence/status)
def __init__(self, name="Playlist", songs=None, pid=-1, favorite=False):
super().__init__()
self.name = name
self.pid = pid
self.favorite = favorite
self.songs: list[Song] = list(songs or [])
self.current_song: Song | None = None
self.playing = False
self.undo = QUndoStack(self)
self.undo.setUndoLimit(40)
self.queue_pos: dict[int, int] = {} # id(song) -> queue position (1-based)
self._shuffle: list[Song] = []
self.filter_text = ""
self.dirty = pid < 0
self.changed.connect(lambda: setattr(self, "dirty", True))
# ---------------------------------------------------------- Qt model api
def rowCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.songs)
def columnCount(self, parent=QModelIndex()):
return len(COLUMNS)
def headerData(self, section, orient, role=Qt.ItemDataRole.DisplayRole):
if orient == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
return COLUMNS[section][1]
return None
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
s = self.songs[index.row()]
key = COL_KEYS[index.column()]
if role == Qt.ItemDataRole.DisplayRole:
return self.display(s, key)
if role == Qt.ItemDataRole.UserRole:
return s
if role == Qt.ItemDataRole.TextAlignmentRole:
if key in ("track", "disc", "year", "length", "bitrate", "samplerate", "bitdepth",
"filesize", "playcount", "skipcount"):
return int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
return int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
if role == Qt.ItemDataRole.FontRole and s is self.current_song:
f = QFont()
f.setWeight(QFont.Weight.DemiBold)
return f
if role == Qt.ItemDataRole.ToolTipRole and key in ("title", "url"):
return s.url
return None
def display(self, s: Song, key: str):
if key == "title":
t = s.display_title()
q = self.queue_pos.get(id(s))
return f"({q}) {t}" if q else t
if key == "track":
return str(s.track) if s.track else ""
if key == "disc":
return str(s.disc) if s.disc else ""
if key == "year":
return str(s.year) if s.year else ""
if key == "length":
d = s.duration()
return fmt_time(d) if d else ""
if key == "bitrate":
return f"{s.bitrate} kbps" if s.bitrate else ""
if key == "samplerate":
return f"{s.samplerate / 1000:g} kHz" if s.samplerate else ""
if key == "bitdepth":
return f"{s.bitdepth}-bit" if s.bitdepth else ""
if key == "filesize":
return _size(s.filesize) if s.filesize else ""
if key in ("lastplayed", "added"):
return _date(getattr(s, key))
if key in ("playcount", "skipcount"):
v = getattr(s, key)
return str(v) if v else ""
if key == "rating":
return ""
if key == "source":
return ""
if key == "url":
return s.path if s.is_local else s.url
return getattr(s, key, "")
def flags(self, index):
f = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsDropEnabled
if index.isValid():
f |= Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsDragEnabled
return f
def supportedDropActions(self):
return Qt.DropAction.MoveAction | Qt.DropAction.CopyAction
def mimeTypes(self):
return [ROWS_MIME, SONGS_MIME, "text/uri-list"]
def mimeData(self, indexes):
rows = sorted({i.row() for i in indexes})
md = QMimeData()
md.setData(ROWS_MIME, json.dumps({"model": id(self), "rows": rows}).encode())
urls = [QUrl.fromLocalFile(self.songs[r].path) if self.songs[r].is_local else QUrl(self.songs[r].url)
for r in rows]
md.setUrls(urls)
return md
def canDropMimeData(self, data, action, row, column, parent):
return any(data.hasFormat(m) for m in (ROWS_MIME, SONGS_MIME, "text/uri-list"))
def dropMimeData(self, data, action, row, column, parent):
if row < 0:
row = parent.row() if parent.isValid() else len(self.songs)
if data.hasFormat(ROWS_MIME):
info = json.loads(bytes(data.data(ROWS_MIME)).decode())
if info.get("model") == id(self):
self.move_rows(info["rows"], row)
return True
if data.hasFormat(SONGS_MIME):
dicts = json.loads(bytes(data.data(SONGS_MIME)).decode())
self.insert_songs([Song.from_dict(d) for d in dicts], row)
return True
if data.hasUrls():
paths, streams = [], []
for u in data.urls():
if u.isLocalFile():
paths.append(u.toLocalFile())
else:
streams.append(Song(url=u.toString()))
if streams:
self.insert_songs(streams, row)
if paths:
PlaylistManager.instance.add_paths(paths, self, row)
return True
return False
# ---------------------------------------------------------- mutation
def _set_songs(self, songs):
self.beginResetModel()
self.songs = songs
self._shuffle = []
self.endResetModel()
self.changed.emit()
def _commit(self, before, text):
self.undo.push(_Snapshot(self, before, list(self.songs), text))
self._shuffle = []
self.changed.emit()
def insert_songs(self, songs: list[Song], row: int = -1):
if not songs:
return
if row < 0 or row > len(self.songs):
row = len(self.songs)
before = list(self.songs)
self.beginInsertRows(QModelIndex(), row, row + len(songs) - 1)
self.songs[row:row] = songs
self.endInsertRows()
self._commit(before, f"Add {len(songs)} songs")
def remove_rows(self, rows):
rows = sorted(set(rows), reverse=True)
if not rows:
return
before = list(self.songs)
for r in rows:
if 0 <= r < len(self.songs):
self.beginRemoveRows(QModelIndex(), r, r)
del self.songs[r]
self.endRemoveRows()
self._commit(before, f"Remove {len(rows)} songs")
def move_rows(self, rows, dest):
rows = sorted(set(rows))
before = list(self.songs)
moving = [self.songs[r] for r in rows]
dest -= sum(1 for r in rows if r < dest)
rest = [s for i, s in enumerate(self.songs) if i not in set(rows)]
rest[dest:dest] = moving
self.beginResetModel()
self.songs = rest
self.endResetModel()
self._commit(before, "Move songs")
def clear(self):
if not self.songs:
return
before = list(self.songs)
self.beginResetModel()
self.songs = []
self.endResetModel()
self._commit(before, "Clear playlist")
def replace(self, songs):
before = list(self.songs)
self.beginResetModel()
self.songs = list(songs)
self.endResetModel()
self._commit(before, "Replace playlist")
def sort(self, column, order=Qt.SortOrder.AscendingOrder):
key = COL_KEYS[column]
before = list(self.songs)
def k(s: Song):
if key in ("title",):
return s.display_title().lower()
if key in ("album",):
return (s.album.lower(), s.disc, s.track)
if key in ("artist", "albumartist"):
return (getattr(s, key).lower(), s.album.lower(), s.disc, s.track)
if key == "length":
return s.duration()
if key == "url":
return s.url.lower()
if key == "source":
return s.source
v = getattr(s, key, "")
return v.lower() if isinstance(v, str) else (v or 0)
self.layoutAboutToBeChanged.emit()
self.songs.sort(key=k, reverse=order == Qt.SortOrder.DescendingOrder)
self.layoutChanged.emit()
self._commit(before, "Sort")
def shuffle_items(self):
before = list(self.songs)
self.beginResetModel()
random.shuffle(self.songs)
self.endResetModel()
self._commit(before, "Shuffle playlist")
def remove_duplicates(self):
seen, keep = set(), []
for s in self.songs:
k = s.key()
if k not in seen:
seen.add(k)
keep.append(s)
if len(keep) != len(self.songs):
self.replace(keep)
def remove_unavailable(self):
keep = [s for s in self.songs if not s.is_local or os.path.exists(s.path)]
if len(keep) != len(self.songs):
self.replace(keep)
def refresh_song(self, song: Song):
for i, s in enumerate(self.songs):
if s is song or (song.id >= 0 and s.id == song.id) or (s.url == song.url and s.begin == song.begin):
if s is not song:
self.songs[i] = song
if self.current_song is s:
self.current_song = song
self.dataChanged.emit(self.index(i, 0), self.index(i, len(COLUMNS) - 1))
# ---------------------------------------------------------- current / order
def row_of(self, song: Song | None) -> int:
if song is None:
return -1
for i, s in enumerate(self.songs):
if s is song:
return i
return -1
def current_row(self) -> int:
return self.row_of(self.current_song)
def set_current(self, song: Song | None):
old = self.current_row()
self.current_song = song
new = self.current_row()
for r in (old, new):
if r >= 0:
self.dataChanged.emit(self.index(r, 0), self.index(r, len(COLUMNS) - 1))
def _ensure_shuffle(self):
if len(self._shuffle) != len(self.songs) or set(map(id, self._shuffle)) != set(map(id, self.songs)):
order = list(self.songs)
random.shuffle(order)
if self.current_song in order:
order.remove(self.current_song)
order.insert(0, self.current_song)
self._shuffle = order
def next_song(self, shuffle: bool, repeat: str) -> Song | None:
if not self.songs:
return None
if shuffle:
self._ensure_shuffle()
seq = self._shuffle
else:
seq = self.songs
cur = self.current_song
idx = -1
if cur is not None:
for i, s in enumerate(seq):
if s is cur:
idx = i
break
nxt = idx + 1
if nxt >= len(seq):
if repeat == "playlist":
if shuffle:
self._shuffle = []
self._ensure_shuffle()
seq = self._shuffle
nxt = 0
else:
return None
return seq[nxt]
def prev_song(self, shuffle: bool) -> Song | None:
if not self.songs:
return None
seq = self._shuffle if shuffle and self._shuffle else self.songs
cur = self.current_song
for i, s in enumerate(seq):
if s is cur:
return seq[i - 1] if i > 0 else seq[-1]
return seq[0]
def total_length(self) -> float:
return sum(s.duration() for s in self.songs)
class PlaylistManager(QObject):
instance: "PlaylistManager" = None
added = pyqtSignal(object)
removed = pyqtSignal(object)
renamed = pyqtSignal(object)
current_changed = pyqtSignal(object) # visible playlist
active_changed = pyqtSignal(object) # playing playlist
queue_changed = pyqtSignal()
summary_changed = pyqtSignal()
busy = pyqtSignal(bool)
def __init__(self):
super().__init__()
PlaylistManager.instance = self
self.playlists: list[PlaylistModel] = []
self.current: PlaylistModel | None = None
self.active: PlaylistModel | None = None
self.queue: list[tuple[PlaylistModel, Song]] = []
self.shuffle = settings.get("playback/shuffle")
self.repeat = settings.get("playback/repeat")
self.stop_after: Song | None = None
self._save_timer = QTimer(self, singleShot=True, interval=1500)
self._save_timer.timeout.connect(self.save_all)
# ---------------------------------------------------------- persistence
@staticmethod
def _refresh_from_library(songs: list[Song]) -> list[Song]:
"""Library songs in saved playlists get fresh tags/stats from the DB."""
ids = [s.id for s in songs if s.id >= 0 and not s.begin]
if not ids:
return songs
fresh = {}
for i in range(0, len(ids), 900):
chunk = ids[i:i + 900]
for r in L.library.query(f"SELECT * FROM songs WHERE id IN ({','.join('?' * len(chunk))})", chunk):
fresh[r["id"]] = L.row_to_song(r)
return [fresh.get(s.id, s) if s.id >= 0 and not s.begin else s for s in songs]
def restore(self):
rows = L.library.load_playlists()
for r in rows:
if not r["is_open"]:
continue
try:
songs = self._refresh_from_library([Song.from_dict(d) for d in json.loads(r["items"] or "[]")])
except (ValueError, TypeError):
songs = []
pl = self._make(r["name"], songs, r["id"], bool(r["favorite"]))
if 0 <= r["current"] < len(songs):
pl.current_song = songs[r["current"]]
if not self.playlists:
self.new_playlist("Playlist")
active_id = L.library.kv("active_playlist")
cur_id = L.library.kv("current_playlist")
self.active = next((p for p in self.playlists if str(p.pid) == active_id), self.playlists[0])
self.set_current(next((p for p in self.playlists if str(p.pid) == cur_id), self.playlists[0]))
def schedule_save(self):
self._save_timer.start()
def save_all(self):
for i, p in enumerate(self.playlists):
if p.dirty or p.pid < 0:
p.pid = L.library.save_playlist(p.pid, p.name, p.songs, ui_order=i, is_open=1,
current=p.current_row(), favorite=int(p.favorite))
p.dirty = False
else:
L.library.update_playlist_meta(p.pid, p.name, i, p.current_row(), int(p.favorite))
if self.active:
L.library.set_kv("active_playlist", self.active.pid)
if self.current:
L.library.set_kv("current_playlist", self.current.pid)
# ---------------------------------------------------------- playlists
def _make(self, name, songs=None, pid=-1, favorite=False) -> PlaylistModel:
pl = PlaylistModel(name, songs, pid, favorite)
pl.changed.connect(self.schedule_save)
pl.changed.connect(self.summary_changed)
self.playlists.append(pl)
self.added.emit(pl)
return pl
def new_playlist(self, name=None, songs=None, activate=True) -> PlaylistModel:
if not name:
n = len(self.playlists) + 1
name = f"Playlist {n}"
pl = self._make(name, songs)
pl.pid = L.library.save_playlist(None, pl.name, pl.songs, ui_order=len(self.playlists))
if activate:
self.set_current(pl)
return pl
def close_playlist(self, pl: PlaylistModel, keep_saved: bool | None = None):
if pl not in self.playlists:
return
if keep_saved is None:
keep_saved = pl.favorite
if keep_saved:
L.library.save_playlist(pl.pid, pl.name, pl.songs, is_open=0, favorite=1,
current=pl.current_row())
else:
L.library.delete_playlist(pl.pid)
idx = self.playlists.index(pl)
self.playlists.remove(pl)
self.queue = [q for q in self.queue if q[0] is not pl]
self.removed.emit(pl)
if not self.playlists:
self.new_playlist("Playlist")
if self.current is pl:
self.set_current(self.playlists[min(idx, len(self.playlists) - 1)])
if self.active is pl:
self.active = self.current
self.schedule_save()
def reopen_saved(self, pid: int):
for p in self.playlists:
if p.pid == pid:
self.set_current(p)
return p
r = L.library.query("SELECT * FROM playlists WHERE id=?", (pid,))
if not r:
return None
r = r[0]
songs = self._refresh_from_library([Song.from_dict(d) for d in json.loads(r["items"] or "[]")])
pl = self._make(r["name"], songs, r["id"], bool(r["favorite"]))
if 0 <= (r["current"] or -1) < len(songs):
pl.current_song = songs[r["current"]]
self.set_current(pl)
self.schedule_save()
return pl
def rename(self, pl, name):
pl.name = name
self.renamed.emit(pl)
self.schedule_save()
def set_current(self, pl):
if pl is self.current:
return
self.current = pl
self.current_changed.emit(pl)
self.summary_changed.emit()
def set_active(self, pl):
if pl is not self.active:
if self.active:
self.active.playing = False
self.active = pl
self.active_changed.emit(pl)
def move_playlist(self, frm, to):
pl = self.playlists.pop(frm)
self.playlists.insert(to, pl)
self.schedule_save()
# ---------------------------------------------------------- adding
def add_paths(self, paths, pl=None, row=-1, play=False, replace=False):
pl = pl or self.current
self.busy.emit(True)
def work():
from .playlistio import import_playlist
out = []
plain = []
for p in paths:
ext = os.path.splitext(p)[1].lower().lstrip(".")
if ext in PLAYLIST_EXTS_SET and os.path.isfile(p):
if plain:
out += L.scan_paths(plain)
plain = []
out += enrich(import_playlist(p))
else:
plain.append(p)
if plain:
out += L.scan_paths(plain)
return out
def done(songs):
self.busy.emit(False)
if pl not in self.playlists:
return
if replace:
pl.replace(songs)
else:
pl.insert_songs(songs, row)
if play and songs:
from .player import Player
self.set_current(pl)
Player.instance.play_song(pl, songs[0])
from .config import run_async
run_async(work, on_done=done, on_error=lambda e: self.busy.emit(False))
def add_songs(self, songs, pl=None, play=False, replace=False, row=-1):
pl = pl or self.current
if replace:
pl.replace(songs)
else:
pl.insert_songs(songs, row)
if play and songs:
from .player import Player
Player.instance.play_song(pl, songs[0])
# ---------------------------------------------------------- queue
def enqueue(self, pl, songs, front=False):
items = [(pl, s) for s in songs]
self.queue = items + self.queue if front else self.queue + items
self._update_queue_marks()
def dequeue(self, song):
self.queue = [q for q in self.queue if q[1] is not song]
self._update_queue_marks()
def clear_queue(self):
self.queue = []
self._update_queue_marks()
def _update_queue_marks(self):
for p in self.playlists:
p.queue_pos = {}
for i, (p, s) in enumerate(self.queue, 1):
p.queue_pos[id(s)] = i
for p in self.playlists:
if p.songs:
p.dataChanged.emit(p.index(0, COL["title"]), p.index(len(p.songs) - 1, COL["title"]))
self.queue_changed.emit()
# ---------------------------------------------------------- navigation
def peek_next(self, auto=True):
"""Return (playlist, song) that would play next, without consuming the queue."""
pl = self.active or self.current
if pl is None:
return None
cur = pl.current_song
if auto and self.stop_after is not None and cur is self.stop_after:
return None
if auto and self.repeat == "track" and cur is not None:
return pl, cur
for qpl, s in self.queue:
if qpl in self.playlists and qpl.row_of(s) >= 0:
return qpl, s
nxt = pl.next_song(self.shuffle, self.repeat)
return (pl, nxt) if nxt else None
def take_next(self, auto=True):
res = self.peek_next(auto)
if res and self.queue and self.queue[0][1] is res[1]:
self.queue.pop(0)
self._update_queue_marks()
elif res:
# skip stale queue entries
while self.queue and (self.queue[0][0] not in self.playlists or self.queue[0][0].row_of(self.queue[0][1]) < 0):
self.queue.pop(0)
if auto and self.stop_after is not None and res is None:
self.stop_after = None
return res
def prev(self):
pl = self.active or self.current
if not pl:
return None
s = pl.prev_song(self.shuffle)
return (pl, s) if s else None
def set_shuffle(self, on: bool):
self.shuffle = on
settings.set("playback/shuffle", on)
for p in self.playlists:
p._shuffle = []
def set_repeat(self, mode: str):
self.repeat = mode
settings.set("playback/repeat", mode)
PLAYLIST_EXTS_SET = {"m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"}
def _remap_missing(songs: list[Song]) -> None:
"""Playlists made on another computer/OS (different home folder, drive
letters, / vs \\): find each missing file in the library by its last two
path parts (album folder + file name) and point the entry there."""
missing = [s for s in songs if s.is_local and not os.path.exists(s.path)]
if not missing or L.library is None:
return
for s in missing:
parts = [p for p in s.path.replace("\\", "/").split("/") if p]
if not parts:
continue
tails = ["/".join(parts[-2:]), parts[-1]] if len(parts) > 1 else [parts[-1]]
for tail in tails:
rows = L.library.query(
"SELECT url FROM songs WHERE lower(replace(substr(url, -?), '\\', '/')) = lower(?) LIMIT 2",
(len(tail) + 1, "/" + tail))
if len(rows) == 1:
s.url = rows[0]["url"]
break
def enrich(songs: list[Song]) -> list[Song]:
"""Replace bare playlist entries with full tag info (library or file)."""
_remap_missing(songs)
plain = [s for s in songs if s.is_local and not s.begin and not s.end]
if not plain:
return songs
found = {s.url: s for s in L.scan_paths([s.path for s in plain if os.path.exists(s.path)])}
out = []
for s in songs:
if s.is_local and not s.begin and not s.end and s.path in found:
out.append(found[s.path])
else:
out.append(s)
return out
def url_to_path(u: str) -> str:
if u.startswith("file://"):
return urllib.parse.unquote(urllib.parse.urlparse(u).path)
return u