(() => { const LAYERS = { video: {label:'Видео', c:'var(--cy)', hex:'#2de2e6', pub:true}, audio: {label:'Аудио', c:'var(--gr)', hex:'#3dff9a', pub:true}, thermal: {label:'Тепловой канал', c:'var(--or)', hex:'#ff8a2a', pub:false}, emotion: {label:'Эмоции', c:'var(--mg)', hex:'#ff2a6d', pub:false}, }; const S = {token:null, user:null, view:'market', sort:'latest', tag:'', q:'', rec:null, col:null, cache:{}}; const $ = s => document.querySelector(s); const $$ = s => [...document.querySelectorAll(s)]; const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const short = id => String(id).slice(0, 8); const store = { get(k){ try { return JSON.parse(localStorage.getItem(k)); } catch(e){ return null; } }, set(k,v){ try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, JSON.stringify(v)); } catch(e){} }, }; let wireN = 0; function wire(msg, cls){ const l = $('#wire-l'), d = document.createElement('div'); d.innerHTML = '' + new Date().toLocaleTimeString('ru-RU') + '' + esc(msg) + ''; l.prepend(d); while (l.children.length > 200) l.lastChild.remove(); $('#wire-last').textContent = msg; $('#wire-n').textContent = ++wireN; } function toast(msg, kind){ const col = {ok:'var(--gr)', er:'var(--rd)', warn:'var(--yl)'}[kind] || 'var(--cy)'; const lab = {ok:'готово', er:'ошибка', warn:'уведомление'}[kind] || 'информация'; const t = document.createElement('div'); t.className = 'toast'; t.style.setProperty('--c', col); t.innerHTML = '' + lab + '' + esc(msg); $('#toasts').append(t); setTimeout(() => { t.classList.add('out'); setTimeout(() => t.remove(), 260); }, 3200); } $('#wire-h').onclick = () => $('#wire').classList.toggle('on'); function localizeError(message){ const messages = { 'bad username': 'Некорректный псевдоним', 'exists': 'Псевдоним уже занят', 'unauthorized': 'Требуется авторизация', 'not found': 'Не найдено', 'too large': 'Запись слишком большая', 'bad magic': 'Неверный заголовок BDv1', 'bad layer b64': 'Некорректные данные канала Base64', 'no META': 'Отсутствует блок META', 'source not found': 'Исходная запись не найдена', 'forbidden source': 'Нет доступа к исходной записи', 'forbidden': 'Доступ запрещён', 'no such record': 'Запись не найдена', 'private collection': 'Коллекция закрыта', 'bad signature': 'Неверная подпись', 'no such fortress': 'Крепость не найдена', 'bad flag': 'Некорректные данные хранилища', 'bad icebreaker': 'Некорректный ледокол', 'bad cell': 'Некорректная ячейка', 'bad op': 'Некорректная команда', 'vm timeout': 'Превышено время работы виртуальной машины', 'bad code': 'Некорректный код программы', }; const text = String(message); if (text.startsWith('vm error:')) return 'Ошибка виртуальной машины'; return messages[text] || 'Не удалось выполнить запрос'; } async function api(path, opt = {}){ const o = {method: opt.method || 'GET', headers: {}}; if (S.token) o.headers.Authorization = 'Bearer ' + S.token; if (opt.json !== undefined){ o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(opt.json); } else if (opt.body !== undefined) o.body = opt.body; let r, j = null; try { r = await fetch(path, o); } catch(e){ setLink(false); wire('ОШИБКА ' + o.method + ' ' + path + ' :: нет связи', 'er'); return {ok:false, status:0, data:null}; } try { j = await r.json(); } catch(e){} if (j && j.error) j.error = localizeError(j.error); if (!opt.quiet || !r.ok) wire((r.ok ? 'ПРИЁМ ' : 'ОШИБКА ') + r.status + ' ' + o.method + ' ' + path + (!r.ok && j && j.error ? ' :: ' + j.error : ''), r.ok ? '' : 'er'); return {ok:r.ok, status:r.status, data:j}; } function setLink(up){ $('#link').classList.toggle('up', up); $('#linktx').textContent = up ? 'связь установлена' : 'нет связи'; } function rng(str){ let h = 2166136261 >>> 0; for (const c of String(str)){ h ^= c.charCodeAt(0); h = Math.imul(h, 16777619); } return () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return ((h >>> 0) % 100000) / 100000; }; } function paintScene(cv, id){ const x = cv.getContext('2d'), w = cv.width, hh = cv.height, R = rng(id); const hue = Math.floor(R()*360), hue2 = (hue + 120 + R()*120) % 360; let g = x.createLinearGradient(0, 0, 0, hh); g.addColorStop(0, `hsl(${hue},60%,6%)`); g.addColorStop(.6, `hsl(${hue2},75%,${18 + R()*10}%)`); g.addColorStop(1, `hsl(${hue},50%,4%)`); x.fillStyle = g; x.fillRect(0, 0, w, hh); const sx = w*(.15 + R()*.7), sy = hh*(.28 + R()*.2), sr = hh*(.1 + R()*.12); g = x.createRadialGradient(sx, sy, 0, sx, sy, sr*3.2); g.addColorStop(0, `hsla(${hue2},100%,72%,.95)`); g.addColorStop(.28, `hsla(${hue2},100%,55%,.4)`); g.addColorStop(1, 'transparent'); x.fillStyle = g; x.fillRect(0, 0, w, hh); for (let i = 0; i < 40; i++){ x.fillStyle = `rgba(255,255,255,${R()*.5})`; x.fillRect(R()*w, R()*hh*.5, 1, 1); } for (let L = 0; L < 3; L++){ const base = hh*(.62 + L*.14), light = 14 - L*4; let px = -R()*20; while (px < w){ const bw = w*(.035 + R()*.075), bh = hh*(.12 + R()*(.5 - L*.12)); x.fillStyle = `hsl(${hue},35%,${light}%)`; x.fillRect(px, base - bh, bw, hh); if (R() > .7){ x.fillRect(px + bw*.45, base - bh - hh*.06, 1.5, hh*.06); } if (L > 0){ const wc = R() > .5 ? hue2 : 48; for (let wy = base - bh + 4; wy < hh - 3; wy += 5) for (let wx = px + 3; wx < px + bw - 3; wx += 4) if (R() > .8){ x.fillStyle = `hsla(${wc},100%,${60 + R()*25}%,${.35 + R()*.5})`; x.fillRect(wx, wy, 1.6, 2); } } if (L === 2 && R() > .82){ const sc = R() > .5 ? '#ff2a6d' : '#2de2e6'; x.fillStyle = sc; x.shadowColor = sc; x.shadowBlur = 8; x.fillRect(px + 2, base - bh + 6, Math.max(3, bw*.3), hh*.12); x.shadowBlur = 0; } px += bw + R()*3; } } x.fillStyle = 'rgba(0,0,0,.28)'; for (let y = 0; y < hh; y += 3) x.fillRect(0, y, w, 1); } function avatar(name){ const R = rng('av:' + name), hue = Math.floor(R()*360), c1 = `hsl(${hue},90%,60%)`, c2 = `hsl(${(hue+160)%360},90%,60%)`; let cells = ''; for (let y = 0; y < 5; y++) for (let x = 0; x < 3; x++){ if (R() > .5){ const col = R() > .3 ? c1 : c2; cells += ``; if (x < 2) cells += ``; } } return `${cells}`; } function b64bytes(b){ try { const s = atob(b), a = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i); return a; } catch(e){ return new Uint8Array(); } } function bytesText(a){ try { return new TextDecoder('utf-8', {fatal:true}).decode(a); } catch(e){ return null; } } function printable(a){ for (const c of a) if (c < 9 || (c > 13 && c < 32) || c === 127) return false; return true; } function hexdump(a){ let out = ''; for (let i = 0; i < a.length; i += 16){ const row = a.slice(i, i + 16); const hx = [...row].map(v => v.toString(16).padStart(2, '0')).join(' ').padEnd(47); const tx = [...row].map(v => v >= 32 && v < 127 ? String.fromCharCode(v) : '.').join(''); out += '' + i.toString(16).padStart(6, '0') + ' ' + hx + ' ' + esc(tx) + '\n'; } return out || '(пусто)'; } function paintWave(cv, bytes, hex, locked){ const r = cv.getBoundingClientRect(), dpr = window.devicePixelRatio || 1; cv.width = Math.max(1, r.width*dpr); cv.height = Math.max(1, r.height*dpr); const x = cv.getContext('2d'), w = cv.width, h = cv.height, mid = h/2; x.clearRect(0, 0, w, h); const bars = Math.floor(w / (3*dpr)); x.fillStyle = hex; for (let i = 0; i < bars; i++){ let v; if (locked) v = .05; else if (!bytes.length) v = .03; else { const b = bytes[Math.floor(i / bars * bytes.length)] || 0, n = bytes[(Math.floor(i / bars * bytes.length) + 1) % bytes.length] || 0; v = .12 + ((b*7 + n*3) % 97) / 97 * .8 * (0.55 + .45*Math.sin(i/7)); } const bh = Math.max(1, v*(h - 8)); x.globalAlpha = .45 + v*.55; x.fillRect(i*3*dpr, mid - bh/2, 2*dpr, bh); } x.globalAlpha = 1; } function renderChip(){ const c = $('#opchip'); if (S.user){ c.innerHTML = avatar(S.user) + '
' + esc(S.user) + '
оператор
'; c.onclick = () => go('rig'); } else { c.innerHTML = '
Подключиться
гость
'; c.onclick = openAuth; } } function openAuth(){ $('#au').classList.add('on'); setTimeout(() => $('#au-u').focus(), 50); } function setSession(token, user){ S.token = token; S.user = user; store.set('nm.session', token ? {token, user} : null); renderChip(); if (S.view === 'rig') loadRig(); } $$('[data-at]').forEach(b => b.onclick = () => { $$('[data-at]').forEach(x => x.classList.toggle('on', x === b)); $('#au-new').classList.toggle('is-hidden', (b.dataset.at === 'new' ? '' : 'none') === 'none'); $('#au-tok').classList.toggle('is-hidden', (b.dataset.at === 'tok' ? '' : 'none') === 'none'); }); async function register(){ const u = $('#au-u').value.trim(); if (!u) return toast('укажите псевдоним', 'warn'); const r = await api('/register', {method:'POST', json:{username:u, bio:$('#au-b').value}}); if (!r.ok) return toast(r.status === 409 ? 'псевдоним уже занят' : (r.data && r.data.error) || 'не удалось зарегистрироваться', 'er'); setSession(r.data.token, r.data.username); $('#au').classList.remove('on'); toast('профиль создан: ' + r.data.username, 'ok'); } async function restore(tok, quiet){ const keep = S.token; S.token = tok; const r = await api('/me', {quiet:true}); if (!r.ok){ S.token = keep; if (!quiet) toast('токен отклонён', 'er'); return false; } setSession(tok, r.data.username); if (!quiet) toast('сессия восстановлена: ' + r.data.username, 'ok'); return true; } $('#au-go').onclick = register; $('#au-u').onkeydown = $('#au-b').onkeydown = e => { if (e.key === 'Enter') register(); }; $('#au-tgo').onclick = async () => { const t = $('#au-t').value.trim(); if (t && await restore(t)) $('#au').classList.remove('on'); }; function needAuth(){ if (S.token) return true; toast('сначала подключитесь', 'warn'); openAuth(); return false; } function go(v, arg){ const h = arg ? v + '/' + encodeURIComponent(arg) : v; if (location.hash === '#' + h) route(); else location.hash = h; } function route(){ const [v, a] = location.hash.replace(/^#/, '').split('/'); const view = ['market','studio','vault','rig','user'].includes(v) ? v : 'market'; S.view = view; $$('.view').forEach(e => e.classList.toggle('on', e.id === 'v-' + view)); $$('nav a').forEach(e => e.classList.toggle('on', e.dataset.go === view)); $('#nav').classList.remove('open'); window.scrollTo(0, 0); if (view === 'market') loadMarket(); if (view === 'studio') renderManifest(); if (view === 'vault') loadCols(a ? decodeURIComponent(a) : null); if (view === 'rig') loadRig(); if (view === 'user') loadUser(decodeURIComponent(a || '')); } document.addEventListener('click', e => { const g = e.target.closest('[data-go]'); if (g){ e.preventDefault(); go(g.dataset.go); } const c = e.target.closest('[data-close]'); if (c) c.closest('.ov').classList.remove('on'); const u = e.target.closest('[data-user]'); if (u){ e.stopPropagation(); $('#pb').classList.remove('on'); go('user', u.dataset.user); } }); $$('.ov').forEach(o => o.addEventListener('mousedown', e => { if (e.target === o) o.classList.remove('on'); })); document.addEventListener('keydown', e => { if (e.key === 'Escape') $$('.ov.on').forEach(o => o.classList.remove('on')); }); $('#burger').onclick = () => $('#nav').classList.toggle('open'); window.addEventListener('hashchange', route); function card(r){ const d = document.createElement('div'); d.className = 'card'; d.innerHTML = '
#' + esc(short(r.id)) + '' + '' + (r.price ? esc(r.price) + ' эб.' : 'бесплатно') + 'BD
' + '
' + esc(r.title || 'Без названия') + '
' + '
@' + esc(r.owner) + '♥ ' + (r.likes|0) + '
' + '
' + (r.tags||[]).map(t => '' + esc(t) + '').join('') + '
'; paintScene(d.querySelector('canvas'), r.id); d.onclick = e => { if (!e.target.closest('[data-user]')) openRecord(r.id); }; return d; } function fillGrid(el, recs, emptyMsg){ el.innerHTML = ''; if (!recs.length){ el.innerHTML = '
Нет сигнала' + esc(emptyMsg || 'здесь пока ничего нет') + '
'; return; } recs.forEach(r => el.append(card(r))); } async function loadMarket(){ let recs; $('#m-more').classList.add('is-hidden'); const filtering = S.q || S.tag; if (filtering){ const p = new URLSearchParams(); if (S.q) p.set('q', S.q); if (S.tag) p.set('tag', S.tag); const r = await api('/search?' + p, {quiet:true}); recs = r.ok ? r.data.results : []; } else if (S.sort === 'trending'){ const r = await api('/trending', {quiet:true}); recs = r.ok ? r.data.records : []; } else { const r = await api('/gallery', {quiet:true}); recs = r.ok ? r.data.records.slice().reverse() : []; $('#m-count').textContent = r.ok ? r.data.total : 0; let cursor = r.ok ? r.data.next_cursor : null; $('#m-more').classList.toggle('is-hidden', !cursor); $('#m-more').onclick = async () => { const button = $('#m-more'); button.disabled = true; const page = await api('/gallery?before=' + encodeURIComponent(cursor)); button.disabled = false; if (!page.ok) return; page.data.records.slice().reverse().forEach(record => $('#m-grid').append(card(record))); cursor = page.data.next_cursor; button.classList.toggle('is-hidden', !cursor); }; const dl = $('#s-srcs'); dl.innerHTML = ''; recs.slice(0, 60).forEach(x => { const o = document.createElement('option'); o.value = x.id; o.label = (x.title || 'Без названия') + ' @' + x.owner; dl.append(o); }); } const f = $('#m-filter'); if (filtering){ f.classList.toggle('is-hidden', ('') === 'none'); f.innerHTML = 'ФИЛЬТР' + (S.q ? 'q: ' + esc(S.q) + '' : '') + (S.tag ? '#' + esc(S.tag) + '' : '') + '× сбросить' + recs.length + ' найдено'; $('#m-reset').onclick = () => { S.q = ''; S.tag = ''; $('#m-q').value = ''; loadMarket(); loadTags(); }; } else f.classList.toggle('is-hidden', ('none') === 'none'); fillGrid($('#m-grid'), recs, filtering ? 'по вашему запросу ничего не найдено' : 'создайте первую запись'); loadTags(); loadFeed(); } async function loadTags(){ const r = await api('/tags', {quiet:true}); if (!r.ok) return; const t = Object.entries(r.data.tags).sort((a, b) => b[1] - a[1]).slice(0, 40); $('#m-tagn').textContent = Object.keys(r.data.tags).length; const el = $('#m-tags'); el.innerHTML = t.length ? '' : '—'; t.forEach(([n, c]) => { const s = document.createElement('span'); s.className = 'chip' + (S.tag === n ? ' on' : ''); s.innerHTML = esc(n) + ' ' + c + ''; s.onclick = () => { S.tag = S.tag === n ? '' : n; loadMarket(); }; el.append(s); }); } async function loadFeed(){ const r = await api('/feed', {quiet:true}); if (!r.ok) return; const seen = [], el = $('#m-feed'); r.data.recent.forEach(n => { if (!seen.includes(n)) seen.push(n); }); el.innerHTML = seen.length ? '' : '
тишина
'; seen.slice(0, 10).forEach((n, i) => { const d = document.createElement('div'); d.className = 'li'; d.dataset.user = n; d.innerHTML = avatar(n) + '' + esc(n) + '' + (i === 0 ? 'сейчас' : '-' + i) + ''; el.append(d); }); } $$('#m-sort button').forEach(b => b.onclick = () => { S.sort = b.dataset.s; $$('#m-sort button').forEach(x => x.classList.toggle('on', x === b)); loadMarket(); }); const runQuery = () => { S.q = $('#m-q').value.trim(); loadMarket(); }; $('#m-go').onclick = runQuery; $('#m-q').onkeydown = e => { if (e.key === 'Enter') runQuery(); }; async function tickTicker(){ const [s, f] = await Promise.all([api('/stats', {quiet:true}), api('/feed', {quiet:true})]); if (!s.ok){ setLink(false); return; } setLink(true); const parts = [ 'ОПЕРАТОРЫ ' + s.data.users + '', 'ЗАПИСИ ' + s.data.records + '', 'КОЛЛЕКЦИИ ' + s.data.collections + '', 'ТЕГИ ' + s.data.tags + '', ]; if (f.ok) f.data.recent.slice(0, 8).forEach(n => parts.push('СИГНАЛ › @' + esc(n) + ' в сети')); $('#ticker').innerHTML = parts.join(''); } let playT = null, playStart = 0; function stopPlay(){ cancelAnimationFrame(playT); playT = null; $('#pb-screen').classList.remove('playing'); } function startPlay(){ const dur = 12000; $('#pb-screen').classList.add('playing'); playStart = performance.now(); const ph = $('#pb-tracks .phead'), tr = $('#pb-tracks'); const step = now => { const p = ((now - playStart) % dur) / dur; const w = tr.clientWidth - 118; ph.style.transform = 'translateX(' + (p * w) + 'px)'; const sec = p * dur / 1000 * 10; $('#pb-tc').textContent = [Math.floor(sec/3600), Math.floor(sec/60)%60, Math.floor(sec)%60].map(v => String(v).padStart(2, '0')).join(':'); playT = requestAnimationFrame(step); }; playT = requestAnimationFrame(step); } $('#pb-play').onclick = () => playT ? stopPlay() : startPlay(); async function openRecord(id){ const r = await api('/records/' + encodeURIComponent(id)); if (!r.ok) return toast('запись недоступна', 'er'); const d = r.data; S.rec = d; stopPlay(); $('#pb-t').textContent = d.title || 'Без названия'; paintScene($('#pb-cv'), d.id); $('#pb-screen').classList.remove('thermal'); $('#pb-hl').textContent = '#' + d.id; $('#pb-hb').textContent = '@' + d.owner; const own = S.user && S.user === d.owner; $('#pb-meta').innerHTML = '
ID
' + esc(d.id) + '
' + '
Владелец
@' + esc(d.owner) + '' + (own ? ' вы' : '') + '
' + '
Цена
' + (d.price ? esc(d.price) + ' эб.' : 'бесплатно') + '
'; $('#pb-tags').innerHTML = (d.tags||[]).map(t => '#' + esc(t) + '').join(''); $$('#pb-tags [data-tag]').forEach(c => c.onclick = () => { S.tag = c.dataset.tag; S.q = ''; $('#pb').classList.remove('on'); go('market'); loadMarket(); }); $('#pb-likes').textContent = d.likes | 0; $('#pb-sig').innerHTML = d.trailer ? 'трейлер · ' + esc((d.trailer.layers || '').split(',').map(n => LAYERS[n]?.label || n).join(', ') || '—') + '
подпись ' + esc(d.trailer.sig) + '' : ''; const layers = d.layers || {}; const names = Object.keys(LAYERS); const tr = $('#pb-tracks'); tr.innerHTML = ''; let first = null; names.forEach(n => { const L = LAYERS[n], has = n in layers, lock = !has && !L.pub && !own; if (!has && !lock) return; const bytes = has ? b64bytes(layers[n]) : new Uint8Array(); const t = document.createElement('div'); t.className = 'trk' + (lock ? ' lock' : ''); t.style.setProperty('--c', L.c); t.innerHTML = '
' + L.label + '' + (lock ? 'закрытый' : bytes.length + ' Б' + (L.pub ? '' : ' · закрытый')) + '
' + (lock ? '■ ЗАШИФРОВАНО ■' : '') + '
'; tr.append(t); t._paint = () => paintWave(t.querySelector('canvas'), bytes, L.hex, lock); t.onclick = () => { $$('#pb-tracks .trk').forEach(x => x.classList.toggle('sel', x === t)); $('#pb-screen').classList.toggle('thermal', n === 'thermal' && !lock); inspect(n, bytes, lock); }; if (!first && !lock) first = t; }); if (!tr.children.length) tr.innerHTML = '
no channels in this pressing
'; const ph = document.createElement('div'); ph.className = 'phead'; tr.append(ph); $('#pb-chn').textContent = Object.keys(layers).length + ' кан.'; $('#pb').classList.add('on'); requestAnimationFrame(() => { $$('#pb-tracks .trk').forEach(t => t._paint && t._paint()); if (first) first.click(); else $('#pb-insp').innerHTML = ''; }); loadComments(d.id); } function inspect(n, bytes, lock){ const el = $('#pb-insp'); el.style.setProperty('--c', LAYERS[n].c); if (lock){ el.innerHTML = '
' + LAYERS[n].label + 'только владельцу
канал закрыт — биржа не передаёт его содержимое
'; return; } const txt = bytesText(bytes), canText = txt !== null && printable(bytes); let mode = canText ? 'text' : 'hex'; const draw = () => { el.innerHTML = '
' + LAYERS[n].label + '
' + '
' + (mode === 'text' ? esc(txt) || '(пусто)' : hexdump(bytes)) + '
'; el.querySelectorAll('[data-m]').forEach(b => b.onclick = () => { mode = b.dataset.m; draw(); }); }; draw(); } async function loadComments(id){ const r = await api('/records/' + encodeURIComponent(id) + '/comments', {quiet:true}); const el = $('#pb-cmts'); const list = r.ok ? r.data.comments : []; el.innerHTML = list.length ? '' : '
комментариев пока нет
'; list.forEach(c => { const d = document.createElement('div'); d.className = 'cm'; d.innerHTML = '
@' + esc(c.user) + '' + new Date(c.ts*1000).toLocaleTimeString('ru-RU') + '
' + esc(c.text) + '
'; el.append(d); }); el.scrollTop = el.scrollHeight; } $('#pb-csend').onclick = async () => { if (!needAuth() || !S.rec) return; const t = $('#pb-cin').value.trim(); if (!t) return; const r = await api('/records/' + encodeURIComponent(S.rec.id) + '/comments', {method:'POST', json:{text:t}}); if (r.ok){ $('#pb-cin').value = ''; loadComments(S.rec.id); } }; $('#pb-cin').onkeydown = e => { if (e.key === 'Enter') $('#pb-csend').click(); }; $('#pb-like').onclick = async () => { if (!needAuth() || !S.rec) return; const r = await api('/records/' + encodeURIComponent(S.rec.id) + '/like', {method:'POST'}); if (r.ok){ $('#pb-likes').textContent = r.data.likes; toast('отметка «Нравится» добавлена', 'ok'); } }; $('#pb-remix').onclick = () => { if (!S.rec) return; $('#s-src').value = S.rec.id; if (!$('#s-title').value) $('#s-title').value = (S.rec.title || 'Без названия') + ' (ремикс)'; $('#pb').classList.remove('on'); stopPlay(); go('studio'); }; $('#pb-collect').onclick = async () => { if (!needAuth() || !S.rec) return; const r = await api('/collections', {quiet:true}); const el = $('#cp-list'); el.innerHTML = ''; const cols = r.ok ? r.data.collections : []; if (!cols.length) el.innerHTML = ''; cols.forEach(c => { const d = document.createElement('div'); d.className = 'li'; d.innerHTML = '' + esc(c.name) + '' + c.items + ' записей · ' + esc(short(c.id)) + ''; d.onclick = async () => { const a = await api('/collections/' + encodeURIComponent(c.id) + '/records', {method:'POST', json:{record_id:S.rec.id}}); if (a.ok){ toast('добавлено в ' + c.name, 'ok'); $('#cp').classList.remove('on'); } }; el.append(d); }); $('#cp').classList.add('on'); }; window.addEventListener('resize', () => { if ($('#pb').classList.contains('on')) $$('#pb-tracks .trk').forEach(t => t._paint && t._paint()); }); new MutationObserver(() => { if (!$('#pb').classList.contains('on')) stopPlay(); }).observe($('#pb'), {attributes:true}); const enc = s => { const b = new TextEncoder().encode(s); let o = ''; b.forEach(c => o += String.fromCharCode(c)); return btoa(o); }; function buildBD(){ const L = ['BDv1']; const src = $('#s-src').value.trim(); L.push('META owner=' + (S.user || 'anon') + (src ? ' source=' + src : '')); const t = $('#s-title').value.trim(); if (t) L.push('TITLE ' + t); $('#s-tags').value.trim().toLowerCase().split(/\s+/).filter(Boolean).forEach(x => L.push('TAG ' + x)); const p = parseInt($('#s-price').value, 10) || 0; if (p > 0) L.push('PRICE ' + p); ['video','audio','thermal','emotion'].forEach(n => { const v = $('#s-' + n).value; if (v) L.push('LAYER ' + n + ' ' + enc(v)); }); return L.join('\n'); } function renderManifest(){ const bd = buildBD(); $('#s-size').textContent = new Blob([bd]).size + ' Б'; $('#s-mani').innerHTML = bd.split('\n').map(line => { const [k, ...rest] = line.split(' '); if (k === 'BDv1') return '' + k + ''; if (k === 'LAYER'){ const b = rest[1] || ''; return 'LAYER ' + esc(rest[0]) + ' ' + esc(b.length > 48 ? b.slice(0, 48) + '…' : b) + ''; } return '' + esc(k) + ' ' + esc(rest.join(' ')); }).join('\n'); } $$('#v-studio .in').forEach(i => i.addEventListener('input', renderManifest)); $('#s-clear').onclick = () => { $$('#v-studio .in').forEach(i => i.value = i.type === 'number' ? 0 : ''); renderManifest(); }; $('#s-press').onclick = async () => { if (!needAuth()) return; const btn = $('#s-press'); btn.disabled = true; const r = await api('/records', {method:'POST', body:buildBD()}); btn.disabled = false; if (!r.ok) return toast('не удалось создать запись: ' + ((r.data && r.data.error) || r.status), 'er'); toast('создана запись #' + short(r.data.id) + ' · ' + (r.data.layers || []).map(n => LAYERS[n]?.label || n).join(', '), 'ok'); wire('создана запись ' + r.data.id + ' каналы=' + (r.data.layers || []).map(n => LAYERS[n]?.label || n).join(','), 'ok'); go('market'); setTimeout(() => openRecord(r.data.id), 120); }; async function loadCols(open){ const el = $('#c-list'); if (!S.token){ el.innerHTML = '
подключитесь для управления коллекциями
'; $('#c-n').textContent = 0; if (open) openCol(open); return; } const r = await api('/collections', {quiet:true}); const cols = r.ok ? r.data.collections : []; $('#c-n').textContent = cols.length; el.innerHTML = cols.length ? '' : '
пока нет
'; cols.forEach(c => { const d = document.createElement('div'); d.className = 'li' + (S.col === c.id ? ' sel' : ''); d.dataset.id = c.id; d.innerHTML = '' + esc(c.name) + '' + c.items + ''; d.onclick = () => go('vault', c.id); el.append(d); }); if (open) openCol(open); } async function openCol(cid){ const r = await api('/collections/' + encodeURIComponent(cid)); if (!r.ok){ toast(r.status === 403 ? 'коллекция закрыта' : 'коллекция не найдена', 'er'); return; } const d = r.data; S.col = d.id; $$('#c-list .li').forEach(x => x.classList.toggle('sel', x.dataset.id === d.id)); $('#c-title').textContent = d.name; $('#c-meta').innerHTML = esc(short(d.id)) + ' · @' + esc(d.owner) + ' · ' + d.total + ' записей'; $('#c-addrow').classList.toggle('is-hidden', (S.user === d.owner ? '' : 'none') === 'none'); fillGrid($('#c-grid'), d.items, 'коллекция пуста'); let offset = d.next_offset; $('#c-more').classList.toggle('is-hidden', offset === null); $('#c-more').onclick = async () => { const button = $('#c-more'); button.disabled = true; const page = await api('/collections/' + encodeURIComponent(cid) + '?offset=' + offset); button.disabled = false; if (!page.ok) return; page.data.items.forEach(record => $('#c-grid').append(card(record))); offset = page.data.next_offset; button.classList.toggle('is-hidden', offset === null); }; } $('#c-make').onclick = async () => { if (!needAuth()) return; const r = await api('/collections', {method:'POST', json:{name:$('#c-name').value.trim() || 'Без названия', public:$('#c-pub').checked}}); if (r.ok){ $('#c-name').value = ''; toast('коллекция создана', 'ok'); go('vault', r.data.id); } }; $('#c-open').onclick = () => { const v = $('#c-open-id').value.trim(); if (v) go('vault', v); }; $('#c-addbtn').onclick = async () => { if (!needAuth() || !S.col) return; const v = $('#c-add').value.trim(); if (!v) return; const r = await api('/collections/' + encodeURIComponent(S.col) + '/records', {method:'POST', json:{record_id:v}}); if (r.ok){ $('#c-add').value = ''; toast('запись добавлена', 'ok'); openCol(S.col); loadCols(); } else toast((r.data && r.data.error) || 'операция не удалась', 'er'); }; async function loadRig(){ if (!S.token){ $('#rig-in').classList.toggle('is-hidden', ('none') === 'none'); $('#rig-out').innerHTML = '
Нет нейросвязисоздайте профиль или восстановите сессию для доступа к терминалу
'; $('#rig-auth').onclick = openAuth; return; } $('#rig-out').innerHTML = ''; $('#rig-in').classList.toggle('is-hidden', ('') === 'none'); const me = await api('/me', {quiet:true}); if (!me.ok){ setSession(null, null); return loadRig(); } const u = await api('/users/' + encodeURIComponent(me.data.username), {quiet:true}); $('#r-av').innerHTML = avatar(me.data.username); $('#r-name').textContent = me.data.username; $('#r-bio').textContent = me.data.bio || '— описание не указано —'; $('#r-recs').textContent = me.data.records.length; $('#r-fol').textContent = u.ok ? u.data.followers : 0; $('#r-fng').textContent = me.data.following.length; $('#r-tokv').textContent = S.token; fillGrid($('#r-grid'), u.ok ? u.data.records.slice().reverse() : [], 'создайте первую запись в студии'); const fl = $('#r-following'); fl.innerHTML = me.data.following.length ? '' : '
подписок пока нет
'; me.data.following.forEach(n => { const d = document.createElement('div'); d.className = 'li'; d.dataset.user = n; d.innerHTML = avatar(n) + '' + esc(n) + ''; fl.append(d); }); } $('#r-tokshow').onclick = () => { const t = $('#r-tok'); t.classList.toggle('show'); $('#r-tokshow').textContent = t.classList.contains('show') ? 'Скрыть' : 'Показать'; }; $('#r-tokcp').onclick = async () => { try { await navigator.clipboard.writeText(S.token); toast('токен скопирован', 'ok'); } catch(e){ toast('нет доступа к буферу обмена', 'er'); } }; $('#r-out').onclick = () => { setSession(null, null); toast('сеанс завершён', 'warn'); go('market'); }; $('#r-pull').onclick = async () => { const r = await api('/flag'); const v = $('#r-vault'); if (r.ok && r.data.flag){ v.className = 'vault'; v.textContent = r.data.flag; } else { v.className = 'vault no'; v.textContent = 'на этом терминале нет закрытого эмоционального канала'; } }; async function loadUser(name){ const r = await api('/users/' + encodeURIComponent(name)); if (!r.ok){ $('#u-h').textContent = 'неизвестно'; fillGrid($('#u-grid'), [], 'оператор не найден'); return; } const d = r.data; $('#u-h').textContent = d.username; $('#u-av').innerHTML = avatar(d.username); $('#u-name').textContent = d.username; $('#u-bio').textContent = d.bio || '—'; $('#u-fol').textContent = d.followers; $('#u-n').textContent = d.records.length; $('#u-follow').classList.toggle('is-hidden', (S.user === d.username ? 'none' : '') === 'none'); $('#u-follow').onclick = async () => { if (!needAuth()) return; const f = await api('/users/' + encodeURIComponent(d.username) + '/follow', {method:'POST'}); if (f.ok){ toast('вы подписались на ' + d.username, 'ok'); loadUser(d.username); } }; fillGrid($('#u-grid'), d.records.slice().reverse(), 'записей пока нет'); } (async () => { renderChip(); const s = store.get('nm.session'); if (s && s.token) await restore(s.token, true); route(); tickTicker(); setInterval(tickTicker, 15000); })(); })();