From e6b22f971a8cbe3d4251371f2dbfc1b8f710a8ba Mon Sep 17 00:00:00 2001 From: npeter83 Date: Mon, 6 Jul 2026 22:14:40 +0200 Subject: [PATCH 1/5] feat(plex): playlist bulk add/remove + group-aware playlist cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add POST /playlists/{id}/items/bulk and /items/remove-bulk so a whole season or show can be added/removed in one call (input order preserved, duplicates skipped). Extend GET /playlists with contains_group= returning per-playlist group_in + a top-level group_size for the bulk add-to-playlist dialog. Include the show's rating_key (show_id) on playlist episode cards so the client can group a playlist by show/season. --- backend/app/routes/plex.py | 101 ++++++++++++++++++++++++++++++++++--- 1 file changed, 95 insertions(+), 6 deletions(-) diff --git a/backend/app/routes/plex.py b/backend/app/routes/plex.py index 0fd000b..9da6260 100644 --- a/backend/app/routes/plex.py +++ b/backend/app/routes/plex.py @@ -186,11 +186,15 @@ def _episode_card(e: PlexItem, st: PlexState | None) -> dict: } -def _leaf_card(it: PlexItem, st: PlexState | None, show_title: str | None = None) -> dict: - """A playable-leaf card (movie or episode). Used by playlists, which can mix both kinds.""" +def _leaf_card( + it: PlexItem, st: PlexState | None, show_title: str | None = None, show_rk: str | None = None +) -> dict: + """A playable-leaf card (movie or episode). Used by playlists, which can mix both kinds. + `show_rk` (the show's rating_key) lets the client group a playlist's episodes by show/season.""" if it.kind == "episode": card = _episode_card(it, st) card["show_title"] = show_title + card["show_id"] = show_rk return card return _movie_card(it, st) @@ -639,15 +643,23 @@ def _playlist_item_query(db: Session, pid: int): @router.get("/playlists") def playlists( contains: str | None = None, + contains_group: str | None = None, user: User = Depends(current_user), db: Session = Depends(get_db), ) -> dict: """The current user's playlists (newest-touched first), each with an item count + a cover thumb. - `contains`=an item rating_key adds `has_item` per playlist (for the 'add to playlist' dialog).""" + `contains`=an item rating_key adds `has_item` per playlist (for the single 'add to playlist' dialog). + `contains_group`=a comma-separated list of rating_keys adds `group_in` per playlist (how many of the + group it already holds) + a top-level `group_size`, for the 'add a whole season/show' dialog.""" contains_id = None if contains: row = db.query(PlexItem.id).filter_by(rating_key=str(contains)).first() contains_id = row[0] if row else None + group_ids: set[int] | None = None + if contains_group is not None: + rks = [s for s in (contains_group or "").split(",") if s] + rows = db.query(PlexItem.id).filter(PlexItem.rating_key.in_(rks or [""])).all() + group_ids = {r[0] for r in rows} out = [] for pl in db.query(PlexPlaylist).filter_by(user_id=user.id).order_by(PlexPlaylist.updated_at.desc()): count = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pl.id).scalar() or 0 @@ -658,8 +670,18 @@ def playlists( db.query(PlexPlaylistItem.id).filter_by(playlist_id=pl.id, item_id=contains_id).first() is not None ) + if group_ids is not None: + card["group_in"] = ( + db.query(func.count(PlexPlaylistItem.id)) + .filter(PlexPlaylistItem.playlist_id == pl.id, PlexPlaylistItem.item_id.in_(group_ids or [0])) + .scalar() + or 0 + ) out.append(card) - return {"playlists": out} + resp: dict = {"playlists": out} + if group_ids is not None: + resp["group_size"] = len(group_ids) + return resp @router.post("/playlists") @@ -694,10 +716,18 @@ def playlist_detail(pid: int, user: User = Depends(current_user), db: Session = ) } shows = { - sh.id: sh.title + sh.id: sh for sh in db.query(PlexShow).filter(PlexShow.id.in_([it.show_id for it in items if it.show_id] or [0])) } - cards = [_leaf_card(it, states.get(it.id), shows.get(it.show_id)) for it in items] + cards = [ + _leaf_card( + it, + states.get(it.id), + shows[it.show_id].title if it.show_id in shows else None, + shows[it.show_id].rating_key if it.show_id in shows else None, + ) + for it in items + ] return {"id": pl.id, "title": pl.title, "items": cards} @@ -748,6 +778,65 @@ def playlist_remove_item(pid: int, item_rating_key: str, user: User = Depends(cu return {"ok": True} +def _items_by_rks(db: Session, rks: list) -> list[PlexItem]: + """Resolve rating_keys to PlexItems, preserving the input order (drops unknown keys).""" + order = [str(k) for k in rks if str(k)] + if not order: + return [] + by_rk = {it.rating_key: it for it in db.query(PlexItem).filter(PlexItem.rating_key.in_(order))} + seen: set[str] = set() + out: list[PlexItem] = [] + for rk in order: + it = by_rk.get(rk) + if it is not None and rk not in seen: + seen.add(rk) + out.append(it) + return out + + +@router.post("/playlists/{pid}/items/bulk") +def playlist_add_bulk(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict: + """Append many items at once (a whole season/show). Already-present items are skipped; the input + order is preserved for the newly-added ones. Returns how many were added + the new total.""" + pl = _own_playlist_or_404(db, pid, user) + items = _items_by_rks(db, payload.get("item_rating_keys") or []) + existing = {row[0] for row in db.query(PlexPlaylistItem.item_id).filter_by(playlist_id=pid)} + pos = int(db.query(func.coalesce(func.max(PlexPlaylistItem.position), -1)).filter_by(playlist_id=pid).scalar()) + added = 0 + for it in items: + if it.id in existing: + continue + pos += 1 + db.add(PlexPlaylistItem(playlist_id=pid, item_id=it.id, position=pos)) + existing.add(it.id) + added += 1 + if added: + pl.updated_at = datetime.now(timezone.utc) + db.commit() + total = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pid).scalar() or 0 + return {"added": added, "item_count": total} + + +@router.post("/playlists/{pid}/items/remove-bulk") +def playlist_remove_bulk(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict: + """Remove many items at once (a whole season/show, or a multi-select). Returns how many were + removed + the new total.""" + pl = _own_playlist_or_404(db, pid, user) + ids = [it.id for it in _items_by_rks(db, payload.get("item_rating_keys") or [])] + removed = 0 + if ids: + removed = ( + db.query(PlexPlaylistItem) + .filter(PlexPlaylistItem.playlist_id == pid, PlexPlaylistItem.item_id.in_(ids)) + .delete(synchronize_session=False) + ) + if removed: + pl.updated_at = datetime.now(timezone.utc) + db.commit() + total = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pid).scalar() or 0 + return {"removed": removed, "item_count": total} + + @router.put("/playlists/{pid}/order") def reorder_playlist(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict: """Set the playlist order from an explicit list of item rating_keys (0-based positions).""" From 2ef22982bb1622e701d0b635540ea19c6ec1020b Mon Sep 17 00:00:00 2001 From: npeter83 Date: Mon, 6 Jul 2026 22:14:56 +0200 Subject: [PATCH 2/5] feat(plex): grouped collapsible playlist view + drag-and-drop + bulk add MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Playlist view now groups a run of episodes from the same show into a collapsible season/show block so a whole series doesn't sprawl into an endless flat list; movies stay standalone (larger poster card in the accordion). Two per-account layouts — Accordion and Tree — persisted via LS.plexPlaylistLayout; show groups start collapsed. Reorder is drag & drop (@dnd-kit): a show block moves as one unit, episodes reorder within their show, keyboard-draggable via KeyboardSensor. Remove works per item, per season, or per whole show. The add-to-playlist dialog is generalised to a single leaf or a whole group (tri-state none/some/all with an in/size count); the show page gains add buttons for an episode, a season, and the whole show. i18n en/hu/de. --- frontend/src/components/PlexBrowse.tsx | 93 +++- frontend/src/components/PlexInfo.tsx | 5 +- frontend/src/components/PlexPlaylistAdd.tsx | 90 ++-- frontend/src/components/PlexPlaylistView.tsx | 488 ++++++++++++++++--- frontend/src/i18n/locales/de/plex.json | 15 +- frontend/src/i18n/locales/en/plex.json | 15 +- frontend/src/i18n/locales/hu/plex.json | 15 +- frontend/src/lib/api.ts | 20 +- frontend/src/lib/storage.ts | 1 + 9 files changed, 603 insertions(+), 139 deletions(-) diff --git a/frontend/src/components/PlexBrowse.tsx b/frontend/src/components/PlexBrowse.tsx index 756321c..ab80ddb 100644 --- a/frontend/src/components/PlexBrowse.tsx +++ b/frontend/src/components/PlexBrowse.tsx @@ -1,10 +1,11 @@ -import { lazy, Suspense, useEffect, useLayoutEffect, useRef, type CSSProperties } from "react"; +import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react"; import { useTranslation } from "react-i18next"; import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, CheckCircle2, Info, Play } from "lucide-react"; +import { ArrowLeft, CheckCircle2, Info, ListPlus, Play } from "lucide-react"; import { api, type PlexCard, type PlexFilters, type PlexPerson } from "../lib/api"; import { useDebounced } from "../lib/useDebounced"; import { useHistorySubview } from "../lib/history"; +import PlexPlaylistAdd, { type PlexAddTarget } from "./PlexPlaylistAdd"; // Lazy: the rich player (pulls in hls.js) loads only when something is first played. const PlexPlayer = lazy(() => import("./PlexPlayer")); @@ -461,6 +462,9 @@ function PlexShowView({ const { t } = useTranslation(); const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) }); const d = q.data; + // "Add to playlist" dialog target (single episode / whole season / whole show); null = closed. + const [addTarget, setAddTarget] = useState(null); + const allEpisodeKeys = (d?.seasons ?? []).flatMap((se) => se.episodes.map((e) => e.id)); return (
@@ -488,41 +492,74 @@ function PlexShowView({ {d.show.summary && (

{d.show.summary}

)} + {allEpisodeKeys.length > 0 && ( + + )}
{d.seasons.map((se) => (
-

{se.title}

+
+

{se.title}

+ {se.episodes.length > 0 && ( + + )} +
{se.episodes.map((ep) => { const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched"; return ( - +
+
+ {ep.episode_number}. + {ep.title} +
+ {ep.summary && ( +
{ep.summary}
+ )} +
{dur(ep.duration_seconds)}
+
+ + +
); })}
@@ -530,6 +567,8 @@ function PlexShowView({ ))} )} + + {addTarget && setAddTarget(null)} />} ); } diff --git a/frontend/src/components/PlexInfo.tsx b/frontend/src/components/PlexInfo.tsx index dd1ca07..248a8e8 100644 --- a/frontend/src/components/PlexInfo.tsx +++ b/frontend/src/components/PlexInfo.tsx @@ -526,7 +526,10 @@ export default function PlexInfo({ /> )} {playlistOpen && ( - setPlaylistOpen(false)} /> + setPlaylistOpen(false)} + /> )} ); diff --git a/frontend/src/components/PlexPlaylistAdd.tsx b/frontend/src/components/PlexPlaylistAdd.tsx index e78dc3e..fc6c629 100644 --- a/frontend/src/components/PlexPlaylistAdd.tsx +++ b/frontend/src/components/PlexPlaylistAdd.tsx @@ -1,42 +1,60 @@ import { useState } from "react"; import { useTranslation } from "react-i18next"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { Check, Plus } from "lucide-react"; +import { Check, Minus, Plus } from "lucide-react"; import { api, type PlexPlaylist } from "../lib/api"; import Modal from "./Modal"; -// "Add this title to a playlist" dialog — per-user (every user has their own playlists), opened from -// the movie info page. Lists my playlists with an in/out toggle (seeded from the backend's has_item) -// and a field to create a new one seeded with this title. Playlists are personal (no admin gate). -export default function PlexPlaylistAdd({ - item, - onClose, -}: { - item: { id: string; title: string }; - onClose: () => void; -}) { +// What we're adding: a single leaf (movie/episode) or a whole group (a season or an entire show, as a +// set of episode rating_keys). Groups get a tri-state (none / some / all) per playlist. +export type PlexAddTarget = + | { kind: "single"; ratingKey: string; title: string } + | { kind: "group"; ratingKeys: string[]; title: string }; + +// "Add to playlist" dialog — per-user (every user has their own playlists). Opened from the movie info +// page (single) and the show page (single episode / whole season / whole show). Lists my playlists with +// an in/out (or partial) state and a field to create a new one seeded with the target. +export default function PlexPlaylistAdd({ target, onClose }: { target: PlexAddTarget; onClose: () => void }) { const { t } = useTranslation(); const qc = useQueryClient(); const [newName, setNewName] = useState(""); const [busy, setBusy] = useState(false); - const [override, setOverride] = useState>(new Map()); // optimistic toggle state + // Optimistic per-playlist in-count override (0..size), so a toggle reflects instantly. + const [override, setOverride] = useState>(new Map()); + + const isGroup = target.kind === "group"; + const size = isGroup ? new Set(target.ratingKeys).size : 1; const listQ = useQuery({ - queryKey: ["plex-playlists", "contains", item.id], - queryFn: () => api.plexPlaylists(item.id), + queryKey: isGroup + ? ["plex-playlists", "group", target.ratingKeys] + : ["plex-playlists", "contains", target.ratingKey], + queryFn: () => + isGroup ? api.plexPlaylists(undefined, target.ratingKeys) : api.plexPlaylists(target.ratingKey), }); const playlists = listQ.data?.playlists ?? []; - const isIn = (p: PlexPlaylist) => (override.has(p.id) ? override.get(p.id)! : !!p.has_item); const refresh = () => qc.invalidateQueries({ queryKey: ["plex-playlists"] }); + // How many of the target a playlist currently holds (0..size). + function inCount(p: PlexPlaylist): number { + const o = override.get(p.id); + if (o !== undefined) return o; + return isGroup ? p.group_in ?? 0 : p.has_item ? 1 : 0; + } + async function toggle(p: PlexPlaylist) { if (busy) return; setBusy(true); - const cur = isIn(p); + const allIn = inCount(p) >= size; try { - if (cur) await api.plexPlaylistRemoveItem(p.id, item.id); - else await api.plexPlaylistAddItem(p.id, item.id); - setOverride((m) => new Map(m).set(p.id, !cur)); + if (isGroup) { + if (allIn) await api.plexPlaylistRemoveBulk(p.id, target.ratingKeys); + else await api.plexPlaylistAddBulk(p.id, target.ratingKeys); + } else { + if (allIn) await api.plexPlaylistRemoveItem(p.id, target.ratingKey); + else await api.plexPlaylistAddItem(p.id, target.ratingKey); + } + setOverride((m) => new Map(m).set(p.id, allIn ? 0 : size)); refresh(); } finally { setBusy(false); @@ -48,9 +66,15 @@ export default function PlexPlaylistAdd({ if (!title || busy) return; setBusy(true); try { - const pl = await api.plexCreatePlaylist(title, item.id); + if (isGroup) { + const pl = await api.plexCreatePlaylist(title); + await api.plexPlaylistAddBulk(pl.id, target.ratingKeys); + setOverride((m) => new Map(m).set(pl.id, size)); + } else { + const pl = await api.plexCreatePlaylist(title, target.ratingKey); + setOverride((m) => new Map(m).set(pl.id, 1)); + } setNewName(""); - setOverride((m) => new Map(m).set(pl.id, true)); refresh(); } finally { setBusy(false); @@ -58,7 +82,7 @@ export default function PlexPlaylistAdd({ } return ( - +
{t("plex.playlistAdd.none")}

) : ( playlists.map((p) => { - const inIt = isIn(p); + const n = inCount(p); + const all = n >= size; + const partial = n > 0 && n < size; return ( ); }) diff --git a/frontend/src/components/PlexPlaylistView.tsx b/frontend/src/components/PlexPlaylistView.tsx index 86083d3..f04ea08 100644 --- a/frontend/src/components/PlexPlaylistView.tsx +++ b/frontend/src/components/PlexPlaylistView.tsx @@ -1,12 +1,300 @@ -import { useState } from "react"; +import { useEffect, useMemo, useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, ChevronDown, ChevronUp, Pencil, Play, Trash2, X } from "lucide-react"; +import { + DndContext, + KeyboardSensor, + PointerSensor, + closestCenter, + useSensor, + useSensors, + type DragEndEvent, +} from "@dnd-kit/core"; +import { + SortableContext, + arrayMove, + sortableKeyboardCoordinates, + useSortable, + verticalListSortingStrategy, +} from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import { + ArrowLeft, + ChevronDown, + ChevronRight, + GripVertical, + ListTree, + Pencil, + Play, + Rows3, + Trash2, + X, +} from "lucide-react"; import { api, type PlexCard } from "../lib/api"; +import { getAccountRaw, LS, setAccountRaw } from "../lib/storage"; import { useConfirm } from "./ConfirmProvider"; -// A playlist's ordered items — reorder (up/down), remove, rename, delete, and "Play all" (which opens -// the player with the whole ordered list as its queue). Rendered as a PlexBrowse subview. +// A playlist's items, grouped for readability: movies stay standalone, while a run of episodes from the +// same show collapses into a season/show group so a whole series doesn't sprawl into an endless flat +// list. Reorder is drag & drop (a whole show-group moves as one block; episodes reorder within their +// show). Two layouts — Accordion (A) and Tree (C) — are a per-account preference. Rendered as a +// PlexBrowse subview; "Play all" opens the player with the whole ordered list as its queue. + +type Layout = "accordion" | "tree"; +type Season = { key: string; number: number | null; items: PlexCard[] }; +type Block = + | { kind: "movie"; id: string; item: PlexCard } + | { kind: "show"; id: string; showKey: string; title: string; items: PlexCard[]; seasons: Season[] }; + +function buildSeasons(items: PlexCard[]): Season[] { + const map = new Map(); + for (const it of items) { + const num = it.season_number ?? null; + const key = String(num ?? "?"); + let s = map.get(key); + if (!s) { + s = { key, number: num, items: [] }; + map.set(key, s); + } + s.items.push(it); + } + return [...map.values()]; +} + +// Turn the flat ordered list into blocks: contiguous episodes of one show group together (then split +// into seasons for display); everything else (movies) is its own block. +function buildBlocks(items: PlexCard[]): Block[] { + const blocks: Block[] = []; + for (const it of items) { + if (it.type === "episode") { + const showKey = it.show_id || it.show_title || "?"; + const last = blocks[blocks.length - 1]; + if (last && last.kind === "show" && last.showKey === showKey) { + last.items.push(it); + } else { + blocks.push({ + kind: "show", + id: `show:${showKey}`, + showKey, + title: it.show_title || it.title, + items: [it], + seasons: [], + }); + } + } else { + blocks.push({ kind: "movie", id: it.id, item: it }); + } + } + for (const b of blocks) if (b.kind === "show") b.seasons = buildSeasons(b.items); + return blocks; +} + +const flatten = (blocks: Block[]): PlexCard[] => + blocks.flatMap((b) => (b.kind === "movie" ? [b.item] : b.items)); + +// Callbacks + shared state passed down to the module-scope block/row components. +type Ctx = { + layout: Layout; + busy: boolean; + expandedShows: Set; + collapsedSeasons: Set; + toggleShow: (k: string) => void; + toggleSeason: (k: string) => void; + onPlay: (rk: string) => void; + onRemove: (keys: string[]) => void; +}; + +function Poster({ src, className }: { src: string; className: string }) { + return ( +
+ +
+ ); +} + +function DragHandle(props: Record) { + return ( + + ); +} + +function EpisodeRow({ ep, ctx, dense }: { ep: PlexCard; ctx: Ctx; dense: boolean }) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: ep.id, + disabled: ctx.busy, + }); + const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 }; + const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched"; + return ( +
+ + {ep.episode_number} + + +
+ ); +} + +function MovieRow({ item, ctx }: { item: PlexCard; ctx: Ctx }) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: item.id, + disabled: ctx.busy, + }); + const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 }; + const dense = ctx.layout === "tree"; + return ( +
+ + + +
+ ); +} + +function ShowGroup({ block, ctx }: { block: Extract; ctx: Ctx }) { + const { t } = useTranslation(); + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: block.id, + disabled: ctx.busy, + }); + const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 }; + const open = ctx.expandedShows.has(block.showKey); + const dense = ctx.layout === "tree"; + const seasonLabel = (s: Season) => + s.number != null ? t("plex.playlist.season", { n: s.number }) : t("plex.playlist.seasonUnknown"); + + return ( +
+ {/* Group header — drag moves the whole show; chevron collapses; X removes the whole show. */} +
+ + + {!dense && ( + + )} + + +
+ + {open && ( +
+ i.id)} strategy={verticalListSortingStrategy}> + {block.seasons.map((s) => { + const sKey = `${block.showKey}:${s.key}`; + const sOpen = !dense || !ctx.collapsedSeasons.has(sKey); + return ( +
+
+ {dense && ( + + )} + + {seasonLabel(s)} · {s.items.length} + + +
+ {sOpen && ( +
+ {s.items.map((ep) => ( + + ))} +
+ )} +
+ ); + })} +
+
+ )} +
+ ); +} + export default function PlexPlaylistView({ playlistId, onBack, @@ -22,38 +310,52 @@ export default function PlexPlaylistView({ const [renaming, setRenaming] = useState(false); const [name, setName] = useState(""); const [busy, setBusy] = useState(false); + const [layout, setLayout] = useState(() => + getAccountRaw(LS.plexPlaylistLayout) === "tree" ? "tree" : "accordion", + ); + useEffect(() => { + setAccountRaw(LS.plexPlaylistLayout, layout); + }, [layout]); + // Show groups start collapsed (compact headers) so a long series doesn't force endless scrolling; + // seasons start expanded once their show is opened. Both are just local view state. + const [expandedShows, setExpandedShows] = useState>(new Set()); + const [collapsedSeasons, setCollapsedSeasons] = useState>(new Set()); const q = useQuery({ queryKey: ["plex-playlist", playlistId], queryFn: () => api.plexPlaylist(playlistId) }); - const items: PlexCard[] = q.data?.items ?? []; - const order = items.map((i) => i.id); + // Local optimistic copy so drag/remove are instant; re-synced whenever the query returns. + const [items, setItems] = useState([]); + useEffect(() => { + if (q.data) setItems(q.data.items); + }, [q.data]); + const blocks = useMemo(() => buildBlocks(items), [items]); + const order = useMemo(() => items.map((i) => i.id), [items]); + const invalidate = () => { qc.invalidateQueries({ queryKey: ["plex-playlist", playlistId] }); qc.invalidateQueries({ queryKey: ["plex-playlists"] }); }; - async function move(idx: number, dir: -1 | 1) { - const to = idx + dir; - if (busy || to < 0 || to >= order.length) return; + function commit(next: PlexCard[]) { + setItems(next); + api + .plexReorderPlaylist(playlistId, next.map((i) => i.id)) + .then(() => qc.invalidateQueries({ queryKey: ["plex-playlists"] })); + } + + async function onRemove(keys: string[]) { + if (busy || !keys.length) return; setBusy(true); - const next = [...order]; - [next[idx], next[to]] = [next[to], next[idx]]; + const set = new Set(keys); + setItems((prev) => prev.filter((i) => !set.has(i.id))); try { - await api.plexReorderPlaylist(playlistId, next); - invalidate(); - } finally { - setBusy(false); - } - } - async function remove(itemRk: string) { - if (busy) return; - setBusy(true); - try { - await api.plexPlaylistRemoveItem(playlistId, itemRk); + if (keys.length === 1) await api.plexPlaylistRemoveItem(playlistId, keys[0]); + else await api.plexPlaylistRemoveBulk(playlistId, keys); invalidate(); } finally { setBusy(false); } } + async function rename() { const title = name.trim(); if (!title) return; @@ -69,8 +371,79 @@ export default function PlexPlaylistView({ onBack(); } + const toggleShow = (k: string) => + setExpandedShows((s) => { + const n = new Set(s); + n.has(k) ? n.delete(k) : n.add(k); + return n; + }); + const toggleSeason = (k: string) => + setCollapsedSeasons((s) => { + const n = new Set(s); + n.has(k) ? n.delete(k) : n.add(k); + return n; + }); + + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 4 } }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + + function onDragEnd(e: DragEndEvent) { + const { active, over } = e; + if (!over || active.id === over.id) return; + const aId = String(active.id); + const oId = String(over.id); + const blockIds = new Set(blocks.map((b) => b.id)); + if (blockIds.has(aId)) { + // Moving a whole block (movie or show). Resolve the drop target to a block. + let oBlockId = oId; + if (!blockIds.has(oId)) { + const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === oId)); + if (!b) return; + oBlockId = b.id; + } + const from = blocks.findIndex((b) => b.id === aId); + const to = blocks.findIndex((b) => b.id === oBlockId); + if (from < 0 || to < 0) return; + commit(flatten(arrayMove(blocks, from, to))); + } else { + // Moving an episode — only within its own show block. + const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === aId)); + if (!b || b.kind !== "show" || !b.items.some((it) => it.id === oId)) return; + const from = b.items.findIndex((it) => it.id === aId); + const to = b.items.findIndex((it) => it.id === oId); + commit(flatten(blocks.map((bl) => (bl.id === b.id ? { ...bl, items: arrayMove(b.items, from, to) } : bl)))); + } + } + + const ctx: Ctx = { + layout, + busy, + expandedShows, + collapsedSeasons, + toggleShow, + toggleSeason, + onPlay: (rk) => onPlay(rk, order), + onRemove, + }; + + const LayoutBtn = ({ v, icon, label }: { v: Layout; icon: ReactNode; label: string }) => ( + + ); + return ( -
+
-
- - - -
- - ))} - + + b.id)} strategy={verticalListSortingStrategy}> +
+ {blocks.map((b) => + b.kind === "movie" ? ( + + ) : ( + + ), + )} +
+
+
)}
diff --git a/frontend/src/i18n/locales/de/plex.json b/frontend/src/i18n/locales/de/plex.json index ddee937..91489ca 100644 --- a/frontend/src/i18n/locales/de/plex.json +++ b/frontend/src/i18n/locales/de/plex.json @@ -158,7 +158,8 @@ "newPlaceholder": "Name der neuen Playlist…", "create": "Erstellen", "none": "Noch keine Playlists. Erstelle oben eine.", - "count": "{{count}} Titel" + "count": "{{count}} Titel", + "groupProgress": "{{in}} / {{size}}" }, "playlist": { "section": "Playlists", @@ -172,6 +173,16 @@ "empty": "Diese Playlist ist leer. Füge Titel über deren Infoseite hinzu.", "up": "Nach oben", "down": "Nach unten", - "remove": "Entfernen" + "remove": "Entfernen", + "layoutAccordion": "Akkordeon-Ansicht", + "layoutTree": "Baum-Ansicht", + "removeShow": "Ganze Serie entfernen", + "removeSeason": "Ganze Staffel entfernen", + "episodes": "{{count}} Folgen", + "season": "Staffel {{n}}", + "seasonUnknown": "Folgen", + "addShow": "Ganze Serie zu einer Playlist", + "addSeason": "Staffel zu einer Playlist", + "addEpisode": "Folge zu einer Playlist" } } diff --git a/frontend/src/i18n/locales/en/plex.json b/frontend/src/i18n/locales/en/plex.json index 7984589..8601de1 100644 --- a/frontend/src/i18n/locales/en/plex.json +++ b/frontend/src/i18n/locales/en/plex.json @@ -158,7 +158,8 @@ "newPlaceholder": "New playlist name…", "create": "Create", "none": "No playlists yet. Create one above.", - "count": "{{count}} items" + "count": "{{count}} items", + "groupProgress": "{{in}} / {{size}}" }, "playlist": { "section": "Playlists", @@ -172,6 +173,16 @@ "empty": "This playlist is empty. Add titles from their info page.", "up": "Move up", "down": "Move down", - "remove": "Remove" + "remove": "Remove", + "layoutAccordion": "Accordion view", + "layoutTree": "Tree view", + "removeShow": "Remove whole show", + "removeSeason": "Remove whole season", + "episodes": "{{count}} episodes", + "season": "Season {{n}}", + "seasonUnknown": "Episodes", + "addShow": "Add whole show to a playlist", + "addSeason": "Add season to a playlist", + "addEpisode": "Add episode to a playlist" } } diff --git a/frontend/src/i18n/locales/hu/plex.json b/frontend/src/i18n/locales/hu/plex.json index bbb7350..a753fbe 100644 --- a/frontend/src/i18n/locales/hu/plex.json +++ b/frontend/src/i18n/locales/hu/plex.json @@ -158,7 +158,8 @@ "newPlaceholder": "Új lista neve…", "create": "Létrehozás", "none": "Még nincs lista. Hozz létre egyet fent.", - "count": "{{count}} elem" + "count": "{{count}} elem", + "groupProgress": "{{in}} / {{size}}" }, "playlist": { "section": "Lejátszási listák", @@ -172,6 +173,16 @@ "empty": "Ez a lista üres. Adj hozzá címeket az info-oldalukról.", "up": "Fel", "down": "Le", - "remove": "Eltávolítás" + "remove": "Eltávolítás", + "layoutAccordion": "Harmonika nézet", + "layoutTree": "Fa nézet", + "removeShow": "Egész sorozat eltávolítása", + "removeSeason": "Egész évad eltávolítása", + "episodes": "{{count}} epizód", + "season": "{{n}}. évad", + "seasonUnknown": "Epizódok", + "addShow": "Egész sorozat listához adása", + "addSeason": "Évad listához adása", + "addEpisode": "Epizód listához adása" } } diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index c49ebd0..feca869 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -653,6 +653,7 @@ export interface PlexCard { season_number?: number | null; // episode episode_number?: number | null; // episode show_title?: string | null; // episode (in a mixed playlist) + show_id?: string | null; // episode: the show's rating_key (for grouping a playlist by show/season) summary?: string | null; // episode } export interface PlexBrowseResult { @@ -737,6 +738,7 @@ export interface PlexPlaylist { item_count: number; thumb?: string | null; has_item?: boolean; // only when the list was fetched with ?contains= + group_in?: number; // only when fetched with ?contains_group=: how many of the group it holds } export interface PlexPlaylistDetail { id: number; @@ -1178,11 +1180,25 @@ export const api = { plexSetCollectionEditable: (rk: string, editable: boolean): Promise => req(`/api/plex/collections/${encodeURIComponent(rk)}/editable`, { method: "POST", body: JSON.stringify({ editable }) }), // --- Playlists (Siftlode-native, per-user, ordered) --- - plexPlaylists: (contains?: string): Promise<{ playlists: PlexPlaylist[] }> => - req(`/api/plex/playlists${contains ? `?contains=${encodeURIComponent(contains)}` : ""}`), + // `contains`=single rating_key → per-playlist has_item; `containsGroup`=a set of rating_keys (a whole + // season/show) → per-playlist group_in + a top-level group_size (for the bulk add-to-playlist dialog). + plexPlaylists: ( + contains?: string, + containsGroup?: string[], + ): Promise<{ playlists: PlexPlaylist[]; group_size?: number }> => { + const p = new URLSearchParams(); + if (contains) p.set("contains", contains); + if (containsGroup) p.set("contains_group", containsGroup.join(",")); + const qs = p.toString(); + return req(`/api/plex/playlists${qs ? `?${qs}` : ""}`); + }, plexPlaylist: (id: number): Promise => req(`/api/plex/playlists/${id}`), plexCreatePlaylist: (title: string, item_rating_key?: string): Promise => req(`/api/plex/playlists`, { method: "POST", body: JSON.stringify({ title, item_rating_key }) }), + plexPlaylistAddBulk: (id: number, itemRks: string[]): Promise<{ added: number; item_count: number }> => + req(`/api/plex/playlists/${id}/items/bulk`, { method: "POST", body: JSON.stringify({ item_rating_keys: itemRks }) }), + plexPlaylistRemoveBulk: (id: number, itemRks: string[]): Promise<{ removed: number; item_count: number }> => + req(`/api/plex/playlists/${id}/items/remove-bulk`, { method: "POST", body: JSON.stringify({ item_rating_keys: itemRks }) }), plexRenamePlaylist: (id: number, title: string): Promise => req(`/api/plex/playlists/${id}`, { method: "PATCH", body: JSON.stringify({ title }) }), plexDeletePlaylist: (id: number): Promise<{ deleted: number }> => diff --git a/frontend/src/lib/storage.ts b/frontend/src/lib/storage.ts index 3e3de01..48162ce 100644 --- a/frontend/src/lib/storage.ts +++ b/frontend/src/lib/storage.ts @@ -27,6 +27,7 @@ export const LS = { plexShow: "siftlode.plexShow", plexSort: "siftlode.plexSort", plexFilters: "siftlode.plexFilters", + plexPlaylistLayout: "siftlode.plexPlaylistLayout", notifHistory: "siftlode.notifications", notifSettings: "siftlode.notifSettings", onboardingDismissed: "siftlode.onboarding.dismissed", From 8c86c6b4a87c77c468f85449ffc53f798d55a067 Mon Sep 17 00:00:00 2001 From: npeter83 Date: Tue, 7 Jul 2026 20:19:18 +0200 Subject: [PATCH 3/5] feat(downloads): editable details with clickable channel and extra links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The edit (pencil) action now edits a download's full display metadata — title, channel name, channel link and any number of extra reference URLs — instead of just the name. The channel and links render as clickable links on the library card, and the channel link is auto-filled from the source (yt-dlp channel_url) when available. Shared watch pages resolve the same per-download overrides, so a rename/channel/link edit is reflected on the public /watch page too, with every link clickable. Adds migration 0049 (media_assets.uploader_url; download_jobs.display_uploader, display_uploader_url, extra_links) and generalizes the rename endpoint into a metadata update with URL validation. EN/HU/DE strings included. --- .../versions/0049_download_display_meta.py | 38 ++++++ backend/app/downloads/links.py | 23 +++- backend/app/models.py | 9 ++ backend/app/routes/downloads.py | 42 +++++- backend/app/routes/public.py | 22 +-- backend/app/worker.py | 2 + frontend/src/components/DownloadCenter.tsx | 128 +++++++++++++++--- frontend/src/components/WatchPage.tsx | 51 ++++++- frontend/src/i18n/locales/de/downloads.json | 12 ++ frontend/src/i18n/locales/en/downloads.json | 12 ++ frontend/src/i18n/locales/hu/downloads.json | 12 ++ frontend/src/lib/api.ts | 17 ++- 12 files changed, 327 insertions(+), 41 deletions(-) create mode 100644 backend/alembic/versions/0049_download_display_meta.py diff --git a/backend/alembic/versions/0049_download_display_meta.py b/backend/alembic/versions/0049_download_display_meta.py new file mode 100644 index 0000000..51c6335 --- /dev/null +++ b/backend/alembic/versions/0049_download_display_meta.py @@ -0,0 +1,38 @@ +"""per-download display metadata + auto channel URL + +Revision ID: 0049_download_display_meta +Revises: 0048_plex_playlists +Create Date: 2026-07-07 + +Lets a user override a download's channel and attach extra reference links (beyond the source), +and captures yt-dlp's canonical channel/uploader URL so an auto-filled channel becomes clickable. + +- media_assets.uploader_url: the channel page URL yt-dlp recorded (nullable; filled by the worker + on extraction — older rows just stay plain text). +- download_jobs.display_uploader / display_uploader_url: per-user channel-name + channel-link + overrides (like display_name — display metadata only, never touches the on-disk file). +- download_jobs.extra_links: optional list of extra reference URLs shown on the card + watch page. +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "0049_download_display_meta" +down_revision: Union[str, None] = "0048_plex_playlists" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column("media_assets", sa.Column("uploader_url", sa.Text(), nullable=True)) + op.add_column("download_jobs", sa.Column("display_uploader", sa.String(length=255), nullable=True)) + op.add_column("download_jobs", sa.Column("display_uploader_url", sa.Text(), nullable=True)) + op.add_column("download_jobs", sa.Column("extra_links", sa.JSON(), nullable=True)) + + +def downgrade() -> None: + op.drop_column("download_jobs", "extra_links") + op.drop_column("download_jobs", "display_uploader_url") + op.drop_column("download_jobs", "display_uploader") + op.drop_column("media_assets", "uploader_url") diff --git a/backend/app/downloads/links.py b/backend/app/downloads/links.py index 896af76..8aa2127 100644 --- a/backend/app/downloads/links.py +++ b/backend/app/downloads/links.py @@ -68,11 +68,26 @@ def owner_view(link: DownloadLink, base_url: str = "") -> dict: } -def public_meta(link: DownloadLink, asset, file_url: str) -> dict: - """Metadata for the public watch page (only ever returned once access is authorized).""" +def public_meta(link: DownloadLink, job, asset, file_url: str) -> dict: + """Metadata for the public watch page (only ever returned once access is authorized). + + Resolves the owner's per-download display overrides (custom title/channel) over the asset's + auto-extracted values, and surfaces the source + any extra reference links as clickable URLs.""" + from app.downloads import service + + source_url = None + if job is not None and job.job_kind != "edit": + source_url = asset.source_webpage_url or ( + service.source_url(job.source_kind, job.source_ref) + if job.source_kind in ("youtube", "url") + else None + ) return { - "title": asset.title, - "uploader": asset.uploader, + "title": (job and job.display_name) or asset.title, + "uploader": (job and job.display_uploader) or asset.uploader, + "uploader_url": (job and job.display_uploader_url) or asset.uploader_url, + "source_url": source_url, + "extra_links": (job and job.extra_links) or [], "duration_s": asset.duration_s, "width": asset.width, "height": asset.height, diff --git a/backend/app/models.py b/backend/app/models.py index c3a9ace..574e52c 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -739,6 +739,9 @@ class MediaAsset(Base, TimestampMixin): # Denormalized naming/metadata for the Plex tree + ad-hoc display. title: Mapped[str | None] = mapped_column(Text) uploader: Mapped[str | None] = mapped_column(String(255)) + # yt-dlp's channel/uploader page URL (channel_url|uploader_url) — lets an auto-filled channel + # render as a clickable link. Null for sources without one (e.g. reddit) or older rows. + uploader_url: Mapped[str | None] = mapped_column(Text) upload_date: Mapped[date | None] = mapped_column(Date) thumbnail_url: Mapped[str | None] = mapped_column(Text) # yt-dlp's canonical page URL for the source (webpage_url) — the clean "downloaded from" @@ -821,6 +824,12 @@ class DownloadJob(Base, TimestampMixin, UpdatedAtMixin): ) profile_snapshot: Mapped[dict] = mapped_column(JSON) display_name: Mapped[str | None] = mapped_column(String(255)) + # Per-user display overrides + extras (like display_name — metadata only, never the file). + # `display_uploader`/`display_uploader_url` override the asset's auto channel name/link; + # `extra_links` is an optional list of extra reference URLs shown on the card + watch page. + display_uploader: Mapped[str | None] = mapped_column(String(255)) + display_uploader_url: Mapped[str | None] = mapped_column(Text) + extra_links: Mapped[list | None] = mapped_column(JSON) status: Mapped[str] = mapped_column( String(16), default="queued", server_default="queued", index=True ) # queued | running | paused | done | error | canceled diff --git a/backend/app/routes/downloads.py b/backend/app/routes/downloads.py index 329e285..f222f9b 100644 --- a/backend/app/routes/downloads.py +++ b/backend/app/routes/downloads.py @@ -100,6 +100,9 @@ def _serialize(job: DownloadJob, asset: MediaAsset | None) -> dict: "profile_id": job.profile_id, "spec": job.profile_snapshot, "display_name": job.display_name, + "display_uploader": job.display_uploader, + "display_uploader_url": job.display_uploader_url, + "extra_links": job.extra_links or [], "job_kind": job.job_kind, "source_job_id": job.source_job_id, "edit_spec": job.edit_spec, @@ -118,6 +121,7 @@ def _serialize(job: DownloadJob, asset: MediaAsset | None) -> dict: "width": asset.width, "height": asset.height, "container": asset.container, + "uploader_url": asset.uploader_url, "thumbnail_url": asset.thumbnail_url, "expires_at": asset.expires_at.isoformat() if asset.expires_at else None, }, @@ -380,17 +384,47 @@ def shared_with_me( return out +_MAX_EXTRA_LINKS = 8 + + +def _clean_url(raw) -> str | None: + """Accept only a plausible http(s) URL (these get rendered as clickable links + embedded in a + public watch page); anything else is dropped rather than trusted.""" + if not isinstance(raw, str): + return None + url = raw.strip() + if not url: + return None + if not url.startswith(("http://", "https://")): + return None + parsed = urlparse(url) + if not parsed.netloc: + return None + return url[:2048] + + @router.patch("/{job_id}") -def rename_download( +def update_download_meta( job_id: int, payload: dict, user: User = Depends(require_human), db: Session = Depends(get_db), ) -> dict: + """Update a download's display metadata: title, channel name + link, and extra reference URLs. + All are display-only overrides — the on-disk file keeps its system-decided, id-bound name.""" job = _own_job(db, user, job_id) - name = (payload.get("display_name") or "").strip() - # Display name only — the on-disk file keeps its system-decided, id-bound name. - job.display_name = name[:255] or None + if "display_name" in payload: + job.display_name = ((payload.get("display_name") or "").strip())[:255] or None + if "display_uploader" in payload: + job.display_uploader = ((payload.get("display_uploader") or "").strip())[:255] or None + if "display_uploader_url" in payload: + job.display_uploader_url = _clean_url(payload.get("display_uploader_url")) + if "extra_links" in payload: + raw = payload.get("extra_links") or [] + if not isinstance(raw, list): + raise HTTPException(status_code=400, detail="extra_links must be a list") + cleaned = [u for u in (_clean_url(x) for x in raw) if u][:_MAX_EXTRA_LINKS] + job.extra_links = cleaned or None db.commit() asset = db.get(MediaAsset, job.asset_id) if job.asset_id else None return _serialize(job, asset) diff --git a/backend/app/routes/public.py b/backend/app/routes/public.py index 226b3c0..80a996f 100644 --- a/backend/app/routes/public.py +++ b/backend/app/routes/public.py @@ -35,10 +35,10 @@ def _link_or_404(db: Session, token: str) -> DownloadLink: return link -def _ready_asset(db: Session, link: DownloadLink) -> MediaAsset: +def _ready_target(db: Session, link: DownloadLink) -> tuple[DownloadJob, MediaAsset]: job = db.get(DownloadJob, link.job_id) asset = db.get(MediaAsset, job.asset_id) if job and job.asset_id else None - if asset is None or asset.status != "ready" or not asset.rel_path: + if job is None or asset is None or asset.status != "ready" or not asset.rel_path: raise HTTPException(status_code=404, detail="This video is no longer available.") # Verify the file is actually on disk here (not just flagged ready), so the watch page never # loads a player for a missing file — meta and file agree. @@ -46,7 +46,11 @@ def _ready_asset(db: Session, link: DownloadLink) -> MediaAsset: root = Path(settings.download_root).resolve() if root not in path.parents or not path.exists(): raise HTTPException(status_code=404, detail="This video is no longer available.") - return asset + return job, asset + + +def _ready_asset(db: Session, link: DownloadLink) -> MediaAsset: + return _ready_target(db, link)[1] def _file_url(token: str, grant: str | None = None) -> str: @@ -61,10 +65,10 @@ def watch_meta(token: str, db: Session = Depends(get_db)) -> dict: link = _link_or_404(db, token) if link.password_hash: return {"needs_password": True} - asset = _ready_asset(db, link) + job, asset = _ready_target(db, link) link.view_count += 1 db.commit() - return {"needs_password": False, **linksmod.public_meta(link, asset, _file_url(token))} + return {"needs_password": False, **linksmod.public_meta(link, job, asset, _file_url(token))} @router.post("/watch/{token}/unlock") @@ -75,15 +79,15 @@ def watch_unlock(token: str, payload: dict, db: Session = Depends(get_db)) -> di link = _link_or_404(db, token) if not link.password_hash: # Not a password link — nothing to unlock; just hand back the plain meta. - asset = _ready_asset(db, link) - return {"needs_password": False, **linksmod.public_meta(link, asset, _file_url(token))} + job, asset = _ready_target(db, link) + return {"needs_password": False, **linksmod.public_meta(link, job, asset, _file_url(token))} if not verify_password((payload.get("password") or ""), link.password_hash): raise HTTPException(status_code=403, detail="Wrong password.") - asset = _ready_asset(db, link) + job, asset = _ready_target(db, link) link.view_count += 1 db.commit() grant = linksmod.make_grant(token) - return {"needs_password": False, **linksmod.public_meta(link, asset, _file_url(token, grant))} + return {"needs_password": False, **linksmod.public_meta(link, job, asset, _file_url(token, grant))} @router.get("/watch/{token}/file") diff --git a/backend/app/worker.py b/backend/app/worker.py index 46c62c8..73d8dc2 100644 --- a/backend/app/worker.py +++ b/backend/app/worker.py @@ -218,6 +218,7 @@ def _fill_asset_meta_early(asset_id: int, info: dict) -> None: return asset.title = normalize_title(info.get("title")) asset.uploader = info.get("uploader") or info.get("channel") + asset.uploader_url = info.get("channel_url") or info.get("uploader_url") asset.thumbnail_url = info.get("thumbnail") asset.duration_s = int(info["duration"]) if info.get("duration") else None asset.upload_date = _parse_upload_date(info.get("upload_date")) @@ -408,6 +409,7 @@ def _download(job_id: int, asset_id: int, source_kind: str, source_ref: str, spe asset.acodec = info.get("acodec") if info.get("acodec") not in (None, "none") else None asset.title = meta.title asset.uploader = meta.uploader + asset.uploader_url = info.get("channel_url") or info.get("uploader_url") asset.upload_date = meta.upload_date asset.thumbnail_url = meta.thumbnail_url asset.source_webpage_url = info.get("webpage_url") diff --git a/frontend/src/components/DownloadCenter.tsx b/frontend/src/components/DownloadCenter.tsx index 406acb6..4db484e 100644 --- a/frontend/src/components/DownloadCenter.tsx +++ b/frontend/src/components/DownloadCenter.tsx @@ -78,6 +78,15 @@ function jobTitle(job: DownloadJob): string { return job.display_name || job.asset?.title || job.source_ref; } +// The channel to show under the title: a user override wins over the auto-extracted asset value. +// `url` is null for sources without a channel link (e.g. reddit) — then it renders as plain text. +function jobChannel(job: DownloadJob): { name: string; url: string | null } { + return { + name: job.display_uploader || job.asset?.uploader || job.source_ref, + url: job.display_uploader_url || job.asset?.uploader_url || null, + }; +} + function IconBtn({ onClick, title, @@ -148,6 +157,27 @@ function SourceRef({ url }: { url: string }) { ); } +// Channel under the title — a clickable link when a channel URL is known, plain text otherwise. +function ChannelLine({ job }: { job: DownloadJob }) { + const { name, url } = jobChannel(job); + if (url) { + return ( + + ); + } + return
{name}
; +} + function DownloadRow({ job, children, @@ -169,9 +199,7 @@ function DownloadRow({ )} {jobTitle(job)}
-
- {job.asset?.uploader || job.source_ref} -
+
{job.asset?.size_bytes ? · {formatBytes(job.asset.size_bytes)} : null} @@ -179,6 +207,7 @@ function DownloadRow({ {job.error ? · {job.error} : null}
{job.source_url && } + {job.extra_links?.map((url) => )} {running && (
{job.phase && !DOWNLOAD_PHASES.includes(job.phase) ? ( @@ -208,30 +237,89 @@ function DownloadRow({ // --- Rename + Share small modals ------------------------------------------------------------ -function RenameModal({ job, onClose }: { job: DownloadJob; onClose: () => void }) { +// Edit a download's display metadata: title, channel (name + link), and extra reference links. +// All are display-only overrides — the on-disk file is never renamed. +function MetaEditModal({ job, onClose }: { job: DownloadJob; onClose: () => void }) { const { t } = useTranslation(); const qc = useQueryClient(); - const [name, setName] = useState(jobTitle(job)); + const [name, setName] = useState(job.display_name || job.asset?.title || ""); + const [channel, setChannel] = useState(job.display_uploader || job.asset?.uploader || ""); + const [channelUrl, setChannelUrl] = useState(job.display_uploader_url || job.asset?.uploader_url || ""); + // Editable extra-link rows; keep one blank row so there's always somewhere to type. + const [links, setLinks] = useState(() => [...(job.extra_links ?? []), ""]); + + const setLink = (i: number, v: string) => setLinks((ls) => ls.map((l, j) => (j === i ? v : l))); + const addLink = () => setLinks((ls) => [...ls, ""]); + const removeLink = (i: number) => setLinks((ls) => ls.filter((_, j) => j !== i)); + const save = useMutation({ - mutationFn: () => api.renameDownload(job.id, name.trim()), + mutationFn: () => + api.updateDownloadMeta(job.id, { + display_name: name.trim(), + display_uploader: channel.trim(), + display_uploader_url: channelUrl.trim(), + extra_links: links.map((l) => l.trim()).filter(Boolean), + }), onSuccess: () => { qc.invalidateQueries({ queryKey: ["downloads"] }); onClose(); }, }); + return ( - - - setName(e.target.value)} className={inputCls} autoFocus /> -

{t("downloads.rename.hint")}

-
- + +
+ + + +
+ {t("downloads.edit.extraLinks")} +
+ {links.map((l, i) => ( +
+ setLink(i, e.target.value)} + placeholder="https://…" + className={inputCls} + /> + removeLink(i)} title={t("downloads.edit.removeLink")} danger> + + +
+ ))} +
+ +
+

{t("downloads.edit.hint")}

+
+ +
); @@ -579,7 +667,7 @@ export default function DownloadCenter({ me }: { me: Me }) { )} - setRenameJob(job)} title={t("downloads.actions.rename")}> + setRenameJob(job)} title={t("downloads.actions.editDetails")}> setShareJob(job)} title={t("downloads.actions.share")}> @@ -643,7 +731,7 @@ export default function DownloadCenter({ me }: { me: Me }) { /> )} {manage && setManage(false)} />} - {renameJob && setRenameJob(null)} />} + {renameJob && setRenameJob(null)} />} {shareJob && setShareJob(null)} />} {editJob && setEditJob(null)} />} diff --git a/frontend/src/components/WatchPage.tsx b/frontend/src/components/WatchPage.tsx index 0738247..e443a9e 100644 --- a/frontend/src/components/WatchPage.tsx +++ b/frontend/src/components/WatchPage.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { Download, Lock, PlayCircle } from "lucide-react"; +import { Download, Link2, Lock, PlayCircle } from "lucide-react"; // Standalone, login-free video page for a shared /watch/ link. Rendered OUTSIDE the app // tree (no auth, no providers) — like the /privacy and /terms pages. Uses plain fetch and a tiny @@ -9,11 +9,24 @@ type Meta = { needs_password: boolean; title?: string | null; uploader?: string | null; + uploader_url?: string | null; + source_url?: string | null; + extra_links?: string[]; duration_s?: number | null; allow_download?: boolean; file_url?: string; }; +// Compact display of a URL: drop the protocol + trailing slash so it fits on one line. +function displayUrl(url: string): string { + try { + const u = new URL(url); + return (u.host + u.pathname + u.search).replace(/\/$/, ""); + } catch { + return url; + } +} + const STR = { en: { loading: "Loading…", @@ -24,6 +37,7 @@ const STR = { watch: "Watch", wrong: "Wrong password.", download: "Download", + links: "Links", brand: "Shared via Siftlode", }, hu: { @@ -35,6 +49,7 @@ const STR = { watch: "Megnézem", wrong: "Hibás jelszó.", download: "Letöltés", + links: "Linkek", brand: "Megosztva a Siftlode-dal", }, de: { @@ -46,6 +61,7 @@ const STR = { watch: "Ansehen", wrong: "Falsches Passwort.", download: "Herunterladen", + links: "Links", brand: "Geteilt über Siftlode", }, } as const; @@ -165,7 +181,19 @@ export default function WatchPage() {

{meta.title || "Video"}

- {meta.uploader &&
{meta.uploader}
} + {meta.uploader && + (meta.uploader_url ? ( + + {meta.uploader} + + ) : ( +
{meta.uploader}
+ ))}
{meta.allow_download && ( )}
+ {(meta.source_url || (meta.extra_links && meta.extra_links.length > 0)) && ( + + )}
)}
diff --git a/frontend/src/i18n/locales/de/downloads.json b/frontend/src/i18n/locales/de/downloads.json index 334c966..83b0c2b 100644 --- a/frontend/src/i18n/locales/de/downloads.json +++ b/frontend/src/i18n/locales/de/downloads.json @@ -56,6 +56,7 @@ "retry": "Erneut", "download": "Auf mein Gerät speichern", "rename": "Umbenennen", + "editDetails": "Details bearbeiten", "share": "Teilen", "edit": "Bearbeiten / schneiden", "removeShared": "Aus meiner Liste entfernen" @@ -83,6 +84,17 @@ "hint": "Ändert nur den angezeigten und beim Speichern verwendeten Namen — die gespeicherte Datei behält ihren Namen.", "save": "Speichern" }, + "edit": { + "title": "Details bearbeiten", + "name": "Titel", + "channel": "Kanal", + "channelUrl": "Kanal-Link", + "extraLinks": "Weitere Links", + "addLink": "Link hinzufügen", + "removeLink": "Link entfernen", + "hint": "Nur Anzeige — die gespeicherte Datei behält ihren Namen. Kanal und Links erscheinen auch auf der Karte und auf geteilten Wiedergabeseiten.", + "save": "Speichern" + }, "share": { "title": "Download teilen", "label": "E-Mail des Empfängers", diff --git a/frontend/src/i18n/locales/en/downloads.json b/frontend/src/i18n/locales/en/downloads.json index 604f68f..4e89fc9 100644 --- a/frontend/src/i18n/locales/en/downloads.json +++ b/frontend/src/i18n/locales/en/downloads.json @@ -56,6 +56,7 @@ "retry": "Retry", "download": "Save to my device", "rename": "Rename", + "editDetails": "Edit details", "share": "Share", "edit": "Edit / trim", "removeShared": "Remove from my list" @@ -83,6 +84,17 @@ "hint": "Only changes the name you see and download with — the stored file keeps its own name.", "save": "Save" }, + "edit": { + "title": "Edit details", + "name": "Title", + "channel": "Channel", + "channelUrl": "Channel link", + "extraLinks": "Extra links", + "addLink": "Add link", + "removeLink": "Remove link", + "hint": "Display only — the stored file keeps its own name. The channel and links also show on the card and on shared watch pages.", + "save": "Save" + }, "share": { "title": "Share download", "label": "Recipient email", diff --git a/frontend/src/i18n/locales/hu/downloads.json b/frontend/src/i18n/locales/hu/downloads.json index 2dafea4..a345960 100644 --- a/frontend/src/i18n/locales/hu/downloads.json +++ b/frontend/src/i18n/locales/hu/downloads.json @@ -56,6 +56,7 @@ "retry": "Újra", "download": "Mentés a gépemre", "rename": "Átnevezés", + "editDetails": "Adatok szerkesztése", "share": "Megosztás", "edit": "Szerkesztés / vágás", "removeShared": "Eltávolítás a listámból" @@ -83,6 +84,17 @@ "hint": "Csak a megjelenített és letöltéskor használt nevet módosítja — a tárolt fájl neve nem változik.", "save": "Mentés" }, + "edit": { + "title": "Adatok szerkesztése", + "name": "Cím", + "channel": "Csatorna", + "channelUrl": "Csatorna link", + "extraLinks": "További linkek", + "addLink": "Link hozzáadása", + "removeLink": "Link eltávolítása", + "hint": "Csak megjelenítés — a tárolt fájl neve nem változik. A csatorna és a linkek a kártyán és a megosztott lejátszó oldalon is megjelennek.", + "save": "Mentés" + }, "share": { "title": "Letöltés megosztása", "label": "Címzett e-mail címe", diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index feca869..9b5058c 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -851,6 +851,7 @@ export interface DownloadAsset { status: string; title: string | null; uploader: string | null; + uploader_url: string | null; // yt-dlp channel/uploader page URL (auto; null for e.g. reddit) upload_date: string | null; duration_s: number | null; size_bytes: number | null; @@ -903,6 +904,9 @@ export interface DownloadJob { profile_id: number | null; spec: DownloadSpec; display_name: string | null; + display_uploader: string | null; // user override of the channel name + display_uploader_url: string | null; // user override of the channel link + extra_links: string[]; // extra reference URLs (beyond source_url) job_kind?: string; // "download" (default) | "edit" source_job_id?: number | null; // parent download an edit was cut from edit_spec?: EditSpec | null; @@ -1410,8 +1414,17 @@ export const api = { cancelDownload: (id: number): Promise => req(`/api/downloads/${id}/cancel`, { method: "POST" }, { idempotent: true }), deleteDownload: (id: number) => req(`/api/downloads/${id}`, { method: "DELETE" }), - renameDownload: (id: number, display_name: string): Promise => - req(`/api/downloads/${id}`, { method: "PATCH", body: JSON.stringify({ display_name }) }), + // Update a download's display metadata (title / channel name+link / extra reference URLs). + updateDownloadMeta: ( + id: number, + meta: { + display_name?: string; + display_uploader?: string; + display_uploader_url?: string; + extra_links?: string[]; + } + ): Promise => + req(`/api/downloads/${id}`, { method: "PATCH", body: JSON.stringify(meta) }), shareDownload: (id: number, email: string): Promise<{ shared_with: string }> => req(`/api/downloads/${id}/share`, { method: "POST", body: JSON.stringify({ email }) }), unshareDownload: (id: number, email: string) => From 8591e45747435407bdda1668b1f0fb0a5e9a3326 Mon Sep 17 00:00:00 2001 From: npeter83 Date: Tue, 7 Jul 2026 20:19:30 +0200 Subject: [PATCH 4/5] feat(share): rich link previews (Open Graph) for /watch pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A shared /watch/{token} link is a client-rendered SPA, so a social crawler only saw the generic index.html — a blank link card. The server now injects per-video Open Graph / Twitter tags (title, channel, thumbnail) into the served HTML for that route, so links unfurl richly in Messenger and other chat apps; real browsers ignore the extra tags and hydrate the page as usual. Password / expired / invalid links fall back to the generic card with no metadata leak. Also shortens the generic site description used for search engines and link previews. --- backend/app/downloads/og.py | 85 +++++++++++++++++++++++++++++++++++++ backend/app/main.py | 17 +++++++- frontend/index.html | 8 +++- 3 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 backend/app/downloads/og.py diff --git a/backend/app/downloads/og.py b/backend/app/downloads/og.py new file mode 100644 index 0000000..60a9590 --- /dev/null +++ b/backend/app/downloads/og.py @@ -0,0 +1,85 @@ +"""Server-rendered Open Graph tags for the public /watch/{token} page. + +The watch page is a client-side SPA, so a social crawler (facebookexternalhit, Twitterbot, …) that +fetches /watch/{token} would otherwise only see the generic index.html — a blank/greyed link card. +This injects per-video OG/Twitter tags into the served HTML so a shared link unfurls with the +video's title, channel and thumbnail. Real browsers ignore the extra tags and hydrate the SPA as +usual. Password-protected / expired / invalid links fall back to the generic card (no metadata leak). +""" +import html +import re +from pathlib import Path + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from app.config import settings +from app.downloads import links as linksmod +from app.models import DownloadJob, DownloadLink, MediaAsset + +_OG_BLOCK = re.compile(r".*?", re.DOTALL) + + +def _tag(prop: str, content: str, attr: str = "property") -> str: + return f'' + + +def _watch_tags(token: str, db: Session) -> str | None: + """Build the OG/Twitter meta block for a watch token, or None to keep the generic card.""" + link = db.execute( + select(DownloadLink).where(DownloadLink.token == token) + ).scalar_one_or_none() + if link is None or linksmod.is_expired(link): + return None + url = f"{settings.app_base}/watch/{token}" + if link.password_hash: + # Password-gated: don't leak the title/thumbnail in the unfurl. + return "\n ".join( + [ + "Siftlode", + _tag("og:title", "Password-protected video"), + _tag("og:description", "Shared via Siftlode"), + _tag("og:type", "video.other"), + _tag("og:url", url), + _tag("og:site_name", "Siftlode"), + ] + ) + job = db.get(DownloadJob, link.job_id) + asset = db.get(MediaAsset, job.asset_id) if job and job.asset_id else None + if job is None or asset is None or asset.status != "ready": + return None + title = (job.display_name or asset.title or "Video").strip() + channel = (job.display_uploader or asset.uploader or "").strip() + image = asset.thumbnail_url # already an absolute (youtube/fb) URL, or None + tags = [ + f"{html.escape(title)}", + _tag("og:title", title), + _tag("og:description", channel or "Shared via Siftlode"), + _tag("og:type", "video.other"), + _tag("og:url", url), + _tag("og:site_name", "Siftlode"), + _tag("twitter:title", title, attr="name"), + ] + if channel: + tags.append(_tag("twitter:description", channel, attr="name")) + if image: + # A real thumbnail → a large image card; without one, a plain (text) card is served. + tags.append(_tag("og:image", image)) + tags.append(_tag("twitter:card", "summary_large_image", attr="name")) + tags.append(_tag("twitter:image", image, attr="name")) + else: + tags.append(_tag("twitter:card", "summary", attr="name")) + return "\n ".join(tags) + + +def render_watch_html(token: str, index_html: Path, db: Session) -> str | None: + """Return index.html with the OG block replaced for this watch token, or None to serve the + generic page unchanged (invalid/expired/not-ready link, or a template without the markers).""" + tags = _watch_tags(token, db) + if tags is None: + return None + text = index_html.read_text(encoding="utf-8") + if "" not in text: + return None + # A function replacement avoids re.sub interpreting backslashes/group refs in `tags`. + return _OG_BLOCK.sub(lambda _m: tags, text, count=1) diff --git a/backend/app/main.py b/backend/app/main.py index bea87ee..772888a 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -20,7 +20,7 @@ if not _siftlode_logger.handlers: log = logging.getLogger("siftlode.app") from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse, JSONResponse +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles from starlette.middleware.sessions import SessionMiddleware @@ -178,6 +178,21 @@ async def index() -> FileResponse: return FileResponse(INDEX_HTML, headers=INDEX_HEADERS) +@app.get("/watch/{token}") +async def watch_page(token: str): + """Serve the SPA for a public share link, but with per-video Open Graph tags injected so the + link unfurls richly (title/channel/thumbnail) in Messenger/social crawlers. A real browser + ignores the extra tags and hydrates WatchPage as usual; invalid/expired/password links fall + back to the generic card.""" + from app.downloads import og + + with SessionLocal() as db: + rendered = og.render_watch_html(token, INDEX_HTML, db) + if rendered is None: + return FileResponse(INDEX_HTML, headers=INDEX_HEADERS) + return HTMLResponse(rendered, headers=INDEX_HEADERS) + + @app.get("/{full_path:path}") async def spa_fallback(full_path: str) -> FileResponse: # Client-side routes fall back to index.html; real API/asset paths are matched above. diff --git a/frontend/index.html b/frontend/index.html index c7ed055..39d73cb 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,17 +4,21 @@ + + Siftlode +
From 1b691cdc5f645a50e804ea4852f9ae75b903a745 Mon Sep 17 00:00:00 2001 From: npeter83 Date: Tue, 7 Jul 2026 20:19:39 +0200 Subject: [PATCH 5/5] chore(release): v0.31.0 --- VERSION | 2 +- frontend/src/lib/releaseNotes.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/VERSION b/VERSION index c25c8e5..26bea73 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.30.0 +0.31.0 diff --git a/frontend/src/lib/releaseNotes.ts b/frontend/src/lib/releaseNotes.ts index b917d8e..226bcce 100644 --- a/frontend/src/lib/releaseNotes.ts +++ b/frontend/src/lib/releaseNotes.ts @@ -14,6 +14,19 @@ export interface ReleaseEntry { } export const RELEASE_NOTES: ReleaseEntry[] = [ + { + version: "0.31.0", + date: "2026-07-07", + summary: "Richer downloads — edit details, clickable channels & links, and prettier share-link previews.", + features: [ + "Downloads: the edit (pencil) button now edits the full details — title, channel name and a channel link, plus any number of extra reference links. The channel and links appear on the download card as clickable links, and a source that carries a channel (like YouTube or Facebook) fills the channel link in automatically.", + "Downloads: shared watch pages now show the correct title, channel and links — including your own edits — with every link clickable. (Renaming a download is now reflected on its share link too.)", + "Shared links now unfurl richly in chat apps like Messenger, with the video's title, channel and thumbnail instead of a blank card. Videos without a thumbnail still show a clean text card.", + ], + chores: [ + "Shorter, clearer site description for search engines and link previews.", + ], + }, { version: "0.30.0", date: "2026-07-06",