'use strict'; // ---- Store: everything you can get, in one place. Books (free sources), free audiobooks, radio stations, and My Store: content the admin adds themselves (books, // music, apps to download, and extensions that add features to the hub). The first three are the same screens as before, shown inside this one. const stApi = (p, opts) => jfetch('/api/store/my' + p, opts); const stOpt = (m, o) => ({ method: m, headers: { 'content-type': 'application/json' }, body: o ? JSON.stringify(o) : undefined }); const ST_KINDS = [['book', 'Books', 'book'], ['music', 'Music', 'music'], ['app', 'Apps', 'files'], ['extension', 'Extensions', 'cog']]; const stKind = k => ST_KINDS.find(x => x[0] === k) || ST_KINDS[2]; const stSize = b => fmtSize(+b || 0); const stCover = it => it.cover ? `/api/store/my/items/${it.id}/cover?v=${it.updated}` : ''; const stHue = s => { let h = 0; for (const ch of String(s)) h = (h * 31 + ch.charCodeAt(0)) % 360; return h; }; let stItems = [], stInstalled = [], stAdmin = false, stFilter = 'all'; /** The sections this person may open (each needs its own tab's permission, except My Store). */ const stSections = () => [['books', 'Books', allowed('read')], ['audiobooks', 'Audiobooks', allowed('audio')], ['radio', 'Radio', allowed('radio')], ['mine', 'My Store', true]].filter(s => s[2]); async function viewStore(args = []) { const secs = stSections(), want = args[0] === 'ext' ? 'mine' : args[0], sec = (secs.find(s => s[0] === want) || secs[0])[0]; const v = $('#view'); v.innerHTML = `

Store

${secs.map(s => `${esc(s[1])}`).join('')}
`; const el = $('#stbody'), host = { el, hash: '#/store/' + sec }; if (sec === 'books') return rdStore(host); if (sec === 'audiobooks') return viewFreeBooks(host); if (sec === 'radio') return viewRadio(host); if (args[0] === 'ext' && args[1]) return stRunExt(el, args[1]); return stMine(el); } // ---------------------------------------------------------------- My Store async function stLoad() { const r = await stApi('/items'); stItems = r.items; stInstalled = r.installed; stAdmin = r.admin; return r; } async function stMine(el) { try { await stLoad(); } catch (e) { el.innerHTML = `

${esc(e.message)}

`; return; } const draw = () => { if (!$('#stbody')) return; const mine = stItems.filter(i => i.kind === 'extension' && stInstalled.includes(i.id)), shown = stItems.filter(i => stFilter === 'all' || i.kind === stFilter); el.innerHTML = `

Books, music, apps and extensions added just for this hub.

${stAdmin ? `` : ''}
${mine.length ? `

My extensions

${mine.map(i => stCard(i, true)).join('')}
` : ''}
All${ST_KINDS.map(k => `${k[1]}`).join('')}
${shown.length ? `
${shown.map(i => stCard(i)).join('')}
` : `

${stItems.length ? 'Nothing of that kind yet.' : stAdmin ? 'Nothing here yet. Add your first book, album, app or extension.' : 'Nothing has been added yet.'}

`}`; el.querySelectorAll('#stkinds a').forEach(a => a.onclick = e => { e.preventDefault(); stFilter = a.dataset.k; draw(); }); el.querySelectorAll('[data-it]').forEach(a => a.onclick = e => { e.preventDefault(); const it = stItems.find(x => x.id === a.dataset.it); if (a.dataset.run) location.hash = '#/store/ext/' + it.id; else stDetail(it, draw); }); if ($('#stadd')) $('#stadd').onclick = () => stEdit(null, draw); }; draw(); } const stCard = (it, run) => `${it.cover ? `` : esc((it.kind === 'extension' && it.icon) || (it.title.match(/\p{L}|\p{N}/u) || ['?'])[0].toUpperCase())} ${esc(it.title)}${esc([stKind(it.kind)[1].replace(/s$/, ''), it.creator].filter(Boolean).join(' · '))}`; function stDetail(it, redraw) { const k = it.kind, f0 = it.files[0], isMine = k === 'extension' && stInstalled.includes(it.id); const url = f => `/api/store/my/items/${it.id}/files/${f.id}`; const el = openSheet(it.title, [stKind(k)[1].replace(/s$/, ''), it.creator, it.version && 'v' + it.version].filter(Boolean).join(' · '), `
${it.cover ? `` : ''}
${it.description ? `

${esc(it.description).replace(/\n/g, '
')}

` : '

No description.

'}
${k === 'music' || k === 'app' ? `
${it.files.map((f, i) => `
${esc(f.name)}${esc(stSize(f.size))}${k === 'music' ? `` : ''}${icon('download')}
`).join('') || '

No files.

'}
` : ''}
${k === 'book' && f0 ? `${allowed('read') ? '' : ''}Download` : ''} ${k === 'music' && it.files.length ? `` : ''} ${k === 'app' && it.url ? `Open link` : ''} ${k === 'extension' && f0 ? `${isMine ? '' : ''}` : ''} ${stAdmin ? '' : ''}
`); const err = t => { el.querySelector('#sterr').textContent = t; }; const tracks = () => it.files.map(f => ({ key: `my:${it.id}:${f.id}`, title: f.name.replace(/\.[^.]+$/, '').replace(/^\d+[\s._-]+/, ''), artist: it.creator || '', album: it.title, thumb: stCover(it), src: url(f), nocache: true })); const play = i => { playQueue(tracks(), i || 0); closeSheet(); }; if (el.querySelector('#stplay')) el.querySelector('#stplay').onclick = () => play(0); el.querySelectorAll('[data-play]').forEach(b => b.onclick = () => play(+b.dataset.play)); if (el.querySelector('#stlib')) el.querySelector('#stlib').onclick = async e => { const b = e.currentTarget; b.disabled = true; try { const r = await stApi(`/items/${it.id}/to-library`, stOpt('POST')); closeSheet(); toast(r.duplicate ? 'Already in your library' : 'Added to your library', { label: 'Open', run: () => { location.hash = '#/read/open/' + r.id; } }); } catch (x) { err(x.message); b.disabled = false; } }; if (el.querySelector('#stinst')) el.querySelector('#stinst').onclick = async e => { const b = e.currentTarget; try { if (!isMine) { b.disabled = true; stInstalled = (await stApi(`/ext/${it.id}/install`, stOpt('POST'))).installed; } closeSheet(); location.hash = '#/store/ext/' + it.id; } catch (x) { err(x.message); b.disabled = false; } }; if (el.querySelector('#stun')) el.querySelector('#stun').onclick = () => { closeSheet(); confirmSheet('Remove this extension?', 'Its saved settings are forgotten too.', 'Remove', async () => { try { stInstalled = (await stApi(`/ext/${it.id}/uninstall`, stOpt('POST'))).installed; toast('Removed'); redraw(); } catch (x) { toast(x.message); } }); }; if (el.querySelector('#stedit')) el.querySelector('#stedit').onclick = () => { closeSheet(); stEdit(it, redraw); }; } // ---- adding and changing (admin) function stEdit(it, redraw) { const x = it || { kind: 'book', title: '', creator: '', description: '', version: '', url: '', icon: '', files: [], cover: false }; let created = false; const el = openSheet(it ? 'Edit item' : 'Add to My Store', '', `
${it ? '' : ``}
${allowed('files') ? `` : ''}
${x.cover ? 'A cover is set' : ''}
${it ? '' : ''}
`); const $e = s => el.querySelector(s), err = t => { $e('#sterr').textContent = t; }; let kind = x.kind; const files = [], existing = [...x.files]; let cover = null; const kindUi = () => { kind = it ? x.kind : $e('#stk').value; $e('#stcl').textContent = kind === 'music' ? 'Artist' : kind === 'book' ? 'Author' : 'Made by'; $e('#stapp').hidden = kind !== 'app' && kind !== 'extension'; $e('#stext').hidden = kind !== 'extension'; $e('#stup').accept = kind === 'book' ? '.epub,.pdf,.mobi,.azw3,.azw,.docx' : kind === 'music' ? 'audio/*,.mp3,.m4a,.flac,.ogg,.opus,.wav' : kind === 'extension' ? '.html' : ''; $e('#stup').multiple = kind === 'music' || kind === 'app'; }; const drawFiles = () => { $e('#stfl').innerHTML = [...existing.map((f, i) => [f.name, stSize(f.size), 'e', i]), ...files.map((f, i) => [f.name || f.path.split('/').pop(), f.size != null ? stSize(f.size) : 'from Files', 'n', i])].map(([n, s, t, i]) => `
${esc(n)}${esc(s)}
`).join('') || '

No files yet.

'; el.querySelectorAll('#stfl [data-t]').forEach(b => b.onclick = () => { (b.dataset.t === 'e' ? existing : files).splice(+b.dataset.i, 1); drawFiles(); }); }; if (!it) $e('#stk').onchange = kindUi; kindUi(); drawFiles(); $e('#stup').onchange = e => { const single = kind !== 'music' && kind !== 'app'; if (single) { files.length = 0; existing.length = 0; } for (const f of e.target.files) files.push(f); e.target.value = ''; drawFiles(); }; if ($e('#stsf')) $e('#stsf').onclick = async () => { const p = await stPickFile(); if (!p) return; if (kind !== 'music' && kind !== 'app') { files.length = 0; existing.length = 0; } files.push({ path: p.path, repo: p.repo, name: p.path.split('/').pop() }); drawFiles(); }; $e('#stcv').onchange = e => { cover = e.target.files[0] || null; $e('#stcvn').textContent = cover ? cover.name : ''; }; $e('#stx').onclick = closeSheet; if ($e('#stdel')) $e('#stdel').onclick = () => { closeSheet(); confirmSheet('Delete this item?', it.title, 'Delete', async () => { try { await stApi('/items/' + it.id, { method: 'DELETE' }); toast('Deleted'); await stLoad(); redraw(); } catch (e) { toast(e.message); } }); }; $e('#stf').onsubmit = async e => { e.preventDefault(); const ok = $e('#stok'); ok.disabled = true; err(''); try { if (!files.length && !existing.length && kind !== 'app') throw new Error('Add the file first'); let saved = await stApi('/items', stOpt('POST', { id: it && it.id, kind, title: $e('#stt').value, creator: $e('#stc').value, description: $e('#std').value, version: $e('#stv').value, url: $e('#stu').value, icon: $e('#sti') ? $e('#sti').value : '' })); if (!it) created = true; for (const f of x.files) if (!existing.some(y => y.id === f.id)) saved = await stApi(`/items/${saved.id}/files/${f.id}`, { method: 'DELETE' }); let n = 0; for (const f of files) { ok.textContent = `Adding ${++n} of ${files.length}…`; saved = f instanceof File ? await stApi(`/items/${saved.id}/files?name=${encodeURIComponent(f.name)}`, { method: 'POST', body: f, headers: { 'content-type': 'application/octet-stream' } }) : await stApi(`/items/${saved.id}/files`, stOpt('POST', { repo: f.repo, path: f.path })); } if (cover) saved = await stApi(`/items/${saved.id}/cover`, { method: 'POST', body: cover, headers: { 'content-type': cover.type } }); closeSheet(); toast(it ? 'Saved' : 'Added'); await stLoad(); redraw(); } catch (x2) { err(x2.message + (created ? ' The item was created without it: open it to finish.' : '')); ok.disabled = false; ok.textContent = it ? 'Save' : 'Add'; } }; } /** Pick one file from your Seafile libraries. Resolves { repo, path } or null. */ function stPickFile() { return new Promise(resolve => { if (!sf.token()) { toast('Open Files and sign in first'); return resolve(null); } let repo = null, dir = '/', done = false; const el = openSheet('Choose a file from Files', '', '
'); const finish = v => { done = true; closeSheet(); resolve(v); }; el.querySelector('.scrim').addEventListener('click', () => { if (!done) resolve(null); }); const draw = async () => { const box = el.querySelector('#stpk'); box.innerHTML = '

Loading…

'; try { if (!repo) { const repos = (await sf.req('/api2/repos/')).filter(r => !r.encrypted).sort((a, b) => a.name.localeCompare(b.name)); box.innerHTML = `
${repos.map(r => ``).join('')}
`; box.querySelectorAll('[data-r]').forEach(b => b.onclick = () => { repo = b.dataset.r; dir = '/'; draw(); }); } else { const items = (await sf.req(`/api2/repos/${encodeURIComponent(repo)}/dir/?p=${encodeURIComponent(dir)}`)).sort((a, b) => (a.type === b.type ? 0 : a.type === 'dir' ? -1 : 1) || a.name.localeCompare(b.name)); box.innerHTML = `

${esc(dir)}

${items.map(x => ``).join('')}
`; box.querySelectorAll('[data-d]').forEach(b => b.onclick = () => { dir = (dir === '/' ? '' : dir) + '/' + b.dataset.d; draw(); }); box.querySelectorAll('[data-f]').forEach(b => b.onclick = () => finish({ repo, path: (dir === '/' ? '' : dir) + '/' + b.dataset.f })); box.querySelector('[data-up]').onclick = () => { if (dir === '/') repo = null; else dir = dir.slice(0, dir.lastIndexOf('/')) || '/'; draw(); }; } box.querySelector('#pcx').onclick = () => finish(null); } catch (e) { box.innerHTML = `

${esc(e.message)}

`; } }; draw(); }); } // ---------------------------------------------------------------- running an extension // The extension is one HTML file in a sandboxed frame (no access to your sign-in or the hub's data). It talks to the hub only through the messages below. async function stRunExt(el, id) { try { await stLoad(); } catch (e) { el.innerHTML = `

${esc(e.message)}

`; return; } const it = stItems.find(x => x.id === id && x.kind === 'extension'); if (!it) { el.innerHTML = '

That extension is not in the store any more.

'; return; } if (!stInstalled.includes(id)) { el.innerHTML = `

Install “${esc(it.title)}” from My Store first.

`; return; } el.innerHTML = `
${icon('back')}My Store${esc(it.title)}
`; const frame = el.querySelector('#stframe'); let data = null, timer; // (the page is fetched by the hub and shown from here, so the frame needs no sign-in of its own; its sandbox keeps it from touching anything of the hub's) fetch(`/api/store/my/ext/${id}/page`).then(r => r.ok ? r.text() : Promise.reject(new Error('Could not load it'))).then(h => { frame.srcdoc = h; }).catch(e => { el.querySelector('#stframe').outerHTML = `

${esc(e.message)}

`; }); const load = async () => data || (data = await stApi(`/ext/${id}/data`).catch(() => ({}))); const save = () => { clearTimeout(timer); timer = setTimeout(() => stApi(`/ext/${id}/data`, stOpt('POST', data)).catch(e => toast(e.message)), 400); }; const onMsg = async e => { if (!document.body.contains(frame)) return removeEventListener('message', onMsg); if (e.source !== frame.contentWindow || !e.data || !e.data.hub) return; const { id: mid, method, args = [] } = e.data; let result, error; try { if (method === 'storage.get') result = (await load())[String(args[0])] ?? null; else if (method === 'storage.all') result = { ...(await load()) }; else if (method === 'storage.set') { const d = await load(); d[String(args[0]).slice(0, 100)] = args[1]; if (JSON.stringify(d).length > 256 * 1024) { delete d[String(args[0]).slice(0, 100)]; throw new Error('Out of space (256 KB)'); } save(); result = true; } else if (method === 'storage.remove') { delete (await load())[String(args[0])]; save(); result = true; } else if (method === 'toast') { toast(String(args[0]).slice(0, 200)); result = true; } else if (method === 'user') result = { name: ME ? ME.name : '' }; else if (method === 'open') { if (/^https?:\/\//i.test(String(args[0]))) window.open(String(args[0]), '_blank', 'noopener,noreferrer'); result = true; } else throw new Error('Unknown request'); } catch (x) { error = x.message; } frame.contentWindow.postMessage({ hub: 1, id: mid, result, error }, '*'); }; addEventListener('message', onMsg); }