nixamp 0.19.1 → 0.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/links.d.ts +9 -0
- package/dist/links.js +31 -1
- package/package.json +1 -1
- package/src/links.ts +31 -1
- package/web/dist/assets/{hls-3VKVEQE3-DLsUeG9Z.js → hls-3VKVEQE3-DUthTvKE.js} +1 -1
- package/web/dist/assets/{index-CwcjINDz.js → index-DBdUq7ap.js} +1 -1
- package/web/dist/assets/{mpegts-Df4FZb-F.js → mpegts-HCJUUrgg.js} +1 -1
- package/web/dist/assets/{mpegts-LO6RVLD6-CI2bOyNC.js → mpegts-LO6RVLD6-p5qT7X7S.js} +1 -1
- package/web/dist/index.html +1 -1
- package/web/dist/sw.js +5 -5
package/dist/links.d.ts
CHANGED
|
@@ -35,6 +35,15 @@ export interface ResolvedLink {
|
|
|
35
35
|
}
|
|
36
36
|
export declare function isDirectMedia(url: string): boolean;
|
|
37
37
|
export declare function isPlaylistLink(url: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* What to call a list that does not name itself: its file, or, when the
|
|
40
|
+
* file is only called "playlist", the folder it sits in. A show's page hands
|
|
41
|
+
* out /podcast/off-protocol/playlist.m3u, and "off protocol" is the name in
|
|
42
|
+
* that; "playlist" is not a name.
|
|
43
|
+
*/
|
|
44
|
+
export declare function playlistNameOf(url: string): string;
|
|
45
|
+
/** The name a list gives itself on a #PLAYLIST line, if it does. */
|
|
46
|
+
export declare function playlistTitleIn(text: string): string;
|
|
38
47
|
/** How much of a playlist is worth reading: a list, not a library dump. */
|
|
39
48
|
export declare const PLAYLIST_MAX_BYTES = 2000000;
|
|
40
49
|
export declare const PLAYLIST_MAX_ENTRIES = 1000;
|
package/dist/links.js
CHANGED
|
@@ -56,6 +56,35 @@ export function isPlaylistLink(url) {
|
|
|
56
56
|
return false;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* What to call a list that does not name itself: its file, or, when the
|
|
61
|
+
* file is only called "playlist", the folder it sits in. A show's page hands
|
|
62
|
+
* out /podcast/off-protocol/playlist.m3u, and "off protocol" is the name in
|
|
63
|
+
* that; "playlist" is not a name.
|
|
64
|
+
*/
|
|
65
|
+
export function playlistNameOf(url) {
|
|
66
|
+
try {
|
|
67
|
+
const parsed = new URL(url);
|
|
68
|
+
const parts = parsed.pathname.split("/").filter(Boolean).map((one) => {
|
|
69
|
+
try {
|
|
70
|
+
return decodeURIComponent(one);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return one;
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
const file = (parts.pop() ?? "").replace(/\.m3u$/i, "");
|
|
77
|
+
const named = /^(playlist|index|list|all|episodes|feed)?$/i.test(file) ? (parts.pop() ?? "") : file;
|
|
78
|
+
return named.replace(/[-_]+/g, " ").trim() || parsed.hostname;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return "Playlist";
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** The name a list gives itself on a #PLAYLIST line, if it does. */
|
|
85
|
+
export function playlistTitleIn(text) {
|
|
86
|
+
return /^#PLAYLIST:\s*(.+)$/im.exec(text)?.[1]?.replace(/[\u0000-\u001F]/g, " ").trim().slice(0, 200) ?? "";
|
|
87
|
+
}
|
|
59
88
|
/** How much of a playlist is worth reading: a list, not a library dump. */
|
|
60
89
|
export const PLAYLIST_MAX_BYTES = 2_000_000;
|
|
61
90
|
export const PLAYLIST_MAX_ENTRIES = 1000;
|
|
@@ -105,7 +134,8 @@ export async function resolvePlaylist(url, options = {}) {
|
|
|
105
134
|
if (!first)
|
|
106
135
|
return { error: "that playlist has nothing in it this can play" };
|
|
107
136
|
return {
|
|
108
|
-
|
|
137
|
+
// Named as the list names itself, else by where it lives.
|
|
138
|
+
title: playlistTitleIn(text) || playlistNameOf(url),
|
|
109
139
|
media: first,
|
|
110
140
|
audio: "",
|
|
111
141
|
// A station: joined where it is, never seeked, and with no end to save.
|
package/package.json
CHANGED
package/src/links.ts
CHANGED
|
@@ -94,6 +94,35 @@ export function isPlaylistLink(url: string): boolean {
|
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
96
|
|
|
97
|
+
/**
|
|
98
|
+
* What to call a list that does not name itself: its file, or, when the
|
|
99
|
+
* file is only called "playlist", the folder it sits in. A show's page hands
|
|
100
|
+
* out /podcast/off-protocol/playlist.m3u, and "off protocol" is the name in
|
|
101
|
+
* that; "playlist" is not a name.
|
|
102
|
+
*/
|
|
103
|
+
export function playlistNameOf(url: string): string {
|
|
104
|
+
try {
|
|
105
|
+
const parsed = new URL(url);
|
|
106
|
+
const parts = parsed.pathname.split("/").filter(Boolean).map((one) => {
|
|
107
|
+
try {
|
|
108
|
+
return decodeURIComponent(one);
|
|
109
|
+
} catch {
|
|
110
|
+
return one;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
const file = (parts.pop() ?? "").replace(/\.m3u$/i, "");
|
|
114
|
+
const named = /^(playlist|index|list|all|episodes|feed)?$/i.test(file) ? (parts.pop() ?? "") : file;
|
|
115
|
+
return named.replace(/[-_]+/g, " ").trim() || parsed.hostname;
|
|
116
|
+
} catch {
|
|
117
|
+
return "Playlist";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The name a list gives itself on a #PLAYLIST line, if it does. */
|
|
122
|
+
export function playlistTitleIn(text: string): string {
|
|
123
|
+
return /^#PLAYLIST:\s*(.+)$/im.exec(text)?.[1]?.replace(/[\u0000-\u001F]/g, " ").trim().slice(0, 200) ?? "";
|
|
124
|
+
}
|
|
125
|
+
|
|
97
126
|
/** How much of a playlist is worth reading: a list, not a library dump. */
|
|
98
127
|
export const PLAYLIST_MAX_BYTES = 2_000_000;
|
|
99
128
|
export const PLAYLIST_MAX_ENTRIES = 1000;
|
|
@@ -142,7 +171,8 @@ export async function resolvePlaylist(
|
|
|
142
171
|
const [first] = list.sources;
|
|
143
172
|
if (!first) return { error: "that playlist has nothing in it this can play" };
|
|
144
173
|
return {
|
|
145
|
-
|
|
174
|
+
// Named as the list names itself, else by where it lives.
|
|
175
|
+
title: playlistTitleIn(text) || playlistNameOf(url),
|
|
146
176
|
media: first,
|
|
147
177
|
audio: "",
|
|
148
178
|
// A station: joined where it is, never seeked, and with no end to save.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./index-
|
|
1
|
+
import{t as e}from"./index-DBdUq7ap.js";var t=3;async function n(n){let{media:r,src:i,isTv:a}=n,{default:o}=await e(async()=>{let{default:e}=await import(`./hls-n74Cnh8A.js`);return{default:e}},[]);if(!o.isSupported())return n.onError(`This browser cannot play HLS streams.`),{destroy:()=>void 0,levels:()=>[]};let s=new o({...a?{maxBufferLength:60,maxMaxBufferLength:120,backBufferLength:30,liveSyncDurationCount:4}:{backBufferLength:90},enableWorker:!0}),c=0,l=!1;s.on(o.Events.ERROR,(e,r)=>{if(!l&&r.fatal){if(c>=t){n.onError(`This stream kept failing and has been stopped.`),s.destroy();return}switch(c+=1,r.type){case o.ErrorTypes.NETWORK_ERROR:n.onNotice(`Reconnecting…`),s.startLoad();break;case o.ErrorTypes.MEDIA_ERROR:n.onNotice(`Recovering…`),s.recoverMediaError();break;default:n.onError(`This stream could not be played.`),s.destroy()}}}),s.on(o.Events.MANIFEST_PARSED,()=>{l||(n.onNotice(null),n.onReady?.({live:s.levels.length>0&&!Number.isFinite(r.duration),levels:u()}))}),s.on(o.Events.LEVEL_LOADED,(e,t)=>{l||n.onReady?.({live:t.details.live,levels:u()})}),s.on(o.Events.FRAG_BUFFERED,()=>{l||n.onNotice(null)});function u(){return s.levels.map((e,t)=>({index:t,height:e.height||null,bitrate:e.bitrate||null,label:e.height?`${String(e.height)}p`:`${String(Math.round((e.bitrate||0)/1e3))}k`}))}return s.loadSource(i),s.attachMedia(r),{destroy(){l=!0,s.destroy()},levels:u,setLevel(e){s.currentLevel=e},currentLevel:()=>s.autoLevelEnabled?-1:s.currentLevel}}export{n as createHlsEngine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function t(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function n(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var r=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}var a=`modulepreload`,o=function(e){return`/`+e},s={},c=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),c=i?.nonce||i?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=l(t.map(t=>{if(t=o(t,n),t=u(t),t in s)return;s[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:a,r||(i.as=`script`),i.crossOrigin=``,i.href=t,c&&i.setAttribute(`nonce`,c),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},l=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],u=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function d(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of u)if(t.test(e.mimeType))return n}let t=f(e.src);for(let[e,n]of l)if(e.test(t))return n;return`unknown`}function f(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function p(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function m(e,t){let n=d(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function h(e,t){let n=t.capabilities??p(),r=m({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await c(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-DLsUeG9Z.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await c(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-CI2bOyNC.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await c(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var ee=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),te=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function g(e){let t=e.lastIndexOf(`.`);return t>0&&te.has(e.slice(t+1).toLowerCase())}function ne(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&ee.has(e.slice(n+1).toLowerCase())}function re(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ie(e){return e.filter(e=>ne(e.name,e.type)).sort((e,t)=>re(ae(e),ae(t))).map(e=>({title:n(e.name),artist:``,album:oe(ae(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...g(e.name)?{kind:`mpegts`}:{}}))}function ae(e){return e.webkitRelativePath||e.name}function oe(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function se(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var ce=2048;function _(e,t){return e||t===`hls`||t===`mpegts`}var le=class{elements;handlers;attached=null;source=``;context=null;analyser=null;wired=new WeakSet;active;frequencies=new Uint8Array;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.crossOrigin=`anonymous`,t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(ue(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(this.context??=new t,this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=ce,this.analyser.smoothingTimeConstant=.6,this.analyser.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:d({src:e.url})),r=_(e.video,n)?this.elements.video:this.elements.audio;r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await h(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}t&&await this.play()}async play(){this.ensureGraph(this.active);try{await this.active.play()}catch(e){this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function ue(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function de(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function fe(e,t){return{...t,tracks:t.tracks??e.tracks}}function v(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function y(e,t,n=``){let r=`${e===``?``:v(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function pe(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:v(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var b=null;function x(e){if(!e&&b!==null)return b;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(b=n),n}catch{return!1}}function me(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return y(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function S(e){if(typeof e!=`object`||!e)return null;let t=e,n=de(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}var he=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}url(e){let t=y(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=pe(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(y(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=S(C(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(y(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=S(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=x()){return me(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function C(e){try{return JSON.parse(e)}catch{return null}}async function ge(e,t,n=``){try{let r=await fetch(y(e,`/api/state`,n),{signal:t});return r.ok?S(await r.json()):null}catch{return null}}function _e(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function ve(e,t=``,n){let r;try{r=await fetch(y(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function ye(e,t,n=``){try{let r=await fetch(y(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function be(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var xe=.14,Se=.02;function Ce(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function we(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function Te(e,t,n=xe){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Ee(e,t,n=Se){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function De(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function Oe(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function ke(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function Ae(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale,i)===r.toLocaleDateString(t.locale,i);return n.toLocaleString(t.locale,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function je(e,t={}){let n=e.data,r=Oe(n.away,n.awayScore),i=Oe(n.home,n.homeScore),a=ke(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=Ae(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var Me=`nixamp.tv`,w=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function Ne(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?T(r):/\bSilk\b/.test(e)&&n===0?!0:w.test(e):T(i)}function T(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Pe(e){return e?12:100}function Fe(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var E=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,D=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,Ie=/\.m3u8(\?.*)?$/i;function O(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function Le(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=O(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return E.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:D.test(o)||Ie.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var Re=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,k=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,ze=/\s+(?:vs\.?|v\.?|at|@)\s+/i,Be=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function A(e){let t=e.replace(k,``).replace(k,``).trim().split(ze);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!Be.test(t)})}function Ve(e){let t=String(e??``).trim();return t===``?!1:A(t.replace(Re,``))||A(t)}var He=`nixamp.remote`,Ue=`nixamp.volume`,We=`nixamp.listenHere`,Ge=1e4,Ke=!1;function j(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function qe(){let n=null;try{n=localStorage.getItem(Me)}catch{}let r=Ne(navigator.userAgent,location.search,navigator.maxTouchPoints,n);if(document.body.classList.toggle(`tv`,r),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Me,r?`1`:`0`)}catch{}let i=document.getElementById(`tv-toggle`);i&&(i.textContent=r?`TV mode: on`:`TV mode`,i.title=r?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,i.addEventListener(`click`,()=>{try{localStorage.setItem(Me,r?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let a=Pe(r),o={status:j(`status`),source:j(`source`),install:j(`install`),video:j(`video`),audio:j(`audio`),title:j(`title-line`),album:j(`album-line`),meta:j(`meta-line`),metaBlurb:j(`meta-blurb`),liveLine:j(`live-line`),downloadNow:j(`download-now`),wayInHere:j(`way-in-here`),embed:j(`embed`),embedFrame:j(`embed-frame`),linkForm:j(`link-form`),linkUrl:j(`link-url`),linkServer:j(`link-server`),linkGoLive:j(`link-go-live`),goLiveNow:j(`go-live-now`),elapsed:j(`elapsed`),total:j(`total`),seek:j(`seek`),fullscreen:j(`fullscreen`),copyNow:j(`copy-now`),canvas:j(`spectrum`),glyphs:j(`glyphs`),levels:j(`levels`),playlist:j(`playlist`),playlistPager:j(`playlist-pager`),crumbs:j(`crumbs`),filter:j(`filter`),playlistTitle:j(`playlist-panel`),note:j(`note`),files:j(`files`),folder:j(`folder`),remoteUrl:j(`remote-url`),remoteForm:j(`remote-form`),remoteState:j(`remote-state`),disconnect:j(`disconnect`),browse:j(`browse`),accountForm:j(`account-form`),accountEmail:j(`account-email`),accountPassword:j(`account-password`),accountSubmit:j(`account-submit`),accountToggle:j(`account-toggle`),accountProviders:j(`account-providers`),accountPanel:j(`account-panel`),accountElsewhere:j(`account-elsewhere`),welcome:j(`welcome`),welcomeCreate:j(`welcome-create`),welcomeBrowse:j(`welcome-browse`),welcomeHide:j(`welcome-hide`),accountSignOut:j(`account-signout`),accountNote:j(`account-note`),adminPanel:j(`admin-panel`),adminNote:j(`admin-note`),adminSaid:j(`admin-said`),adminConnections:j(`admin-connections`),publishPanel:j(`publish-panel`),publishNote:j(`publish-note`),publishList:j(`publish-list`),adminRestream:j(`admin-restream`),adminReplace:j(`admin-replace`),adminSource:j(`admin-source`),adminName:j(`admin-name`),adminAdd:j(`admin-add`),homeNote:j(`home-note`),loadHome:j(`load-home`),directory:j(`directory`),recentNote:j(`recent-note`),recentList:j(`recent-list`),followingNote:j(`following-note`),followingList:j(`following-list`),serversPanel:j(`servers-panel`),serversNote:j(`servers-note`),serversList:j(`servers-list`),favoritesPanel:j(`favorites-panel`),favoritesNote:j(`favorites-note`),favoritesList:j(`favorites-list`),favHere:j(`fav-here`),partiesPanel:j(`parties-panel`),partiesNote:j(`parties-note`),partiesList:j(`parties-list`),partyForm:j(`party-form`),partyCode:j(`party-code`),connectionsNote:j(`connections-note`),connectionsList:j(`connections-list`),catalogsPanel:j(`catalogs-panel`),catalogsNote:j(`catalogs-note`),catalogsForm:j(`catalogs-form`),catalogSource:j(`catalog-source`),catalogName:j(`catalog-name`),catalogsList:j(`catalogs-list`),catalogsCrumbs:j(`catalogs-crumbs`),catalogsFilter:j(`catalogs-filter`),catalogsEntries:j(`catalogs-entries`),notifyPanel:j(`notify-panel`),notifyNote:j(`notify-note`),notifyWeb:j(`notify-web`),notifyEmail:j(`notify-email`),notifySms:j(`notify-sms`),notifyPhone:j(`notify-phone`),notifyPhoneForm:j(`notify-phone-form`),notifyPhoneNote:j(`notify-phone-note`),directoryNote:j(`directory-note`),directoryList:j(`directory-list`),onairPanel:j(`onair-panel`),onairNote:j(`onair-note`),onairList:j(`onair-list`),sharePanel:j(`share-panel`),shareNote:j(`share-note`),shareLink:j(`share-link`),shareCopy:j(`share-copy`),sharePhone:j(`share-phone`),shareSend:j(`share-send`),liveControls:j(`live-controls`),goLive:j(`go-live`),stopLive:j(`stop-live`),shareTo:j(`share-to`),listenOnly:j(`listen-only`),listenHere:j(`listen-here`),volume:j(`volume`),prev:j(`prev`),playPause:j(`play-pause`),stop:j(`stop`),next:j(`next`)},s={rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`},c=(e,t)=>{e.innerHTML=s[t]},l=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,u=`local`,d=``,f=[],p=``,m=!0,h=``;function ee(e){try{return new URL(e).origin}catch{return e}}let te=!1,g=``,ne=0,re=new Map,ae=e=>re.get(G(e))??null;function oe(e,t){let n=n=>{te=n,g=``,o.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),o.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,c(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,c(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:Z?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let ce=``,_=[],ue=0,v=de(),y=`idle`,b=``,x=`Pick files, or connect to a nixamp running somewhere else.`,me=!1,S=-1,C=null,xe=0,Se=0,Oe=!1,Ae=()=>Se>0||Oe;async function w(e){Se+=1,V();try{return await e()}finally{--Se,V()}}let T=null,E=null,D=null;function Ie(){o.embed.hidden||(o.embedFrame.src=`about:blank`),o.embed.hidden=!0}let O=null,Re=``,k=null;function ze(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Re=i,k&&clearTimeout(k),k=null,!r){if(O?.key===i)return;O=null}if(u!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(I.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Re!==i)return;O={key:i,match:r.match??null},V();let a=O.match;a?.kind===`fixture`&&ke(a)!==`post`&&(k=setTimeout(()=>{k=null,!(Re!==i||F.source===``&&!C)&&ze(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Be=!1,A=``,qe=``,Je=null,Ye=``,M=Array(24).fill(0),N=Array(24).fill(0),Xe=[],P=()=>u===`remote`&&!o.listenHere.checked,Ze=()=>u===`remote`&&!o.adminPanel.hidden,Qe=!1,$e=()=>Ze()||u===`remote`&&Qe;function et(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:o.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function tt(){if(u!==`remote`||D)return null;if(T?.catalog&&T.entry)return{kind:`entry`,catalog:T.catalog,entry:T.entry};if(C)return{kind:`channel`,id:C.id,name:C.name};let e=v.tracks[R()];return e&&(F.source!==``||P())?{kind:`track`,index:R(),name:t(e)}:null}async function nt(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;x=`Putting ${n} on the air…`,V();try{let r=``,i=``,a=!0;{let t=e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(I.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){x=s.error??`${n} would not go on the air.`,V();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(Ze()&&(Be?await fetch(I.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await lr(!0)),await Wn(),Q(),i!==``&&C?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await Zn({id:i,name:n,video:a},!0,t)}let o=rr(r),s=A?` Call ${qe||`the line`} and key ${A} to talk about it.`:``;o===``?x=`${n} is on the air and you are watching it.${s}`:(await nr(o,t,`✓`),x=`${n} is on the air and you are watching it. Link copied.${s}`),V()}catch{x=`could not reach the server`,V()}finally{t.disabled=!1}}function rt(e,t=`Join live`){c(e,`live`),e.append(document.createTextNode(` ${t}`))}function it(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,c(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),nt(e(),n)}),n}let F=new le({audio:o.audio,video:o.video},{onTime:(e,t)=>{let n=_[ue];u===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{Qn()||u===`remote`&&S<0&&!P()||B(1)},onState:()=>V(),onBusy:e=>{Oe!==e&&(Oe=e,V())},onError:e=>{Qn()||(x=e,V(),Jn())}}),I=new he({onSnapshot:e=>{if(v=fe(v,e),g.startsWith(`track:`)&&v.tracks.length>0){let e=Number(g.slice(6));if(g=``,Number.isInteger(e)&&e>=0&&e<v.tracks.length){let t=ne;dt(e).then(()=>{t>0&&(F.seek(t),setTimeout(()=>F.seek(t),600))})}}P()&&(M=e.bars.length>0?e.bars:M,N=Ee(N,M)),V()},onStatus:(e,t)=>{y=e,b=t??``,V()}}),L=()=>u===`remote`?v.tracks.length:_.length,R=()=>u===`remote`?P()||S<0?v.index:Math.min(S,Math.max(0,v.tracks.length-1)):ue,at=()=>{if(C)return C.name;if(D)return D.label;let e=u===`remote`?v.tracks[R()]:_[R()];return e?t(e):`Nothing loaded.`},ot=()=>C?`live on this server`:D?`playing here, in this browser`:T?.kind===`live`&&u===`remote`?`live on ${d||`this server`}`:(u===`remote`?v.tracks[R()]:_[R()])?.album||`—`;function st(){if(u!==`remote`||C===null&&T?.kind!==`live`){o.liveLine.hidden=!0,o.liveLine.replaceChildren();return}let e=d||`this server`,t=C?C.name:E?.server.nowPlaying||at(),n=[C?`Live on ${e}: `:`Live from ${e}, now playing: `,ur(t)],r=C?E?.channels.find(e=>e.id===C?.id)?.code??``:Be?A:``;r&&n.push(`. To talk about it, call `,ur(qe||`the line`),` and key `,ur(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);o.liveLine.dataset.drawn!==i&&(o.liveLine.dataset.drawn=i,o.liveLine.hidden=!1,o.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let ct=()=>P()?v.tracks[R()]?.duration??0:F.duration,lt=()=>P()?v.position:F.position,ut=()=>P()?v.playing:F.playing;async function z(e){if(u===`remote`){if(P()){await I.send({type:`play`,index:e});return}await dt(e);return}let t=_[e];t&&(ue=e,C=null,T={kind:`file`},await w(()=>F.load(t,!0)),jt(t.video),Mt(),V())}async function dt(e){let t=v.tracks[e];t&&(S=e,C=null,T={kind:`file`},ze(t.title,`auto`),await w(()=>F.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:I.media(e,0),video:t.video===!0,objectUrl:!1},!0)),jt(t.video===!0),Mt())}async function ft(){if(P()){await I.send({type:`toggle`});return}L()!==0&&(F.playing?F.pause():F.position>0?await F.play():await z(R()),V())}async function B(e){let t=L();if(t!==0){if(P()){await I.send({type:e>0?`next`:`prev`});return}await z((R()+e+t)%t)}}async function pt(){if(Ie(),D=null,P()){await I.send({type:`stop`});return}C=null,T=null,F.stop(),M=Array(24).fill(0),N=[...M],V()}let mt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,ht=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],gt=``;function _t(){let t=[],n=``,r=null,i=C?E?.channels.find(e=>e.id===C?.id):void 0,a=F.source===``&&!C&&!(P()&&v.tracks[R()]);if(!a){C?t.push(T?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):T?.kind===`vod`?t.push(`ON DEMAND`):T?.kind===`live`?t.push(`LIVE`):u===`remote`&&P()?t.push(`ON THE SERVER`):t.push(`FILE`),!o.video.hidden&&o.video.videoWidth>0?t.push(`${o.video.videoWidth}×${o.video.videoHeight}`):o.video.hidden?t.push(`audio`):t.push(`video`),i?(t.push(i.via===`pull`?`${i.listeners} watching`:`${i.listeners} listening · over ${i.via}`),i.startedAt>0&&t.push(`on air ${e(Math.max(0,(Date.now()-i.startedAt)/1e3))}`),i.redials&&t.push(`redialled ${i.redials}×`),Ze()&&i.error&&t.push(i.error)):u===`remote`&&!C?(v.tracks[R()]&&L()>0&&t.push(`track ${R()+1} of ${L()}`),P()&&E&&t.push(`${E.server.playing?`playing`:`stopped`} on ${d||`the server`}`)):u===`local`&&L()>0&&t.push(`track ${R()+1} of ${L()}`),T?.catalog!==void 0&&(T.kind===`channel`?C!==null:T.kind===`vod`&&F.source!==``)&&T?.catalog&&(t.push(T.entry?.group?`${T.catalog.name} › ${T.entry.group}`:T.catalog.name),n=T.entry?.logo??``);let a=O?.key===Re?O.match:null;if(a?.kind===`fixture`)r=je(a),t.unshift(r.status,...r.chips);else if(a){a.image&&(n=a.image);let e=a.data;if(a.kind===`title`){a.year&&t.push(String(a.year));let n=typeof e.rating==`number`?e.rating:null;n&&t.push(`★ ${n.toFixed(1)}`);let r=Array.isArray(e.genres)?e.genres.slice(0,2).map(String):[];r.length&&t.push(r.join(` · `));let i=typeof e.runtimeMin==`number`?e.runtimeMin:0;i&&t.push(`${i} min`)}else if(a.kind===`channel`){let n=typeof e.country==`string`?e.country:``,r=Array.isArray(e.categories)?e.categories.slice(0,2).map(String):[],i=typeof e.network==`string`?e.network:``;n&&t.push(n),r.length&&t.push(r.join(` · `)),i&&t.push(i)}}if(C&&T?.link){let e=``;try{e=new URL(T.link.url).hostname.replace(/^www\./,``)}catch{}t.push(T.link.extractor&&T.link.extractor!==`direct`&&T.link.extractor!==`generic`?`${T.link.extractor} · ${e}`:e||`link`)}Be&&A&&P()&&!C&&T?.kind!==`live`&&t.push(qe?`☎ ${qe} · key ${A}`:`☎ code ${A}`)}let s=O?.key===Re?O.match:null,c=!a&&!r&&s?.summary?s.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${c}`;if(l===gt)return;gt=l,o.meta.hidden=t.length===0,o.metaBlurb.textContent=c,o.metaBlurb.hidden=c===``;let f=[];if(r){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let n=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,n.push(i),r?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),n.push(t)}if(e.logo!==``){let r=document.createElement(`img`);r.className=`meta-team-logo`,r.alt=``,r.src=e.logo,r.addEventListener(`error`,()=>{r.hidden=!0}),t?n.unshift(r):n.push(r)}return n},n=document.createElement(`span`);n.className=`meta-dash`,n.textContent=`–`,e.replaceChildren(...t(r.away,!0),n,...t(r.home,!1)),f.push(e)}if(n!==``&&/^https?:\/\//.test(n)){let e=document.createElement(`img`);e.className=s?.kind===`title`&&n===s.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let e of t){let t=document.createElement(`span`);t.className=r?.state===`in`&&e===r.status?`meta-chip chip-live`:`meta-chip`,t.textContent=e,f.push(t)}o.meta.replaceChildren(...f)}function V(){let t=L(),n=ut(),r=Ae();o.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,o.status.dataset.playing=r?`loading`:String(n),o.title.textContent=at(),st(),_t(),o.goLiveNow.hidden=!$e()||tt()===null;let i=n?`${at()} · ${l}`:l;document.title!==i&&(document.title=i),o.copyNow.hidden=F.source===``,o.downloadNow.hidden=!(C&&T?.link?.download),Ft(),o.album.textContent=ot();let a=lt(),s=ct();o.elapsed.textContent=e(a),o.total.textContent=s>0?e(s):`--:--`,me||(o.seek.value=String(s>0?Math.round(a/s*1e3):0),o.seek.disabled=s<=0||P()),o.playPause.textContent=n?`❚❚`:`▶`,o.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),o.playlistTitle.dataset.title=u===`remote`?`Files on ${d||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,o.source.textContent=u===`remote`?`connected · ${d||I.address.replace(/^https?:\/\//,``)||`—`}`:_.length>0?`local · ${_.length} files`:`no source`,At(),o.remoteState.textContent=u===`remote`?`${y}${b?` — ${b}`:``}`:`not connected`,o.remoteState.dataset.status=u===`remote`?y:`idle`,o.disconnect.hidden=u!==`remote`;let c=u===`remote`&&v.note!==``?v.note:x;o.note.textContent=c,o.note.hidden=c===``,Tt(),o.glyphs.textContent=M.map(ht).join(``);let[f,p]=P()?v.levels:F.levels();o.levels.textContent=mt(f,p)}let vt=``,yt=-1,H=``,bt=0;function xt(e){H=e,bt=0,vt=``,Tt()}function St(e,t,n,r,i){if(o.playlistPager.hidden=n<=1,n<=1){o.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{bt=t,vt=``,Tt(),o.playlist.scrollIntoView({block:`nearest`})}),i},s=document.createElement(`span`);s.className=`pager-where`,s.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,o.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),s,a(`Next ›`,t+1,`The page after this one`))}function Ct(e){if(o.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>xt(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),o.crumbs.replaceChildren(...r)}function wt(e,t){let n=document.createElement(`li`);n.className=`folder`;let r=document.createElement(`span`);r.className=`name`,r.textContent=`${e}/`;let i=document.createElement(`span`);return i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i),n.tabIndex=0,n.addEventListener(`click`,()=>xt(H===``?e:`${H}/${e}`)),n}function Tt(){let n=u===`remote`?v.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):_.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=o.filter.value.trim().toLowerCase(),i=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),s=e=>r!==``||H===``||e===H||e.startsWith(`${H}/`),l=e=>r!==``||e===H,d=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of i){if(!s(e.folder)||l(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=i.filter(e=>l(e.folder)&&s(e.folder)),m=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),h=Fe(m.length+p.length,bt,a);bt=h.page;let ee=m.slice(h.from,h.to),te=p.slice(Math.max(0,h.from-m.length),Math.max(0,h.to-m.length)),g=`${u}:${H}:${r}:${h.page}/${a}:${m.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(g!==vt){vt=g,Ct(r===``&&(m.length>0||H!==``)),St(m.length+p.length,h.page,h.pages,h.from,h.to);let t=[];for(let[e,n]of ee)t.push(wt(e,n));let n=``,i=p.some(e=>e.group!==``);for(let r of te){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(Et(r.group)));let a=document.createElement(`li`);a.className=`row`,a.tabIndex=0,a.dataset.index=String(r.index);let o=document.createElement(`span`);o.className=`n`,o.textContent=String(r.index+1).padStart(2,` `);let s=document.createElement(`span`);s.className=`name`,s.textContent=r.name;let l=document.createElement(`span`);if(l.className=`time`,l.textContent=r.seconds>0?e(r.seconds):`--:--`,a.append(o,s,l),u===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${r.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),nr(rr(`track:${r.index}`,S===r.index?F.position:0),e,`✓`)}),a.append(e),$e()&&a.append(it(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}o.playlist.replaceChildren(...t)}let ne=R(),re=ut(),ie;for(let e of Array.from(o.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===ne;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&re),r&&(ie=t)}if(ne!==yt){yt=ne;let e=p.findIndex(e=>e.index===ne);if(e>=0&&!ie){bt=Math.floor((m.length+e)/a),vt=``,Tt();return}ie?.scrollIntoView({block:`nearest`})}}function Et(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!o.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,t=>{t.stopPropagation(),Dt(e)}),t.append(n)}return t}async function Dt(e){try{let t=await fetch(I.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();U(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}}function Ot(){let t=o.canvas,n=Math.min(2,globalThis.devicePixelRatio||1),r=Math.round(t.clientWidth*n),i=Math.round(t.clientHeight*n);r>0&&i>0&&(t.width!==r||t.height!==i)&&(t.width=r,t.height=i);let a=t.getContext(`2d`);if(P())N=Ee(N,M);else{let e=F.read();e.length>0&&(Xe.length!==25&&(Xe=Ce(24,e.length)),M=Te(M,we(e,Xe)),N=Ee(N,M))}if(a){let e=getComputedStyle(document.documentElement);De(a,{width:t.width,height:t.height},M,N,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(ut()){o.glyphs.textContent=M.map(ht).join(``);let[t,n]=P()?v.levels:F.levels();o.levels.textContent=mt(t,n),o.elapsed.textContent=e(lt());let r=ct();!me&&r>0&&(o.seek.value=String(Math.round(lt()/r*1e3)))}requestAnimationFrame(Ot)}let kt=``;function At(){if(u!==`remote`){o.wayInHere.hidden=!0,kt=``;return}let e=Ze()&&!te,t=ce||I.address,n=e?null:ae(I.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===kt)return;kt=r;let[i,a]=oe({name:d||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,o.wayInHere.replaceChildren(i,a),o.wayInHere.hidden=!1}function jt(e){o.video.hidden=!e,o.fullscreen.hidden=!e,Ie(),D=null}function Mt(){`mediaSession`in navigator&&(navigator.mediaSession.metadata=new MediaMetadata({title:at(),album:ot(),artist:`nixamp`,artwork:[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]}),navigator.mediaSession.setActionHandler(`play`,()=>void ft()),navigator.mediaSession.setActionHandler(`pause`,()=>void ft()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void B(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void B(-1)))}o.filter.addEventListener(`input`,()=>{bt=0,vt=``,Tt()}),o.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),o.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&z(n)}),o.fullscreen.addEventListener(`click`,()=>{let e=o.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),o.prev.addEventListener(`click`,()=>void B(-1)),o.next.addEventListener(`click`,()=>void B(1)),o.stop.addEventListener(`click`,()=>void pt()),o.playPause.addEventListener(`click`,()=>void ft());async function Nt(e){let t=Le(e,et());if(!t){if(!$e()){x=u===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,V();return}await Pt(e);return}if(C=null,F.stop(),t.kind===`embed`){T={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},jt(!1),o.embedFrame.src=t.src,o.embed.hidden=!1,D={url:e,label:t.label,kind:`embed`},x=`Playing ${t.label} here, in this browser.`,V();return}T={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await w(()=>F.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),jt(t.video),D={url:e,label:t.label,kind:`direct`},x=`Playing ${t.label} here, in this browser.`,V()}async function Pt(e){if(u!==`remote`){x=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}x=`Asking ${d||`the server`} to fetch ${e}…`,V(),await w(async()=>{let t,n={};try{t=await fetch(I.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{x=`could not reach the server`;return}if(!t.ok||!n.channel){x=n.error??`that link would not play.`;return}try{await fetch(I.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await Zn({id:n.channel,name:n.name||e,video:n.video!==!1},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(x=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),V()}o.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.linkUrl.value.trim();t!==``&&Nt(t)});function Ft(){let e=u===`remote`?I.address:``,t=f.filter(t=>ee(t.url)!==ee(e)),n=JSON.stringify({here:e,name:d,carries:m,others:t});if(n===p)return;p=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${d||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}o.linkServer.replaceChildren(...r),o.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,o.linkServer.hidden=t.length===0}async function It(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;f=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Ft()}catch{}}async function Lt(){let e=o.linkUrl.value.trim()||D?.url||``;if(e===``){x=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=o.linkServer.value;if(t!==``&&(u!==`remote`||ee(t)!==ee(I.address))){let n=f.find(e=>e.url===t)?.name??t;h=e,x=`Connecting to ${n} to go live with it…`,V(),Rt(t);return}if(u!==`remote`){x=f.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste its address below.`,V();return}if(!m){x=`${d||`This server`} has no ffmpeg, so it cannot carry a link.`+(f.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!$e()){x=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await Pt(e)}function Rt(e){let t=o.linkUrl.value.trim();te=!0,g=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit(),o.linkUrl.value=t}o.linkGoLive.addEventListener(`click`,()=>{Lt()}),o.linkServer.addEventListener(`change`,()=>{let e=o.linkServer.value;e!==``&&Rt(e)}),o.downloadNow.addEventListener(`click`,()=>{let e=T?.link;if(!e||u!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(I.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),x=`Fetching it through the server; your browser will save it when it arrives.`,V()}),o.goLiveNow.addEventListener(`click`,()=>{let e=tt();e&&nt(e,o.goLiveNow)}),o.seek.addEventListener(`input`,()=>{me=!0}),o.seek.addEventListener(`change`,()=>{let e=ct();e>0&&F.seek(Number(o.seek.value)/1e3*e),me=!1}),o.volume.addEventListener(`input`,()=>{let e=Number(o.volume.value)/100;F.volume=e;try{localStorage.setItem(Ue,String(e))}catch{}});let zt=e=>{e.addEventListener(`change`,()=>{let t=ie(Array.from(e.files??[]));if(t.length===0){x=`Nothing playable in that selection.`,V();return}se(_),_=t,ue=0,u=`local`,I.close(),x=``,z(0)})};zt(o.files),zt(o.folder),o.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.remoteUrl.value,{base:n,key:r}=pe(t);if(n===``){x=`That is not an address.`,V();return}(async()=>{y=`connecting`,V();let e=be(n);if(e){y=`error`,b=e,x=e,h=``,u=`local`,V();return}if(await ye(n,void 0,r)===null){y=`error`;let e=_e(n);b=e?`needs the server's name`:`not answering`,x=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,u=`local`,V();return}let i=await ve(n,r);if(i){y=`error`,b=i,x=i,h=``,u=`local`,V();return}u=`remote`,x=``;try{localStorage.setItem(He,t.trim())}catch{}I.connect(t),Q(),_n(),qn(!0),Zt(),Wn(),V()})()});let Bt=``,Vt=null,Ht=async(e=!1)=>{o.directory.hidden=!1,e||(o.directoryNote.textContent=`Looking for live streams…`,o.directoryList.replaceChildren()),Vt||=setInterval(()=>{!o.directory.hidden&&document.visibilityState===`visible`&&Ht(!0)},Ge);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],f=t.map(e=>({name:e.name,url:e.url})),Ft();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:Z});if(e&&i===Bt)return;Bt=i,en(r.recent??[])}catch{e||(o.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(o.directoryList.replaceChildren(),t.length===0){o.directoryNote.textContent=`Nobody is streaming right now.`;return}o.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let a=[`${e.tracks.toLocaleString()} files to browse`];e.playing!==!1&&e.nowPlaying?a.push(`playing ${e.nowPlaying}`):a.push(`player idle`),e.code&&a.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=a.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ae(e.url),c=(t,n=``)=>{te=t,g=n,o.remoteUrl.value=t?e.url:s??e.url,o.directory.hidden=!0,o.remoteForm.requestSubmit()},l=document.createElement(`ul`);l.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=document.createElement(`button`);o.type=`button`,o.className=`button`,rt(o),o.title=`Join ${t}, live on ${e.name}`,o.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,o),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:s},()=>{o.directory.hidden=!0});if(t.append(n,u,d),Z&&t.append(ln(e.url,e.name)),e.ownerId&&Z&&e.ownerId!==Z&&t.append(An(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&Z&&e.ownerId===Z){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));o.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{o.directoryNote.textContent=`could not reach the directory`}finally{await Ht()}})()}),t.append(n)}o.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!o.directory.hidden&&Ht(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),Ht()}let Ut=null,Wt=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Gt=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Kt=``,qt=``,Jt=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Kt)return;Kt=t,o.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}o.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[Wt(t.network),`network-${t.network}`],[Gt(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}o.adminConnections.append(e)}};function U(e){o.adminSaid.textContent=e,o.adminSaid.hidden=e===``}let Yt=async()=>{try{let e=await fetch(I.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;o.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,Jt(t.connections??[]),Xt(t.publish??[],(t.channels??[]).map(e=>e.id)),cr(t.home??``,t.root??``),Q()}catch{o.adminNote.textContent=`lost touch with the server`}};function Xt(e,t){o.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===qt)return;if(qt=n,e.length===0){o.publishList.replaceChildren();return}let r=e.length-t.length;o.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,o.publishList.replaceChildren(...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,o.textContent=`Copy`,o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Zt=async()=>{if(u!==`remote`){o.adminPanel.hidden=!0,o.publishPanel.hidden=!0,Ut&&clearInterval(Ut),Ut=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(I.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;if(te&&(e=!1),Qe=i&&!e,o.adminPanel.hidden=!e,h!==``){let e=h;h=``,$e()?Pt(e):(x=`Sign in to nixamp.com to go live here.`,V())}if(Ut&&clearInterval(Ut),Ut=null,Q(),_n(),Wn(),o.listenOnly.hidden=e,!e){o.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}o.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Yt(),Ut=setInterval(()=>void Yt(),2e3)};function Qt(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;U(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),a=await i.json();if(!i.ok){U(a.error??`that did not work`);return}U(`${a.channel?.name||t||e} is on the air.`),o.adminSource.value=``,o.adminName.value=``,Wn(),Q()}catch{U(`could not reach the server`)}})()}o.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=o.adminSource.value.trim();t&&Qt(t,o.adminName.value.trim())}),o.adminAdd.addEventListener(`click`,()=>{let e=o.adminSource.value.trim();if(!e)return;U(`Reading ${e}…`);let t=o.adminReplace.checked,n=o.adminName.value.trim();(async()=>{try{let r=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();U(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(o.adminSource.value=``,o.adminName.value=``,Wn(),Q())}catch{U(`could not reach the server`)}})()});let $t=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},en=e=>{o.recentList.replaceChildren();let t=Z?e.filter(e=>e.ownerId&&e.ownerId!==Z):[];if(o.recentNote.hidden=t.length===0,t.length!==0)for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${$t(e.endedAt)}`:`ended ${$t(e.endedAt)}`,n.append(r,i),t.append(n,An(e.ownerId,e.name)),o.recentList.append(t)}},tn=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function nn(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${tn(e.party.positionNow)}`:`❚❚ ${tn(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,a.textContent=`Watch`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Room`,t.append(n,a,o),t}async function rn(){if(!Z){o.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){o.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];o.partiesPanel.hidden=!1,o.partiesNote.textContent=t.length===0?`No parties on right now. Have a code from a site? Put it in.`:`Parties on now. Watch opens the film where it lives; Room is here.`,o.partiesList.replaceChildren(...t.map(nn))}catch{o.partiesPanel.hidden=!0}}o.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){x=n.error??`no party with that code`,V();return}o.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{x=`could not ask about that party`,V()}})()});async function an(){if(!Z){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];o.connectionsNote.hidden=t.length===0,o.connectionsList.hidden=t.length===0,o.connectionsList.replaceChildren(...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,a.textContent=`Disconnect`,a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await an()})()}),t.append(n,a),t}))}catch{o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0}}let W=new Set,G=e=>{try{return new URL(e).origin}catch{return e}},on=e=>[...W].some(t=>G(t)===G(e));async function sn(){if(!Z){W=new Set,o.favoritesPanel.hidden=!0,un();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){o.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];W=new Set(t.map(e=>e.url)),o.favoritesPanel.hidden=t.length===0,o.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,o.favoritesList.replaceChildren(...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...oe({name:e.name||e.url,view:e.url,admin:ae(e.url)}),ln(e.url,e.name)),t}))}catch{o.favoritesPanel.hidden=!0}un()}async function cn(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){x=n?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{x=`could not reach nixamp.com`,V();return}if(n)W.add(e);else for(let t of[...W])G(t)===G(e)&&W.delete(t);await sn()}function ln(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=on(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...W].find(t=>G(t)===G(e))??e;cn(on(e)?i:e,t,!on(e)).then(r)}),n}function un(){let e=u===`remote`?I.shareLink:``;if(o.favHere.hidden=!(Z&&e),o.favHere.hidden)return;let t=on(e);o.favHere.textContent=t?`♥`:`♡`,o.favHere.dataset.on=t?`yes`:`no`,o.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,o.favHere.setAttribute(`aria-label`,o.favHere.title)}c(o.copyNow,`copy`),o.copyNow.addEventListener(`click`,()=>{nr(F.source,o.copyNow,`✓`)}),o.favHere.addEventListener(`click`,()=>{let e=ir()||I.shareLink;if(!e)return;let t=[...W].find(t=>G(t)===G(e))??e;cn(on(e)?t:e,d||I.address,!on(e)).then(un)});let dn=r?a:200,K=[],q=null,J=null,fn=``,Y=[],pn=0,mn=null,hn=0;function gn(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}async function _n(){if(u!==`remote`){o.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(I.url(`/api/catalogs`))}catch{o.catalogsPanel.hidden=!0;return}if(!e.ok){o.catalogsPanel.hidden=!0;return}K=(await e.json().catch(()=>({}))).catalogs??[],q&&=K.find(e=>e.id===q?.id)??null,q||(J=null),o.catalogsPanel.hidden=!1,vn()}function vn(){let e=!o.adminPanel.hidden;o.catalogsForm.hidden=!e;let t=K.reduce((e,t)=>e+t.live,0),n=K.reduce((e,t)=>e+t.vod,0);o.catalogsNote.textContent=K.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${K.length} ${K.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,yn();let r=q!==null&&J!==null;if(o.catalogsList.hidden=r,o.catalogsFilter.hidden=!r,o.catalogsEntries.hidden=!r,r){wn();return}if(q){xn(q);return}o.catalogsList.replaceChildren(...K.map(t=>bn(t,e)))}function yn(){let e=q!==null;if(o.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>{q=null,J=null,vn()},!1),n(),t(q?.name??``,()=>{J=null,vn()},J===null)];J!==null&&r.push(n(),t(J===``?`All groups`:J,()=>void 0,!0)),o.catalogsCrumbs.replaceChildren(...r)}function bn(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,a.textContent=[`${e.entries.toLocaleString()} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString()} live`,`${e.vod.toLocaleString()} on demand`,`refreshed ${gn(e.refreshedAt)}`].join(` · `),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.addEventListener(`click`,()=>{q=e,J=null,vn()}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{En(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Remove`,r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Dn(e)}),n.append(t,r)}return n}async function xn(e){o.catalogsList.replaceChildren();let t=[];try{let n=await w(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{x=`Could not read the groups in ${e.name}.`,V();return}if(q?.id!==e.id||J!==null)return;let n=[Sn(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Sn(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];o.catalogsList.replaceChildren(...n)}function Sn(e,t,n,r,i){let a=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{J=t,fn=``,o.catalogsFilter.value=``,Y=[],pn=0,vn(),Cn(0)}),a.append(s,u),a}async function Cn(e){let t=q,n=J;if(!t||n===null)return;let r=++hn,i=new URLSearchParams({group:n,q:fn,offset:String(e),limit:String(dn)}),a;try{let e=await w(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{x=`Could not read ${t.name}.`,V();return}r===hn&&(pn=a.total??0,Y=e===0?a.entries??[]:[...Y,...a.entries??[]],wn())}function wn(){let t=q;if(!t)return;let n=Y.map(n=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`name`,i.textContent=n.title;let a=document.createElement(`span`);if(a.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,a.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(i,a),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(e,`copy`),e.title=`Copy this entry's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.title}`),e.addEventListener(`click`,r=>{r.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(t.id)}/entries/${encodeURIComponent(n.id)}/stream`;nr(I.url(i),e,`✓`)}),r.append(e)}return $e()&&r.append(it(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{Tn(t,n,r)}),r});if(Y.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=fn?`Nothing called "${fn}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(Y.length<pn){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${Y.length.toLocaleString()} of ${pn.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),Cn(Y.length)}),e.append(t),n.push(e)}o.catalogsEntries.replaceChildren(...n)}async function Tn(e,t,n){n?.classList.add(`loading`),x=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await w(async()=>{let n,i={};try{n=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{x=`could not reach the server`;return}if(!n.ok){x=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await Zn({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){C=null,S=-1,T={kind:`vod`,...r},ze(a,`title`),await F.load({title:a,artist:``,album:``,duration:0,url:I.url(i.url),video:!0,objectUrl:!1},!0),jt(!0),x=`Playing ${a}.`;return}x=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),V()}}async function En(e){U(`Reading ${e.name} again…`);try{let t=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));U(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}_n()}async function Dn(e){try{U((await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{U(`could not reach the server`)}q?.id===e.id&&(q=null,J=null),_n()}o.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.catalogSource.value.trim(),n=o.catalogName.value.trim();t&&(async()=>{U(`Reading ${n||t}…`);try{let e=await fetch(I.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){U(r.error??`that did not work`);return}U(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),o.catalogSource.value=``,o.catalogName.value=``}catch{U(`could not reach the server`)}_n()})()}),o.catalogsFilter.addEventListener(`input`,()=>{mn&&clearTimeout(mn),mn=setTimeout(()=>{mn=null,fn=o.catalogsFilter.value.trim(),Cn(0)},250)});let On=async()=>{o.serversList.replaceChildren();try{let e=await fetch(`/api/v1/servers`);if(!e.ok){o.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];re=new Map(t.map(e=>[G(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),o.serversPanel.hidden=!1,o.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. View one, administer it, or forget it.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let a=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=oe({name:e.name,view:a,admin:a});ye(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=document.createElement(`button`);l.type=`button`,l.className=`ghost`,l.textContent=`Forget`,l.addEventListener(`click`,()=>{(async()=>{l.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await On()}catch{l.disabled=!1}})()}),t.append(n,s,c,l),o.serversList.append(t)}}catch{o.serversPanel.hidden=!0}},kn=async()=>{o.followingList.replaceChildren();try{let e=await fetch(`/api/v1/follows`);if(!e.ok){o.followingNote.hidden=!0;return}let t=(await e.json()).following??[];o.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let a=document.createElement(`button`);a.type=`button`,a.className=`ghost follow`,a.textContent=`Unfollow`,a.addEventListener(`click`,()=>{(async()=>{a.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),o.followingList.children.length===0&&(o.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),o.followingList.append(t)}}catch{o.followingNote.hidden=!0}},An=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,n.textContent=`Follow`,n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{n.textContent=e?`Following`:`Follow`,n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),kn())}catch{}finally{n.disabled=!1}})()}),n},jn=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},Mn=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Nn=async()=>{if(!Mn())return o.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return o.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return o.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return o.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:jn(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return o.notifyNote.textContent=`This device will be told.`,!0}catch{return o.notifyNote.textContent=`Could not set this device up.`,!1}},Pn=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},Fn=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();o.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(o.notifyPhone.value=n.phone)}catch{o.notifyPhoneNote.textContent=`could not reach nixamp.com`}},In=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();o.notifyEmail.checked=t.wantsEmail!==!1,o.notifySms.checked=t.wantsSms===!0,o.notifyPhone.value=t.phone??``;let n=Mn()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;o.notifyWeb.checked=t.wantsWeb!==!1&&n,o.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};o.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(o.notifyWeb.checked){let e=await Nn();o.notifyWeb.checked=e,await Fn({wantsWeb:e});return}await Pn(),await Fn({wantsWeb:!1}),o.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),o.notifyEmail.addEventListener(`change`,()=>{Fn({wantsEmail:o.notifyEmail.checked})}),o.notifySms.addEventListener(`change`,()=>{(async()=>{if(o.notifySms.checked&&!o.notifyPhone.value.trim()){o.notifyPhoneNote.textContent=`Add a phone number first.`,o.notifySms.checked=!1,o.notifyPhone.focus();return}await Fn({wantsSms:o.notifySms.checked})})()}),o.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),Fn({phone:o.notifyPhone.value.trim()})});let X=!1,Z=``,Ln=!1,Rn=`nixamp.welcome`,zn=()=>{let e=!1;try{e=localStorage.getItem(Rn)===`hidden`}catch{}o.welcome.hidden=!Ln||Z!==``||e},Bn=e=>{let t=e!==null;o.notifyPanel.hidden=!t,t?(In(),kn(),On()):(o.serversPanel.hidden=!0,o.followingNote.hidden=!0,o.followingList.replaceChildren(),o.recentNote.hidden=!0,o.recentList.replaceChildren()),o.accountForm.hidden=t,o.accountProviders.hidden=t||o.accountProviders.childElementCount===0,o.accountSignOut.hidden=!t,o.accountNote.textContent=t?`Signed in as ${e}.`:X?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,o.accountSubmit.textContent=X?`Create account`:`Sign in`,o.accountToggle.textContent=X?`I have one`:`Create one`,o.accountPassword.autocomplete=X?`new-password`:`current-password`,zn()},Vn=async()=>{let e=[];Ln=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Ln=!0,e=(await t.json()).providers??[])}catch{}o.accountProviders.replaceChildren(),o.accountProviders.hidden=e.length===0,o.accountPanel.hidden=!Ln,o.accountElsewhere.hidden=Ln,zn();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,o.accountProviders.append(e)}},Hn=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();Z=e.ok?t.account?.id??``:``,Bn(e.ok?t.account?.email??`you`:null)}catch{Z=``,Bn(null)}if(I.session=``,Z!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));I.session=e.ok&&typeof t.token==`string`?t.token:``}catch{I.session=``}u===`remote`&&Zt()}sn(),rn(),an(),Un()};function Un(){if(Ye===``)return;let e=Ye;Ye=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit()}o.accountToggle.addEventListener(`click`,()=>{X=!X,Bn(null)}),o.welcomeCreate.addEventListener(`click`,()=>{X=!0,Bn(null),o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),o.accountEmail.focus({preventScroll:!0})}),o.welcomeBrowse.addEventListener(`click`,()=>{o.directory.hidden?o.browse.click():o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Rn,`hidden`)}catch{}o.welcome.hidden=!0}),o.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.accountEmail.value.trim(),n=o.accountPassword.value;(async()=>{o.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${X?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){o.accountNote.textContent=r.error??`that did not work`;return}Z=r.account?.id??``,o.accountPassword.value=``,Bn(r.account?.email??t),Zt(),Un()}catch{o.accountNote.textContent=`could not reach nixamp.com`}finally{o.accountSubmit.disabled=!1}})()}),o.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}Z=``,Bn(null),I.close(),S=-1,u=`local`,y=`idle`,b=``,o.remoteUrl.value=``,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.catalogsPanel.hidden=!0,o.listenOnly.hidden=!0,qn(!1);try{localStorage.removeItem(He)}catch{}x=`Signed out, and disconnected from the server.`,Zt(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Ye=t,g=e.get(`play`)??``,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t,x=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname))}catch{}Vn(),Hn(),Zt(),It(),o.browse.addEventListener(`click`,()=>{if(!o.directory.hidden){o.directory.hidden=!0;return}Ht(),o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.disconnect.addEventListener(`click`,()=>{I.close(),o.listenOnly.hidden=!0,S=-1,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.onairPanel.dataset.title=`Live on this server`,o.catalogsPanel.hidden=!0,o.catalogsPanel.dataset.title=`Catalogs on this server`,d=``,ce=``,un(),qn(!1),u=`local`,y=`idle`,b=``,V()});async function Wn(){if(u!==`remote`||I.shareLink===``){o.sharePanel.hidden=!0;return}o.sharePanel.hidden=!1;let e=ir(),t=globalThis.location.origin;o.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,o.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,o.sharePhone.hidden=!0,o.shareSend.hidden=!0,o.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(I.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ce=r.url,o.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Be=r.live,A=r.live?r.code:``,qe=n,o.liveControls.hidden=o.adminPanel.hidden||!r.possible,o.goLive.hidden=r.live,o.stopLive.hidden=!r.live,o.sharePhone.hidden=!1,!r.live){o.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){o.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,o.shareSend.hidden=!1;return}o.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),ur(n),document.createTextNode(` and key `),ur(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),o.shareSend.hidden=!1}}let Gn=``,Kn=null,qn=e=>{Kn&&clearInterval(Kn),Kn=null,e&&(Kn=setInterval(()=>void Q(),6e3))};async function Q(){if(u!==`remote`){o.onairPanel.hidden=!0;return}let e;try{let t=await fetch(I.url(`/api/streams`));if(!t.ok){o.onairPanel.hidden=!0;return}e=await t.json(),m=e.server.carries!==!1,e.server.name&&e.server.name!==d&&(d=e.server.name,o.onairPanel.dataset.title=`Live on ${d}`,o.catalogsPanel.dataset.title=`Catalogs on ${d}`,un(),V())}catch{o.onairPanel.hidden=!0;return}o.onairPanel.hidden=!1,E=e,ar(e);let t=`${o.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}`;if(t===Gn)return;Gn=t;let n=e.restreams??[],r=e.channels.length+n.length;o.onairNote.textContent=r===0?`One stream, from this server's own files.`:`${r+1} streams: this server's own files, and ${r} more on it.`;let i=[],a=e.server.playing,s=!o.adminPanel.hidden;i.push(or({title:e.server.name,detail:[a?`playing ${e.server.nowPlaying}`:e.server.nowPlaying?`stopped on ${e.server.nowPlaying}`:`nothing loaded`,`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:a?`Join live`:s?`Start the stream`:`Nothing playing`,onPlay:()=>{if(a){Xn(e.server.nowPlaying);return}s&&Yn()},link:e.server.live?e.server.url:``,...a?{page:rr(`live`)}:{},direct:a?I.url(`/api/live`):``}));for(let e of n)i.push(or({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{z(e.at)},link:``,direct:I.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=I.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&r.push(`☎ ${t.code}`),t.redials&&r.push(`redialled ${t.redials}×`),s&&t.error&&r.push(t.error),i.push(or({title:t.name,detail:r.join(` · `),onPlay:()=>{Zn({id:t.id,name:t.name,video:e})},link:n,page:rr(`channel:${t.id}`),direct:n,onRestart:s&&t.via===`pull`?()=>{$n(t.id,t.name)}:void 0,onStop:s||Qe&&Z!==``&&t.startedBy===Z?()=>{tr(t.id,t.name)}:void 0,onRename:s||Qe&&Z!==``&&t.startedBy===Z?()=>{er(t.id,t.name)}:void 0}))}o.onairList.replaceChildren(...i)}async function Jn(){if(u===`remote`)try{if((await fetch(I.media(R(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;x=Z===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,Z===``&&o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function Yn(){U(`Starting the stream on the server…`);try{await I.send({type:`play`,index:Math.max(0,R())})}catch{U(`could not reach the server`);return}await Xn(v.tracks[R()]?.title??``),U(`Playing to the room. Anybody with the view link sees this.`),await Q()}async function Xn(e){S=-1,C=null,T={kind:`live`},ze(e,`auto`),await w(()=>F.load({title:e||`Live`,artist:``,album:``,duration:0,url:I.url(`/api/live`),video:!0,objectUrl:!1},!0)),jt(!0),x=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function Zn(e,t=!0,n){S=-1,C=e,t&&(xe=0),t&&(T=n??{kind:`channel`}),t&&ze(e.name,T?.link||Ve(e.name)?`auto`:`channel`);let r=e.video&&et();await w(()=>F.load({title:e.name,artist:``,album:``,duration:0,url:I.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),jt(e.video),C===e&&(x=`Watching ${e.name}, live on this server.`),V()}function Qn(){let e=C;return e?Je?!0:xe>=5?(x=`${e.name} stopped, and did not come back.`,C=null,T=null,V(),!0):(xe+=1,x=`${e.name} started over; rejoining…`,V(),Je=setTimeout(()=>{Je=null,C===e&&Zn(e,!1)},2e3),!0):!1}function $(e){o.onairNote.textContent=e,U(e)}async function $n(e,t){$(`Restarting ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}Gn=``,Q()}async function er(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){$(`Renaming ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));$(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{$(`could not reach the server`)}C?.id===e&&(C={...C,name:r}),Gn=``,Q(),V()}}async function tr(e,t){$(`Taking ${t} off the air…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}C?.id===e&&(C=null,F.stop()),Gn=``,Q()}async function nr(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{x=e,V();return}n===`✓`||n===`✓`?c(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function rr(e,t=0){let n=ir();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function ir(){if(ce!==``)return ce;let e=u===`remote`?I.shareLink:``;return/\/admin\//.test(e)?``:e}function ar(e){if(g===``)return;let t=g;if(t===`live`){g=``,e.server.playing?Xn(e.server.nowPlaying):(x=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){g=``,Nt(t.slice(5));return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(g=``,Zn({id:r.id,name:r.name,video:r.kind!==`audio`}))}function or(e){let t=document.createElement(`li`);t.className=`onair`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let o=document.createElement(`button`);o.type=`button`,o.className=`button`,rt(o,e.playLabel??`Join live`),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,c(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;nr(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{nr(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,a),t}let sr=``;function cr(e,t){sr=e;let n=e!==``&&t===e;o.loadHome.hidden=e===``,o.homeNote.hidden=e===``,e!==``&&(o.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,o.loadHome.disabled=!1)}o.loadHome.addEventListener(`click`,()=>{sr!==``&&(o.loadHome.disabled=!0,U(`Reading this server's files…`),(async()=>{try{let e=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:sr})}),t=await e.json();U(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{U(`could not reach the server`)}finally{o.loadHome.disabled=!1}})())});let lr=async e=>{o.goLive.disabled=!0,o.stopLive.disabled=!0,o.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(I.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();o.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{o.shareNote.textContent=`could not reach the server`}finally{o.goLive.disabled=!1,o.stopLive.disabled=!1,await Wn()}};o.goLive.addEventListener(`click`,()=>void lr(!0)),o.stopLive.addEventListener(`click`,()=>void lr(!1));function ur(e){let t=document.createElement(`b`);return t.textContent=e,t}o.shareCopy.addEventListener(`click`,()=>{o.shareLink.select(),navigator.clipboard?.writeText(o.shareLink.value).then(()=>{o.shareNote.textContent=`Copied. Send it to anybody.`},()=>{o.shareNote.textContent=`Copy it from the box above.`})}),o.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=o.shareTo.value.trim();t!==``&&(async()=>{o.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:ir()})}),n=await e.json();o.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(o.shareTo.value=``)}catch{o.shareNote.textContent=`could not send that`}})()}),o.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(We,o.listenHere.checked?`1`:`0`)}catch{}u===`remote`&&(async()=>{o.listenHere.checked?(await I.send({type:`stop`}),await dt(v.index)):(F.stop(),S=-1),V()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),ft();return;case`s`:pt();return;case`n`:case`ArrowRight`:B(1);return;case`p`:case`ArrowLeft`:B(-1);return;case`ArrowDown`:e.preventDefault(),z(Math.min(L()-1,R()+1));return;case`ArrowUp`:e.preventDefault(),z(Math.max(0,R()-1));return}});let dr=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),dr=e,o.install.hidden=!1}),o.install.addEventListener(`click`,()=>{dr?.prompt(),dr=null,o.install.hidden=!0});try{let e=localStorage.getItem(Ue);e!==null&&(o.volume.value=String(Math.round(Number(e)*100)),F.volume=Number(e));let t=localStorage.getItem(He);t&&(o.remoteUrl.value=t),localStorage.getItem(We)===`0`&&(o.listenHere.checked=!1)}catch{}(async()=>{if(o.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await ye(e)===null)return;let t=await ge(e);t&&t.trackCount!==0&&(o.remoteUrl.value=e,u=`remote`,x=``,I.connect(e),V())})(),(()=>{if(Ke||Ye!==``)return;let e=()=>F.source!==``||F.playing||Ae()||C!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{Ke=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||n.play().catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,n.play().then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),V(),requestAnimationFrame(Ot)}qe(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{c as t};
|
|
1
|
+
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function t(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function n(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var r=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}var a=`modulepreload`,o=function(e){return`/`+e},s={},c=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),c=i?.nonce||i?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=l(t.map(t=>{if(t=o(t,n),t=u(t),t in s)return;s[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:a,r||(i.as=`script`),i.crossOrigin=``,i.href=t,c&&i.setAttribute(`nonce`,c),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},l=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],u=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function d(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of u)if(t.test(e.mimeType))return n}let t=f(e.src);for(let[e,n]of l)if(e.test(t))return n;return`unknown`}function f(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function p(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function m(e,t){let n=d(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function h(e,t){let n=t.capabilities??p(),r=m({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await c(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-DUthTvKE.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await c(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-p5qT7X7S.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await c(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var ee=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),te=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function g(e){let t=e.lastIndexOf(`.`);return t>0&&te.has(e.slice(t+1).toLowerCase())}function ne(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&ee.has(e.slice(n+1).toLowerCase())}function re(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ie(e){return e.filter(e=>ne(e.name,e.type)).sort((e,t)=>re(ae(e),ae(t))).map(e=>({title:n(e.name),artist:``,album:oe(ae(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...g(e.name)?{kind:`mpegts`}:{}}))}function ae(e){return e.webkitRelativePath||e.name}function oe(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function se(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var ce=2048;function _(e,t){return e||t===`hls`||t===`mpegts`}var le=class{elements;handlers;attached=null;source=``;context=null;analyser=null;wired=new WeakSet;active;frequencies=new Uint8Array;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.crossOrigin=`anonymous`,t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(ue(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(this.context??=new t,this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=ce,this.analyser.smoothingTimeConstant=.6,this.analyser.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:d({src:e.url})),r=_(e.video,n)?this.elements.video:this.elements.audio;r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await h(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}t&&await this.play()}async play(){this.ensureGraph(this.active);try{await this.active.play()}catch(e){this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function ue(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function de(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function fe(e,t){return{...t,tracks:t.tracks??e.tracks}}function v(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function y(e,t,n=``){let r=`${e===``?``:v(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function pe(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:v(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var b=null;function x(e){if(!e&&b!==null)return b;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(b=n),n}catch{return!1}}function me(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return y(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function S(e){if(typeof e!=`object`||!e)return null;let t=e,n=de(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}var he=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}url(e){let t=y(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=pe(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(y(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=S(C(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(y(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=S(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=x()){return me(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function C(e){try{return JSON.parse(e)}catch{return null}}async function ge(e,t,n=``){try{let r=await fetch(y(e,`/api/state`,n),{signal:t});return r.ok?S(await r.json()):null}catch{return null}}function _e(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function ve(e,t=``,n){let r;try{r=await fetch(y(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function ye(e,t,n=``){try{let r=await fetch(y(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function be(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var xe=.14,Se=.02;function Ce(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function we(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function Te(e,t,n=xe){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Ee(e,t,n=Se){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function De(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function Oe(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function ke(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function Ae(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale,i)===r.toLocaleDateString(t.locale,i);return n.toLocaleString(t.locale,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function je(e,t={}){let n=e.data,r=Oe(n.away,n.awayScore),i=Oe(n.home,n.homeScore),a=ke(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=Ae(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var Me=`nixamp.tv`,w=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function Ne(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?T(r):/\bSilk\b/.test(e)&&n===0?!0:w.test(e):T(i)}function T(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Pe(e){return e?12:100}function Fe(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var E=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,D=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,Ie=/\.m3u8(\?.*)?$/i;function O(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function Le(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=O(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return E.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:D.test(o)||Ie.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var Re=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,k=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,ze=/\s+(?:vs\.?|v\.?|at|@)\s+/i,Be=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function A(e){let t=e.replace(k,``).replace(k,``).trim().split(ze);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!Be.test(t)})}function Ve(e){let t=String(e??``).trim();return t===``?!1:A(t.replace(Re,``))||A(t)}var He=`nixamp.remote`,Ue=`nixamp.volume`,We=`nixamp.listenHere`,Ge=1e4,Ke=!1;function j(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function qe(){let n=null;try{n=localStorage.getItem(Me)}catch{}let r=Ne(navigator.userAgent,location.search,navigator.maxTouchPoints,n);if(document.body.classList.toggle(`tv`,r),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Me,r?`1`:`0`)}catch{}let i=document.getElementById(`tv-toggle`);i&&(i.textContent=r?`TV mode: on`:`TV mode`,i.title=r?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,i.addEventListener(`click`,()=>{try{localStorage.setItem(Me,r?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let a=Pe(r),o={status:j(`status`),source:j(`source`),install:j(`install`),video:j(`video`),audio:j(`audio`),title:j(`title-line`),album:j(`album-line`),meta:j(`meta-line`),metaBlurb:j(`meta-blurb`),liveLine:j(`live-line`),downloadNow:j(`download-now`),wayInHere:j(`way-in-here`),embed:j(`embed`),embedFrame:j(`embed-frame`),linkForm:j(`link-form`),linkUrl:j(`link-url`),linkServer:j(`link-server`),linkGoLive:j(`link-go-live`),goLiveNow:j(`go-live-now`),elapsed:j(`elapsed`),total:j(`total`),seek:j(`seek`),fullscreen:j(`fullscreen`),copyNow:j(`copy-now`),canvas:j(`spectrum`),glyphs:j(`glyphs`),levels:j(`levels`),playlist:j(`playlist`),playlistPager:j(`playlist-pager`),crumbs:j(`crumbs`),filter:j(`filter`),playlistTitle:j(`playlist-panel`),note:j(`note`),files:j(`files`),folder:j(`folder`),remoteUrl:j(`remote-url`),remoteForm:j(`remote-form`),remoteState:j(`remote-state`),disconnect:j(`disconnect`),browse:j(`browse`),accountForm:j(`account-form`),accountEmail:j(`account-email`),accountPassword:j(`account-password`),accountSubmit:j(`account-submit`),accountToggle:j(`account-toggle`),accountProviders:j(`account-providers`),accountPanel:j(`account-panel`),accountElsewhere:j(`account-elsewhere`),welcome:j(`welcome`),welcomeCreate:j(`welcome-create`),welcomeBrowse:j(`welcome-browse`),welcomeHide:j(`welcome-hide`),accountSignOut:j(`account-signout`),accountNote:j(`account-note`),adminPanel:j(`admin-panel`),adminNote:j(`admin-note`),adminSaid:j(`admin-said`),adminConnections:j(`admin-connections`),publishPanel:j(`publish-panel`),publishNote:j(`publish-note`),publishList:j(`publish-list`),adminRestream:j(`admin-restream`),adminReplace:j(`admin-replace`),adminSource:j(`admin-source`),adminName:j(`admin-name`),adminAdd:j(`admin-add`),homeNote:j(`home-note`),loadHome:j(`load-home`),directory:j(`directory`),recentNote:j(`recent-note`),recentList:j(`recent-list`),followingNote:j(`following-note`),followingList:j(`following-list`),serversPanel:j(`servers-panel`),serversNote:j(`servers-note`),serversList:j(`servers-list`),favoritesPanel:j(`favorites-panel`),favoritesNote:j(`favorites-note`),favoritesList:j(`favorites-list`),favHere:j(`fav-here`),partiesPanel:j(`parties-panel`),partiesNote:j(`parties-note`),partiesList:j(`parties-list`),partyForm:j(`party-form`),partyCode:j(`party-code`),connectionsNote:j(`connections-note`),connectionsList:j(`connections-list`),catalogsPanel:j(`catalogs-panel`),catalogsNote:j(`catalogs-note`),catalogsForm:j(`catalogs-form`),catalogSource:j(`catalog-source`),catalogName:j(`catalog-name`),catalogsList:j(`catalogs-list`),catalogsCrumbs:j(`catalogs-crumbs`),catalogsFilter:j(`catalogs-filter`),catalogsEntries:j(`catalogs-entries`),notifyPanel:j(`notify-panel`),notifyNote:j(`notify-note`),notifyWeb:j(`notify-web`),notifyEmail:j(`notify-email`),notifySms:j(`notify-sms`),notifyPhone:j(`notify-phone`),notifyPhoneForm:j(`notify-phone-form`),notifyPhoneNote:j(`notify-phone-note`),directoryNote:j(`directory-note`),directoryList:j(`directory-list`),onairPanel:j(`onair-panel`),onairNote:j(`onair-note`),onairList:j(`onair-list`),sharePanel:j(`share-panel`),shareNote:j(`share-note`),shareLink:j(`share-link`),shareCopy:j(`share-copy`),sharePhone:j(`share-phone`),shareSend:j(`share-send`),liveControls:j(`live-controls`),goLive:j(`go-live`),stopLive:j(`stop-live`),shareTo:j(`share-to`),listenOnly:j(`listen-only`),listenHere:j(`listen-here`),volume:j(`volume`),prev:j(`prev`),playPause:j(`play-pause`),stop:j(`stop`),next:j(`next`)},s={rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`},c=(e,t)=>{e.innerHTML=s[t]},l=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,u=`local`,d=``,f=[],p=``,m=!0,h=``;function ee(e){try{return new URL(e).origin}catch{return e}}let te=!1,g=``,ne=0,re=new Map,ae=e=>re.get(G(e))??null;function oe(e,t){let n=n=>{te=n,g=``,o.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),o.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,c(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,c(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:Z?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let ce=``,_=[],ue=0,v=de(),y=`idle`,b=``,x=`Pick files, or connect to a nixamp running somewhere else.`,me=!1,S=-1,C=null,xe=0,Se=0,Oe=!1,Ae=()=>Se>0||Oe;async function w(e){Se+=1,V();try{return await e()}finally{--Se,V()}}let T=null,E=null,D=null;function Ie(){o.embed.hidden||(o.embedFrame.src=`about:blank`),o.embed.hidden=!0}let O=null,Re=``,k=null;function ze(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Re=i,k&&clearTimeout(k),k=null,!r){if(O?.key===i)return;O=null}if(u!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(I.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Re!==i)return;O={key:i,match:r.match??null},V();let a=O.match;a?.kind===`fixture`&&ke(a)!==`post`&&(k=setTimeout(()=>{k=null,!(Re!==i||F.source===``&&!C)&&ze(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Be=!1,A=``,qe=``,Je=null,Ye=``,M=Array(24).fill(0),N=Array(24).fill(0),Xe=[],P=()=>u===`remote`&&!o.listenHere.checked,Ze=()=>u===`remote`&&!o.adminPanel.hidden,Qe=!1,$e=()=>Ze()||u===`remote`&&Qe;function et(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:o.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function tt(){if(u!==`remote`||D)return null;if(T?.catalog&&T.entry)return{kind:`entry`,catalog:T.catalog,entry:T.entry};if(C)return{kind:`channel`,id:C.id,name:C.name};let e=v.tracks[R()];return e&&(F.source!==``||P())?{kind:`track`,index:R(),name:t(e)}:null}async function nt(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;x=`Putting ${n} on the air…`,V();try{let r=``,i=``,a=!0;{let t=e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(I.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){x=s.error??`${n} would not go on the air.`,V();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(Ze()&&(Be?await fetch(I.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await lr(!0)),await Wn(),Q(),i!==``&&C?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await Zn({id:i,name:n,video:a},!0,t)}let o=rr(r),s=A?` Call ${qe||`the line`} and key ${A} to talk about it.`:``;o===``?x=`${n} is on the air and you are watching it.${s}`:(await nr(o,t,`✓`),x=`${n} is on the air and you are watching it. Link copied.${s}`),V()}catch{x=`could not reach the server`,V()}finally{t.disabled=!1}}function rt(e,t=`Join live`){c(e,`live`),e.append(document.createTextNode(` ${t}`))}function it(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,c(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),nt(e(),n)}),n}let F=new le({audio:o.audio,video:o.video},{onTime:(e,t)=>{let n=_[ue];u===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{Qn()||u===`remote`&&S<0&&!P()||B(1)},onState:()=>V(),onBusy:e=>{Oe!==e&&(Oe=e,V())},onError:e=>{Qn()||(x=e,V(),Jn())}}),I=new he({onSnapshot:e=>{if(v=fe(v,e),g.startsWith(`track:`)&&v.tracks.length>0){let e=Number(g.slice(6));if(g=``,Number.isInteger(e)&&e>=0&&e<v.tracks.length){let t=ne;dt(e).then(()=>{t>0&&(F.seek(t),setTimeout(()=>F.seek(t),600))})}}P()&&(M=e.bars.length>0?e.bars:M,N=Ee(N,M)),V()},onStatus:(e,t)=>{y=e,b=t??``,V()}}),L=()=>u===`remote`?v.tracks.length:_.length,R=()=>u===`remote`?P()||S<0?v.index:Math.min(S,Math.max(0,v.tracks.length-1)):ue,at=()=>{if(C)return C.name;if(D)return D.label;let e=u===`remote`?v.tracks[R()]:_[R()];return e?t(e):`Nothing loaded.`},ot=()=>C?`live on this server`:D?`playing here, in this browser`:T?.kind===`live`&&u===`remote`?`live on ${d||`this server`}`:(u===`remote`?v.tracks[R()]:_[R()])?.album||`—`;function st(){if(u!==`remote`||C===null&&T?.kind!==`live`){o.liveLine.hidden=!0,o.liveLine.replaceChildren();return}let e=d||`this server`,t=C?C.name:E?.server.nowPlaying||at(),n=[C?`Live on ${e}: `:`Live from ${e}, now playing: `,ur(t)],r=C?E?.channels.find(e=>e.id===C?.id)?.code??``:Be?A:``;r&&n.push(`. To talk about it, call `,ur(qe||`the line`),` and key `,ur(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);o.liveLine.dataset.drawn!==i&&(o.liveLine.dataset.drawn=i,o.liveLine.hidden=!1,o.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let ct=()=>P()?v.tracks[R()]?.duration??0:F.duration,lt=()=>P()?v.position:F.position,ut=()=>P()?v.playing:F.playing;async function z(e){if(u===`remote`){if(P()){await I.send({type:`play`,index:e});return}await dt(e);return}let t=_[e];t&&(ue=e,C=null,T={kind:`file`},await w(()=>F.load(t,!0)),jt(t.video),Mt(),V())}async function dt(e){let t=v.tracks[e];t&&(S=e,C=null,T={kind:`file`},ze(t.title,`auto`),await w(()=>F.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:I.media(e,0),video:t.video===!0,objectUrl:!1},!0)),jt(t.video===!0),Mt())}async function ft(){if(P()){await I.send({type:`toggle`});return}L()!==0&&(F.playing?F.pause():F.position>0?await F.play():await z(R()),V())}async function B(e){let t=L();if(t!==0){if(P()){await I.send({type:e>0?`next`:`prev`});return}await z((R()+e+t)%t)}}async function pt(){if(Ie(),D=null,P()){await I.send({type:`stop`});return}C=null,T=null,F.stop(),M=Array(24).fill(0),N=[...M],V()}let mt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,ht=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],gt=``;function _t(){let t=[],n=``,r=null,i=C?E?.channels.find(e=>e.id===C?.id):void 0,a=F.source===``&&!C&&!(P()&&v.tracks[R()]);if(!a){C?t.push(T?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):T?.kind===`vod`?t.push(`ON DEMAND`):T?.kind===`live`?t.push(`LIVE`):u===`remote`&&P()?t.push(`ON THE SERVER`):t.push(`FILE`),!o.video.hidden&&o.video.videoWidth>0?t.push(`${o.video.videoWidth}×${o.video.videoHeight}`):o.video.hidden?t.push(`audio`):t.push(`video`),i?(t.push(i.via===`pull`?`${i.listeners} watching`:`${i.listeners} listening · over ${i.via}`),i.startedAt>0&&t.push(`on air ${e(Math.max(0,(Date.now()-i.startedAt)/1e3))}`),i.redials&&t.push(`redialled ${i.redials}×`),Ze()&&i.error&&t.push(i.error)):u===`remote`&&!C?(v.tracks[R()]&&L()>0&&t.push(`track ${R()+1} of ${L()}`),P()&&E&&t.push(`${E.server.playing?`playing`:`stopped`} on ${d||`the server`}`)):u===`local`&&L()>0&&t.push(`track ${R()+1} of ${L()}`),T?.catalog!==void 0&&(T.kind===`channel`?C!==null:T.kind===`vod`&&F.source!==``)&&T?.catalog&&(t.push(T.entry?.group?`${T.catalog.name} › ${T.entry.group}`:T.catalog.name),n=T.entry?.logo??``);let a=O?.key===Re?O.match:null;if(a?.kind===`fixture`)r=je(a),t.unshift(r.status,...r.chips);else if(a){a.image&&(n=a.image);let e=a.data;if(a.kind===`title`){a.year&&t.push(String(a.year));let n=typeof e.rating==`number`?e.rating:null;n&&t.push(`★ ${n.toFixed(1)}`);let r=Array.isArray(e.genres)?e.genres.slice(0,2).map(String):[];r.length&&t.push(r.join(` · `));let i=typeof e.runtimeMin==`number`?e.runtimeMin:0;i&&t.push(`${i} min`)}else if(a.kind===`channel`){let n=typeof e.country==`string`?e.country:``,r=Array.isArray(e.categories)?e.categories.slice(0,2).map(String):[],i=typeof e.network==`string`?e.network:``;n&&t.push(n),r.length&&t.push(r.join(` · `)),i&&t.push(i)}}if(C&&T?.link){let e=``;try{e=new URL(T.link.url).hostname.replace(/^www\./,``)}catch{}t.push(T.link.extractor&&T.link.extractor!==`direct`&&T.link.extractor!==`generic`?`${T.link.extractor} · ${e}`:e||`link`)}Be&&A&&P()&&!C&&T?.kind!==`live`&&t.push(qe?`☎ ${qe} · key ${A}`:`☎ code ${A}`)}let s=O?.key===Re?O.match:null,c=!a&&!r&&s?.summary?s.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${c}`;if(l===gt)return;gt=l,o.meta.hidden=t.length===0,o.metaBlurb.textContent=c,o.metaBlurb.hidden=c===``;let f=[];if(r){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let n=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,n.push(i),r?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),n.push(t)}if(e.logo!==``){let r=document.createElement(`img`);r.className=`meta-team-logo`,r.alt=``,r.src=e.logo,r.addEventListener(`error`,()=>{r.hidden=!0}),t?n.unshift(r):n.push(r)}return n},n=document.createElement(`span`);n.className=`meta-dash`,n.textContent=`–`,e.replaceChildren(...t(r.away,!0),n,...t(r.home,!1)),f.push(e)}if(n!==``&&/^https?:\/\//.test(n)){let e=document.createElement(`img`);e.className=s?.kind===`title`&&n===s.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let e of t){let t=document.createElement(`span`);t.className=r?.state===`in`&&e===r.status?`meta-chip chip-live`:`meta-chip`,t.textContent=e,f.push(t)}o.meta.replaceChildren(...f)}function V(){let t=L(),n=ut(),r=Ae();o.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,o.status.dataset.playing=r?`loading`:String(n),o.title.textContent=at(),st(),_t(),o.goLiveNow.hidden=!$e()||tt()===null;let i=n?`${at()} · ${l}`:l;document.title!==i&&(document.title=i),o.copyNow.hidden=F.source===``,o.downloadNow.hidden=!(C&&T?.link?.download),Ft(),o.album.textContent=ot();let a=lt(),s=ct();o.elapsed.textContent=e(a),o.total.textContent=s>0?e(s):`--:--`,me||(o.seek.value=String(s>0?Math.round(a/s*1e3):0),o.seek.disabled=s<=0||P()),o.playPause.textContent=n?`❚❚`:`▶`,o.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),o.playlistTitle.dataset.title=u===`remote`?`Files on ${d||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,o.source.textContent=u===`remote`?`connected · ${d||I.address.replace(/^https?:\/\//,``)||`—`}`:_.length>0?`local · ${_.length} files`:`no source`,At(),o.remoteState.textContent=u===`remote`?`${y}${b?` — ${b}`:``}`:`not connected`,o.remoteState.dataset.status=u===`remote`?y:`idle`,o.disconnect.hidden=u!==`remote`;let c=u===`remote`&&v.note!==``?v.note:x;o.note.textContent=c,o.note.hidden=c===``,Tt(),o.glyphs.textContent=M.map(ht).join(``);let[f,p]=P()?v.levels:F.levels();o.levels.textContent=mt(f,p)}let vt=``,yt=-1,H=``,bt=0;function xt(e){H=e,bt=0,vt=``,Tt()}function St(e,t,n,r,i){if(o.playlistPager.hidden=n<=1,n<=1){o.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{bt=t,vt=``,Tt(),o.playlist.scrollIntoView({block:`nearest`})}),i},s=document.createElement(`span`);s.className=`pager-where`,s.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,o.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),s,a(`Next ›`,t+1,`The page after this one`))}function Ct(e){if(o.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>xt(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),o.crumbs.replaceChildren(...r)}function wt(e,t){let n=document.createElement(`li`);n.className=`folder`;let r=document.createElement(`span`);r.className=`name`,r.textContent=`${e}/`;let i=document.createElement(`span`);return i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i),n.tabIndex=0,n.addEventListener(`click`,()=>xt(H===``?e:`${H}/${e}`)),n}function Tt(){let n=u===`remote`?v.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):_.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=o.filter.value.trim().toLowerCase(),i=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),s=e=>r!==``||H===``||e===H||e.startsWith(`${H}/`),l=e=>r!==``||e===H,d=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of i){if(!s(e.folder)||l(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=i.filter(e=>l(e.folder)&&s(e.folder)),m=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),h=Fe(m.length+p.length,bt,a);bt=h.page;let ee=m.slice(h.from,h.to),te=p.slice(Math.max(0,h.from-m.length),Math.max(0,h.to-m.length)),g=`${u}:${H}:${r}:${h.page}/${a}:${m.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(g!==vt){vt=g,Ct(r===``&&(m.length>0||H!==``)),St(m.length+p.length,h.page,h.pages,h.from,h.to);let t=[];for(let[e,n]of ee)t.push(wt(e,n));let n=``,i=p.some(e=>e.group!==``);for(let r of te){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(Et(r.group)));let a=document.createElement(`li`);a.className=`row`,a.tabIndex=0,a.dataset.index=String(r.index);let o=document.createElement(`span`);o.className=`n`,o.textContent=String(r.index+1).padStart(2,` `);let s=document.createElement(`span`);s.className=`name`,s.textContent=r.name;let l=document.createElement(`span`);if(l.className=`time`,l.textContent=r.seconds>0?e(r.seconds):`--:--`,a.append(o,s,l),u===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${r.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),nr(rr(`track:${r.index}`,S===r.index?F.position:0),e,`✓`)}),a.append(e),$e()&&a.append(it(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}o.playlist.replaceChildren(...t)}let ne=R(),re=ut(),ie;for(let e of Array.from(o.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===ne;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&re),r&&(ie=t)}if(ne!==yt){yt=ne;let e=p.findIndex(e=>e.index===ne);if(e>=0&&!ie){bt=Math.floor((m.length+e)/a),vt=``,Tt();return}ie?.scrollIntoView({block:`nearest`})}}function Et(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!o.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,t=>{t.stopPropagation(),Dt(e)}),t.append(n)}return t}async function Dt(e){try{let t=await fetch(I.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();U(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}}function Ot(){let t=o.canvas,n=Math.min(2,globalThis.devicePixelRatio||1),r=Math.round(t.clientWidth*n),i=Math.round(t.clientHeight*n);r>0&&i>0&&(t.width!==r||t.height!==i)&&(t.width=r,t.height=i);let a=t.getContext(`2d`);if(P())N=Ee(N,M);else{let e=F.read();e.length>0&&(Xe.length!==25&&(Xe=Ce(24,e.length)),M=Te(M,we(e,Xe)),N=Ee(N,M))}if(a){let e=getComputedStyle(document.documentElement);De(a,{width:t.width,height:t.height},M,N,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(ut()){o.glyphs.textContent=M.map(ht).join(``);let[t,n]=P()?v.levels:F.levels();o.levels.textContent=mt(t,n),o.elapsed.textContent=e(lt());let r=ct();!me&&r>0&&(o.seek.value=String(Math.round(lt()/r*1e3)))}requestAnimationFrame(Ot)}let kt=``;function At(){if(u!==`remote`){o.wayInHere.hidden=!0,kt=``;return}let e=Ze()&&!te,t=ce||I.address,n=e?null:ae(I.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===kt)return;kt=r;let[i,a]=oe({name:d||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,o.wayInHere.replaceChildren(i,a),o.wayInHere.hidden=!1}function jt(e){o.video.hidden=!e,o.fullscreen.hidden=!e,Ie(),D=null}function Mt(){`mediaSession`in navigator&&(navigator.mediaSession.metadata=new MediaMetadata({title:at(),album:ot(),artist:`nixamp`,artwork:[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]}),navigator.mediaSession.setActionHandler(`play`,()=>void ft()),navigator.mediaSession.setActionHandler(`pause`,()=>void ft()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void B(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void B(-1)))}o.filter.addEventListener(`input`,()=>{bt=0,vt=``,Tt()}),o.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),o.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&z(n)}),o.fullscreen.addEventListener(`click`,()=>{let e=o.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),o.prev.addEventListener(`click`,()=>void B(-1)),o.next.addEventListener(`click`,()=>void B(1)),o.stop.addEventListener(`click`,()=>void pt()),o.playPause.addEventListener(`click`,()=>void ft());async function Nt(e){let t=Le(e,et());if(!t){if(!$e()){x=u===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,V();return}await Pt(e);return}if(C=null,F.stop(),t.kind===`embed`){T={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},jt(!1),o.embedFrame.src=t.src,o.embed.hidden=!1,D={url:e,label:t.label,kind:`embed`},x=`Playing ${t.label} here, in this browser.`,V();return}T={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await w(()=>F.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),jt(t.video),D={url:e,label:t.label,kind:`direct`},x=`Playing ${t.label} here, in this browser.`,V()}async function Pt(e){if(u!==`remote`){x=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}x=`Asking ${d||`the server`} to fetch ${e}…`,V(),await w(async()=>{let t,n={};try{t=await fetch(I.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{x=`could not reach the server`;return}if(!t.ok||!n.channel){x=n.error??`that link would not play.`;return}try{await fetch(I.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await Zn({id:n.channel,name:n.name||e,video:n.video!==!1},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(x=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),V()}o.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.linkUrl.value.trim();t!==``&&Nt(t)});function Ft(){let e=u===`remote`?I.address:``,t=f.filter(t=>ee(t.url)!==ee(e)),n=JSON.stringify({here:e,name:d,carries:m,others:t});if(n===p)return;p=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${d||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}o.linkServer.replaceChildren(...r),o.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,o.linkServer.hidden=t.length===0}async function It(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;f=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Ft()}catch{}}async function Lt(){let e=o.linkUrl.value.trim()||D?.url||``;if(e===``){x=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=o.linkServer.value;if(t!==``&&(u!==`remote`||ee(t)!==ee(I.address))){let n=f.find(e=>e.url===t)?.name??t;h=e,x=`Connecting to ${n} to go live with it…`,V(),Rt(t);return}if(u!==`remote`){x=f.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste its address below.`,V();return}if(!m){x=`${d||`This server`} has no ffmpeg, so it cannot carry a link.`+(f.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!$e()){x=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await Pt(e)}function Rt(e){let t=o.linkUrl.value.trim();te=!0,g=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit(),o.linkUrl.value=t}o.linkGoLive.addEventListener(`click`,()=>{Lt()}),o.linkServer.addEventListener(`change`,()=>{let e=o.linkServer.value;e!==``&&Rt(e)}),o.downloadNow.addEventListener(`click`,()=>{let e=T?.link;if(!e||u!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(I.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),x=`Fetching it through the server; your browser will save it when it arrives.`,V()}),o.goLiveNow.addEventListener(`click`,()=>{let e=tt();e&&nt(e,o.goLiveNow)}),o.seek.addEventListener(`input`,()=>{me=!0}),o.seek.addEventListener(`change`,()=>{let e=ct();e>0&&F.seek(Number(o.seek.value)/1e3*e),me=!1}),o.volume.addEventListener(`input`,()=>{let e=Number(o.volume.value)/100;F.volume=e;try{localStorage.setItem(Ue,String(e))}catch{}});let zt=e=>{e.addEventListener(`change`,()=>{let t=ie(Array.from(e.files??[]));if(t.length===0){x=`Nothing playable in that selection.`,V();return}se(_),_=t,ue=0,u=`local`,I.close(),x=``,z(0)})};zt(o.files),zt(o.folder),o.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.remoteUrl.value,{base:n,key:r}=pe(t);if(n===``){x=`That is not an address.`,V();return}(async()=>{y=`connecting`,V();let e=be(n);if(e){y=`error`,b=e,x=e,h=``,u=`local`,V();return}if(await ye(n,void 0,r)===null){y=`error`;let e=_e(n);b=e?`needs the server's name`:`not answering`,x=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,u=`local`,V();return}let i=await ve(n,r);if(i){y=`error`,b=i,x=i,h=``,u=`local`,V();return}u=`remote`,x=``;try{localStorage.setItem(He,t.trim())}catch{}I.connect(t),Q(),_n(),qn(!0),Zt(),Wn(),V()})()});let Bt=``,Vt=null,Ht=async(e=!1)=>{o.directory.hidden=!1,e||(o.directoryNote.textContent=`Looking for live streams…`,o.directoryList.replaceChildren()),Vt||=setInterval(()=>{!o.directory.hidden&&document.visibilityState===`visible`&&Ht(!0)},Ge);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],f=t.map(e=>({name:e.name,url:e.url})),Ft();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:Z});if(e&&i===Bt)return;Bt=i,en(r.recent??[])}catch{e||(o.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(o.directoryList.replaceChildren(),t.length===0){o.directoryNote.textContent=`Nobody is streaming right now.`;return}o.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let a=[`${e.tracks.toLocaleString()} files to browse`];e.playing!==!1&&e.nowPlaying?a.push(`playing ${e.nowPlaying}`):a.push(`player idle`),e.code&&a.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=a.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ae(e.url),c=(t,n=``)=>{te=t,g=n,o.remoteUrl.value=t?e.url:s??e.url,o.directory.hidden=!0,o.remoteForm.requestSubmit()},l=document.createElement(`ul`);l.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=document.createElement(`button`);o.type=`button`,o.className=`button`,rt(o),o.title=`Join ${t}, live on ${e.name}`,o.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,o),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:s},()=>{o.directory.hidden=!0});if(t.append(n,u,d),Z&&t.append(ln(e.url,e.name)),e.ownerId&&Z&&e.ownerId!==Z&&t.append(An(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&Z&&e.ownerId===Z){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));o.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{o.directoryNote.textContent=`could not reach the directory`}finally{await Ht()}})()}),t.append(n)}o.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!o.directory.hidden&&Ht(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),Ht()}let Ut=null,Wt=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Gt=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Kt=``,qt=``,Jt=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Kt)return;Kt=t,o.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}o.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[Wt(t.network),`network-${t.network}`],[Gt(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}o.adminConnections.append(e)}};function U(e){o.adminSaid.textContent=e,o.adminSaid.hidden=e===``}let Yt=async()=>{try{let e=await fetch(I.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;o.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,Jt(t.connections??[]),Xt(t.publish??[],(t.channels??[]).map(e=>e.id)),cr(t.home??``,t.root??``),Q()}catch{o.adminNote.textContent=`lost touch with the server`}};function Xt(e,t){o.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===qt)return;if(qt=n,e.length===0){o.publishList.replaceChildren();return}let r=e.length-t.length;o.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,o.publishList.replaceChildren(...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,o.textContent=`Copy`,o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Zt=async()=>{if(u!==`remote`){o.adminPanel.hidden=!0,o.publishPanel.hidden=!0,Ut&&clearInterval(Ut),Ut=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(I.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;if(te&&(e=!1),Qe=i&&!e,o.adminPanel.hidden=!e,h!==``){let e=h;h=``,$e()?Pt(e):(x=`Sign in to nixamp.com to go live here.`,V())}if(Ut&&clearInterval(Ut),Ut=null,Q(),_n(),Wn(),o.listenOnly.hidden=e,!e){o.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}o.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Yt(),Ut=setInterval(()=>void Yt(),2e3)};function Qt(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;U(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),a=await i.json();if(!i.ok){U(a.error??`that did not work`);return}U(`${a.channel?.name||t||e} is on the air.`),o.adminSource.value=``,o.adminName.value=``,Wn(),Q()}catch{U(`could not reach the server`)}})()}o.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=o.adminSource.value.trim();t&&Qt(t,o.adminName.value.trim())}),o.adminAdd.addEventListener(`click`,()=>{let e=o.adminSource.value.trim();if(!e)return;U(`Reading ${e}…`);let t=o.adminReplace.checked,n=o.adminName.value.trim();(async()=>{try{let r=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();U(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(o.adminSource.value=``,o.adminName.value=``,Wn(),Q())}catch{U(`could not reach the server`)}})()});let $t=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},en=e=>{o.recentList.replaceChildren();let t=Z?e.filter(e=>e.ownerId&&e.ownerId!==Z):[];if(o.recentNote.hidden=t.length===0,t.length!==0)for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${$t(e.endedAt)}`:`ended ${$t(e.endedAt)}`,n.append(r,i),t.append(n,An(e.ownerId,e.name)),o.recentList.append(t)}},tn=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function nn(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${tn(e.party.positionNow)}`:`❚❚ ${tn(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,a.textContent=`Watch`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Room`,t.append(n,a,o),t}async function rn(){if(!Z){o.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){o.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];o.partiesPanel.hidden=!1,o.partiesNote.textContent=t.length===0?`No parties on right now. Have a code from a site? Put it in.`:`Parties on now. Watch opens the film where it lives; Room is here.`,o.partiesList.replaceChildren(...t.map(nn))}catch{o.partiesPanel.hidden=!0}}o.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){x=n.error??`no party with that code`,V();return}o.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{x=`could not ask about that party`,V()}})()});async function an(){if(!Z){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];o.connectionsNote.hidden=t.length===0,o.connectionsList.hidden=t.length===0,o.connectionsList.replaceChildren(...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,a.textContent=`Disconnect`,a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await an()})()}),t.append(n,a),t}))}catch{o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0}}let W=new Set,G=e=>{try{return new URL(e).origin}catch{return e}},on=e=>[...W].some(t=>G(t)===G(e));async function sn(){if(!Z){W=new Set,o.favoritesPanel.hidden=!0,un();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){o.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];W=new Set(t.map(e=>e.url)),o.favoritesPanel.hidden=t.length===0,o.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,o.favoritesList.replaceChildren(...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...oe({name:e.name||e.url,view:e.url,admin:ae(e.url)}),ln(e.url,e.name)),t}))}catch{o.favoritesPanel.hidden=!0}un()}async function cn(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){x=n?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{x=`could not reach nixamp.com`,V();return}if(n)W.add(e);else for(let t of[...W])G(t)===G(e)&&W.delete(t);await sn()}function ln(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=on(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...W].find(t=>G(t)===G(e))??e;cn(on(e)?i:e,t,!on(e)).then(r)}),n}function un(){let e=u===`remote`?I.shareLink:``;if(o.favHere.hidden=!(Z&&e),o.favHere.hidden)return;let t=on(e);o.favHere.textContent=t?`♥`:`♡`,o.favHere.dataset.on=t?`yes`:`no`,o.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,o.favHere.setAttribute(`aria-label`,o.favHere.title)}c(o.copyNow,`copy`),o.copyNow.addEventListener(`click`,()=>{nr(F.source,o.copyNow,`✓`)}),o.favHere.addEventListener(`click`,()=>{let e=ir()||I.shareLink;if(!e)return;let t=[...W].find(t=>G(t)===G(e))??e;cn(on(e)?t:e,d||I.address,!on(e)).then(un)});let dn=r?a:200,K=[],q=null,J=null,fn=``,Y=[],pn=0,mn=null,hn=0;function gn(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}async function _n(){if(u!==`remote`){o.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(I.url(`/api/catalogs`))}catch{o.catalogsPanel.hidden=!0;return}if(!e.ok){o.catalogsPanel.hidden=!0;return}K=(await e.json().catch(()=>({}))).catalogs??[],q&&=K.find(e=>e.id===q?.id)??null,q||(J=null),o.catalogsPanel.hidden=!1,vn()}function vn(){let e=!o.adminPanel.hidden;o.catalogsForm.hidden=!e;let t=K.reduce((e,t)=>e+t.live,0),n=K.reduce((e,t)=>e+t.vod,0);o.catalogsNote.textContent=K.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${K.length} ${K.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,yn();let r=q!==null&&J!==null;if(o.catalogsList.hidden=r,o.catalogsFilter.hidden=!r,o.catalogsEntries.hidden=!r,r){wn();return}if(q){xn(q);return}o.catalogsList.replaceChildren(...K.map(t=>bn(t,e)))}function yn(){let e=q!==null;if(o.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>{q=null,J=null,vn()},!1),n(),t(q?.name??``,()=>{J=null,vn()},J===null)];J!==null&&r.push(n(),t(J===``?`All groups`:J,()=>void 0,!0)),o.catalogsCrumbs.replaceChildren(...r)}function bn(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,a.textContent=[`${e.entries.toLocaleString()} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString()} live`,`${e.vod.toLocaleString()} on demand`,`refreshed ${gn(e.refreshedAt)}`].join(` · `),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.addEventListener(`click`,()=>{q=e,J=null,vn()}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{En(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Remove`,r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Dn(e)}),n.append(t,r)}return n}async function xn(e){o.catalogsList.replaceChildren();let t=[];try{let n=await w(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{x=`Could not read the groups in ${e.name}.`,V();return}if(q?.id!==e.id||J!==null)return;let n=[Sn(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Sn(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];o.catalogsList.replaceChildren(...n)}function Sn(e,t,n,r,i){let a=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{J=t,fn=``,o.catalogsFilter.value=``,Y=[],pn=0,vn(),Cn(0)}),a.append(s,u),a}async function Cn(e){let t=q,n=J;if(!t||n===null)return;let r=++hn,i=new URLSearchParams({group:n,q:fn,offset:String(e),limit:String(dn)}),a;try{let e=await w(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{x=`Could not read ${t.name}.`,V();return}r===hn&&(pn=a.total??0,Y=e===0?a.entries??[]:[...Y,...a.entries??[]],wn())}function wn(){let t=q;if(!t)return;let n=Y.map(n=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`name`,i.textContent=n.title;let a=document.createElement(`span`);if(a.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,a.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(i,a),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(e,`copy`),e.title=`Copy this entry's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.title}`),e.addEventListener(`click`,r=>{r.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(t.id)}/entries/${encodeURIComponent(n.id)}/stream`;nr(I.url(i),e,`✓`)}),r.append(e)}return $e()&&r.append(it(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{Tn(t,n,r)}),r});if(Y.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=fn?`Nothing called "${fn}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(Y.length<pn){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${Y.length.toLocaleString()} of ${pn.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),Cn(Y.length)}),e.append(t),n.push(e)}o.catalogsEntries.replaceChildren(...n)}async function Tn(e,t,n){n?.classList.add(`loading`),x=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await w(async()=>{let n,i={};try{n=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{x=`could not reach the server`;return}if(!n.ok){x=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await Zn({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){C=null,S=-1,T={kind:`vod`,...r},ze(a,`title`),await F.load({title:a,artist:``,album:``,duration:0,url:I.url(i.url),video:!0,objectUrl:!1},!0),jt(!0),x=`Playing ${a}.`;return}x=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),V()}}async function En(e){U(`Reading ${e.name} again…`);try{let t=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));U(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}_n()}async function Dn(e){try{U((await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{U(`could not reach the server`)}q?.id===e.id&&(q=null,J=null),_n()}o.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.catalogSource.value.trim(),n=o.catalogName.value.trim();t&&(async()=>{U(`Reading ${n||t}…`);try{let e=await fetch(I.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){U(r.error??`that did not work`);return}U(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),o.catalogSource.value=``,o.catalogName.value=``}catch{U(`could not reach the server`)}_n()})()}),o.catalogsFilter.addEventListener(`input`,()=>{mn&&clearTimeout(mn),mn=setTimeout(()=>{mn=null,fn=o.catalogsFilter.value.trim(),Cn(0)},250)});let On=async()=>{o.serversList.replaceChildren();try{let e=await fetch(`/api/v1/servers`);if(!e.ok){o.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];re=new Map(t.map(e=>[G(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),o.serversPanel.hidden=!1,o.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. View one, administer it, or forget it.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let a=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=oe({name:e.name,view:a,admin:a});ye(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=document.createElement(`button`);l.type=`button`,l.className=`ghost`,l.textContent=`Forget`,l.addEventListener(`click`,()=>{(async()=>{l.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await On()}catch{l.disabled=!1}})()}),t.append(n,s,c,l),o.serversList.append(t)}}catch{o.serversPanel.hidden=!0}},kn=async()=>{o.followingList.replaceChildren();try{let e=await fetch(`/api/v1/follows`);if(!e.ok){o.followingNote.hidden=!0;return}let t=(await e.json()).following??[];o.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let a=document.createElement(`button`);a.type=`button`,a.className=`ghost follow`,a.textContent=`Unfollow`,a.addEventListener(`click`,()=>{(async()=>{a.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),o.followingList.children.length===0&&(o.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),o.followingList.append(t)}}catch{o.followingNote.hidden=!0}},An=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,n.textContent=`Follow`,n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{n.textContent=e?`Following`:`Follow`,n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),kn())}catch{}finally{n.disabled=!1}})()}),n},jn=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},Mn=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Nn=async()=>{if(!Mn())return o.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return o.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return o.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return o.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:jn(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return o.notifyNote.textContent=`This device will be told.`,!0}catch{return o.notifyNote.textContent=`Could not set this device up.`,!1}},Pn=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},Fn=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();o.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(o.notifyPhone.value=n.phone)}catch{o.notifyPhoneNote.textContent=`could not reach nixamp.com`}},In=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();o.notifyEmail.checked=t.wantsEmail!==!1,o.notifySms.checked=t.wantsSms===!0,o.notifyPhone.value=t.phone??``;let n=Mn()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;o.notifyWeb.checked=t.wantsWeb!==!1&&n,o.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};o.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(o.notifyWeb.checked){let e=await Nn();o.notifyWeb.checked=e,await Fn({wantsWeb:e});return}await Pn(),await Fn({wantsWeb:!1}),o.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),o.notifyEmail.addEventListener(`change`,()=>{Fn({wantsEmail:o.notifyEmail.checked})}),o.notifySms.addEventListener(`change`,()=>{(async()=>{if(o.notifySms.checked&&!o.notifyPhone.value.trim()){o.notifyPhoneNote.textContent=`Add a phone number first.`,o.notifySms.checked=!1,o.notifyPhone.focus();return}await Fn({wantsSms:o.notifySms.checked})})()}),o.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),Fn({phone:o.notifyPhone.value.trim()})});let X=!1,Z=``,Ln=!1,Rn=`nixamp.welcome`,zn=()=>{let e=!1;try{e=localStorage.getItem(Rn)===`hidden`}catch{}o.welcome.hidden=!Ln||Z!==``||e},Bn=e=>{let t=e!==null;o.notifyPanel.hidden=!t,t?(In(),kn(),On()):(o.serversPanel.hidden=!0,o.followingNote.hidden=!0,o.followingList.replaceChildren(),o.recentNote.hidden=!0,o.recentList.replaceChildren()),o.accountForm.hidden=t,o.accountProviders.hidden=t||o.accountProviders.childElementCount===0,o.accountSignOut.hidden=!t,o.accountNote.textContent=t?`Signed in as ${e}.`:X?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,o.accountSubmit.textContent=X?`Create account`:`Sign in`,o.accountToggle.textContent=X?`I have one`:`Create one`,o.accountPassword.autocomplete=X?`new-password`:`current-password`,zn()},Vn=async()=>{let e=[];Ln=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Ln=!0,e=(await t.json()).providers??[])}catch{}o.accountProviders.replaceChildren(),o.accountProviders.hidden=e.length===0,o.accountPanel.hidden=!Ln,o.accountElsewhere.hidden=Ln,zn();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,o.accountProviders.append(e)}},Hn=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();Z=e.ok?t.account?.id??``:``,Bn(e.ok?t.account?.email??`you`:null)}catch{Z=``,Bn(null)}if(I.session=``,Z!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));I.session=e.ok&&typeof t.token==`string`?t.token:``}catch{I.session=``}u===`remote`&&Zt()}sn(),rn(),an(),Un()};function Un(){if(Ye===``)return;let e=Ye;Ye=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit()}o.accountToggle.addEventListener(`click`,()=>{X=!X,Bn(null)}),o.welcomeCreate.addEventListener(`click`,()=>{X=!0,Bn(null),o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),o.accountEmail.focus({preventScroll:!0})}),o.welcomeBrowse.addEventListener(`click`,()=>{o.directory.hidden?o.browse.click():o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Rn,`hidden`)}catch{}o.welcome.hidden=!0}),o.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.accountEmail.value.trim(),n=o.accountPassword.value;(async()=>{o.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${X?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){o.accountNote.textContent=r.error??`that did not work`;return}Z=r.account?.id??``,o.accountPassword.value=``,Bn(r.account?.email??t),Zt(),Un()}catch{o.accountNote.textContent=`could not reach nixamp.com`}finally{o.accountSubmit.disabled=!1}})()}),o.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}Z=``,Bn(null),I.close(),S=-1,u=`local`,y=`idle`,b=``,o.remoteUrl.value=``,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.catalogsPanel.hidden=!0,o.listenOnly.hidden=!0,qn(!1);try{localStorage.removeItem(He)}catch{}x=`Signed out, and disconnected from the server.`,Zt(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Ye=t,g=e.get(`play`)??``,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t,x=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(o.linkUrl.value=n,t!==``&&g===``?g=`link:${n}`:t===``&&(x=`A link to go live with is in the box: pick a server beside it and press Go live.`))}catch{}Vn(),Hn(),Zt(),It(),o.browse.addEventListener(`click`,()=>{if(!o.directory.hidden){o.directory.hidden=!0;return}Ht(),o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.disconnect.addEventListener(`click`,()=>{I.close(),o.listenOnly.hidden=!0,S=-1,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.onairPanel.dataset.title=`Live on this server`,o.catalogsPanel.hidden=!0,o.catalogsPanel.dataset.title=`Catalogs on this server`,d=``,ce=``,un(),qn(!1),u=`local`,y=`idle`,b=``,V()});async function Wn(){if(u!==`remote`||I.shareLink===``){o.sharePanel.hidden=!0;return}o.sharePanel.hidden=!1;let e=ir(),t=globalThis.location.origin;o.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,o.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,o.sharePhone.hidden=!0,o.shareSend.hidden=!0,o.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(I.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ce=r.url,o.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Be=r.live,A=r.live?r.code:``,qe=n,o.liveControls.hidden=o.adminPanel.hidden||!r.possible,o.goLive.hidden=r.live,o.stopLive.hidden=!r.live,o.sharePhone.hidden=!1,!r.live){o.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){o.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,o.shareSend.hidden=!1;return}o.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),ur(n),document.createTextNode(` and key `),ur(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),o.shareSend.hidden=!1}}let Gn=``,Kn=null,qn=e=>{Kn&&clearInterval(Kn),Kn=null,e&&(Kn=setInterval(()=>void Q(),6e3))};async function Q(){if(u!==`remote`){o.onairPanel.hidden=!0;return}let e;try{let t=await fetch(I.url(`/api/streams`));if(!t.ok){o.onairPanel.hidden=!0;return}e=await t.json(),m=e.server.carries!==!1,e.server.name&&e.server.name!==d&&(d=e.server.name,o.onairPanel.dataset.title=`Live on ${d}`,o.catalogsPanel.dataset.title=`Catalogs on ${d}`,un(),V())}catch{o.onairPanel.hidden=!0;return}o.onairPanel.hidden=!1,E=e,ar(e);let t=`${o.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}`;if(t===Gn)return;Gn=t;let n=e.restreams??[],r=e.channels.length+n.length;o.onairNote.textContent=r===0?`One stream, from this server's own files.`:`${r+1} streams: this server's own files, and ${r} more on it.`;let i=[],a=e.server.playing,s=!o.adminPanel.hidden;i.push(or({title:e.server.name,detail:[a?`playing ${e.server.nowPlaying}`:e.server.nowPlaying?`stopped on ${e.server.nowPlaying}`:`nothing loaded`,`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:a?`Join live`:s?`Start the stream`:`Nothing playing`,onPlay:()=>{if(a){Xn(e.server.nowPlaying);return}s&&Yn()},link:e.server.live?e.server.url:``,...a?{page:rr(`live`)}:{},direct:a?I.url(`/api/live`):``}));for(let e of n)i.push(or({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{z(e.at)},link:``,direct:I.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=I.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&r.push(`☎ ${t.code}`),t.redials&&r.push(`redialled ${t.redials}×`),s&&t.error&&r.push(t.error),i.push(or({title:t.name,detail:r.join(` · `),onPlay:()=>{Zn({id:t.id,name:t.name,video:e})},link:n,page:rr(`channel:${t.id}`),direct:n,onRestart:s&&t.via===`pull`?()=>{$n(t.id,t.name)}:void 0,onStop:s||Qe&&Z!==``&&t.startedBy===Z?()=>{tr(t.id,t.name)}:void 0,onRename:s||Qe&&Z!==``&&t.startedBy===Z?()=>{er(t.id,t.name)}:void 0}))}o.onairList.replaceChildren(...i)}async function Jn(){if(u===`remote`)try{if((await fetch(I.media(R(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;x=Z===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,Z===``&&o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function Yn(){U(`Starting the stream on the server…`);try{await I.send({type:`play`,index:Math.max(0,R())})}catch{U(`could not reach the server`);return}await Xn(v.tracks[R()]?.title??``),U(`Playing to the room. Anybody with the view link sees this.`),await Q()}async function Xn(e){S=-1,C=null,T={kind:`live`},ze(e,`auto`),await w(()=>F.load({title:e||`Live`,artist:``,album:``,duration:0,url:I.url(`/api/live`),video:!0,objectUrl:!1},!0)),jt(!0),x=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function Zn(e,t=!0,n){S=-1,C=e,t&&(xe=0),t&&(T=n??{kind:`channel`}),t&&ze(e.name,T?.link||Ve(e.name)?`auto`:`channel`);let r=e.video&&et();await w(()=>F.load({title:e.name,artist:``,album:``,duration:0,url:I.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),jt(e.video),C===e&&(x=`Watching ${e.name}, live on this server.`),V()}function Qn(){let e=C;return e?Je?!0:xe>=5?(x=`${e.name} stopped, and did not come back.`,C=null,T=null,V(),!0):(xe+=1,x=`${e.name} started over; rejoining…`,V(),Je=setTimeout(()=>{Je=null,C===e&&Zn(e,!1)},2e3),!0):!1}function $(e){o.onairNote.textContent=e,U(e)}async function $n(e,t){$(`Restarting ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}Gn=``,Q()}async function er(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){$(`Renaming ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));$(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{$(`could not reach the server`)}C?.id===e&&(C={...C,name:r}),Gn=``,Q(),V()}}async function tr(e,t){$(`Taking ${t} off the air…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}C?.id===e&&(C=null,F.stop()),Gn=``,Q()}async function nr(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{x=e,V();return}n===`✓`||n===`✓`?c(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function rr(e,t=0){let n=ir();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function ir(){if(ce!==``)return ce;let e=u===`remote`?I.shareLink:``;return/\/admin\//.test(e)?``:e}function ar(e){if(g===``)return;let t=g;if(t===`live`){g=``,e.server.playing?Xn(e.server.nowPlaying):(x=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){g=``,Nt(t.slice(5));return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(g=``,Zn({id:r.id,name:r.name,video:r.kind!==`audio`}))}function or(e){let t=document.createElement(`li`);t.className=`onair`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let o=document.createElement(`button`);o.type=`button`,o.className=`button`,rt(o,e.playLabel??`Join live`),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,c(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;nr(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{nr(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,a),t}let sr=``;function cr(e,t){sr=e;let n=e!==``&&t===e;o.loadHome.hidden=e===``,o.homeNote.hidden=e===``,e!==``&&(o.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,o.loadHome.disabled=!1)}o.loadHome.addEventListener(`click`,()=>{sr!==``&&(o.loadHome.disabled=!0,U(`Reading this server's files…`),(async()=>{try{let e=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:sr})}),t=await e.json();U(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{U(`could not reach the server`)}finally{o.loadHome.disabled=!1}})())});let lr=async e=>{o.goLive.disabled=!0,o.stopLive.disabled=!0,o.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(I.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();o.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{o.shareNote.textContent=`could not reach the server`}finally{o.goLive.disabled=!1,o.stopLive.disabled=!1,await Wn()}};o.goLive.addEventListener(`click`,()=>void lr(!0)),o.stopLive.addEventListener(`click`,()=>void lr(!1));function ur(e){let t=document.createElement(`b`);return t.textContent=e,t}o.shareCopy.addEventListener(`click`,()=>{o.shareLink.select(),navigator.clipboard?.writeText(o.shareLink.value).then(()=>{o.shareNote.textContent=`Copied. Send it to anybody.`},()=>{o.shareNote.textContent=`Copy it from the box above.`})}),o.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=o.shareTo.value.trim();t!==``&&(async()=>{o.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:ir()})}),n=await e.json();o.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(o.shareTo.value=``)}catch{o.shareNote.textContent=`could not send that`}})()}),o.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(We,o.listenHere.checked?`1`:`0`)}catch{}u===`remote`&&(async()=>{o.listenHere.checked?(await I.send({type:`stop`}),await dt(v.index)):(F.stop(),S=-1),V()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),ft();return;case`s`:pt();return;case`n`:case`ArrowRight`:B(1);return;case`p`:case`ArrowLeft`:B(-1);return;case`ArrowDown`:e.preventDefault(),z(Math.min(L()-1,R()+1));return;case`ArrowUp`:e.preventDefault(),z(Math.max(0,R()-1));return}});let dr=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),dr=e,o.install.hidden=!1}),o.install.addEventListener(`click`,()=>{dr?.prompt(),dr=null,o.install.hidden=!0});try{let e=localStorage.getItem(Ue);e!==null&&(o.volume.value=String(Math.round(Number(e)*100)),F.volume=Number(e));let t=localStorage.getItem(He);t&&(o.remoteUrl.value=t),localStorage.getItem(We)===`0`&&(o.listenHere.checked=!1)}catch{}(async()=>{if(o.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await ye(e)===null)return;let t=await ge(e);t&&t.trackCount!==0&&(o.remoteUrl.value=e,u=`remote`,x=``,I.connect(e),V())})(),(()=>{if(Ke||Ye!==``)return;let e=()=>F.source!==``||F.playing||Ae()||C!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{Ke=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||n.play().catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,n.play().then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),V(),requestAnimationFrame(Ot)}qe(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{c as t};
|