Tauri 2 shell with a React/TypeScript interface and libmpv playback composed beneath the web view (DirectComposition on Windows). Shared code with per-OS platform modules and configs so macOS and Linux can follow. - Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home - Home, Movies and TV Shows (Discover, Library, Collections), search, people - Title pages with logos, ratings, cast, extras, seasons and episodes - Direct play with Plex conversion fallback, tracks, markers, autoplay - Metadata editing, artwork, fix match, refresh, analyze and deletion - Resumable offline downloads - App settings and Plex server administration with a live dashboard - Signed updater feed and Forgejo CI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
348 lines
15 KiB
TypeScript
348 lines
15 KiB
TypeScript
/** Library browsing and title operations against one server. */
|
|
import type { PlexServer, Params } from './client';
|
|
import { arr, num, parseHub, parseItem, parseSection, str } from './parse';
|
|
import type { FilterOption, Hub, Item, Page, Section } from './types';
|
|
|
|
const items = (mc: any) => arr(mc.Metadata).map(parseItem);
|
|
|
|
export async function sections(s: PlexServer): Promise<Section[]> {
|
|
const mc = await s.container('/library/sections');
|
|
return arr(mc.Directory).map(parseSection);
|
|
}
|
|
|
|
export async function serverInfo(s: PlexServer) {
|
|
return s.container('/');
|
|
}
|
|
|
|
const VIDEO_TYPES = new Set(['movie', 'show', 'season', 'episode', 'collection', 'clip']);
|
|
|
|
export async function homeHubs(s: PlexServer): Promise<Hub[]> {
|
|
const mc = await s.container('/hubs', { count: 20, includeExternalMetadata: 1, includeLibraryPlaylists: 0 });
|
|
return arr(mc.Hub)
|
|
.map(parseHub)
|
|
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
|
}
|
|
|
|
export async function sectionHubs(s: PlexServer, sectionId: string): Promise<Hub[]> {
|
|
const mc = await s.container(`/hubs/sections/${sectionId}`, { count: 20, includeExternalMetadata: 1 });
|
|
return arr(mc.Hub)
|
|
.map(parseHub)
|
|
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
|
}
|
|
|
|
/** Continue Watching across libraries (Plex's own hub honors removals). */
|
|
export async function continueWatching(s: PlexServer, sectionId?: string): Promise<Item[]> {
|
|
const path = sectionId ? `/hubs/sections/${sectionId}/continueWatching/items` : '/hubs/continueWatching/items';
|
|
try {
|
|
const mc = await s.container(path, { 'X-Plex-Container-Size': 40, includeExternalMetadata: 1 });
|
|
return items(mc);
|
|
} catch {
|
|
const mc = await s.container('/library/onDeck', { 'X-Plex-Container-Size': 40 });
|
|
return items(mc).filter((i) => !sectionId || i.librarySectionId === sectionId);
|
|
}
|
|
}
|
|
|
|
export async function hubItems(s: PlexServer, key: string, start = 0, size = 60): Promise<Page<Item>> {
|
|
const mc = await s.container(key, { 'X-Plex-Container-Start': start, 'X-Plex-Container-Size': size, includeExternalMetadata: 1 });
|
|
const list = items(mc).length ? items(mc) : arr(mc.Hub).flatMap((h: any) => arr(h.Metadata).map(parseItem));
|
|
return { items: list, total: num(mc.totalSize ?? mc.size), offset: start };
|
|
}
|
|
|
|
/** Metadata types used by library queries. */
|
|
export const TYPE_ID: Record<string, number> = { movie: 1, show: 2, season: 3, episode: 4, collection: 18 };
|
|
|
|
export async function libraryPage(
|
|
s: PlexServer,
|
|
sectionId: string,
|
|
opts: { type?: number; sort?: string; filters?: Record<string, string>; title?: string; start: number; size: number },
|
|
): Promise<Page<Item>> {
|
|
const params: Params = {
|
|
'X-Plex-Container-Start': opts.start,
|
|
'X-Plex-Container-Size': opts.size,
|
|
type: opts.type,
|
|
sort: opts.sort,
|
|
includeGuids: 0,
|
|
...opts.filters,
|
|
};
|
|
if (opts.title) params['title'] = opts.title;
|
|
const mc = await s.container(`/library/sections/${sectionId}/all`, params);
|
|
return { items: items(mc), total: num(mc.totalSize ?? mc.size), offset: opts.start };
|
|
}
|
|
|
|
export interface LibraryMeta {
|
|
filters: { filter: string; type: string; title: string; key: string }[];
|
|
sorts: { key: string; title: string; defaultDirection: string }[];
|
|
}
|
|
|
|
export async function libraryMeta(s: PlexServer, sectionId: string, type: number): Promise<LibraryMeta> {
|
|
const mc = await s.container(`/library/sections/${sectionId}/all`, { includeMeta: 1, 'X-Plex-Container-Size': 0, type });
|
|
const name = Object.entries(TYPE_ID).find(([, v]) => v === type)?.[0];
|
|
const t = arr(mc.Meta?.Type).find((x: any) => x.type === name) ?? arr(mc.Meta?.Type)[0];
|
|
return {
|
|
filters: arr(t?.Filter).map((f: any) => ({ filter: str(f.filter), type: str(f.filterType), title: str(f.title), key: str(f.key) })),
|
|
sorts: arr(t?.Sort).map((x: any) => ({ key: str(x.key), title: str(x.title), defaultDirection: str(x.defaultDirection) || 'asc' })),
|
|
};
|
|
}
|
|
|
|
export async function filterOptions(s: PlexServer, path: string, type?: number): Promise<FilterOption[]> {
|
|
const mc = await s.container(path, { type });
|
|
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title) }));
|
|
}
|
|
|
|
export async function firstCharacters(s: PlexServer, sectionId: string, params: Params): Promise<{ key: string; title: string; size: number }[]> {
|
|
const mc = await s.container(`/library/sections/${sectionId}/firstCharacter`, params);
|
|
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
|
|
}
|
|
|
|
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
|
|
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
|
|
return items(mc);
|
|
}
|
|
|
|
export async function metadata(s: PlexServer, id: string): Promise<Item> {
|
|
const mc = await s.container(`/library/metadata/${id}`, {
|
|
includeMarkers: 1,
|
|
includeChapters: 1,
|
|
includeExtras: 1,
|
|
includeConcerts: 1,
|
|
includeOnDeck: 1,
|
|
includeReviews: 0,
|
|
includePreferences: 1,
|
|
includeExternalMedia: 0,
|
|
checkFiles: 1,
|
|
asyncAugmentMetadata: 0,
|
|
});
|
|
const first = arr(mc.Metadata)[0];
|
|
if (!first) throw new Error('This title is unavailable.');
|
|
const item = parseItem(first);
|
|
item.raw.__librarySectionID = mc.librarySectionID;
|
|
if (!item.librarySectionId) item.librarySectionId = str(mc.librarySectionID);
|
|
return item;
|
|
}
|
|
|
|
export async function children(s: PlexServer, id: string): Promise<Item[]> {
|
|
const mc = await s.container(`/library/metadata/${id}/children`, { includeMarkers: 0, excludeAllLeaves: 1 });
|
|
return items(mc);
|
|
}
|
|
|
|
export async function allLeaves(s: PlexServer, id: string): Promise<Item[]> {
|
|
const mc = await s.container(`/library/metadata/${id}/allLeaves`);
|
|
return items(mc);
|
|
}
|
|
|
|
/** The show's next episode (Plex's OnDeck), if any. */
|
|
export async function onDeckFor(_s: PlexServer, item: Item): Promise<Item | null> {
|
|
const od = arr(item.raw?.OnDeck?.Metadata)[0];
|
|
if (od) return parseItem(od);
|
|
return null;
|
|
}
|
|
|
|
export async function related(s: PlexServer, id: string): Promise<Hub[]> {
|
|
const mc = await s.container(`/library/metadata/${id}/related`, { includeExternalMetadata: 1, count: 20 });
|
|
return arr(mc.Hub).map(parseHub).filter((h) => h.items.length);
|
|
}
|
|
|
|
export async function collectionItems(s: PlexServer, id: string): Promise<Item[]> {
|
|
const mc = await s.container(`/library/collections/${id}/children`);
|
|
return items(mc);
|
|
}
|
|
|
|
/** Titles featuring a person, across the server's movie and TV libraries. */
|
|
export async function personTitles(s: PlexServer, personId: string, libs: Section[]): Promise<Item[]> {
|
|
const video = libs.filter((l) => l.type === 'movie' || l.type === 'show');
|
|
const results = await Promise.all(
|
|
video.map(async (l) => {
|
|
const out: Item[] = [];
|
|
let start = 0;
|
|
for (let guard = 0; guard < 10; guard++) {
|
|
const mc = await s.container(`/library/sections/${l.id}/all`, {
|
|
actor: personId,
|
|
sort: 'originallyAvailableAt:desc',
|
|
'X-Plex-Container-Start': start,
|
|
'X-Plex-Container-Size': 100,
|
|
});
|
|
const batch = items(mc);
|
|
out.push(...batch);
|
|
start += batch.length;
|
|
if (!batch.length || start >= num(mc.totalSize ?? mc.size)) break;
|
|
}
|
|
// Directors and writers too, when the person has no acting credits here.
|
|
if (!out.length) {
|
|
for (const tag of ['director', 'writer']) {
|
|
const mc = await s.container(`/library/sections/${l.id}/all`, { [tag]: personId, sort: 'originallyAvailableAt:desc' });
|
|
out.push(...items(mc));
|
|
}
|
|
}
|
|
return out;
|
|
}),
|
|
);
|
|
const seen = new Set<string>();
|
|
return results.flat().filter((i) => (seen.has(i.id) ? false : (seen.add(i.id), true)));
|
|
}
|
|
|
|
export async function person(s: PlexServer, id: string): Promise<any> {
|
|
try {
|
|
const mc = await s.container(`/library/people/${id}`);
|
|
return arr(mc.Directory)[0] ?? arr(mc.Metadata)[0] ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export interface SearchResult {
|
|
hubs: Hub[];
|
|
people: { id: string; tag: string; thumb: string }[];
|
|
}
|
|
|
|
export async function search(s: PlexServer, query: string, sectionId?: string): Promise<SearchResult> {
|
|
const mc = await s.container('/hubs/search', { query, limit: 30, includeCollections: 1, sectionId, includeExternalMedia: 0 });
|
|
const hubs = arr(mc.Hub);
|
|
const people = hubs
|
|
.filter((h: any) => h.type === 'actor' || h.type === 'director')
|
|
.flatMap((h: any) => arr(h.Directory ?? h.Metadata))
|
|
.map((p: any) => ({ id: str(p.id ?? p.ratingKey), tag: str(p.tag ?? p.title), thumb: str(p.thumb) }))
|
|
.filter((p: any) => p.id && p.tag);
|
|
const seenPeople = new Set<string>();
|
|
return {
|
|
hubs: hubs
|
|
.map(parseHub)
|
|
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type)),
|
|
people: people.filter((p) => (seenPeople.has(p.id) ? false : (seenPeople.add(p.id), true))),
|
|
};
|
|
}
|
|
|
|
// —— Watch state ————————————————————————————————————————————————
|
|
|
|
export async function setWatched(s: PlexServer, id: string, watched: boolean) {
|
|
await s.get(watched ? '/:/scrobble' : '/:/unscrobble', { key: id, identifier: 'com.plexapp.plugins.library' });
|
|
}
|
|
|
|
export async function removeFromContinueWatching(s: PlexServer, id: string) {
|
|
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
|
|
}
|
|
|
|
export async function rate(s: PlexServer, id: string, rating: number) {
|
|
await s.send('PUT', '/:/rate', { key: id, identifier: 'com.plexapp.plugins.library', rating: rating < 0 ? -1 : rating });
|
|
}
|
|
|
|
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
|
|
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
|
|
}
|
|
|
|
// —— Library management ——————————————————————————————————————————
|
|
|
|
export const refreshMetadata = (s: PlexServer, id: string, force = true) => s.send('PUT', `/library/metadata/${id}/refresh`, { force: force ? 1 : 0 });
|
|
export const analyze = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/analyze`);
|
|
export const unmatch = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/unmatch`);
|
|
export const splitApart = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/split`);
|
|
export const merge = (s: PlexServer, id: string, others: string[]) => s.send('PUT', `/library/metadata/${id}/merge`, { ids: others.join(',') });
|
|
export const deleteItem = (s: PlexServer, id: string) => s.send('DELETE', `/library/metadata/${id}`);
|
|
export const deleteMedia = (s: PlexServer, id: string, mediaId: string) => s.send('DELETE', `/library/metadata/${id}/media/${mediaId}`);
|
|
|
|
export interface MatchCandidate {
|
|
guid: string;
|
|
name: string;
|
|
year: number;
|
|
score: number;
|
|
thumb: string;
|
|
summary: string;
|
|
matched: boolean;
|
|
}
|
|
|
|
export async function matches(s: PlexServer, id: string, opts: { title?: string; year?: string; agent?: string; language?: string }): Promise<MatchCandidate[]> {
|
|
const mc = await s.container(`/library/metadata/${id}/matches`, {
|
|
manual: 1,
|
|
title: opts.title,
|
|
year: opts.year,
|
|
agent: opts.agent,
|
|
language: opts.language,
|
|
});
|
|
return arr(mc.SearchResult).map((r: any) => ({
|
|
guid: str(r.guid),
|
|
name: str(r.name),
|
|
year: num(r.year),
|
|
score: num(r.score),
|
|
thumb: str(r.thumb),
|
|
summary: str(r.summary),
|
|
matched: r.matched === 1 || r.matched === true || r.matched === '1',
|
|
}));
|
|
}
|
|
|
|
export const applyMatch = (s: PlexServer, id: string, guid: string, name: string, year?: number) =>
|
|
s.send('PUT', `/library/metadata/${id}/match`, { guid, name, year });
|
|
|
|
export async function artworkOptions(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos'): Promise<{ key: string; thumb: string; selected: boolean; provider: string }[]> {
|
|
const mc = await s.container(`/library/metadata/${id}/${kind}`);
|
|
return arr(mc.Metadata).map((m: any) => ({ key: str(m.key), thumb: str(m.thumb || m.key), selected: m.selected === true || m.selected === 1, provider: str(m.provider) }));
|
|
}
|
|
|
|
export const selectArtwork = (s: PlexServer, id: string, kind: 'poster' | 'art' | 'clearLogo', url: string) =>
|
|
s.send('PUT', `/library/metadata/${id}/${kind}`, { url });
|
|
|
|
export async function uploadArtwork(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos', data: Blob) {
|
|
await s.send('POST', `/library/metadata/${id}/${kind}`, undefined, { body: data });
|
|
}
|
|
|
|
/**
|
|
* Edits metadata through the section `all` endpoint, as Plex Web does. Field
|
|
* values are locked so later refreshes keep them.
|
|
*/
|
|
export async function editMetadata(
|
|
s: PlexServer,
|
|
item: Item,
|
|
fields: Record<string, string>,
|
|
tagFields: Record<string, { add: string[]; remove: string[] }> = {},
|
|
locks: Record<string, boolean> = {},
|
|
) {
|
|
const type = TYPE_ID[item.type] ?? 1;
|
|
const params: Params = { type, id: item.id, includeExternalMedia: 1 };
|
|
for (const [k, v] of Object.entries(fields)) {
|
|
params[`${k}.value`] = v;
|
|
params[`${k}.locked`] = locks[k] === false ? 0 : 1;
|
|
}
|
|
for (const [tag, change] of Object.entries(tagFields)) {
|
|
change.add.forEach((v, i) => (params[`${tag}[${i}].tag.tag`] = v));
|
|
if (change.remove.length) params[`${tag}[].tag.tag-`] = change.remove.join(',');
|
|
params[`${tag}.locked`] = locks[tag] === false ? 0 : 1;
|
|
}
|
|
for (const [k, locked] of Object.entries(locks)) {
|
|
if (!(k in fields) && !(k in tagFields)) params[`${k}.locked`] = locked ? 1 : 0;
|
|
}
|
|
const section = item.librarySectionId || str(item.raw?.__librarySectionID);
|
|
await s.send('PUT', `/library/sections/${section}/all`, params);
|
|
}
|
|
|
|
/** Collections: create, add, remove. */
|
|
export async function addToCollection(s: PlexServer, item: Item, collection: string) {
|
|
await editMetadata(s, item, {}, { collection: { add: [collection], remove: [] } });
|
|
}
|
|
|
|
export async function removeFromCollection(s: PlexServer, collectionId: string, itemId: string) {
|
|
await s.send('DELETE', `/library/collections/${collectionId}/items/${itemId}`);
|
|
}
|
|
|
|
export async function playlists(s: PlexServer): Promise<Item[]> {
|
|
const mc = await s.container('/playlists', { playlistType: 'video', smart: 0 });
|
|
return items(mc);
|
|
}
|
|
|
|
export async function addToPlaylist(s: PlexServer, playlistId: string, machineId: string, itemId: string) {
|
|
await s.send('PUT', `/playlists/${playlistId}/items`, { uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}` });
|
|
}
|
|
|
|
export async function createPlaylist(s: PlexServer, title: string, machineId: string, itemId: string) {
|
|
await s.send('POST', '/playlists', {
|
|
type: 'video',
|
|
title,
|
|
smart: 0,
|
|
uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}`,
|
|
});
|
|
}
|
|
|
|
/** Library change detection: small response; compared every few seconds. */
|
|
export async function libraryRevision(s: PlexServer): Promise<string> {
|
|
const mc = await s.container('/library/sections');
|
|
return arr(mc.Directory)
|
|
.map((d: any) => [d.key, d.contentChangedAt, d.scannedAt, d.updatedAt].join(':'))
|
|
.join('|');
|
|
}
|