Plex: edit a title's details (fields locked on save) and choose its poster or background, owner only, through a narrow write rule in the proxy
build-container / build (push) Successful in 19m31s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nmemmertandClaude Sonnet 5.5 committed 2026-10-22 12:42:32 -04:00
1 parent b171f35be6
commit 5c5a7b5155
5 files changed
+113 -5

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ e.g. hub.necloud.us. Settings: `SEAFILE_URL`, `ONLYOFFICE_URL` env vars in docke
- **Tasks**: to-do lists stored in NE Hub (`/data/tasks.json`), with due dates, notes and completion. If the connected iCloud - **Tasks**: to-do lists stored in NE Hub (`/data/tasks.json`), with due dates, notes and completion. If the connected iCloud
account exposes reminder lists over CalDAV they appear too and sync both ways. Apple hides Reminders lists that were upgraded account exposes reminder lists over CalDAV they appear too and sync both ways. Apple hides Reminders lists that were upgraded
for iOS 13+, so for most accounts only NE Hub lists are available. for iOS 13+, so for most accounts only NE Hub lists are available.
- **Plex PINs and editing**: a Plex Home profile that has a PIN in Plex (the owner's included) asks for it every time you switch to it; plex.tv checks it and five wrong guesses make the hub wait ten minutes. The **Edit** button on a movie, show, season or episode (only when you are the Plex server's owner) opens the fields Plex's own Edit dialog has: title, sort title, original title, release date, content rating, studio, tagline, summary and genres, plus choosing a poster or background (or adding one from an image link). Only changed fields are saved, and each is locked in Plex so a refresh does not undo it. The hub's Plex proxy allows just those edit requests (nothing else on the server can be changed).
- **Settings sync**: your preferences (mail addresses, audiobooks sign-in (encrypted), Plex library, Office save location, calendar/task views, recent files) are saved on the server in `/data/settings.json` and shared by every device. The Seafile sign-in token is saved there too (encrypted), so Settings shows Seafile as signed in on every device. Only the music queue stays in the browser. - **Settings sync**: your preferences (mail addresses, audiobooks sign-in (encrypted), Plex library, Office save location, calendar/task views, recent files) are saved on the server in `/data/settings.json` and shared by every device. The Seafile sign-in token is saved there too (encrypted), so Settings shows Seafile as signed in on every device. Only the music queue stays in the browser.
- **Search**: libraries, file names (scans libraries if Seafile has no search index) and Plex artists/albums/tracks. - **Search**: libraries, file names (scans libraries if Seafile has no search index) and Plex artists/albums/tracks.
- **Music**: Plex player. Sign in goes through plex.tv (no password handled), the server proxies your Plex server and adds the token itself, and a mini player keeps playing as you move between tabs; the current and next two tracks are downloaded in full so changing songs is instant and a slow or lost connection does not stop playback; the Home dashboard and the Music tab show a live Now Playing card (follows the song, seek bar, shuffle/repeat, previous/next, lyrics, queue) above the rest; the queue (play next / add to queue) and position are remembered. The player reports what is playing to Plex (play, pause, stop, position every 10 s), so it appears under Now Playing / Activity in the Plex dashboard as "NE Hub", under the Plex account you signed in with. **Plex Home users**: if your Plex account has a Plex Home (managed users, kids, guests), the Music tab shows "Playing as <name>" with a switch link; pick another person (and enter their PIN if they have one) and Music, playlists, ratings and the Plex dashboard follow that person. The account that signed in is kept so switching back needs no PIN. It is per hub person, remembered across restarts, and has only been tried against a fake plex.tv. **Lyrics and karaoke**: the Lyrics button (on the Now Playing card, in the full player, and in the wide mini player) opens a full-screen lyrics view that follows the song, tap a line to jump to it, A−/A+ change the size, and **Karaoke** shows just the current line big with the colour sweeping across it as it is sung (word by word when the source has word timing, otherwise across the line). Lyrics come from Plex first if the song has them (embedded, a `.lrc` file next to it, or Plex Pass), otherwise from the bundled **Lyrica** service (`lyrica` container; sources LRCLIB, Musixmatch via Lrcmux, NetEase, Megalobiz; YouTube auto-captions are never used, and an answer for a recording of a very different length is refused). Lookups send the artist and title to those public sources and are kept in `/data/lyrics` so a song is looked up once. If the timing is off, the − / + buttons shift it half a second at a time (remembered per song); "Wrong lyrics?" lets you search with a corrected artist or title. Remove the `lyrica` service and the hub's `LYRICS_API_URL` line to skip the online lookup (Plex lyrics still work). No vocal removal. - **Music**: Plex player. Sign in goes through plex.tv (no password handled), the server proxies your Plex server and adds the token itself, and a mini player keeps playing as you move between tabs; the current and next two tracks are downloaded in full so changing songs is instant and a slow or lost connection does not stop playback; the Home dashboard and the Music tab show a live Now Playing card (follows the song, seek bar, shuffle/repeat, previous/next, lyrics, queue) above the rest; the queue (play next / add to queue) and position are remembered. The player reports what is playing to Plex (play, pause, stop, position every 10 s), so it appears under Now Playing / Activity in the Plex dashboard as "NE Hub", under the Plex account you signed in with. **Plex Home users**: if your Plex account has a Plex Home (managed users, kids, guests), the Music tab shows "Playing as <name>" with a switch link; pick another person (and enter their PIN if they have one) and Music, playlists, ratings and the Plex dashboard follow that person. The account that signed in is kept so switching back needs no PIN. It is per hub person, remembered across restarts, and has only been tried against a fake plex.tv. **Lyrics and karaoke**: the Lyrics button (on the Now Playing card, in the full player, and in the wide mini player) opens a full-screen lyrics view that follows the song, tap a line to jump to it, A−/A+ change the size, and **Karaoke** shows just the current line big with the colour sweeping across it as it is sung (word by word when the source has word timing, otherwise across the line). Lyrics come from Plex first if the song has them (embedded, a `.lrc` file next to it, or Plex Pass), otherwise from the bundled **Lyrica** service (`lyrica` container; sources LRCLIB, Musixmatch via Lrcmux, NetEase, Megalobiz; YouTube auto-captions are never used, and an answer for a recording of a very different length is refused). Lookups send the artist and title to those public sources and are kept in `/data/lyrics` so a song is looked up once. If the timing is off, the − / + buttons shift it half a second at a time (remembered per song); "Wrong lyrics?" lets you search with a corrected artist or title. Remove the `lyrica` service and the hub's `LYRICS_API_URL` line to skip the online lookup (Plex lyrics still work). No vocal removal.
+7
View File
@@ -701,3 +701,10 @@ body.nav-mini .ngrp span { display: none; }
.sw.on{border-color:var(--text)} .sw.on{border-color:var(--text)}
.sw.custom{background:conic-gradient(#d9453a,#e5a00d,#2f9e6e,#4f7cff,#8a5cf0,#d9453a);overflow:hidden} .sw.custom{background:conic-gradient(#d9453a,#e5a00d,#2f9e6e,#4f7cff,#8a5cf0,#d9453a);overflow:hidden}
.sw.custom input{position:absolute;inset:0;opacity:0;width:100%;height:100%;cursor:pointer} .sw.custom input{position:absolute;inset:0;opacity:0;width:100%;height:100%;cursor:pointer}
/* Plex details editor: image choices */
.vimgs{display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:8px;margin:6px 0}
.vimgs.arts{grid-template-columns:repeat(auto-fill,minmax(150px,1fr))}
.vpick{padding:0;min-height:0;border:2px solid transparent;border-radius:8px;overflow:hidden;background:var(--panel2);cursor:pointer;line-height:0}
.vpick.on{border-color:var(--accent)}
.vpick img{width:100%;height:auto;display:block}
+55
View File
@@ -109,6 +109,9 @@ async function videoItem(id) {
<p class="vsum">${esc(m.summary || '')}</p> <p class="vsum">${esc(m.summary || '')}</p>
${m.Genre && m.Genre.length ? `<p class="sub"><b>Genres</b> ${names(m.Genre)}</p>` : ''}${m.Director && m.Director.length ? `<p class="sub"><b>Director</b> ${names(m.Director, 'tag', 3)}</p>` : ''}${m.Role && m.Role.length ? `<p class="sub"><b>Cast</b> ${names(m.Role, 'tag', 8)}</p>` : ''} ${m.Genre && m.Genre.length ? `<p class="sub"><b>Genres</b> ${names(m.Genre)}</p>` : ''}${m.Director && m.Director.length ? `<p class="sub"><b>Director</b> ${names(m.Director, 'tag', 3)}</p>` : ''}${m.Role && m.Role.length ? `<p class="sub"><b>Cast</b> ${names(m.Role, 'tag', 8)}</p>` : ''}
<div id="vkids"></div></div>`; <div id="vkids"></div></div>`;
jfetch('/api/plex/status').then(st => { // Plex only lets its owner edit details, so the button is offered only then
if (st.canEdit && $('#vact') && !$('#vedit')) { $('#vact').insertAdjacentHTML('beforeend', '<button class="btn ghost" id="vedit">Edit</button>'); $('#vedit').onclick = () => videoEdit(m); }
}).catch(() => {});
if ($('#vplay')) $('#vplay').onclick = () => { location.hash = `#/video/watch/${id}`; }; if ($('#vplay')) $('#vplay').onclick = () => { location.hash = `#/video/watch/${id}`; };
if ($('#vstart')) $('#vstart').onclick = () => { store.set('video_from_start', id); location.hash = `#/video/watch/${id}`; }; if ($('#vstart')) $('#vstart').onclick = () => { store.set('video_from_start', id); location.hash = `#/video/watch/${id}`; };
if ($('#vnext')) $('#vnext').onclick = () => { location.hash = `#/video/watch/${next.ratingKey}`; }; if ($('#vnext')) $('#vnext').onclick = () => { location.hash = `#/video/watch/${next.ratingKey}`; };
@@ -394,3 +397,55 @@ addEventListener('keydown', e => {
else if (k === 'm') el.muted = !el.muted; else if (k === 'n' || k === 'N') videoGo(1); else if (k === 'p' || k === 'P') videoGo(-1); else if (k === 'm') el.muted = !el.muted; else if (k === 'n' || k === 'N') videoGo(1); else if (k === 'p' || k === 'P') videoGo(-1);
else if (/^[0-9]$/.test(k) && vp.m.duration) { videoSeek(vp.m.duration / 1000 * (+k / 10)); } else if (/^[0-9]$/.test(k) && vp.m.duration) { videoSeek(vp.m.duration / 1000 * (+k / 10)); }
}, true); }, true);
// ---- Edit a title's details the way Plex's Edit dialog does: only what changed is saved, and each saved field is locked so a Plex refresh keeps it.
const VD_TYPE = { movie: 1, show: 2, season: 3, episode: 4 };
async function videoEdit(m) {
const kind = m.type, rich = kind === 'movie' || kind === 'show', genres = (m.Genre || []).map(g => g.tag);
const F = [['title', 'Title'], ['titleSort', 'Sort title'], ['originalTitle', 'Original title'], ['originallyAvailableAt', kind === 'show' ? 'First aired' : 'Release date', 'date'], ['contentRating', 'Content rating'], ...(rich ? [['studio', 'Studio'], ['tagline', 'Tagline']] : []), ['summary', 'Summary', 'area']]
.filter(([k]) => kind !== 'season' || ['title', 'titleSort', 'summary'].includes(k));
const old = k => String(m[k] || ''), dateOf = v => String(v || '').slice(0, 10);
const el = openSheet('Edit ' + (m.title || ''), '', `<div class="sgrp" role="tablist" style="margin-bottom:8px"><a href="#" data-t="d" aria-selected="true" class="on">Details</a><a href="#" data-t="p" aria-selected="false">Poster</a><a href="#" data-t="a" aria-selected="false">Background</a></div>
<form id="vf"><div id="vtab-d">${F.map(([k, l, t]) => `<label for="ve-${k}">${l}</label>${t === 'area' ? `<textarea id="ve-${k}" rows="5">${esc(old(k))}</textarea>` : `<input type="${t || 'text'}" id="ve-${k}" value="${esc(t === 'date' ? dateOf(m[k]) : old(k))}" autocomplete="off">`}`).join('')}
${rich ? `<label for="ve-genre">Genres <small>(separate with commas)</small></label><input type="text" id="ve-genre" value="${esc(genres.join(', '))}" autocomplete="off">` : ''}
<p class="sub" style="margin:10px 0 0">Changed fields are locked in Plex, so scans and refreshes will not put the old values back.</p></div>
<div id="vtab-p" hidden></div><div id="vtab-a" hidden></div>
<div class="bar"><button class="btn ghost" type="button" id="sx" style="flex:1;justify-content:center">Cancel</button><button class="btn" id="vs" style="flex:1;justify-content:center">Save</button></div><div class="err" id="ve"></div></form>`);
el.querySelector('.sheet').classList.add('wide');
el.querySelector('#sx').onclick = closeSheet;
const loaded = {};
const images = async (tab, what) => { // posters / backgrounds: pick one, or add from an image link
const box = el.querySelector('#vtab-' + tab); box.innerHTML = '<p class="empty">Loading…</p>';
try {
const mc = await px.get(`/library/metadata/${m.ratingKey}/${what}`), list = mc.Metadata || [];
box.innerHTML = `<div class="vimgs ${what}">${list.map((x, i) => `<button type="button" class="vpick ${x.selected ? 'on' : ''}" data-i="${i}" aria-label="Use this image"><img alt="" loading="lazy" src="${/^https?:/.test(x.thumb || '') ? esc(x.thumb) : vdArt(x.thumb, 200, 300)}"></button>`).join('') || '<p class="empty">No images yet.</p>'}</div>
<label>Add from an image link</label><div class="bar" style="margin-top:4px"><input type="url" class="vurl" placeholder="https://…" autocomplete="off" style="flex:1"><button type="button" class="btn ghost vadd">Add</button></div><div class="err vie"></div>`;
const put = async (url, add) => {
const r = await fetch(`/plex/library/metadata/${m.ratingKey}/${add ? what : what === 'posters' ? 'poster' : 'art'}?url=${encodeURIComponent(url)}`, { method: add ? 'POST' : 'PUT' });
if (!r.ok) throw new Error(r.status === 403 || r.status === 404 ? 'Only the Plex owner can change images' : 'Plex would not take that (' + r.status + ')');
};
box.querySelectorAll('.vpick').forEach(b => b.onclick = async () => { try { await put(list[+b.dataset.i].ratingKey || list[+b.dataset.i].key); box.querySelectorAll('.vpick').forEach(x => x.classList.toggle('on', x === b)); toast('Image changed'); changed = true; } catch (e) { box.querySelector('.vie').textContent = e.message; } });
box.querySelector('.vadd').onclick = async () => { const u = box.querySelector('.vurl').value.trim(); if (!/^https:\/\//.test(u)) { box.querySelector('.vie').textContent = 'Use a link that starts with https://'; return; } try { await put(u, true); toast('Image added'); changed = true; loaded[tab] = false; images(tab, what); } catch (e) { box.querySelector('.vie').textContent = e.message; } };
} catch (e) { box.innerHTML = `<p class="err">${esc(e.message)}</p>`; }
};
let changed = false;
el.querySelectorAll('.sgrp a[data-t]').forEach(a => a.onclick = ev => {
ev.preventDefault(); const t = a.dataset.t;
el.querySelectorAll('.sgrp a[data-t]').forEach(x => { x.classList.toggle('on', x === a); x.setAttribute('aria-selected', x === a); });
['d', 'p', 'a'].forEach(k => { el.querySelector('#vtab-' + k).hidden = k !== t; }); el.querySelector('#vs').hidden = t !== 'd';
if (t !== 'd' && !loaded[t]) { loaded[t] = true; images(t, t === 'p' ? 'posters' : 'arts'); }
});
el.querySelector('#vf').onsubmit = async ev => {
ev.preventDefault(); const btn = el.querySelector('#vs'); btn.disabled = true; el.querySelector('#ve').textContent = '';
const q = new URLSearchParams({ type: VD_TYPE[kind] || 1, id: m.ratingKey, includeExternalMedia: 1 }); let n = 0;
for (const [k, , t] of F) { const v = el.querySelector('#ve-' + k).value.trim(); if (v !== (t === 'date' ? dateOf(m[k]) : old(k))) { q.set(k + '.value', v); q.set(k + '.locked', 1); n++; } }
if (rich) { const g = [...new Set(el.querySelector('#ve-genre').value.split(',').map(x => x.trim()).filter(Boolean))]; if (g.join('|') !== genres.join('|')) { g.forEach((x, i) => q.set(`genre[${i}].tag.tag`, x)); q.set('genre.locked', 1); n++; } }
if (!n) { closeSheet(); if (changed) route(); return; }
try {
const r = await fetch(`/plex/library/sections/${m.librarySectionID}/all?${q}`, { method: 'PUT' });
if (!r.ok) throw new Error(r.status === 403 || r.status === 404 ? 'Only the Plex owner can change details' : 'Plex would not save that (' + r.status + ')');
closeSheet(); toast('Saved in Plex'); route();
} catch (e) { btn.disabled = false; el.querySelector('#ve').textContent = e.message; }
};
}
+36 -4
View File
@@ -320,7 +320,7 @@ async function plexApi(req, res) {
const u = new URL(req.url, 'http://x'), st = plexLoad(), token = st.token; const u = new URL(req.url, 'http://x'), st = plexLoad(), token = st.token;
try { try {
if (u.pathname === '/api/plex/status') { if (u.pathname === '/api/plex/status') {
return json(res, 200, { signedIn: !!token, server: st.srv ? st.name || 'Plex' : null, user: st.user ? { id: st.user.id, title: st.user.title, thumb: st.user.thumb, admin: st.user.admin } : null }); return json(res, 200, { signedIn: !!token, server: st.srv ? st.name || 'Plex' : null, user: st.user ? { id: st.user.id, title: st.user.title, thumb: st.user.thumb, admin: st.user.admin } : null, canEdit: !!token && await plexCanEdit(st) });
} }
if (u.pathname === '/api/plex/pin' && req.method === 'POST') { if (u.pathname === '/api/plex/pin' && req.method === 'POST') {
const pin = await plexTv('/api/v2/pins?strong=true', null, { method: 'POST' }); const pin = await plexTv('/api/v2/pins?strong=true', null, { method: 'POST' });
@@ -407,8 +407,40 @@ async function plexApi(req, res) {
} catch (e) { json(res, 502, { error: e.message }); } } catch (e) { json(res, 502, { error: e.message }); }
} }
// Only playlists may be changed through the proxy (create, add, remove, rename, delete); everything else on the Plex server stays read-only. // Only playlists and a title's own details (the fields Plex's Edit dialog has, and its poster/background choice) may be changed through the proxy;
const PLEX_WRITABLE = /^\/plex\/playlists(\/\d+)?(\/items(\/\d+)?)?\?|^\/plex\/playlists(\/\d+)?(\/items(\/\d+)?)?$/; // everything else on the Plex server stays read-only. Plex itself refuses edits from anyone who is not allowed, and the hub checks too (plexCanEdit).
const PLEX_PLAYLISTS = /^\/plex\/playlists(\/\d+)?(\/items(\/\d+)?)?\?|^\/plex\/playlists(\/\d+)?(\/items(\/\d+)?)?$/;
const EDIT_FIELDS = 'title|titleSort|originalTitle|originallyAvailableAt|contentRating|studio|tagline|summary';
const EDIT_TAGS = 'genre|label|collection';
const EDIT_KEY = new RegExp(`^(type|id|includeExternalMedia|(${EDIT_FIELDS})\\.(value|locked)|(${EDIT_TAGS})\\.locked|(${EDIT_TAGS})\\[\\d{1,3}\\]\\.tag\\.tag)$`);
/** Is this request one of the allowed edits of a title's details? */
function plexEditRequest(method, url) {
const u = new URL(url, 'http://x'), p = u.pathname;
if (u.href.length > 12000) return false;
let m;
if (method === 'PUT' && (m = /^\/plex\/library\/sections\/\d+\/all$/.exec(p))) { // save fields: ?type=1&id=<key>&title.value=..&title.locked=1
const q = u.searchParams;
return /^[1-4]$/.test(q.get('type') || '') && /^\d+$/.test(q.get('id') || '') && [...q.keys()].every(k => EDIT_KEY.test(k));
}
if ((m = /^\/plex\/library\/metadata\/\d+\/(poster|art|posters|arts)$/.exec(p))) { // choose or add a poster / background
const img = u.searchParams.get('url') || '';
return [...u.searchParams.keys()].every(k => k === 'url') && /^(https:\/\/[^\s]{4,2000}|\/library\/metadata\/\d+\/(file|thumb|art)[^\s]*|(upload|metadata|media):\/\/[\w./%-]{1,300})$/.test(img)
&& (m[1].length > 3 ? ['POST', 'PUT'] : ['PUT']).includes(method) && (method === 'PUT' ? /^(poster|art)$/.test(m[1]) : /^(posters|arts)$/.test(m[1]));
}
return false;
}
const PLEX_WRITABLE_URL = (method, url) => PLEX_PLAYLISTS.test(url) || plexEditRequest(method, url);
const editOk = new Map(); // token + server -> { t, ok }
/** Only the server's owner (or an admin of the Home) may edit details: the person's own plex.tv view of the server says so. */
async function plexCanEdit(st) {
if (!st.token || !st.sid) return false;
const k = st.token + '|' + st.sid, c = editOk.get(k);
if (c && Date.now() - c.t < 5 * 60e3) return c.ok;
let ok = false;
try { const rs = await plexTv(RESOURCES, st.token); ok = !!rs.find(x => x.clientIdentifier === st.sid && truthy(x.owned)); } catch { return false; }
editOk.set(k, { t: Date.now(), ok });
return ok;
}
async function plexProxy(req, res) { async function plexProxy(req, res) {
const st = plexLoad(); const st = plexLoad();
if (!st.srv || !st.stk) { res.writeHead(401); return res.end(); } if (!st.srv || !st.stk) { res.writeHead(401); return res.end(); }
@@ -579,7 +611,7 @@ async function handleRequest(req, res) {
if (pathname.startsWith('/api/signal/')) return signal.enabled() ? signal.handle(req, res) : forbidden(res, 'Signal is not set up on this server'); if (pathname.startsWith('/api/signal/')) return signal.enabled() ? signal.handle(req, res) : forbidden(res, 'Signal is not set up on this server');
if (pathname.startsWith('/api/mail/')) return mail.handle(req, res); if (pathname.startsWith('/api/mail/')) return mail.handle(req, res);
if (req.url.startsWith('/api/plex/')) return plexApi(req, res); if (req.url.startsWith('/api/plex/')) return plexApi(req, res);
if (req.url.startsWith('/plex/') && (req.method === 'GET' || (['POST', 'PUT', 'DELETE'].includes(req.method) && PLEX_WRITABLE.test(req.url)))) return plexProxy(req, res); if (req.url.startsWith('/plex/') && (req.method === 'GET' || (['POST', 'PUT', 'DELETE'].includes(req.method) && PLEX_WRITABLE_URL(req.method, req.url) && (PLEX_PLAYLISTS.test(req.url) || await plexCanEdit(plexLoad()))))) return plexProxy(req, res);
if (req.url.startsWith('/sf/')) return proxySeafile(req, res); if (req.url.startsWith('/sf/')) return proxySeafile(req, res);
return serveStatic(req, res); return serveStatic(req, res);
}); });
+14 -1
View File
@@ -36,7 +36,7 @@ const jsonOut = (rs, code, o) => { rs.writeHead(code, { 'content-type': 'applica
tv.resourceCalls++; tv.resourceCalls++;
const who = rq.headers['x-plex-token'], other = { KIDTOKEN: 'KIDSRV', GUESTTOKEN: 'GUESTSRV' }[who]; const who = rq.headers['x-plex-token'], other = { KIDTOKEN: 'KIDSRV', GUESTTOKEN: 'GUESTSRV' }[who];
if (who !== tv.accountToken && !other) return jsonOut(rs, 401, { error: 'bad token' }); if (who !== tv.accountToken && !other) return jsonOut(rs, 401, { error: 'bad token' });
return jsonOut(rs, 200, [{ name: 'E-va', clientIdentifier: 'sid1', provides: 'server', owned: true, accessToken: other || tv.serverToken, return jsonOut(rs, 200, [{ name: 'E-va', clientIdentifier: 'sid1', provides: 'server', owned: who === tv.accountToken, accessToken: other || tv.serverToken,
connections: [{ uri: `http://127.0.0.1:${tv.plexPort}`, local: false, relay: false, address: '127.0.0.1', port: tv.plexPort }] }]); connections: [{ uri: `http://127.0.0.1:${tv.plexPort}`, local: false, relay: false, address: '127.0.0.1', port: tv.plexPort }] }]);
} }
rs.writeHead(404); rs.end(); rs.writeHead(404); rs.end();
@@ -95,6 +95,18 @@ const jsonOut = (rs, code, o) => { rs.writeHead(code, { 'content-type': 'applica
const bad = [['DELETE', '/plex/library/metadata/5'], ['PUT', '/plex/library/sections/1/refresh'], ['POST', '/plex/playlists/7/../library/metadata/5'], ['DELETE', '/plex/library/sections/1']]; const bad = [['DELETE', '/plex/library/metadata/5'], ['PUT', '/plex/library/sections/1/refresh'], ['POST', '/plex/playlists/7/../library/metadata/5'], ['DELETE', '/plex/library/sections/1']];
const refused = []; for (const [m, p] of bad) { const x = await call(p, undefined, m); refused.push(x.status); } const refused = []; for (const [m, p] of bad) { const x = await call(p, undefined, m); refused.push(x.status); }
ok('but nothing else on the Plex server can be changed through the hub', refused.every(x => x >= 400) && !plexReqs.length, [refused, plexReqs]); ok('but nothing else on the Plex server can be changed through the hub', refused.every(x => x >= 400) && !plexReqs.length, [refused, plexReqs]);
// ---- editing a title's details (what Plex's Edit dialog has) and choosing its poster
r = await call('/api/plex/status'); ok('the owner is told they can edit details', r.json.canEdit === true, r.json);
const E = '/plex/library/sections/1/all?type=1&id=5&title.value=' + encodeURIComponent('New & Title') + '&title.locked=1&summary.value=Hi&summary.locked=1&genre%5B0%5D.tag.tag=Drama&genre%5B1%5D.tag.tag=Comedy&genre.locked=1&originallyAvailableAt.value=2020-01-02&originallyAvailableAt.locked=1';
plexReqs.length = 0; r = await call(E, undefined, 'PUT');
ok('the owner can save a title\'s details, locked so a refresh keeps them', r.status === 200 && plexReqs.length === 1 && plexReqs[0].startsWith('PUT /library/sections/1/all?type=1&id=5&title.value=New') && plexReqs[0].includes('title.locked=1'), [r.status, plexReqs]);
plexReqs.length = 0; r = await call('/plex/library/metadata/5/poster?url=' + encodeURIComponent('/library/metadata/5/thumb/123'), undefined, 'PUT'); ok('and pick one of its posters', r.status === 200 && plexReqs.length === 1, [r.status, plexReqs]);
plexReqs.length = 0; r = await call('/plex/library/metadata/5/posters?url=' + encodeURIComponent('https://img.example/p.jpg'), undefined, 'POST'); ok('or add one from an image link', r.status === 200 && plexReqs.length === 1, [r.status, plexReqs]);
plexReqs.length = 0;
const badEdit = [['PUT', '/plex/library/sections/1/all?type=1&id=5&mediaType=9&title.value=x'], ['PUT', '/plex/library/sections/1/all?type=1&id=5&deleteAll=1'], ['PUT', '/plex/library/sections/1/all?type=1&title.value=x'], ['PUT', '/plex/library/sections/1/all?type=9&id=5'],
['DELETE', '/plex/library/sections/1/all?type=1&id=5&title.value=x'], ['PUT', '/plex/library/metadata/5/poster?url=file:///etc/passwd'], ['PUT', '/plex/library/metadata/5/poster?url=http://10.0.0.1/x.jpg'], ['PUT', '/plex/library/metadata/5/poster?url=https://a.example/x.jpg&extra=1'], ['POST', '/plex/library/metadata/5/poster?url=https://a.example/x.jpg'], ['PUT', '/plex/library/metadata/5/posters?url=https://a.example/x.jpg']];
const bst = []; for (const [m, p] of badEdit) bst.push((await call(p, undefined, m)).status);
ok('anything else in an edit request is refused before it reaches Plex', bst.every(x => x >= 400) && !plexReqs.length, [bst, plexReqs]);
// ================= Plex Home: using Plex as someone else in the Home ================= // ================= Plex Home: using Plex as someone else in the Home =================
r = await call('/api/plex/users'); ok('the Plex Home is listed (read from plex.tv\'s XML), with who is using NE Hub now', r.status === 200 && r.json.users.length === 3 && r.json.users.find(x => x.id === '1').current && r.json.users.find(x => x.id === '2').protected && r.json.users.find(x => x.id === '2').restricted && r.json.users.find(x => x.id === '1').admin, r.json); r = await call('/api/plex/users'); ok('the Plex Home is listed (read from plex.tv\'s XML), with who is using NE Hub now', r.status === 200 && r.json.users.length === 3 && r.json.users.find(x => x.id === '1').current && r.json.users.find(x => x.id === '2').protected && r.json.users.find(x => x.id === '2').restricted && r.json.users.find(x => x.id === '1').admin, r.json);
@@ -106,6 +118,7 @@ const jsonOut = (rs, code, o) => { rs.writeHead(code, { 'content-type': 'applica
seen.length = 0; r = await call('/api/plex/switch', { id: '2', pin: '1234' }); ok('with the right PIN the hub switches to that person', r.status === 200 && r.json.user.title === 'Kid', r); seen.length = 0; r = await call('/api/plex/switch', { id: '2', pin: '1234' }); ok('with the right PIN the hub switches to that person', r.status === 200 && r.json.user.title === 'Kid', r);
r = await call('/api/plex/status'); ok('status says who is using Plex now', r.json.user && r.json.user.title === 'Kid' && r.json.signedIn && r.json.server === 'E-va', r.json); r = await call('/api/plex/status'); ok('status says who is using Plex now', r.json.user && r.json.user.title === 'Kid' && r.json.signedIn && r.json.server === 'E-va', r.json);
r = await call('/plex/library/sections'); ok('Plex requests now use that person\'s own server token', r.status === 200 && seen[seen.length - 1] === 'KIDSRV', [r.status, seen]); r = await call('/plex/library/sections'); ok('Plex requests now use that person\'s own server token', r.status === 200 && seen[seen.length - 1] === 'KIDSRV', [r.status, seen]);
plexReqs.length = 0; r = await call('/api/plex/status'); const ke = await call(E, undefined, 'PUT'); ok('a Home member who is not the owner cannot edit (no Edit button, and the hub refuses)', r.json.canEdit === false && ke.status >= 400 && !plexReqs.length, [r.json, ke.status, plexReqs]);
s = savedPlex(); ok('the owner\'s sign-in is kept (to switch back, and to list the Home) and the new one is saved', s && s.mainToken === 'ACCOUNT' && s.token === 'KIDTOKEN' && s.stk === 'KIDSRV' && s.user.title === 'Kid', s); s = savedPlex(); ok('the owner\'s sign-in is kept (to switch back, and to list the Home) and the new one is saved', s && s.mainToken === 'ACCOUNT' && s.token === 'KIDTOKEN' && s.stk === 'KIDSRV' && s.user.title === 'Kid', s);
r = await call('/api/plex/users'); ok('the list still works as the owner and marks the new current person', r.json.users.find(x => x.id === '2').current && !r.json.users.find(x => x.id === '1').current, r.json); r = await call('/api/plex/users'); ok('the list still works as the owner and marks the new current person', r.json.users.find(x => x.id === '2').current && !r.json.users.find(x => x.id === '1').current, r.json);
r = await call('/api/plex/switch', { id: '3' }); ok('switching straight to another person works (no PIN needed for them)', r.status === 200 && r.json.user.title === 'Guest', r); r = await call('/api/plex/switch', { id: '3' }); ok('switching straight to another person works (no PIN needed for them)', r.status === 200 && r.json.user.title === 'Guest', r);