Web-based Winamp controller for CarPC � Go backend, mobile-first UI
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

596 líneas
21KB

  1. 'use strict';
  2. // ── Compatibility helpers ─────────────────────────────────────────────────────
  3. // fetch() is available from Safari 10.1 / iOS 10.3 onwards.
  4. // For iOS 9 (iPad 2) we fall back to a minimal XHR wrapper that matches
  5. // the subset of the fetch API we actually use.
  6. function apiFetch(url, opts) {
  7. if (window.fetch) return fetch(url, opts);
  8. opts = opts || {};
  9. return new Promise(function(resolve, reject) {
  10. var xhr = new XMLHttpRequest();
  11. xhr.open(opts.method || 'GET', url);
  12. var headers = opts.headers || {};
  13. Object.keys(headers).forEach(function(k) { xhr.setRequestHeader(k, headers[k]); });
  14. xhr.onload = function() {
  15. var text = xhr.responseText;
  16. resolve({
  17. ok: xhr.status >= 200 && xhr.status < 300,
  18. json: function() { return JSON.parse(text); },
  19. text: function() { return text; }
  20. });
  21. };
  22. xhr.onerror = function() { reject(new Error('XHR error')); };
  23. xhr.send(opts.body || null);
  24. });
  25. }
  26. // String.prototype.padStart not available in iOS < 10.
  27. function pad2(n) { return n < 10 ? '0' + n : '' + n; }
  28. // iOS version detection — used to pick emoji vs. ASCII symbols.
  29. // Media-control emoji (⏮ ⏸ ⏹ ⏭) and several other glyphs are absent on iOS 9.
  30. var isLegacyIOS = (function() {
  31. var m = navigator.userAgent.match(/OS (\d+)_/);
  32. return /iPad|iPhone/.test(navigator.userAgent) && m && parseInt(m[1], 10) <= 9;
  33. }());
  34. // Symbol set: modern emoji for capable browsers, plain text for iOS ≤ 9.
  35. var SYM = isLegacyIOS ? {
  36. prev: '<<',
  37. play: '▶', // U+25B6 — works on iOS 9
  38. pause: '||',
  39. stop: '■', // U+25A0 — works on iOS 9
  40. next: '>>',
  41. volOn: 'vol',
  42. volOff: 'mut',
  43. playlist:'PL',
  44. skip: '✕' // U+2715 — works on iOS 9
  45. } : {
  46. prev: '⏮',
  47. play: '▶',
  48. pause: '⏸',
  49. stop: '⏹',
  50. next: '⏭',
  51. volOn: '🔊',
  52. volOff: '🔇',
  53. playlist:'📋',
  54. skip: '🚫'
  55. };
  56. // NodeList.prototype.forEach not available in iOS < 10.
  57. // Wrap querySelectorAll results in a real Array before iterating.
  58. function qsa(selector, root) {
  59. return Array.prototype.slice.call((root || document).querySelectorAll(selector));
  60. }
  61. // ── DOM refs ──────────────────────────────────────────────────────────────────
  62. var $ = function(id) { return document.getElementById(id); };
  63. var statusDot = $('winamp-status');
  64. var stateLabel = $('state-label');
  65. var trackTitle = $('track-title');
  66. var playlistPos = $('playlist-pos');
  67. var progressFill = $('progress-fill');
  68. var timeCurrent = $('time-current');
  69. var timeLength = $('time-length');
  70. var volumeFill = $('volume-fill');
  71. var volumePct = $('volume-pct');
  72. var btnMute = $('btn-mute');
  73. var btnPlay = $('btn-play');
  74. var killistPanel = $('killist-panel');
  75. var killistItems = $('killist-items');
  76. var playlistOverlay = $('playlist-overlay');
  77. var playlistList = $('playlist-list');
  78. var canvas = $('viz');
  79. var ctx2d = canvas.getContext('2d');
  80. // ── State ─────────────────────────────────────────────────────────────────────
  81. var currentVolume = 50;
  82. var currentPlaylistPos = 0; // 1-based, updated from status
  83. var currentRating = -1; // -1 = not yet loaded
  84. var lastRatedTitle = ''; // track we last fetched rating for
  85. var ws = null;
  86. var reconnectTimer = null;
  87. // Viz state
  88. var NUM_BARS = 64;
  89. var peaks = new Float32Array(NUM_BARS);
  90. var lastBars = new Float32Array(NUM_BARS);
  91. var rafId = null;
  92. var lastVizAt = 0; // timestamp of last received viz frame
  93. var winampPlaying = false;
  94. // Canvas display mode — cycles on click: viz → actual → remaining → viz
  95. var VIZ_MODES = ['viz', 'actual', 'remaining'];
  96. var vizMode = 'viz';
  97. var currentPosition = 0;
  98. var currentLength = 0;
  99. // ── WebSocket ─────────────────────────────────────────────────────────────────
  100. function connect() {
  101. var proto = location.protocol === 'https:' ? 'wss' : 'ws';
  102. ws = new WebSocket(proto + '://' + location.host + '/ws');
  103. ws.addEventListener('open', function() {
  104. statusDot.className = 'ok';
  105. stateLabel.textContent = 'Verbunden';
  106. clearTimeout(reconnectTimer);
  107. });
  108. ws.addEventListener('close', function() {
  109. statusDot.className = 'err';
  110. stateLabel.textContent = 'Verbindung unterbrochen…';
  111. ws = null;
  112. reconnectTimer = setTimeout(connect, 3000);
  113. });
  114. ws.addEventListener('error', function() { ws.close(); });
  115. ws.addEventListener('message', function(e) {
  116. var msg;
  117. try { msg = JSON.parse(e.data); } catch(_e) { return; }
  118. if (msg.type === 'status') applyStatus(msg);
  119. if (msg.type === 'viz') applyViz(msg.bars);
  120. });
  121. }
  122. function send(obj) {
  123. if (ws && ws.readyState === WebSocket.OPEN) {
  124. ws.send(JSON.stringify(obj));
  125. }
  126. }
  127. // ── Status handler ────────────────────────────────────────────────────────────
  128. function applyStatus(st) {
  129. if (!st.running) {
  130. statusDot.className = 'err';
  131. stateLabel.textContent = 'Winamp nicht gestartet';
  132. trackTitle.textContent = '–';
  133. playlistPos.textContent = '';
  134. return;
  135. }
  136. statusDot.className = 'ok';
  137. var stateMap = { playing: '▶ Spielt', paused: '⏸ Pause', stopped: '⏹ Stop' };
  138. stateLabel.textContent = stateMap[st.state] != null ? stateMap[st.state] : st.state;
  139. trackTitle.textContent = st.title || '–';
  140. // Fetch rating whenever the track changes.
  141. if (st.title && st.title !== lastRatedTitle) {
  142. lastRatedTitle = st.title;
  143. fetchRating();
  144. }
  145. if (!st.title || !st.running) {
  146. lastRatedTitle = '';
  147. renderStars(0);
  148. }
  149. playlistPos.textContent = st.playlist_length
  150. ? st.playlist_pos + ' / ' + st.playlist_length : '';
  151. if (st.playlist_pos !== currentPlaylistPos) {
  152. currentPlaylistPos = st.playlist_pos;
  153. updatePlaylistHighlight();
  154. }
  155. if (st.length > 0) {
  156. currentPosition = st.position;
  157. currentLength = st.length;
  158. progressFill.style.width = (st.position / st.length * 100).toFixed(1) + '%';
  159. timeCurrent.textContent = fmtTime(st.position);
  160. timeLength.textContent = '-' + fmtTime(st.length - st.position);
  161. } else {
  162. progressFill.style.width = '0%';
  163. timeCurrent.textContent = '0:00';
  164. timeLength.textContent = '-0:00';
  165. }
  166. btnPlay.textContent = st.state === 'playing' ? SYM.pause : SYM.play;
  167. winampPlaying = st.state === 'playing';
  168. if (typeof st.volume === 'number') {
  169. currentVolume = st.volume;
  170. updateVolumeFill(st.muted);
  171. updateMuteBtn(st.muted);
  172. }
  173. }
  174. // ── Controls ──────────────────────────────────────────────────────────────────
  175. btnPlay.addEventListener('click', function() {
  176. var playing = btnPlay.textContent === SYM.pause;
  177. send({ cmd: playing ? 'pause' : 'play' });
  178. });
  179. $('btn-stop').addEventListener('click', function() { send({ cmd: 'stop' }); });
  180. $('btn-next').addEventListener('click', function() { send({ cmd: 'next' }); });
  181. $('btn-prev').addEventListener('click', function() { send({ cmd: 'prev' }); });
  182. qsa('.btn-seek').forEach(function(btn) {
  183. btn.addEventListener('click', function() {
  184. send({ cmd: 'seek', delta: parseInt(btn.dataset.delta, 10) });
  185. });
  186. });
  187. $('progress-bar').addEventListener('click', function(e) {
  188. var current = parseTime(timeCurrent.textContent);
  189. var remaining = parseTime(timeLength.textContent.replace('-', ''));
  190. var total = current + remaining;
  191. if (!total) return;
  192. var rect = e.currentTarget.getBoundingClientRect();
  193. var target = Math.round((e.clientX - rect.left) / rect.width * total);
  194. send({ cmd: 'seek', delta: target - current });
  195. });
  196. // ── Volume ────────────────────────────────────────────────────────────────────
  197. $('btn-vol-up').addEventListener('click', function() {
  198. currentVolume = Math.min(100, currentVolume + 5);
  199. send({ cmd: 'volume', level: currentVolume });
  200. updateVolumeFill();
  201. });
  202. $('btn-vol-down').addEventListener('click', function() {
  203. currentVolume = Math.max(0, currentVolume - 5);
  204. send({ cmd: 'volume', level: currentVolume });
  205. updateVolumeFill();
  206. });
  207. $('volume-bar').addEventListener('click', function(e) {
  208. var rect = e.currentTarget.getBoundingClientRect();
  209. currentVolume = Math.round((e.clientX - rect.left) / rect.width * 100);
  210. send({ cmd: 'volume', level: currentVolume });
  211. updateVolumeFill();
  212. });
  213. btnMute.addEventListener('click', function() {
  214. var nowMuted = btnMute.classList.contains('muted');
  215. send({ cmd: 'mute', muted: !nowMuted });
  216. updateMuteBtn(!nowMuted);
  217. updateVolumeFill(!nowMuted);
  218. });
  219. function updateVolumeFill(muted) {
  220. if (muted === undefined) muted = btnMute.classList.contains('muted');
  221. volumeFill.style.width = currentVolume + '%';
  222. volumePct.textContent = currentVolume + ' %';
  223. volumeFill.classList.toggle('muted', muted);
  224. }
  225. function updateMuteBtn(muted) {
  226. btnMute.textContent = muted ? SYM.volOff : SYM.volOn;
  227. if (isLegacyIOS) { btnMute.style.fontSize = '16px'; btnMute.style.fontWeight = 'bold'; }
  228. btnMute.classList.toggle('muted', muted);
  229. }
  230. // ── Rating (stars) ────────────────────────────────────────────────────────────
  231. var starEls = qsa('.star');
  232. function fetchRating() {
  233. apiFetch('/api/rating')
  234. .then(function(r) { return r.json(); })
  235. .then(function(data) {
  236. currentRating = data.stars != null ? data.stars : 0;
  237. renderStars(currentRating);
  238. })
  239. .catch(function() { renderStars(0); });
  240. }
  241. function renderStars(n) {
  242. currentRating = n;
  243. starEls.forEach(function(s) {
  244. var v = parseInt(s.dataset.v, 10);
  245. var lit = v <= n;
  246. s.textContent = lit ? '★' : '☆';
  247. s.classList.toggle('lit', lit);
  248. });
  249. }
  250. starEls.forEach(function(s) {
  251. s.addEventListener('click', function() {
  252. var v = parseInt(s.dataset.v, 10);
  253. var newRating = v === currentRating ? 0 : v;
  254. var prevRating = currentRating;
  255. renderStars(newRating);
  256. apiFetch('/api/rating', {
  257. method: 'POST',
  258. headers: { 'Content-Type': 'application/json' },
  259. body: JSON.stringify({ stars: newRating }),
  260. }).catch(function() { renderStars(prevRating); });
  261. });
  262. });
  263. // ── KillList ──────────────────────────────────────────────────────────────────
  264. $('btn-kill').addEventListener('click', function() {
  265. send({ cmd: 'killist_add' });
  266. showToast('🚫 Track zur Skip-Liste hinzugefügt');
  267. });
  268. $('btn-show-killist').addEventListener('click', function() {
  269. apiFetch('/api/killist')
  270. .then(function(r) { return r.json(); })
  271. .then(function(list) { renderKillist(list || []); })
  272. .catch(function() { renderKillist([]); });
  273. });
  274. function renderKillist(list) {
  275. killistItems.innerHTML = '';
  276. list.forEach(function(title) {
  277. var li = document.createElement('li');
  278. li.innerHTML = '<span>' + escHtml(title) + '</span>';
  279. var btn = document.createElement('button');
  280. btn.textContent = '✕';
  281. btn.onclick = function() {
  282. send({ cmd: 'killist_remove', title: title });
  283. li.remove();
  284. };
  285. li.appendChild(btn);
  286. killistItems.appendChild(li);
  287. });
  288. killistPanel.classList.remove('hidden');
  289. }
  290. $('btn-close-killist').addEventListener('click', function() {
  291. killistPanel.classList.add('hidden');
  292. });
  293. // ── Visualisation (Canvas) ────────────────────────────────────────────────────
  294. canvas.addEventListener('click', function() {
  295. vizMode = VIZ_MODES[(VIZ_MODES.indexOf(vizMode) + 1) % VIZ_MODES.length];
  296. });
  297. function applyViz(bars) {
  298. if (!bars || bars.length === 0) return;
  299. lastBars = new Float32Array(bars);
  300. lastVizAt = performance.now();
  301. }
  302. function renderFrame(ts) {
  303. ts = ts || 0;
  304. rafId = requestAnimationFrame(renderFrame);
  305. // Resize canvas to CSS size (handles window resize / DPR).
  306. var dpr = window.devicePixelRatio || 1;
  307. var cssW = canvas.clientWidth;
  308. var cssH = canvas.clientHeight;
  309. if (canvas.width !== Math.round(cssW * dpr) ||
  310. canvas.height !== Math.round(cssH * dpr)) {
  311. canvas.width = Math.round(cssW * dpr);
  312. canvas.height = Math.round(cssH * dpr);
  313. ctx2d.scale(dpr, dpr);
  314. }
  315. var w = cssW;
  316. var h = cssH;
  317. if (w === 0 || h === 0) return;
  318. // Background
  319. ctx2d.fillStyle = '#000';
  320. ctx2d.fillRect(0, 0, w, h);
  321. // ── Time display modes ──────────────────────────────────────────────────────
  322. if (vizMode === 'actual' || vizMode === 'remaining') {
  323. var isActual = vizMode === 'actual';
  324. var secs = isActual ? currentPosition : Math.max(0, currentLength - currentPosition);
  325. var prefix = isActual ? '' : '-';
  326. var timeStr = prefix + fmtTimeLong(secs);
  327. var label = isActual ? 'ELAPSED' : 'REMAINING';
  328. ctx2d.textAlign = 'center';
  329. ctx2d.textBaseline = 'middle';
  330. ctx2d.font = 'bold ' + Math.round(h * 0.52) + 'px monospace';
  331. ctx2d.fillStyle = isActual ? '#e0e0e0' : '#e94560';
  332. ctx2d.fillText(timeStr, w / 2, h * 0.48);
  333. ctx2d.font = Math.round(h * 0.18) + 'px monospace';
  334. ctx2d.fillStyle = '#444';
  335. ctx2d.fillText(label, w / 2, h * 0.82);
  336. return;
  337. }
  338. // ── Spectrum mode ───────────────────────────────────────────────────────────
  339. var hasSignal = winampPlaying && (performance.now() - lastVizAt) < 1500;
  340. // Classic fixed vertical gradient: green at bottom → yellow → red at top.
  341. var grad = ctx2d.createLinearGradient(0, h, 0, 0);
  342. if (hasSignal) {
  343. grad.addColorStop(0, '#00aa00');
  344. grad.addColorStop(0.6, '#aaaa00');
  345. grad.addColorStop(1, '#cc0000');
  346. } else {
  347. grad.addColorStop(0, '#003300');
  348. grad.addColorStop(0.6, '#333300');
  349. grad.addColorStop(1, '#330000');
  350. }
  351. var n = NUM_BARS;
  352. var gap = 1;
  353. var barW = Math.max(1, (w - gap * (n - 1)) / n);
  354. for (var i = 0; i < n; i++) {
  355. var val;
  356. if (hasSignal) {
  357. val = lastBars[i] || 0;
  358. if (val > peaks[i]) peaks[i] = val;
  359. else peaks[i] = Math.max(0, peaks[i] - 0.008);
  360. } else {
  361. var phase = (ts / 1800) + (i / n) * Math.PI * 2;
  362. var breath = (Math.sin(ts / 2000) * 0.5 + 0.5) * 0.08;
  363. val = Math.max(0, Math.sin(phase) * breath);
  364. peaks[i] = Math.max(0, peaks[i] - 0.02);
  365. }
  366. var x = Math.round(i * (barW + gap));
  367. var barH = val * h;
  368. if (barH > 0.5) {
  369. ctx2d.fillStyle = grad;
  370. ctx2d.fillRect(x, h - barH, barW, barH);
  371. }
  372. if (peaks[i] > 0.02) {
  373. var py = Math.round(h - peaks[i] * h) - 1;
  374. ctx2d.fillStyle = hasSignal ? 'rgba(255,255,255,0.6)' : 'rgba(255,255,255,0.15)';
  375. ctx2d.fillRect(x, py, barW, 2);
  376. }
  377. }
  378. if (!ws || ws.readyState !== WebSocket.OPEN) {
  379. drawLabel(ctx2d, w, h, '● NO SIGNAL', '#333');
  380. } else if (!winampPlaying) {
  381. drawLabel(ctx2d, w, h, '▶ PLAY', '#1a3a1a');
  382. }
  383. }
  384. function drawLabel(ctx, w, h, text, color) {
  385. ctx.font = 'bold ' + Math.round(h * 0.22) + 'px monospace';
  386. ctx.textAlign = 'center';
  387. ctx.textBaseline = 'middle';
  388. ctx.fillStyle = color;
  389. ctx.fillText(text, w / 2, h / 2);
  390. }
  391. // ── Helpers ───────────────────────────────────────────────────────────────────
  392. function fmtTime(secs) {
  393. var m = Math.floor(secs / 60);
  394. var s = Math.floor(secs % 60);
  395. return m + ':' + pad2(s);
  396. }
  397. // Like fmtTime but always zero-pads to hh:mm:ss for the canvas display.
  398. function fmtTimeLong(secs) {
  399. secs = Math.floor(secs);
  400. var h = Math.floor(secs / 3600);
  401. var m = Math.floor((secs % 3600) / 60);
  402. var s = secs % 60;
  403. return pad2(h) + ':' + pad2(m) + ':' + pad2(s);
  404. }
  405. function parseTime(str) {
  406. var parts = (str || '0:00').split(':').map(Number);
  407. return parts[0] * 60 + (parts[1] || 0);
  408. }
  409. function escHtml(s) {
  410. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  411. }
  412. var toastTimer;
  413. function showToast(msg) {
  414. var el = $('toast');
  415. if (!el) {
  416. el = document.createElement('div');
  417. el.id = 'toast';
  418. el.style.cssText = [
  419. 'position:fixed', 'bottom:24px', 'left:50%', 'transform:translateX(-50%)',
  420. 'background:#333', 'color:#fff', 'padding:10px 20px', 'border-radius:8px',
  421. 'font-size:14px', 'z-index:999', 'opacity:0', 'transition:opacity .2s',
  422. 'pointer-events:none',
  423. ].join(';');
  424. document.body.appendChild(el);
  425. }
  426. el.textContent = msg;
  427. el.style.opacity = '1';
  428. clearTimeout(toastTimer);
  429. toastTimer = setTimeout(function() { el.style.opacity = '0'; }, 2500);
  430. }
  431. // ── Playlist ──────────────────────────────────────────────────────────────────
  432. $('btn-show-playlist').addEventListener('click', openPlaylist);
  433. $('btn-close-playlist').addEventListener('click', function() {
  434. playlistOverlay.classList.add('hidden');
  435. });
  436. function openPlaylist() {
  437. playlistOverlay.classList.remove('hidden');
  438. playlistList.innerHTML = '<li id="playlist-loading">Lade…</li>';
  439. apiFetch('/api/playlist')
  440. .then(function(r) { return r.json(); })
  441. .then(function(tracks) {
  442. if (!tracks || tracks.length === 0) {
  443. playlistList.innerHTML = '<li id="playlist-loading">Playlist leer</li>';
  444. return;
  445. }
  446. var frag = document.createDocumentFragment();
  447. tracks.forEach(function(t) {
  448. var li = document.createElement('li');
  449. li.dataset.index = t.index - 1; // 0-based for jump
  450. if (t.index === currentPlaylistPos) li.classList.add('current');
  451. var idx = document.createElement('span');
  452. idx.className = 'pl-idx';
  453. idx.textContent = t.index;
  454. var title = document.createElement('span');
  455. title.className = 'pl-title';
  456. title.textContent = t.title || '–';
  457. li.appendChild(idx);
  458. li.appendChild(title);
  459. li.addEventListener('click', function() {
  460. send({ cmd: 'jump', index: parseInt(li.dataset.index, 10) });
  461. playlistOverlay.classList.add('hidden');
  462. });
  463. frag.appendChild(li);
  464. });
  465. playlistList.innerHTML = '';
  466. playlistList.appendChild(frag);
  467. scrollToCurrentTrack();
  468. })
  469. .catch(function() {
  470. playlistList.innerHTML = '<li id="playlist-loading">Fehler beim Laden</li>';
  471. });
  472. }
  473. function updatePlaylistHighlight() {
  474. if (playlistOverlay.classList.contains('hidden')) return;
  475. qsa('li', playlistList).forEach(function(li) {
  476. var isCurrent = parseInt(li.dataset.index, 10) === currentPlaylistPos - 1;
  477. li.classList.toggle('current', isCurrent);
  478. });
  479. scrollToCurrentTrack();
  480. }
  481. function scrollToCurrentTrack() {
  482. var current = playlistList.querySelector('li.current');
  483. if (current) current.scrollIntoView(true);
  484. }
  485. // ── Boot ──────────────────────────────────────────────────────────────────────
  486. // Replace text and tune font so the symbol fills ~¾ of the button.
  487. // Centering is already handled by flex on .btn.
  488. // Defined outside if-block — function declarations inside blocks are
  489. // forbidden in strict mode on older engines and can kill the whole script.
  490. function legacySym(id, text, size) {
  491. var el = $(id);
  492. el.textContent = text;
  493. el.style.fontSize = size;
  494. el.style.fontWeight = 'bold';
  495. el.style.letterSpacing = '2px';
  496. }
  497. // Replace emoji with legacy symbols on iOS 9 where the glyphs are missing.
  498. if (isLegacyIOS) {
  499. // Transport controls (btn-h = 64px):
  500. // two-char symbols (<<, >>) → 26px bold; single-char (■ ▶) → 36px bold.
  501. legacySym('btn-prev', SYM.prev, '26px');
  502. legacySym('btn-play', SYM.play, '36px');
  503. legacySym('btn-stop', SYM.stop, '36px');
  504. legacySym('btn-next', SYM.next, '26px');
  505. // Volume mute (48px tall)
  506. legacySym('btn-mute', SYM.volOn, '16px');
  507. // Playlist action button (52px tall)
  508. legacySym('btn-show-playlist', SYM.playlist, '18px');
  509. // Kill button: drop the emoji, keep the label
  510. $('btn-kill').textContent = SYM.skip + ' Überspringen';
  511. }
  512. connect();
  513. renderFrame();