Files
hub/public/music-extras.js
T

65 lines
4.4 KiB
JavaScript

// Music extras: Plex playlists you can change (create, add, remove, rename, delete, save the queue) and a sleep timer.
// Uses the player globals from app.js (px, pl, jfetch, actionSheet, textSheet, confirmSheet, toast, syncUI, saveState).
// ---- Plex playlists. The hub only lets /plex/playlists... writes through, so nothing else on the server can be changed from here.
const plx = {
_m: null,
async mid() { return plx._m || (plx._m = (await px.get('/identity')).machineIdentifier); },
async uri(keys) { return `server://${await plx.mid()}/com.plexapp.plugins.library/library/metadata/${keys.join(',')}`; },
async call(method, path) {
const r = await fetch('/plex' + path, { method, headers: { Accept: 'application/json' } });
if (!r.ok) throw new Error('Plex said no (' + r.status + '). Your Plex account may not be allowed to change playlists.');
return r.json().catch(() => ({}));
},
async list() { return ((await px.get('/playlists?playlistType=audio')).Metadata || []).filter(p => !p.smart); },
async create(title, keys) { return plx.call('POST', `/playlists?type=audio&smart=0&title=${encodeURIComponent(title)}&uri=${encodeURIComponent(await plx.uri(keys))}`); },
async add(id, keys) { return plx.call('PUT', `/playlists/${encodeURIComponent(id)}/items?uri=${encodeURIComponent(await plx.uri(keys))}`); },
remove: (id, pid) => plx.call('DELETE', `/playlists/${encodeURIComponent(id)}/items/${encodeURIComponent(pid)}`),
rename: (id, title) => plx.call('PUT', `/playlists/${encodeURIComponent(id)}?title=${encodeURIComponent(title)}`),
del: id => plx.call('DELETE', `/playlists/${encodeURIComponent(id)}`),
};
/** Pick a playlist (or make a new one) and put these tracks in it. */
async function addToPlaylist(tracks, suggest = '') {
const keys = tracks.map(t => t.key).filter(Boolean); if (!keys.length) return;
let lists = [];
try { lists = await plx.list(); } catch (e) { return toast(e.message); }
const newOne = () => textSheet('New playlist', 'Playlist name', 'Create', async name => {
try { await plx.create(name, keys); toast('Playlist “' + name + '” created'); if (location.hash.startsWith('#/music/playlists')) route(); } catch (e) { toast(e.message); }
}, suggest);
actionSheet('Add to playlist', keys.length + (keys.length === 1 ? ' track' : ' tracks'), [
{ label: 'New playlist…', icon: 'plus', run: newOne },
...lists.map(p => ({ label: p.title, icon: 'music', run: async () => { try { await plx.add(p.ratingKey, keys); toast('Added to ' + p.title); if (location.hash === '#/music/playlist/' + p.ratingKey) route(); } catch (e) { toast(e.message); } } })),
]);
}
// ---- Sleep timer: fades the music out and pauses after a set time, or when the current song ends.
const sleepT = { end: 0, eot: false, timer: null, fade: null };
function sleepClear() { clearTimeout(sleepT.timer); clearInterval(sleepT.fade); sleepT.end = 0; sleepT.eot = false; pl.a.volume = 1; }
function sleepLabel() {
if (sleepT.eot) return 'Sleep · end of song';
if (sleepT.end) return 'Sleep · ' + Math.max(1, Math.round((sleepT.end - Date.now()) / 6e4)) + ' min';
return 'Sleep';
}
function sleepFade() {
clearInterval(sleepT.fade);
const t0 = Date.now(), v0 = pl.a.volume || 1;
sleepT.fade = setInterval(() => {
const f = Math.min(1, (Date.now() - t0) / 8000);
pl.a.volume = Math.max(0, v0 * (1 - f));
if (f >= 1) { clearInterval(sleepT.fade); pl.a.pause(); pl.a.volume = 1; sleepT.end = 0; const b = document.getElementById('cnz'); if (b) b.textContent = 'Sleep'; toast('Sleep timer: music stopped'); }
}, 200);
}
function sleepSet(minutes) {
sleepClear();
if (minutes === 'eot') sleepT.eot = true;
else if (minutes > 0) { sleepT.end = Date.now() + minutes * 6e4; sleepT.timer = setTimeout(sleepFade, minutes * 6e4); }
const b = document.getElementById('cnz'); if (b) b.textContent = sleepLabel();
toast(minutes ? (minutes === 'eot' ? 'Music will stop when this song ends' : 'Music will fade out in ' + minutes + ' minutes') : 'Sleep timer off');
}
function sleepSheet() {
const opts = [[15, '15 minutes'], [30, '30 minutes'], [45, '45 minutes'], [60, '1 hour'], [90, '1.5 hours'], ['eot', 'When this song ends']].map(([v, label]) => ({ label, icon: 'pause', run: () => sleepSet(v) }));
if (sleepT.end || sleepT.eot) opts.push({ label: 'Turn off the timer', icon: 'x', run: () => sleepSet(0) });
actionSheet('Sleep timer', sleepLabel() === 'Sleep' ? 'Fades the music out and pauses' : sleepLabel(), opts);
}