v0.98.0: playlist Get Info (right-click): created, songs changed, last played on any machine, the link it was imported from, and a cover any playlist can have

This commit is contained in:
2026-11-17 22:47:25 -08:00
parent f21c31940f
commit 2964158281
12 changed files with 465 additions and 5 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.97.0"
__version__ = "0.98.0"
+58 -1
View File
@@ -52,6 +52,7 @@ from lintunes.gui.url_import_progress import UrlImportProgress
from lintunes.gui.shazam_import import ShazamImportWindow, ShazamPreviewDialog
from lintunes.gui import web_upload_progress as web_progress
from lintunes.gui.info_dialog import InfoDialog
from lintunes.gui.playlist_info_dialog import PlaylistInfoDialog
from lintunes.gui.music_folder_dialog import MusicFolderDialog
from lintunes.gui.preferences_dialog import PreferencesDialog
from lintunes.gui.track_table import format_total_time
@@ -115,6 +116,23 @@ class _ResetRelay(QObject):
_CURRENT_TARGET = object()
def _as_jpeg_or_png(data: bytes) -> bytes:
"""A cover as playlist_art keeps it: JPEG or PNG as given, anything Qt
can read (WebP, GIF, BMP…) re-encoded as PNG."""
if playlist_art.image_suffix(data):
return data
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
from PyQt6.QtGui import QImage
image = QImage()
if not image.loadFromData(data):
raise ValueError("not an image")
out = QByteArray()
buffer = QBuffer(out)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, "PNG")
return bytes(out)
class MainWindow(QMainWindow):
# A playlist's cover finished downloading (emitted off the GUI thread).
_playlist_art_saved = pyqtSignal(str)
@@ -310,6 +328,7 @@ class MainWindow(QMainWindow):
# downloads nothing leaves no empty playlist behind).
self._url_new_name = ""
self._url_new_cover = ""
self._url_source = ""
self._url_new_pid = ""
self._url_rows = None # a Spotify/Apple list, in order
self._url_owned = 0
@@ -353,6 +372,7 @@ class MainWindow(QMainWindow):
self._sidebar.playlist_selected.connect(self._show_playlist)
self._sidebar.tree.export_requested.connect(self._export_playlist)
self._sidebar.tree.dj_prepare_requested.connect(self._prepare_playlist_for_dj)
self._sidebar.tree.info_requested.connect(self._playlist_info)
self._sidebar.art.download_art_requested.connect(
lambda tid: self._download_album_art([tid]))
self._content.currentChanged.connect(self._update_totals)
@@ -1571,6 +1591,38 @@ class MainWindow(QMainWindow):
self._update_now_playing_icon()
self._update_playlist_art()
def _playlist_info(self, pid: str):
"""The playlist's Get Info; OK renames it and sets its cover."""
playlist = self._manager.library.playlists.get(pid)
if playlist is None:
return
data_dir = self._manager.data_dir
path = playlist_art.find(data_dir, pid)
try:
art = path.read_bytes() if path is not None else None
except OSError:
art = None
tracks = [self._manager.library.tracks[t] for t in playlist.track_ids
if t in self._manager.library.tracks]
dialog = PlaylistInfoDialog(
playlist, tracks, art=art,
last_played=self._manager.playlist_last_played(pid), parent=self)
if not dialog.exec():
return
if dialog.new_name():
self._manager.rename_playlist(pid, dialog.new_name())
change = dialog.art_change()
if change is not None:
try:
if change:
playlist_art.save(data_dir, pid, _as_jpeg_or_png(change))
else:
playlist_art.remove(data_dir, pid)
except (OSError, ValueError) as e:
QMessageBox.warning(self, "Playlist Art",
f"Couldn't save the cover:\n\n{e}")
self._update_playlist_art()
def _update_playlist_art(self, *_):
"""Hand the art panel the shown playlist's cover (it shows it only
while nothing is playing)."""
@@ -1979,6 +2031,7 @@ class MainWindow(QMainWindow):
self._url_inserted = 0
self._url_new_name = dialog.new_playlist_name()
self._url_new_cover = dialog.new_playlist_cover()
self._url_source = dialog.url()
self._url_new_pid = ""
self._url_imported = 0
self._url_identify = True
@@ -2163,7 +2216,8 @@ class MainWindow(QMainWindow):
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)
playlist = self._manager.create_playlist(
self._url_new_name, source_url=self._url_source)
self._url_new_pid = playlist.persistent_id
self._url_new_name = ""
if self._url_new_cover: # shown by the art panel
@@ -3301,6 +3355,9 @@ class MainWindow(QMainWindow):
else:
self._listen_context = self._now_playing_context
self.setWindowTitle(f"{track.name} — {track.artist} · LinTunes")
if self._now_playing_context.startswith("playlist:"):
self._manager.record_playlist_play(
self._now_playing_context.split(":", 1)[1])
self._update_now_playing_icon()
def _on_listen_ended(self, key, track, started, heard_ms, how):
+167
View File
@@ -0,0 +1,167 @@
"""A playlist's Get Info (Round 130; the sidebar's right-click › Get Info).
What it shows: the name (editable), what kind of playlist it is, its songs
and their total length, when LinTunes made it (``Playlist.date_created`` —
playlists from before Round 130 and from the iTunes import don't know), when
its songs last changed (``date_modified``), when a song was last started
from it on any machine (``storage/playlist_plays.py``), and the link it was
imported from (``source_url``). And its cover, which any playlist can have:
paste, drop or choose an image, or remove it.
Passive, like the song Get Info: nothing is written until OK, and then by
the caller (``MainWindow._playlist_info``), which reads ``new_name()`` and
``art_change()``.
"""
from datetime import datetime
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtGui import QDesktopServices
from PyQt6.QtWidgets import (
QApplication, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QLabel,
QLineEdit, QPushButton, QVBoxLayout,
)
from lintunes.gui.info_dialog import ArtSquare
from lintunes.models.playlist import PlaylistType
ART_SIZE = 200
_KINDS = {PlaylistType.REGULAR: "Playlist", PlaylistType.FOLDER: "Folder",
PlaylistType.SMART: "Smart Playlist",
PlaylistType.SYSTEM: "Built-in Playlist"}
def when_text(stamp: str | None) -> str:
"""An ISO stamp as local date and time, "—" for none."""
if not stamp:
return "—"
try:
when = datetime.fromisoformat(stamp)
except ValueError:
return stamp
if when.tzinfo is not None:
when = when.astimezone()
return when.strftime("%-d %B %Y, %-I:%M %p")
def length_text(ms: int) -> str:
minutes = round(ms / 60000)
hours, minutes = divmod(minutes, 60)
if hours:
return f"{hours} hr {minutes} min"
return f"{minutes} min"
class PlaylistInfoDialog(QDialog):
def __init__(self, playlist, tracks, *, art: bytes | None = None,
last_played: str | None = None, parent=None):
super().__init__(parent)
self.setWindowTitle(f"{playlist.name} — Info")
self._playlist = playlist
self._art_change = None # None: unchanged; b"": removed
layout = QVBoxLayout(self)
top = QHBoxLayout()
layout.addLayout(top)
art_column = QVBoxLayout()
self._art = ArtSquare()
self._art.setFixedSize(ART_SIZE, ART_SIZE)
self._art.set_artwork(art, "no artwork\n\npaste or drop an image")
self._art.art_staged.connect(self._on_art_staged)
self._art.hint_changed.connect(self._show_hint)
art_column.addWidget(self._art)
buttons = QHBoxLayout()
choose = QPushButton("Choose…")
choose.clicked.connect(self._art.choose_file)
paste = QPushButton("Paste")
paste.clicked.connect(self._art.paste_from_clipboard)
self._remove = QPushButton("Remove")
self._remove.clicked.connect(self._on_remove)
self._remove.setEnabled(bool(art))
for button in (choose, paste, self._remove):
buttons.addWidget(button)
art_column.addLayout(buttons)
self._hint = QLabel("")
self._hint.setEnabled(False)
self._hint.setWordWrap(True)
self._hint.setMaximumWidth(ART_SIZE)
art_column.addWidget(self._hint)
art_column.addStretch(1)
top.addLayout(art_column)
form = QFormLayout()
top.addLayout(form, 1)
self._name = QLineEdit(playlist.name)
self._name.setMinimumWidth(340)
form.addRow("Name:", self._name)
form.addRow("Kind:", self._label(_KINDS.get(playlist.playlist_type,
"Playlist")))
if playlist.playlist_type != PlaylistType.FOLDER:
total = sum(t.total_time or 0 for t in tracks)
n = len(tracks)
form.addRow("Songs:", self._label(
f"{n} song{'' if n == 1 else 's'}"
+ (f", {length_text(total)}" if total else "")))
form.addRow("Created:", self._label(when_text(playlist.date_created)))
form.addRow("Songs changed:",
self._label(when_text(playlist.date_modified)))
form.addRow("Last played:", self._label(when_text(last_played)))
source = playlist.source_url
if source:
row = QHBoxLayout()
self._source = QLineEdit(source)
self._source.setReadOnly(True)
self._source.setCursorPosition(0)
copy = QPushButton("Copy")
copy.clicked.connect(
lambda: QApplication.clipboard().setText(source))
open_link = QPushButton("Open")
open_link.clicked.connect(
lambda: QDesktopServices.openUrl(QUrl(source)))
row.addWidget(self._source, 1)
row.addWidget(copy)
row.addWidget(open_link)
form.addRow("Imported from:", row)
else:
form.addRow("Imported from:", self._label("—"))
self._source_label = source
box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel)
box.accepted.connect(self.accept)
box.rejected.connect(self.reject)
layout.addWidget(box)
@staticmethod
def _label(text: str) -> QLabel:
label = QLabel(text)
label.setTextInteractionFlags(
Qt.TextInteractionFlag.TextSelectableByMouse
| Qt.TextInteractionFlag.LinksAccessibleByMouse)
return label
def _show_hint(self, text: str):
self._hint.setText(text)
def _on_art_staged(self, data: bytes, _mime: str):
self._art_change = data
self._remove.setEnabled(True)
def _on_remove(self):
self._art_change = b""
self._art.set_artwork(None, "no artwork\n\npaste or drop an image")
self._remove.setEnabled(False)
self._hint.setText("The cover goes when you click OK")
# ---- what the caller reads ----
def new_name(self) -> str:
"""The name to rename to, or "" to leave it."""
name = self._name.text().strip()
return name if name and name != self._playlist.name else ""
def art_change(self) -> bytes | None:
"""None: leave the cover; b"": remove it; else the new image."""
return self._art_change
+5 -1
View File
@@ -552,6 +552,7 @@ class PlaylistTree(QTreeWidget):
playlist_selected = pyqtSignal(str) # persistent_id
export_requested = pyqtSignal(str) # persistent_id
dj_prepare_requested = pyqtSignal(str) # persistent_id
info_requested = pyqtSignal(str) # persistent_id: Get Info
# A friend's playlist I follow (key "cassette:<token>:<their pid>").
followed_selected = pyqtSignal(str)
unfollow_requested = pyqtSignal(str)
@@ -939,9 +940,10 @@ class PlaylistTree(QTreeWidget):
new_playlist = menu.addAction("New Playlist")
new_smart = menu.addAction("New Smart Playlist")
new_folder = menu.addAction("New Playlist Folder")
rename = delete = edit_smart = export = dj_prepare = None
rename = delete = edit_smart = export = dj_prepare = info = None
if kind in ("playlist", "folder", "smart"):
menu.addSeparator()
info = menu.addAction("Get Info")
if kind == "smart":
edit_smart = menu.addAction("Edit Smart Playlist…")
rename = menu.addAction("Rename")
@@ -962,6 +964,8 @@ class PlaylistTree(QTreeWidget):
self.edit_smart_playlist(pid)
elif chosen is new_folder:
self.create_folder_interactive(parent_pid)
elif info is not None and chosen is info:
self.info_requested.emit(pid)
elif export is not None and chosen is export:
self.export_requested.emit(pid)
elif dj_prepare is not None and chosen is dj_prepare:
+27 -1
View File
@@ -124,12 +124,17 @@ class LibraryManager(QObject):
# ---- playlist structure ----
def create_playlist(self, name: str, parent_pid: str = "") -> Playlist:
def create_playlist(self, name: str, parent_pid: str = "",
source_url: str = "") -> Playlist:
"""``source_url``: the link it was imported from (Get Info shows
it)."""
playlist = Playlist(
name=name,
persistent_id=self.new_persistent_id(),
parent_persistent_id=parent_pid,
playlist_type=PlaylistType.REGULAR,
date_created=_utc_now_iso(),
source_url=source_url,
)
self._insert_playlists([playlist])
self.undo_stack.push(Command(
@@ -144,6 +149,7 @@ class LibraryManager(QObject):
persistent_id=self.new_persistent_id(),
parent_persistent_id=parent_pid,
playlist_type=PlaylistType.FOLDER,
date_created=_utc_now_iso(),
)
self._insert_playlists([folder])
self.undo_stack.push(Command(
@@ -169,6 +175,7 @@ class LibraryManager(QObject):
parent_persistent_id=parent_pid,
playlist_type=PlaylistType.SMART,
smart_criteria=criteria,
date_created=_utc_now_iso(),
)
self._insert_playlists([playlist])
self.recompute_smart_playlist(playlist.persistent_id, force=True)
@@ -198,6 +205,25 @@ class LibraryManager(QObject):
self.recompute_smart_playlist(pid, force=True)
self.playlists_changed.emit()
# ---- when playlists were played (playlist Get Info) ----
@property
def playlist_plays(self):
if getattr(self, "_playlist_plays", None) is None:
from lintunes.storage.playlist_plays import PlaylistPlays
self._playlist_plays = PlaylistPlays(self.data_dir,
self.play_journal.machine)
return self._playlist_plays
def record_playlist_play(self, pid: str):
"""A song started from ``pid``: stamp it in this machine's own
file (never the playlist's JSON — see playlist_plays.py)."""
if pid in self.library.playlists:
self.playlist_plays.record(pid)
def playlist_last_played(self, pid: str) -> str | None:
return self.playlist_plays.last_played(pid)
def rename_playlist(self, pid: str, name: str):
playlist = self.library.playlists.get(pid)
if playlist and name and playlist.name != name:
+11
View File
@@ -66,6 +66,11 @@ class Playlist:
# retention window. Without it a merge is a union and a song removed on one
# machine comes back from the other forever; see lintunes/tombstones.py.
track_events: dict = field(default_factory=dict)
# Round 130 (playlist Get Info): when LinTunes made it (absent on older
# and imported playlists), and the link it was imported from, if any.
# Both are set once, at creation, so they can't conflict.
date_created: Optional[str] = None
source_url: str = ""
# Set only for SMART playlists. Membership (track_ids) is derived from this
# by the LibraryManager; for imported playlists track_ids also doubles as a
# snapshot fallback when the criteria couldn't be fully parsed.
@@ -103,6 +108,10 @@ class Playlist:
d["parent_persistent_id"] = self.parent_persistent_id
if self.date_modified:
d["date_modified"] = self.date_modified
if self.date_created:
d["date_created"] = self.date_created
if self.source_url:
d["source_url"] = self.source_url
if self.track_events:
# JSON object keys are strings; track ids are ints everywhere else.
d["track_events"] = {str(tid): event
@@ -126,6 +135,8 @@ class Playlist:
settings=PlaylistSettings.from_dict(d.get("settings", {})),
is_system=d.get("is_system", False),
date_modified=d.get("date_modified"),
date_created=d.get("date_created"),
source_url=d.get("source_url") or "",
track_events={int(tid): list(event)
for tid, event in (d.get("track_events") or {}).items()},
smart_criteria=smart_criteria,
+9 -1
View File
@@ -1,7 +1,8 @@
"""A playlist's own cover image (Round 130).
Spotify and Apple Music playlists (and albums) have a cover, and a playlist
made from one of their links in Import from URL keeps it. The sidebar art panel
made from one of their links in Import from URL keeps it. Any playlist's can
be set or removed in its Get Info (``gui/playlist_info_dialog.py``). The sidebar art panel
shows it while nothing is playing and that playlist is shown
(``SidebarArt.set_playlist_art``).
@@ -71,6 +72,13 @@ def save(data_dir: Path, pid: str, data: bytes) -> Path:
return path
def remove(data_dir: Path, pid: str):
"""Take the playlist's cover away (whatever its format)."""
folder = Path(data_dir) / DIRNAME
for suffix in _SUFFIXES:
(folder / f"{pid}{suffix}").unlink(missing_ok=True)
def download(url: str) -> bytes:
resp = requests.get(url, headers={"User-Agent": USER_AGENT},
timeout=TIMEOUT, stream=True)
+82
View File
@@ -0,0 +1,82 @@
"""When each playlist was last played (Round 130, playlist Get Info).
Not in the playlist's JSON: that file would change on every song from both
machines, the conflict Round 42 took away from live smart playlists. So the
play journals' rule (``play_journal.py``): each machine keeps its own
``<data_dir>/playlist_plays/<machine id>.json`` (``{pid: ISO time}``), only
it ever writes that file, and "last played" is the newest stamp across all
of them. "Played" means a song started from that playlist.
A stamp is written at most once a minute per playlist, so a skip through
twenty songs is one write.
"""
import json
import logging
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
log = logging.getLogger(__name__)
DIRNAME = "playlist_plays"
MIN_GAP = timedelta(minutes=1)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _parse(stamp):
try:
when = datetime.fromisoformat(stamp)
except (TypeError, ValueError):
return None
return when if when.tzinfo else when.replace(tzinfo=timezone.utc)
class PlaylistPlays:
def __init__(self, data_dir: Path, machine: str):
self.folder = Path(data_dir) / DIRNAME
self.path = self.folder / f"{machine}.json"
self._mine = self._read(self.path)
@staticmethod
def _read(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def record(self, pid: str, when: str | None = None) -> bool:
"""This machine played ``pid`` now. True when it was written."""
when = when or _now_iso()
new, old = _parse(when), _parse(self._mine.get(pid))
if new is None or (old is not None and new - old < MIN_GAP):
return False
self._mine[pid] = when
try:
self.folder.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_name(self.path.name + ".tmp")
tmp.write_text(json.dumps(self._mine, indent=1, sort_keys=True),
encoding="utf-8")
os.replace(tmp, self.path)
except OSError as e:
log.warning("couldn't save playlist plays: %s", e)
return False
return True
def last_played(self, pid: str) -> str | None:
"""The newest stamp for ``pid`` across every machine, or None."""
best, best_at = None, None
paths = [self.path]
try:
paths += [p for p in self.folder.glob("*.json") if p != self.path]
except OSError:
pass
for path in paths:
data = self._mine if path == self.path else self._read(path)
when = _parse(data.get(pid))
if when is not None and (best_at is None or when > best_at):
best, best_at = data.get(pid), when
return best