Files
linkspin/public/assets/video-spin.js
T
2026-11-23 04:52:20 -06:00

109 lines
14 KiB
JavaScript

// Video Spin (2026-11-22): the third view on the Links screen. One short link that rotates through video pages on Social Tube.
// It is a spin link underneath (rotator.js, kind 'video'): pause, weights and removal go through the spin-link routes; creating one,
// adding videos and the play counts go through /api/my/videospins (server.js), which checks every video with Video App Income.
(function () {
'use strict';
if (!window.CR || !document.getElementById('vsWs')) return;
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast;
let D = null, SPINS = [], SEL = null, HOST = '', PLAYS = {}, BUSY = false;
let WANT = Number((/^#v([0-9]+)$/.exec(location.hash) || [])[1]) || 0; // the Video Spin named in the address when the page opened
const mark = () => { if (!$('vsWs').hidden) history.replaceState(null, '', '#v' + (SEL || '')); };
const base = () => 'https://' + (HOST || location.host), linkOf = s => base() + '/r/' + s.code;
const clicks7 = s => s.hits7 || 0;
const zoneCode = s => '<iframe src="' + base() + '/vz/' + s.code + '" width="315" height="560" style="border:0;border-radius:14px;max-width:100%" allow="fullscreen" allowfullscreen loading="lazy" title="Videos"></iframe>';
const state = s => s.paused ? { cls: 'warn', t: 'PAUSED' } : !s.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE VIDEO' } : { cls: 'ok', t: 'LIVE' };
// ── view switch: this script only owns the Video Spins view; banner-spin.js keeps switching the other two ──
function show(on) {
$('vsWs').hidden = !on; const vb = $('vsNewBtn'); if (vb) vb.hidden = !on;
if (on) { $('ws').hidden = true; $('bsWs').hidden = true; const nb = $('newBtn'), bn = $('bsNewBtn'); if (nb) nb.hidden = true; if (bn) bn.hidden = true; }
}
$('vsw').querySelectorAll('button').forEach(b => b.addEventListener('click', () => {
const on = b.dataset.v === 'videos'; show(on);
if (on) load(true);
}));
(function addBtn(n) { const nb = $('newBtn'); if (!nb) { if (n < 50) setTimeout(() => addBtn(n + 1), 200); return; }
const b = document.createElement('button'); b.className = 'btn pri'; b.id = 'vsNewBtn'; b.type = 'button'; b.hidden = $('vsWs').hidden; b.textContent = '+ New Video Spin'; nb.parentNode.appendChild(b);
b.addEventListener('click', () => { SEL = null; render(); const i = $('vsNewName'); if (i) i.focus(); }); })(0);
async function load(keep) {
try { D = await CR.get('/api/my/videospins'); } catch (e) { toast(e.message, true); return; }
SPINS = (D.spins || []).slice().sort((a, b) => clicks7(b) - clicks7(a) || b.created - a.created);
const hs = D.hosts || []; if (!HOST || !hs.includes(HOST)) HOST = hs[0] || location.host;
if (!keep || !SPINS.some(s => s.id === SEL)) SEL = null;
if (WANT) { if (SPINS.some(s => s.id === WANT)) SEL = WANT; WANT = 0; }
mark(); setTimeout(mark, 1500); // the spin-link list reloads in the background and may set its own address; keep ours while this view is open
render(); if (SEL) loadPlays();
}
async function loadPlays() { const id = SEL; try { const r = await CR.get('/api/my/videospins/' + id + '/plays'); if (id === SEL) { PLAYS = r.plays || {}; renderDetail(); } } catch (e) {} }
function render() { renderList(); renderDetail(); }
function renderList() {
const L = D.limits || { spins: 0, videos: 0 }, t = D.tier || { label: '' };
$('vsCount').textContent = SPINS.length + ' Video Spin' + (SPINS.length === 1 ? '' : 's');
$('vsTier').innerHTML = L.spins ? esc(t.label) + ' tier: ' + L.spins + ' Video Spins, ' + L.videos + ' videos in each.'
: 'Video Spins start at the Starter tier (any package of your own): 2 Video Spins with 5 videos in each.';
$('vsItems').innerHTML = SPINS.length ? SPINS.map(s => { const h = state(s); return '<div class="item' + (s.id === SEL ? ' on' : '') + '" data-id="' + s.id + '" role="button" tabindex="0">'
+ '<div><div class="nm">' + esc(s.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + ' <span class="tag plain">' + s.destinations.length + ' video' + (s.destinations.length === 1 ? '' : 's') + '</span></div><div class="cd">' + esc((HOST || location.host) + '/r/' + s.code) + '</div></div>'
+ '<div class="rt"><span class="n">' + fmt(clicks7(s)) + '</span><span class="muted" style="font-size:10px">7 d</span></div></div>'; }).join('')
: '<div class="empty"><div class="muted">No Video Spins yet.</div></div>';
$('vsItems').querySelectorAll('.item').forEach(el => { const go = () => { SEL = Number(el.dataset.id); PLAYS = {}; history.replaceState(null, '', '#v' + SEL); render(); loadPlays(); };
el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
}
function renderDetail() {
const box = $('vsDetail'), s = SPINS.find(x => x.id === SEL), L = D.limits || { spins: 0, videos: 0 };
if (!s) {
const can = D.on && L.spins > 0 && SPINS.length < L.spins;
box.innerHTML = '<div class="vsp"><div class="h-disp" style="font-size:18px">Video Spin</div>'
+ '<p class="muted" style="margin:8px 0 14px;max-width:560px">One short link that plays a different video page each time it is opened. Pick videos you made on Video App Income, or add any member\'s video by its Social Tube link. Share the one link; the videos take turns. People who go on to make their own video are credited to you.</p>'
+ '<details id="vsHow" style="margin:0 0 14px;max-width:640px"><summary style="cursor:pointer;font-weight:600">Watch how this works (1:42)</summary>'
+ '<video controls playsinline preload="none" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.jpg?v=20261122a" style="display:block;width:100%;height:auto;background:#000;border-radius:12px;margin-top:10px" aria-label="Video: Marty walks through Video Spins, 1 minute 42 seconds"><source src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.mp4?v=20261122a" type="video/mp4"></video></details>'
+ (D.vaiError ? '<p class="muted" style="margin:0 0 12px">' + esc(D.vaiError) + '</p>' : '')
+ (!D.on ? '<p class="muted">Video Spins are not switched on yet.</p>'
: can ? '<div class="vsrow"><input class="field" id="vsNewName" maxlength="80" placeholder="Name this Video Spin, for example: My best videos"><button class="btn pri" type="button" id="vsCreate">Create</button></div>'
: '<p class="muted">' + (L.spins ? 'You have all ' + L.spins + ' Video Spins your tier holds. Remove one to make another.' : 'Video Spins start at the Starter tier (any package of your own).') + '</p>')
+ '</div>';
const c = $('vsCreate'); if (c) { const go = async () => { const name = $('vsNewName').value.trim(); if (!name) { toast('Give it a name first.', true); return; } if (BUSY) return; BUSY = true;
try { const r = await api('/api/my/videospins', { name }); SEL = r.rotation.id; history.replaceState(null, '', '#v' + SEL); toast('Video Spin created. Now add videos.'); await load(true); } catch (e) { toast(e.message, true); } BUSY = false; };
c.addEventListener('click', go); $('vsNewName').addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); }
return;
}
const inSpin = new Set(s.destinations.map(d => d.vid)), mine = (D.videos || []).filter(v => !inSpin.has(v.id)), room = Math.max(0, L.videos - s.destinations.length);
const rows = s.destinations.map(d => { const p = PLAYS[d.vid] || null, gone = p && p.live === false;
const tag = gone ? '<span class="tag bad">REMOVED BY OWNER</span>' : !d.active ? '<span class="tag warn">' + (d.autoPaused ? 'PAUSED: NOT LOADING' : 'PAUSED') + '</span>' : '';
return '<div class="vsv"><img src="' + esc(d.poster || '') + '" alt="" loading="lazy"><div class="vsi"><b>' + esc(d.label || 'Video') + '</b> ' + tag + '<div class="muted">' + (d.vowner ? 'By ' + esc(d.vowner) + '. ' : '') + fmt(d.hits || 0) + ' click' + ((d.hits || 0) === 1 ? '' : 's')
+ (p ? ', ' + fmt(p.views) + ' opened, ' + fmt(p.plays) + ' played, ' + fmt(p.taps) + ' tapped the button' : '') + '</div></div>'
+ '<div class="vsa"><button class="btn sm" type="button" data-act="' + (d.active ? 'pause' : 'resume') + '" data-d="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm" type="button" data-act="remove" data-d="' + d.id + '">Remove</button></div></div>'; }).join('');
box.innerHTML = '<div class="vsp"><div class="vshead"><h2>' + esc(s.name) + '</h2><span class="tag ' + state(s).cls + '">' + state(s).t + '</span></div>'
+ '<div class="vsrow"><input class="field mono" id="vsLink" readonly value="' + esc(linkOf(s)) + '"><button class="btn pri" type="button" id="vsCopy">Copy link</button><button class="btn" type="button" id="vsPause">' + (s.paused ? 'Resume' : 'Pause') + '</button><button class="btn" type="button" id="vsDel">Delete</button></div>'
+ '<p class="muted" style="margin:8px 0 0">' + fmt(s.hits || 0) + ' clicks in all, ' + fmt(s.hits7 || 0) + ' in the last 7 days' + (s.conversions ? ', ' + s.conversions + ' conversion' + (s.conversions === 1 ? '' : 's') : '') + '. Each open goes to one of the videos below.</p>'
+ '<details class="vsz"><summary>Put it on a web page (rotating player)</summary><p class="muted" style="margin:8px 0">Paste this code into any page. Each page view plays a different video from this spin, with that video\'s own button. Page views are not counted as clicks; plays and button taps show under each video.</p><textarea class="field mono" id="vsZone" readonly rows="3" style="width:100%">' + esc(zoneCode(s)) + '</textarea><div class="vsrow" style="margin-top:8px"><button class="btn" type="button" id="vsZoneCopy">Copy code</button></div></details>'
+ '<h3 class="vsh">Videos in this spin <span class="muted">' + s.destinations.length + ' of ' + L.videos + '</span></h3>'
+ (rows || '<p class="muted">No videos yet. Add some below; the link starts working with the first one.</p>')
+ '<h3 class="vsh">Add your videos</h3>'
+ (D.vaiError ? '<p class="muted">' + esc(D.vaiError) + '</p>' : !D.member ? '<p class="muted">No Video App Income account was found for your email address. Make your first video at <a href="https://linkspin.app/r/nwvai?src=linkspin&amp;s2=" target="_blank" rel="noopener">videoappincome.com</a> (it is free), then come back.</p>'
: !room ? '<p class="muted">This Video Spin is full for your tier.</p>'
: mine.length ? '<div class="vsgrid">' + mine.map(v => '<label class="vsc"><input type="checkbox" value="' + esc(v.id) + '"><img src="' + esc(v.poster) + '" alt="" loading="lazy"><span>' + esc(v.title) + '</span></label>').join('') + '</div><div class="vsrow" style="margin-top:10px"><button class="btn pri" type="button" id="vsAddMine">Add selected</button><span class="muted">Room for ' + room + ' more.</span></div>'
: '<p class="muted">' + ((D.videos || []).length ? 'All of your videos are already in this spin.' : 'You have no videos on Social Tube yet. Make one on Video App Income and it appears here.') + '</p>')
+ '<h3 class="vsh">Add any member\'s video</h3><p class="muted" style="margin:0 0 8px">Open the video on socialtube.club and paste its address. Its owner gets the views; people who go on to join are credited to you.</p>'
+ (room ? '<div class="vsrow"><input class="field" id="vsLinkIn" maxlength="300" placeholder="https://socialtube.club/watch/..."><button class="btn" type="button" id="vsAddLink">Add</button></div>' : '<p class="muted">This Video Spin is full for your tier.</p>')
+ '</div>';
$('vsCopy').addEventListener('click', () => { const u = linkOf(s); (navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(u) : Promise.reject()).then(() => toast('Link copied'), () => { $('vsLink').select(); toast('Select and copy the link', true); }); });
$('vsZoneCopy').addEventListener('click', () => { const u = zoneCode(s); (navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(u) : Promise.reject()).then(() => toast('Code copied'), () => { $('vsZone').select(); toast('Select and copy the code', true); }); });
$('vsPause').addEventListener('click', () => act(() => api('/api/my/rotations/' + s.id, { paused: !s.paused }), s.paused ? 'Resumed' : 'Paused'));
$('vsDel').addEventListener('click', e => { const b = e.currentTarget; if (b.dataset.arm !== '1') { b.dataset.arm = '1'; b.textContent = 'Tap again to delete'; setTimeout(() => { b.dataset.arm = ''; b.textContent = 'Delete'; }, 4000); return; }
act(async () => { await api('/api/my/rotations/' + s.id, { remove: true }); SEL = null; history.replaceState(null, '', '#v'); }, 'Video Spin deleted'); });
box.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => { const a = b.dataset.act, p = '/api/my/rotations/' + s.id + '/dest/' + b.dataset.d;
act(() => api(p, a === 'remove' ? { remove: true } : { active: a === 'resume' }), a === 'remove' ? 'Video removed from this spin' : a === 'resume' ? 'Video resumed' : 'Video paused'); }));
const am = $('vsAddMine'); if (am) am.addEventListener('click', () => { const ids = [...box.querySelectorAll('.vsc input:checked')].map(x => x.value); if (!ids.length) { toast('Tick at least one video.', true); return; }
act(() => api('/api/my/videospins/' + s.id + '/add', { ids }), ids.length === 1 ? 'Video added' : ids.length + ' videos added'); });
const al = $('vsAddLink'); if (al) { const go = () => { const link = $('vsLinkIn').value.trim(); if (!link) { toast('Paste a Social Tube video link first.', true); return; } act(() => api('/api/my/videospins/' + s.id + '/add', { link }), 'Video added'); };
al.addEventListener('click', go); $('vsLinkIn').addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); }
}
async function act(fn, done) { if (BUSY) return; BUSY = true; try { await fn(); if (done) toast(done); await load(true); } catch (e) { toast(e.message, true); } BUSY = false; }
window.VideoSpin = { reload: () => load(true) };
if (/^#v/.test(location.hash)) setTimeout(() => { const b = $('vsw').querySelector('button[data-v="videos"]'); if (b) b.click(); }, 400);
})();