Web-based Winamp controller for CarPC � Go backend, mobile-first UI
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

395 lines
14KB

  1. 'use strict';
  2. // ── DOM refs ──────────────────────────────────────────────────────────────────
  3. const $ = id => document.getElementById(id);
  4. const statusDot = $('winamp-status');
  5. const stateLabel = $('state-label');
  6. const trackTitle = $('track-title');
  7. const playlistPos = $('playlist-pos');
  8. const progressFill = $('progress-fill');
  9. const timeCurrent = $('time-current');
  10. const timeLength = $('time-length');
  11. const volumeFill = $('volume-fill');
  12. const volumePct = $('volume-pct');
  13. const btnMute = $('btn-mute');
  14. const btnPlay = $('btn-play');
  15. const killistPanel = $('killist-panel');
  16. const killistItems = $('killist-items');
  17. const playlistOverlay = $('playlist-overlay');
  18. const playlistList = $('playlist-list');
  19. const canvas = $('viz');
  20. const ctx2d = canvas.getContext('2d');
  21. // ── State ─────────────────────────────────────────────────────────────────────
  22. let currentVolume = 50;
  23. let currentPlaylistPos = 0; // 1-based, updated from status
  24. let ws = null;
  25. let reconnectTimer = null;
  26. // Viz state
  27. const NUM_BARS = 64;
  28. const peaks = new Float32Array(NUM_BARS);
  29. let lastBars = new Float32Array(NUM_BARS);
  30. let rafId = null;
  31. let lastVizAt = 0; // timestamp of last received viz frame
  32. let winampPlaying = false;
  33. // ── WebSocket ─────────────────────────────────────────────────────────────────
  34. function connect() {
  35. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  36. ws = new WebSocket(`${proto}://${location.host}/ws`);
  37. ws.addEventListener('open', () => {
  38. statusDot.className = 'ok';
  39. stateLabel.textContent = 'Verbunden';
  40. clearTimeout(reconnectTimer);
  41. });
  42. ws.addEventListener('close', () => {
  43. statusDot.className = 'err';
  44. stateLabel.textContent = 'Verbindung unterbrochen…';
  45. ws = null;
  46. reconnectTimer = setTimeout(connect, 3000);
  47. });
  48. ws.addEventListener('error', () => ws.close());
  49. ws.addEventListener('message', e => {
  50. let msg;
  51. try { msg = JSON.parse(e.data); } catch { return; }
  52. if (msg.type === 'status') applyStatus(msg);
  53. if (msg.type === 'viz') applyViz(msg.bars);
  54. });
  55. }
  56. function send(obj) {
  57. if (ws && ws.readyState === WebSocket.OPEN) {
  58. ws.send(JSON.stringify(obj));
  59. }
  60. }
  61. // ── Status handler ────────────────────────────────────────────────────────────
  62. function applyStatus(st) {
  63. if (!st.running) {
  64. statusDot.className = 'err';
  65. stateLabel.textContent = 'Winamp nicht gestartet';
  66. trackTitle.textContent = '–';
  67. playlistPos.textContent = '';
  68. return;
  69. }
  70. statusDot.className = 'ok';
  71. const stateMap = { playing: '▶ Spielt', paused: '⏸ Pause', stopped: '⏹ Stop' };
  72. stateLabel.textContent = stateMap[st.state] ?? st.state;
  73. trackTitle.textContent = st.title || '–';
  74. playlistPos.textContent = st.playlist_length
  75. ? `${st.playlist_pos} / ${st.playlist_length}` : '';
  76. if (st.playlist_pos !== currentPlaylistPos) {
  77. currentPlaylistPos = st.playlist_pos;
  78. updatePlaylistHighlight();
  79. }
  80. if (st.length > 0) {
  81. progressFill.style.width = (st.position / st.length * 100).toFixed(1) + '%';
  82. timeCurrent.textContent = fmtTime(st.position);
  83. timeLength.textContent = fmtTime(st.length);
  84. } else {
  85. progressFill.style.width = '0%';
  86. timeCurrent.textContent = '0:00';
  87. timeLength.textContent = '0:00';
  88. }
  89. btnPlay.textContent = st.state === 'playing' ? '⏸' : '▶';
  90. winampPlaying = st.state === 'playing';
  91. if (typeof st.volume === 'number') {
  92. currentVolume = st.volume;
  93. updateVolumeFill(st.muted);
  94. updateMuteBtn(st.muted);
  95. }
  96. }
  97. // ── Controls ──────────────────────────────────────────────────────────────────
  98. btnPlay.addEventListener('click', () => {
  99. // Optimistic toggle — server will push the real state back immediately.
  100. const playing = btnPlay.textContent === '⏸';
  101. send({ cmd: playing ? 'pause' : 'play' });
  102. });
  103. $('btn-stop').addEventListener('click', () => send({ cmd: 'stop' }));
  104. $('btn-next').addEventListener('click', () => send({ cmd: 'next' }));
  105. $('btn-prev').addEventListener('click', () => send({ cmd: 'prev' }));
  106. document.querySelectorAll('.btn-seek').forEach(btn => {
  107. btn.addEventListener('click', () =>
  108. send({ cmd: 'seek', delta: parseInt(btn.dataset.delta, 10) }));
  109. });
  110. $('progress-bar').addEventListener('click', async e => {
  111. // We need current length — read from last status (stored in DOM for now via timeLength).
  112. const total = parseTime(timeLength.textContent);
  113. if (!total) return;
  114. const rect = e.currentTarget.getBoundingClientRect();
  115. const target = Math.round((e.clientX - rect.left) / rect.width * total);
  116. const current = parseTime(timeCurrent.textContent);
  117. send({ cmd: 'seek', delta: target - current });
  118. });
  119. // ── Volume ────────────────────────────────────────────────────────────────────
  120. $('btn-vol-up').addEventListener('click', () => {
  121. currentVolume = Math.min(100, currentVolume + 5);
  122. send({ cmd: 'volume', level: currentVolume });
  123. updateVolumeFill();
  124. });
  125. $('btn-vol-down').addEventListener('click', () => {
  126. currentVolume = Math.max(0, currentVolume - 5);
  127. send({ cmd: 'volume', level: currentVolume });
  128. updateVolumeFill();
  129. });
  130. $('volume-bar').addEventListener('click', e => {
  131. const rect = e.currentTarget.getBoundingClientRect();
  132. currentVolume = Math.round((e.clientX - rect.left) / rect.width * 100);
  133. send({ cmd: 'volume', level: currentVolume });
  134. updateVolumeFill();
  135. });
  136. btnMute.addEventListener('click', () => {
  137. const nowMuted = btnMute.classList.contains('muted');
  138. send({ cmd: 'mute', muted: !nowMuted });
  139. updateMuteBtn(!nowMuted);
  140. updateVolumeFill(!nowMuted);
  141. });
  142. function updateVolumeFill(muted = btnMute.classList.contains('muted')) {
  143. volumeFill.style.width = currentVolume + '%';
  144. volumePct.textContent = currentVolume + ' %';
  145. volumeFill.classList.toggle('muted', muted);
  146. }
  147. function updateMuteBtn(muted) {
  148. btnMute.textContent = muted ? '🔇' : '🔊';
  149. btnMute.classList.toggle('muted', muted);
  150. }
  151. // ── KillList ──────────────────────────────────────────────────────────────────
  152. $('btn-kill').addEventListener('click', () => {
  153. send({ cmd: 'killist_add' });
  154. showToast('🚫 Track zur Skip-Liste hinzugefügt');
  155. });
  156. $('btn-show-killist').addEventListener('click', async () => {
  157. const list = await fetch('/api/killist').then(r => r.json()).catch(() => []);
  158. killistItems.innerHTML = '';
  159. (list || []).forEach(title => {
  160. const li = document.createElement('li');
  161. li.innerHTML = `<span>${escHtml(title)}</span>`;
  162. const btn = document.createElement('button');
  163. btn.textContent = '✕';
  164. btn.onclick = () => {
  165. send({ cmd: 'killist_remove', title });
  166. li.remove();
  167. };
  168. li.appendChild(btn);
  169. killistItems.appendChild(li);
  170. });
  171. killistPanel.classList.remove('hidden');
  172. });
  173. $('btn-close-killist').addEventListener('click', () =>
  174. killistPanel.classList.add('hidden'));
  175. // ── Visualisation (Canvas) ────────────────────────────────────────────────────
  176. function applyViz(bars) {
  177. if (!bars || bars.length === 0) return;
  178. lastBars = new Float32Array(bars);
  179. lastVizAt = performance.now();
  180. }
  181. function renderFrame(ts = 0) {
  182. rafId = requestAnimationFrame(renderFrame);
  183. // Resize canvas to CSS size (handles window resize / DPR).
  184. // Setting canvas.width resets the transform, so we re-apply scale.
  185. const dpr = window.devicePixelRatio || 1;
  186. const cssW = canvas.clientWidth;
  187. const cssH = canvas.clientHeight;
  188. if (canvas.width !== Math.round(cssW * dpr) || canvas.height !== Math.round(cssH * dpr)) {
  189. canvas.width = Math.round(cssW * dpr);
  190. canvas.height = Math.round(cssH * dpr);
  191. ctx2d.scale(dpr, dpr);
  192. }
  193. const w = cssW;
  194. const h = cssH;
  195. if (w === 0 || h === 0) return;
  196. // Check if real viz data is fresh (< 1.5 s old) and Winamp is playing.
  197. const hasSignal = winampPlaying && (performance.now() - lastVizAt) < 1500;
  198. // Background
  199. ctx2d.fillStyle = '#000';
  200. ctx2d.fillRect(0, 0, w, h);
  201. const n = NUM_BARS;
  202. const gap = 1;
  203. const barW = Math.max(1, (w - gap * (n - 1)) / n);
  204. for (let i = 0; i < n; i++) {
  205. let val;
  206. if (hasSignal) {
  207. // Real spectrum data
  208. val = lastBars[i] || 0;
  209. if (val > peaks[i]) peaks[i] = val;
  210. else peaks[i] = Math.max(0, peaks[i] - 0.012);
  211. } else {
  212. // Idle animation: slow sine "breathing" across the bars.
  213. // Amplitude fades out when paused/stopped.
  214. const phase = (ts / 1800) + (i / n) * Math.PI * 2;
  215. const breath = (Math.sin(ts / 2000) * 0.5 + 0.5) * 0.08; // 0..0.08
  216. val = Math.max(0, Math.sin(phase) * breath);
  217. peaks[i] = Math.max(0, peaks[i] - 0.02); // let peaks fall quickly
  218. }
  219. const x = Math.round(i * (barW + gap));
  220. const barH = val * h;
  221. if (barH > 0.5) {
  222. // Bar colour: green (120°) → yellow (60°) → red (0°)
  223. const hue = Math.round((1 - val) * 120);
  224. const lit = hasSignal ? 42 : 25; // dimmer in idle
  225. ctx2d.fillStyle = `hsl(${hue},100%,${lit}%)`;
  226. ctx2d.fillRect(x, h - barH, barW, barH);
  227. }
  228. // Peak indicator
  229. if (peaks[i] > 0.02) {
  230. const py = Math.round(h - peaks[i] * h) - 1;
  231. ctx2d.fillStyle = hasSignal ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.2)';
  232. ctx2d.fillRect(x, py, barW, 2);
  233. }
  234. }
  235. // "No signal" label when disconnected or stopped
  236. if (!ws || ws.readyState !== WebSocket.OPEN) {
  237. drawLabel(ctx2d, w, h, '● NO SIGNAL', '#333');
  238. } else if (!winampPlaying) {
  239. drawLabel(ctx2d, w, h, '▶ PLAY', '#1a3a1a');
  240. }
  241. }
  242. function drawLabel(ctx, w, h, text, color) {
  243. ctx.font = `bold ${Math.round(h * 0.22)}px monospace`;
  244. ctx.textAlign = 'center';
  245. ctx.textBaseline = 'middle';
  246. ctx.fillStyle = color;
  247. ctx.fillText(text, w / 2, h / 2);
  248. }
  249. // ── Helpers ───────────────────────────────────────────────────────────────────
  250. function fmtTime(secs) {
  251. const m = Math.floor(secs / 60);
  252. const s = String(Math.floor(secs % 60)).padStart(2, '0');
  253. return `${m}:${s}`;
  254. }
  255. function parseTime(str) {
  256. const [m, s] = (str || '0:00').split(':').map(Number);
  257. return m * 60 + (s || 0);
  258. }
  259. function escHtml(s) {
  260. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  261. }
  262. let toastTimer;
  263. function showToast(msg) {
  264. let el = $('toast');
  265. if (!el) {
  266. el = document.createElement('div');
  267. el.id = 'toast';
  268. el.style.cssText = [
  269. 'position:fixed', 'bottom:24px', 'left:50%', 'transform:translateX(-50%)',
  270. 'background:#333', 'color:#fff', 'padding:10px 20px', 'border-radius:8px',
  271. 'font-size:14px', 'z-index:999', 'opacity:0', 'transition:opacity .2s',
  272. 'pointer-events:none',
  273. ].join(';');
  274. document.body.appendChild(el);
  275. }
  276. el.textContent = msg;
  277. el.style.opacity = '1';
  278. clearTimeout(toastTimer);
  279. toastTimer = setTimeout(() => { el.style.opacity = '0'; }, 2500);
  280. }
  281. // ── Playlist ──────────────────────────────────────────────────────────────────
  282. $('btn-show-playlist').addEventListener('click', openPlaylist);
  283. $('btn-close-playlist').addEventListener('click', () => {
  284. playlistOverlay.classList.add('hidden');
  285. });
  286. async function openPlaylist() {
  287. playlistOverlay.classList.remove('hidden');
  288. playlistList.innerHTML = '<li id="playlist-loading">Lade…</li>';
  289. let tracks;
  290. try {
  291. tracks = await fetch('/api/playlist').then(r => r.json());
  292. } catch {
  293. playlistList.innerHTML = '<li id="playlist-loading">Fehler beim Laden</li>';
  294. return;
  295. }
  296. if (!tracks || tracks.length === 0) {
  297. playlistList.innerHTML = '<li id="playlist-loading">Playlist leer</li>';
  298. return;
  299. }
  300. const frag = document.createDocumentFragment();
  301. tracks.forEach(t => {
  302. const li = document.createElement('li');
  303. li.dataset.index = t.index - 1; // store 0-based for jump
  304. if (t.index === currentPlaylistPos) li.classList.add('current');
  305. const idx = document.createElement('span');
  306. idx.className = 'pl-idx';
  307. idx.textContent = t.index;
  308. const title = document.createElement('span');
  309. title.className = 'pl-title';
  310. title.textContent = t.title || '–';
  311. li.appendChild(idx);
  312. li.appendChild(title);
  313. li.addEventListener('click', () => {
  314. send({ cmd: 'jump', index: parseInt(li.dataset.index, 10) });
  315. playlistOverlay.classList.add('hidden');
  316. });
  317. frag.appendChild(li);
  318. });
  319. playlistList.innerHTML = '';
  320. playlistList.appendChild(frag);
  321. scrollToCurrentTrack();
  322. }
  323. function updatePlaylistHighlight() {
  324. if (playlistOverlay.classList.contains('hidden')) return;
  325. playlistList.querySelectorAll('li').forEach(li => {
  326. const isCurrent = parseInt(li.dataset.index, 10) === currentPlaylistPos - 1;
  327. li.classList.toggle('current', isCurrent);
  328. });
  329. scrollToCurrentTrack();
  330. }
  331. function scrollToCurrentTrack() {
  332. const current = playlistList.querySelector('li.current');
  333. if (current) current.scrollIntoView({ block: 'center', behavior: 'smooth' });
  334. }
  335. // ── Boot ──────────────────────────────────────────────────────────────────────
  336. connect();
  337. renderFrame();