feat: Playtube Stream Dock Plugin 1.0.0 (Ajazz AKP153E) mit Icon-Pack
This commit is contained in:
+220
@@ -0,0 +1,220 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Alle Tastenaktionen des Plugins: was ein Tastendruck an Playtube schickt (request) und wie die
|
||||
* Taste dazu aussieht (render). Reine Funktionen ohne Netzwerk - dadurch gut testbar.
|
||||
*
|
||||
* Zustaende (State) entsprechen den Bildern im manifest.json, Reihenfolge = Index.
|
||||
*/
|
||||
|
||||
const PREFIX = 'com.fojadrachi.playtube.';
|
||||
|
||||
const DEFAULTS = Object.freeze({
|
||||
target: 'auto', // "auto" | "youtube" | "music"
|
||||
step: 5, // Lautstaerke-Schritt in Prozent
|
||||
volume: 30, // Ziel-Lautstaerke der Aktion "Lautstaerke setzen"
|
||||
seconds: 10, // Sprungweite beim Vor-/Zurueckspulen
|
||||
tab: 'toggle', // Aktion "Tab wechseln": "toggle" | "youtube" | "music"
|
||||
playlistId: '',
|
||||
playlistTitle: '',
|
||||
});
|
||||
|
||||
const TARGETS = ['auto', 'youtube', 'music'];
|
||||
const TABS = ['toggle', 'youtube', 'music'];
|
||||
|
||||
function clampInt(value, min, max, fallback) {
|
||||
const number = Number.parseInt(value, 10);
|
||||
if (!Number.isFinite(number)) return fallback;
|
||||
return Math.max(min, Math.min(max, number));
|
||||
}
|
||||
|
||||
/** Macht aus den (evtl. leeren/fehlerhaften) Einstellungen einer Taste gueltige Werte. */
|
||||
function normalizeSettings(raw, titleDefault = false) {
|
||||
const settings = { ...DEFAULTS, ...(raw || {}) };
|
||||
if (!TARGETS.includes(settings.target)) settings.target = DEFAULTS.target;
|
||||
if (!TABS.includes(settings.tab)) settings.tab = DEFAULTS.tab;
|
||||
settings.step = clampInt(settings.step, 1, 25, DEFAULTS.step);
|
||||
settings.volume = clampInt(settings.volume, 0, 100, DEFAULTS.volume);
|
||||
settings.seconds = clampInt(settings.seconds, 1, 300, DEFAULTS.seconds);
|
||||
const show = raw && raw.showTitle !== undefined ? raw.showTitle : titleDefault;
|
||||
settings.showTitle = show === true || show === 'true';
|
||||
settings.playlistId = typeof settings.playlistId === 'string' ? settings.playlistId.trim() : '';
|
||||
settings.playlistTitle = typeof settings.playlistTitle === 'string' ? settings.playlistTitle : '';
|
||||
return settings;
|
||||
}
|
||||
|
||||
/** Welcher Tab ist gemeint? "auto" = der Tab, den Playtube als aktiv meldet. */
|
||||
function pickTab(state, target) {
|
||||
if (!state || !state.tabs) return null;
|
||||
const name = target === 'auto' ? state.activeTab : target;
|
||||
const info = state.tabs[name];
|
||||
return info ? { name, info } : null;
|
||||
}
|
||||
|
||||
/** Bricht Text fuer die kleinen Tasten-Displays um (Woerter, dann harte Trennung). */
|
||||
function wrapTitle(text, perLine = 8, maxLines = 3) {
|
||||
const words = String(text || '').trim().split(/\s+/).filter(Boolean);
|
||||
const lines = [];
|
||||
let current = '';
|
||||
let truncated = false;
|
||||
const push = (line) => {
|
||||
if (lines.length < maxLines) lines.push(line);
|
||||
else truncated = true;
|
||||
};
|
||||
for (let word of words) {
|
||||
while (word.length > perLine) {
|
||||
if (current) {
|
||||
push(current);
|
||||
current = '';
|
||||
}
|
||||
push(word.slice(0, perLine));
|
||||
word = word.slice(perLine);
|
||||
}
|
||||
if (!word) continue;
|
||||
if (!current) current = word;
|
||||
else if (current.length + 1 + word.length <= perLine) current += ` ${word}`;
|
||||
else {
|
||||
push(current);
|
||||
current = word;
|
||||
}
|
||||
}
|
||||
if (current) push(current);
|
||||
if (truncated && lines.length) lines[lines.length - 1] = `${lines[lines.length - 1].slice(0, perLine - 2)}..`;
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function volumeTitle(tab) {
|
||||
const volume = tab && tab.info.volume;
|
||||
return typeof volume === 'number' ? `${Math.round(volume)}%` : '';
|
||||
}
|
||||
|
||||
const OFFLINE_TITLE = 'Playtube\noffline';
|
||||
|
||||
/**
|
||||
* Definition pro Aktion. `id` = letzter Teil der UUID (siehe manifest.json).
|
||||
* - request(settings): {cmd, fields} oder null (Taste tut dann nichts, zeigt Alarm)
|
||||
* - render(settings, state, connected): {state?, title?, coverUrl?}
|
||||
* - press: "up" (Standard, beim Loslassen) oder "down" (sofort; mit repeat = Dauerdruck)
|
||||
*/
|
||||
const DEFINITIONS = {
|
||||
playpause: {
|
||||
titleDefault: false,
|
||||
request: (s) => ({ cmd: 'play_pause', fields: { target: s.target } }),
|
||||
render: (s, state, connected) => {
|
||||
if (!connected) return { state: 0, title: s.showTitle ? OFFLINE_TITLE : '' };
|
||||
const tab = pickTab(state, s.target);
|
||||
return {
|
||||
state: tab && tab.info.playing ? 1 : 0,
|
||||
title: s.showTitle && tab && tab.info.title ? wrapTitle(tab.info.title) : '',
|
||||
};
|
||||
},
|
||||
},
|
||||
next: { request: (s) => ({ cmd: 'next', fields: { target: s.target } }) },
|
||||
previous: { request: (s) => ({ cmd: 'previous', fields: { target: s.target } }) },
|
||||
seekback: {
|
||||
request: (s) => ({ cmd: 'seek', fields: { target: s.target, value: -s.seconds } }),
|
||||
render: (s) => ({ title: `-${s.seconds}s` }),
|
||||
},
|
||||
seekforward: {
|
||||
request: (s) => ({ cmd: 'seek', fields: { target: s.target, value: s.seconds } }),
|
||||
render: (s) => ({ title: `+${s.seconds}s` }),
|
||||
},
|
||||
volumeup: {
|
||||
press: 'down',
|
||||
repeat: { delayMs: 450, intervalMs: 140 },
|
||||
request: (s) => ({ cmd: 'volume_change', fields: { target: s.target, value: s.step } }),
|
||||
render: (s, state, connected) => ({ title: connected ? volumeTitle(pickTab(state, s.target)) : '' }),
|
||||
},
|
||||
volumedown: {
|
||||
press: 'down',
|
||||
repeat: { delayMs: 450, intervalMs: 140 },
|
||||
request: (s) => ({ cmd: 'volume_change', fields: { target: s.target, value: -s.step } }),
|
||||
render: (s, state, connected) => ({ title: connected ? volumeTitle(pickTab(state, s.target)) : '' }),
|
||||
},
|
||||
volumeset: {
|
||||
request: (s) => ({ cmd: 'set_volume', fields: { target: s.target, value: s.volume } }),
|
||||
render: (s) => ({ title: `${s.volume}%` }),
|
||||
},
|
||||
mute: {
|
||||
request: (s) => ({ cmd: 'mute_toggle', fields: { target: s.target } }),
|
||||
render: (s, state, connected) => {
|
||||
const tab = connected ? pickTab(state, s.target) : null;
|
||||
return { state: tab && tab.info.muted ? 1 : 0, title: tab && !tab.info.muted ? volumeTitle(tab) : '' };
|
||||
},
|
||||
},
|
||||
nowplaying: {
|
||||
titleDefault: true,
|
||||
request: (s) => ({ cmd: 'play_pause', fields: { target: s.target } }),
|
||||
render: (s, state, connected) => {
|
||||
if (!connected) return { coverUrl: null, title: s.showTitle ? OFFLINE_TITLE : '' };
|
||||
const tab = pickTab(state, s.target);
|
||||
const info = tab && tab.info;
|
||||
return {
|
||||
coverUrl: info && info.hasVideo && info.thumbnail ? info.thumbnail : null,
|
||||
title: s.showTitle && info && info.title ? wrapTitle(info.title) : '',
|
||||
};
|
||||
},
|
||||
},
|
||||
like: {
|
||||
request: (s) => ({ cmd: 'like', fields: { target: s.target } }),
|
||||
render: (s, state, connected) => {
|
||||
const tab = connected ? pickTab(state, s.target) : null;
|
||||
return { state: tab && tab.info.likeStatus === 'like' ? 1 : 0 };
|
||||
},
|
||||
},
|
||||
shuffle: { request: (s) => ({ cmd: 'shuffle', fields: { target: s.target } }) },
|
||||
repeat: {
|
||||
request: (s) => ({ cmd: 'repeat', fields: { target: s.target } }),
|
||||
render: (s, state, connected) => {
|
||||
const tab = connected ? pickTab(state, s.target) : null;
|
||||
const mode = String((tab && tab.info.repeatMode) || '').toUpperCase();
|
||||
return { state: mode === 'ALL' ? 1 : mode === 'ONE' ? 2 : 0 };
|
||||
},
|
||||
},
|
||||
playlist: {
|
||||
request: (s) => (s.playlistId ? { cmd: 'play_playlist', fields: { playlist: s.playlistId } } : null),
|
||||
render: (s) => ({ title: s.playlistTitle ? wrapTitle(s.playlistTitle) : '' }),
|
||||
},
|
||||
switchtab: {
|
||||
request: (s) => ({ cmd: 'switch_tab', fields: { target: s.tab === 'toggle' ? 'auto' : s.tab } }),
|
||||
render: (s, state, connected) => {
|
||||
if (!connected || !state) return { title: '' };
|
||||
if (state.visibleTab === 'music') return { title: 'Music' };
|
||||
if (state.visibleTab === 'youtube') return { title: 'YouTube' };
|
||||
return { title: '' };
|
||||
},
|
||||
},
|
||||
show: { request: () => ({ cmd: 'show', fields: {} }) },
|
||||
};
|
||||
|
||||
function actionIdFromUuid(uuid) {
|
||||
if (typeof uuid !== 'string' || !uuid.startsWith(PREFIX)) return null;
|
||||
const id = uuid.slice(PREFIX.length);
|
||||
return Object.prototype.hasOwnProperty.call(DEFINITIONS, id) ? id : null;
|
||||
}
|
||||
|
||||
/** Darstellung einer Taste; fehlende Felder heissen "nicht aendern". */
|
||||
function renderAction(id, rawSettings, state, connected) {
|
||||
const definition = DEFINITIONS[id];
|
||||
const settings = normalizeSettings(rawSettings, definition.titleDefault);
|
||||
return definition.render ? definition.render(settings, state, connected) : {};
|
||||
}
|
||||
|
||||
/** {cmd, fields} fuer einen Tastendruck oder null. */
|
||||
function buildRequest(id, rawSettings) {
|
||||
const definition = DEFINITIONS[id];
|
||||
const settings = normalizeSettings(rawSettings, definition.titleDefault);
|
||||
return definition.request(settings);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PREFIX,
|
||||
DEFAULTS,
|
||||
DEFINITIONS,
|
||||
normalizeSettings,
|
||||
pickTab,
|
||||
wrapTitle,
|
||||
actionIdFromUuid,
|
||||
renderAction,
|
||||
buildRequest,
|
||||
};
|
||||
@@ -0,0 +1,290 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Verbindet Stream Dock (host), Playtube (client) und die Aktionsdefinitionen (actions):
|
||||
* - haelt fuer jede sichtbare Taste Aktion + Einstellungen,
|
||||
* - fuehrt Tastendruecke als Playtube-Befehle aus (Lautstaerke: Dauerdruck mit Wiederholung),
|
||||
* - fragt den Status regelmaessig ab und aktualisiert Titel/Zustand/Cover der Tasten,
|
||||
* - beantwortet die Playlist-Anfrage des Property Inspectors.
|
||||
*/
|
||||
|
||||
const {
|
||||
DEFINITIONS, actionIdFromUuid, buildRequest, normalizeSettings, pickTab, renderAction,
|
||||
} = require('./actions');
|
||||
const { buildInfoSvg, svgToDataUri } = require('./infoPanel');
|
||||
|
||||
const POLL_INTERVAL_MS = 1000;
|
||||
const REFRESH_AFTER_COMMAND_MS = 350;
|
||||
const COVER_CACHE_LIMIT = 24;
|
||||
const COVER_TIMEOUT_MS = 4000;
|
||||
const KEY_IMAGE_PX = 144;
|
||||
|
||||
/** YouTube Music liefert Cover mit "=w60-h60-..." - fuer scharfe Tasten auf Tastengroesse ziehen. */
|
||||
function sharpCoverUrl(url) {
|
||||
return String(url).replace(/=w\d+-h\d+/, `=w${KEY_IMAGE_PX}-h${KEY_IMAGE_PX}`);
|
||||
}
|
||||
|
||||
async function defaultFetchImage(url) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(COVER_TIMEOUT_MS) });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const type = (response.headers.get('content-type') || 'image/jpeg').split(';')[0];
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
return `data:${type};base64,${bytes.toString('base64')}`;
|
||||
}
|
||||
|
||||
class Controller {
|
||||
/**
|
||||
* @param {object} deps
|
||||
* @param {import('./host').StreamDockHost} deps.host
|
||||
* @param {import('./playtubeClient').PlaytubeClient} deps.client
|
||||
* @param {{info: Function, warn: Function, error: Function}} deps.logger
|
||||
* @param {Function} [deps.fetchImage] - (url) => Promise<dataUri>
|
||||
* @param {number} [deps.pollIntervalMs]
|
||||
*/
|
||||
constructor({ host, client, logger, fetchImage, pollIntervalMs }) {
|
||||
this.host = host;
|
||||
this.client = client;
|
||||
this.logger = logger;
|
||||
this.fetchImage = fetchImage || defaultFetchImage;
|
||||
this.pollIntervalMs = pollIntervalMs ?? POLL_INTERVAL_MS;
|
||||
|
||||
this.keys = new Map(); // context -> {actionId, settings, last (zuletzt gesendete Darstellung)}
|
||||
this.state = null;
|
||||
this.covers = new Map(); // url -> dataUri (Einfuegereihenfolge = Alter)
|
||||
this.coverLoading = new Set();
|
||||
this.repeaters = new Map(); // context -> {delayTimer, intervalTimer}
|
||||
this.pollTimer = null;
|
||||
this.refreshTimer = null;
|
||||
this.polling = false;
|
||||
}
|
||||
|
||||
start() {
|
||||
this.host.on('event', (message) => this.handleEvent(message));
|
||||
this.client.on('connected', (name) => {
|
||||
this.logger.info(`Mit Playtube verbunden (${name})`);
|
||||
this.poll();
|
||||
});
|
||||
this.client.on('disconnected', () => {
|
||||
this.logger.info('Verbindung zu Playtube getrennt');
|
||||
this.state = null;
|
||||
this.renderAll();
|
||||
});
|
||||
this.client.start();
|
||||
this.pollTimer = setInterval(() => this.poll(), this.pollIntervalMs);
|
||||
}
|
||||
|
||||
stop() {
|
||||
clearInterval(this.pollTimer);
|
||||
clearTimeout(this.refreshTimer);
|
||||
for (const context of [...this.repeaters.keys()]) this.stopRepeat(context);
|
||||
this.client.stop();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Ereignisse
|
||||
|
||||
handleEvent(message) {
|
||||
const { event, context } = message;
|
||||
switch (event) {
|
||||
case 'willAppear':
|
||||
return this.onAppear(message);
|
||||
case 'willDisappear':
|
||||
this.stopRepeat(context);
|
||||
this.keys.delete(context);
|
||||
return undefined;
|
||||
case 'didReceiveSettings':
|
||||
return this.onSettings(message);
|
||||
case 'keyDown':
|
||||
return this.onKeyDown(context);
|
||||
case 'keyUp':
|
||||
return this.onKeyUp(context);
|
||||
case 'sendToPlugin':
|
||||
return this.onPropertyInspectorMessage(message);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
onAppear(message) {
|
||||
const actionId = actionIdFromUuid(message.action);
|
||||
if (!actionId) return;
|
||||
const payload = message.payload || {};
|
||||
const settings = payload.settings || {};
|
||||
const info = payload.controller === 'Information';
|
||||
this.logger.info(`willAppear ${actionId} controller=${payload.controller} info=${info}`);
|
||||
this.keys.set(message.context, { actionId, settings, info, last: null });
|
||||
this.renderKey(message.context);
|
||||
if (this.client.connected && !this.state) this.poll();
|
||||
}
|
||||
|
||||
onSettings(message) {
|
||||
const key = this.keys.get(message.context);
|
||||
if (!key) return;
|
||||
key.settings = (message.payload && message.payload.settings) || {};
|
||||
key.last = null;
|
||||
this.renderKey(message.context);
|
||||
}
|
||||
|
||||
onKeyDown(context) {
|
||||
const key = this.keys.get(context);
|
||||
if (!key) return;
|
||||
const definition = DEFINITIONS[key.actionId];
|
||||
if (definition.press !== 'down') return;
|
||||
this.execute(context);
|
||||
const { delayMs, intervalMs } = definition.repeat || {};
|
||||
if (!delayMs) return;
|
||||
this.stopRepeat(context);
|
||||
const timers = {};
|
||||
timers.delayTimer = setTimeout(() => {
|
||||
timers.intervalTimer = setInterval(() => this.execute(context, { quiet: true }), intervalMs);
|
||||
}, delayMs);
|
||||
this.repeaters.set(context, timers);
|
||||
}
|
||||
|
||||
onKeyUp(context) {
|
||||
const key = this.keys.get(context);
|
||||
if (!key) return;
|
||||
if (DEFINITIONS[key.actionId].press === 'down') {
|
||||
this.stopRepeat(context);
|
||||
return;
|
||||
}
|
||||
this.execute(context);
|
||||
}
|
||||
|
||||
stopRepeat(context) {
|
||||
const timers = this.repeaters.get(context);
|
||||
if (!timers) return;
|
||||
clearTimeout(timers.delayTimer);
|
||||
clearInterval(timers.intervalTimer);
|
||||
this.repeaters.delete(context);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Befehle
|
||||
|
||||
/** Fuehrt die Aktion einer Taste aus; `quiet` = kein Alarm bei Fehler (Dauerdruck). */
|
||||
async execute(context, { quiet = false } = {}) {
|
||||
const key = this.keys.get(context);
|
||||
if (!key) return;
|
||||
const request = buildRequest(key.actionId, key.settings);
|
||||
if (!request) {
|
||||
this.host.showAlert(context);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.client.request(request.cmd, request.fields);
|
||||
this.scheduleRefresh();
|
||||
} catch (error) {
|
||||
this.logger.warn(`${request.cmd} fehlgeschlagen: ${error.message}`);
|
||||
if (quiet) this.stopRepeat(context);
|
||||
else this.host.showAlert(context);
|
||||
}
|
||||
}
|
||||
|
||||
scheduleRefresh() {
|
||||
clearTimeout(this.refreshTimer);
|
||||
this.refreshTimer = setTimeout(() => this.poll(), REFRESH_AFTER_COMMAND_MS);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Status
|
||||
|
||||
async poll() {
|
||||
if (this.polling || !this.client.connected || this.keys.size === 0) return;
|
||||
this.polling = true;
|
||||
try {
|
||||
this.state = await this.client.status();
|
||||
this.renderAll();
|
||||
} catch (error) {
|
||||
this.logger.warn(`Status nicht lesbar: ${error.message}`);
|
||||
} finally {
|
||||
this.polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
renderAll() {
|
||||
for (const context of this.keys.keys()) this.renderKey(context);
|
||||
}
|
||||
|
||||
renderKey(context) {
|
||||
const key = this.keys.get(context);
|
||||
if (!key) return;
|
||||
if (key.info && key.actionId === 'nowplaying') {
|
||||
this.renderInfo(context, key);
|
||||
return;
|
||||
}
|
||||
const view = renderAction(key.actionId, key.settings, this.state, this.client.connected);
|
||||
const coverUrl = view.coverUrl ? sharpCoverUrl(view.coverUrl) : null;
|
||||
const cover = coverUrl ? this.covers.get(coverUrl) || null : null;
|
||||
if (coverUrl && !cover) this.loadCover(coverUrl);
|
||||
|
||||
const next = { state: view.state, title: view.title, cover: cover ? coverUrl : null };
|
||||
const previous = key.last || {};
|
||||
const changed = (name) => previous[name] !== next[name];
|
||||
key.last = next;
|
||||
|
||||
if (view.state !== undefined && changed('state')) this.host.setState(context, view.state);
|
||||
if (view.title !== undefined && changed('title')) this.host.setTitle(context, view.title);
|
||||
// Cover anzeigen; ohne Cover (nichts laeuft) das Standardbild der Taste wiederherstellen.
|
||||
if (view.coverUrl !== undefined && changed('cover')) this.host.setImage(context, cover);
|
||||
}
|
||||
|
||||
/** Hohes Info-Display: komplette "Aktueller Titel"-Karte als SVG-Bild. */
|
||||
renderInfo(context, key) {
|
||||
let view = null;
|
||||
if (this.client.connected) {
|
||||
const tab = pickTab(this.state, normalizeSettings(key.settings).target);
|
||||
const info = (tab && tab.info) || {};
|
||||
const coverUrl = info.thumbnail ? sharpCoverUrl(info.thumbnail) : null;
|
||||
const coverDataUri = coverUrl ? this.covers.get(coverUrl) || null : null;
|
||||
if (coverUrl && !coverDataUri) this.loadCover(coverUrl);
|
||||
view = {
|
||||
title: info.title || '',
|
||||
subtitle: info.subtitle || '',
|
||||
playing: Boolean(info.playing),
|
||||
currentTime: info.currentTime,
|
||||
duration: info.duration,
|
||||
volume: info.volume,
|
||||
coverDataUri,
|
||||
};
|
||||
}
|
||||
const svg = buildInfoSvg(view);
|
||||
if (svg === key.lastSvg) return;
|
||||
key.lastSvg = svg;
|
||||
this.host.setTitle(context, '');
|
||||
this.host.setImage(context, svgToDataUri(svg));
|
||||
}
|
||||
|
||||
async loadCover(url) {
|
||||
if (this.coverLoading.has(url)) return;
|
||||
this.coverLoading.add(url);
|
||||
try {
|
||||
const dataUri = await this.fetchImage(url);
|
||||
this.covers.set(url, dataUri);
|
||||
while (this.covers.size > COVER_CACHE_LIMIT) this.covers.delete(this.covers.keys().next().value);
|
||||
this.renderAll();
|
||||
} catch (error) {
|
||||
this.logger.warn(`Cover nicht ladbar: ${error.message}`);
|
||||
} finally {
|
||||
this.coverLoading.delete(url);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Property Inspector
|
||||
|
||||
async onPropertyInspectorMessage(message) {
|
||||
const payload = message.payload || {};
|
||||
if (payload.command !== 'requestPlaylists') return;
|
||||
const reply = (body) => this.host.sendToPropertyInspector(message.action, message.context, body);
|
||||
if (!this.client.connected) {
|
||||
reply({ command: 'playlists', ok: false, error: 'offline', playlists: [] });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const playlists = await this.client.listPlaylists();
|
||||
reply({ command: 'playlists', ok: true, playlists });
|
||||
} catch (error) {
|
||||
this.logger.warn(`Playlists nicht lesbar: ${error.message}`);
|
||||
reply({ command: 'playlists', ok: false, error: error.code || 'error', message: error.message, playlists: [] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Controller, sharpCoverUrl };
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Verbindung zur Stream-Dock-Software (Ajazz/Mirabox "Stream Dock").
|
||||
*
|
||||
* Die Software startet das Plugin mit
|
||||
* node plugin/index.js -port <P> -pluginUUID <U> -registerEvent <E> -info <JSON>
|
||||
* und erwartet, dass sich das Plugin per WebSocket auf ws://127.0.0.1:<P> mit
|
||||
* {"uuid": <U>, "event": <E>} registriert. Danach kommen Ereignisse (willAppear, keyDown,
|
||||
* keyUp, didReceiveSettings, sendToPlugin, ...) als JSON; Befehle (setTitle, setImage,
|
||||
* setState, ...) gehen als JSON zurueck. Das Protokoll ist mit dem Elgato-Stream-Deck-SDK
|
||||
* kompatibel.
|
||||
*/
|
||||
|
||||
const { EventEmitter } = require('events');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const found = {};
|
||||
for (let i = 0; i < argv.length - 1; i += 1) {
|
||||
switch (argv[i]) {
|
||||
case '-port': found.port = argv[i + 1]; break;
|
||||
case '-pluginUUID': found.uuid = argv[i + 1]; break;
|
||||
case '-registerEvent': found.registerEvent = argv[i + 1]; break;
|
||||
case '-info': found.info = argv[i + 1]; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
let info = {};
|
||||
try {
|
||||
info = JSON.parse(found.info || '{}');
|
||||
} catch {
|
||||
info = {};
|
||||
}
|
||||
return { port: found.port, uuid: found.uuid, registerEvent: found.registerEvent, info };
|
||||
}
|
||||
|
||||
const WS_OPEN = 1;
|
||||
|
||||
class StreamDockHost extends EventEmitter {
|
||||
/**
|
||||
* @param {{port: string|number, uuid: string, registerEvent: string, info?: object}} args
|
||||
* @param {{WebSocket?: Function}} [deps] - Ersatz fuer das ws-Paket (Tests)
|
||||
*/
|
||||
constructor(args, deps = {}) {
|
||||
super();
|
||||
this.port = args.port;
|
||||
this.uuid = args.uuid;
|
||||
this.registerEvent = args.registerEvent;
|
||||
this.info = args.info || {};
|
||||
this.WebSocket = deps.WebSocket || require('ws');
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
get language() {
|
||||
return (this.info.application && this.info.application.language) || 'en';
|
||||
}
|
||||
|
||||
connect() {
|
||||
this.ws = new this.WebSocket(`ws://127.0.0.1:${this.port}`);
|
||||
this.ws.on('open', () => {
|
||||
this._send({ uuid: this.uuid, event: this.registerEvent });
|
||||
this.emit('open');
|
||||
});
|
||||
this.ws.on('message', (raw) => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(raw.toString());
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.emit('event', message);
|
||||
});
|
||||
this.ws.on('close', () => this.emit('close'));
|
||||
this.ws.on('error', (error) => this.emit('error', error));
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.ws) this.ws.close();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Befehle
|
||||
|
||||
setTitle(context, title) {
|
||||
this._send({ event: 'setTitle', context, payload: { target: 0, title: String(title ?? '') } });
|
||||
}
|
||||
|
||||
/** image = Data-URI (PNG/JPEG/SVG); ohne Wert wird das Standardbild des Zustands wiederhergestellt. */
|
||||
setImage(context, image) {
|
||||
const payload = { target: 0 };
|
||||
if (image) payload.image = image;
|
||||
this._send({ event: 'setImage', context, payload });
|
||||
}
|
||||
|
||||
setState(context, state) {
|
||||
this._send({ event: 'setState', context, payload: { state } });
|
||||
}
|
||||
|
||||
setSettings(context, settings) {
|
||||
this._send({ event: 'setSettings', context, payload: settings });
|
||||
}
|
||||
|
||||
getSettings(context) {
|
||||
this._send({ event: 'getSettings', context });
|
||||
}
|
||||
|
||||
showAlert(context) {
|
||||
this._send({ event: 'showAlert', context });
|
||||
}
|
||||
|
||||
showOk(context) {
|
||||
this._send({ event: 'showOk', context });
|
||||
}
|
||||
|
||||
sendToPropertyInspector(action, context, payload) {
|
||||
this._send({ event: 'sendToPropertyInspector', action, context, payload });
|
||||
}
|
||||
|
||||
_send(message) {
|
||||
if (this.ws && this.ws.readyState === WS_OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { StreamDockHost, parseArgs };
|
||||
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* "Aktueller Titel" fuer die Info-Felder rechts am Geraet (Controller "Information"): ein
|
||||
* einzelnes quadratisches Bild - Cover als Hintergrund, unten Titel, Interpret und Fortschritt.
|
||||
*/
|
||||
|
||||
const { wrapTitle } = require('./actions');
|
||||
|
||||
const SIZE = 144;
|
||||
const BACKGROUND = '#171b24';
|
||||
const ACCENT = '#ff4d5e';
|
||||
const TRACK = '#3a4152';
|
||||
const MUTED_TEXT = '#c3c9d6';
|
||||
const BAR_X = 10;
|
||||
const BAR_WIDTH = SIZE - 2 * BAR_X;
|
||||
const BAR_Y = 132;
|
||||
const BAR_HEIGHT = 6;
|
||||
const TITLE_LINE_HEIGHT = 25;
|
||||
const TITLE_BASELINE_OFFSET = 7; // Schrifthoehe/3: bringt die optische Mitte der Zeile auf die Blockmitte
|
||||
const FONT = 'font-family="Segoe UI, Arial, sans-serif"';
|
||||
const XML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
|
||||
function escapeXml(text) {
|
||||
return String(text).replace(/[&<>"']/g, (char) => XML_ESCAPES[char]);
|
||||
}
|
||||
|
||||
function formatTime(seconds) {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return '0:00';
|
||||
const whole = Math.floor(seconds);
|
||||
return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function textLines(text, x, y, lineHeight, size, color, weight, anchor = 'middle') {
|
||||
return String(text).split('\n').filter(Boolean).map((line, index) => (
|
||||
`<text x="${x}" y="${y + index * lineHeight}" ${FONT} font-size="${size}" font-weight="${weight}" `
|
||||
+ `fill="${color}" text-anchor="${anchor}">${escapeXml(line)}</text>`)).join('');
|
||||
}
|
||||
|
||||
function noteMarkup(cx, cy, scale) {
|
||||
const s = scale;
|
||||
return `<circle cx="${cx - 9 * s}" cy="${cy + 14 * s}" r="${10 * s}" fill="${ACCENT}"/>`
|
||||
+ `<rect x="${cx - 1 * s}" y="${cy - 22 * s}" width="${6 * s}" height="${38 * s}" fill="${ACCENT}"/>`
|
||||
+ `<polygon points="${cx + 5 * s},${cy - 22 * s} ${cx + 24 * s},${cy - 12 * s} ${cx + 5 * s},${cy - 4 * s}" fill="${ACCENT}"/>`;
|
||||
}
|
||||
|
||||
function backgroundMarkup(coverDataUri) {
|
||||
if (!coverDataUri) return `<rect width="${SIZE}" height="${SIZE}" fill="${BACKGROUND}"/>${noteMarkup(72, 44, 1.1)}`;
|
||||
return `<rect width="${SIZE}" height="${SIZE}" fill="${BACKGROUND}"/>`
|
||||
+ `<image x="0" y="0" width="${SIZE}" height="${SIZE}" preserveAspectRatio="xMidYMid slice" href="${coverDataUri}"/>`;
|
||||
}
|
||||
|
||||
/** Abdunklung unten, damit Text auf jedem Cover lesbar bleibt. */
|
||||
function shadeMarkup() {
|
||||
return '<defs><linearGradient id="shade" x1="0" y1="0" x2="0" y2="1">'
|
||||
+ '<stop offset="0" stop-color="#000" stop-opacity="0"/><stop offset="0.35" stop-color="#000" stop-opacity="0.72"/>'
|
||||
+ '<stop offset="1" stop-color="#000" stop-opacity="0.9"/></linearGradient></defs>'
|
||||
+ `<rect x="0" y="30" width="${SIZE}" height="${SIZE - 30}" fill="url(#shade)"/>`;
|
||||
}
|
||||
|
||||
function playStateMarkup(playing) {
|
||||
const cx = 118;
|
||||
const cy = 26;
|
||||
const disc = `<circle cx="${cx}" cy="${cy}" r="19" fill="#000" fill-opacity="0.6"/>`;
|
||||
if (playing) {
|
||||
return `${disc}<rect x="${cx - 9}" y="${cy - 10}" width="6" height="20" fill="#fff"/>`
|
||||
+ `<rect x="${cx + 3}" y="${cy - 10}" width="6" height="20" fill="#fff"/>`;
|
||||
}
|
||||
return `${disc}<polygon points="${cx - 7},${cy - 11} ${cx + 11},${cy} ${cx - 7},${cy + 11}" fill="#fff"/>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} view - {title, subtitle, playing, currentTime, duration, coverDataUri}
|
||||
* oder null, wenn Playtube nicht verbunden ist
|
||||
* @returns {string} SVG-Text (144x144)
|
||||
*/
|
||||
function buildInfoSvg(view) {
|
||||
const head = `<svg xmlns="http://www.w3.org/2000/svg" width="${SIZE}" height="${SIZE}" viewBox="0 0 ${SIZE} ${SIZE}">`;
|
||||
if (!view) {
|
||||
return `${head}<rect width="${SIZE}" height="${SIZE}" fill="${BACKGROUND}"/>${noteMarkup(72, 44, 1.1)}`
|
||||
+ `${textLines('Playtube offline', 72, 120, 0, 14, '#ffffff', 'bold')}</svg>`;
|
||||
}
|
||||
const hasTrack = Boolean(view.title);
|
||||
const ratio = view.duration > 0 ? Math.max(0, Math.min(1, view.currentTime / view.duration)) : 0;
|
||||
const parts = [backgroundMarkup(view.coverDataUri), shadeMarkup()];
|
||||
if (hasTrack) {
|
||||
// Titel (und darunter der Interpret) als Block genau in der Bildmitte, mittig ausgerichtet.
|
||||
const title = wrapTitle(view.title, 10, 2);
|
||||
const lineCount = title.split('\n').length;
|
||||
const blockCenter = view.subtitle ? SIZE / 2 - 12 : SIZE / 2;
|
||||
const firstBaseline = blockCenter - ((lineCount - 1) * TITLE_LINE_HEIGHT) / 2 + TITLE_BASELINE_OFFSET;
|
||||
parts.push(textLines(title, SIZE / 2, firstBaseline, TITLE_LINE_HEIGHT, 22, '#ffffff', 'bold'));
|
||||
if (view.subtitle) {
|
||||
const subtitleY = firstBaseline + (lineCount - 1) * TITLE_LINE_HEIGHT + 27;
|
||||
parts.push(textLines(wrapTitle(view.subtitle, 13, 1), SIZE / 2, subtitleY, 0, 16, MUTED_TEXT, 'normal'));
|
||||
}
|
||||
parts.push(playStateMarkup(view.playing));
|
||||
} else {
|
||||
parts.push(textLines('Nichts spielt', 72, 120, 0, 14, '#ffffff', 'bold'));
|
||||
}
|
||||
parts.push(`<rect x="${BAR_X}" y="${BAR_Y}" width="${BAR_WIDTH}" height="${BAR_HEIGHT}" rx="3" fill="${TRACK}"/>`);
|
||||
parts.push(`<rect x="${BAR_X}" y="${BAR_Y}" width="${(BAR_WIDTH * ratio).toFixed(1)}" height="${BAR_HEIGHT}" rx="3" fill="${ACCENT}"/>`);
|
||||
return `${head}${parts.join('')}</svg>`;
|
||||
}
|
||||
|
||||
function svgToDataUri(svg) {
|
||||
return `data:image/svg+xml;base64,${Buffer.from(svg, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
module.exports = { buildInfoSvg, svgToDataUri, formatTime, SIZE };
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const MAX_BYTES = 512 * 1024;
|
||||
|
||||
/**
|
||||
* Sehr einfacher Datei-Logger (log/plugin.log neben dem Plugin). Wird beim Ueberschreiten von
|
||||
* 512 KB rotiert (plugin.log -> plugin.old.log). Logging darf das Plugin nie stoeren, jeder
|
||||
* Dateifehler wird geschluckt.
|
||||
*/
|
||||
function createLogger(directory) {
|
||||
const file = path.join(directory, 'plugin.log');
|
||||
let ready = false;
|
||||
|
||||
function ensure() {
|
||||
if (ready) return true;
|
||||
try {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
ready = true;
|
||||
} catch {
|
||||
ready = false;
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
function write(level, message) {
|
||||
if (!ensure()) return;
|
||||
try {
|
||||
try {
|
||||
if (fs.statSync(file).size > MAX_BYTES) fs.renameSync(file, path.join(directory, 'plugin.old.log'));
|
||||
} catch {
|
||||
// Datei existiert noch nicht - nichts zu rotieren
|
||||
}
|
||||
fs.appendFileSync(file, `${new Date().toISOString()} ${level} ${message}\n`);
|
||||
} catch {
|
||||
// Logging ist optional
|
||||
}
|
||||
}
|
||||
|
||||
const describe = (value) => (value instanceof Error ? value.stack || value.message : String(value));
|
||||
return {
|
||||
info: (message) => write('INFO ', describe(message)),
|
||||
warn: (message) => write('WARN ', describe(message)),
|
||||
error: (message) => write('ERROR', describe(message)),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createLogger };
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Einstiegspunkt des Plugins (wird von build.mjs zu plugin/index.js gebuendelt).
|
||||
* Stream Dock startet: node plugin/index.js -port P -pluginUUID U -registerEvent E -info {...}
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { StreamDockHost, parseArgs } = require('./host');
|
||||
const { PlaytubeClient } = require('./playtubeClient');
|
||||
const { Controller } = require('./controller');
|
||||
const { createLogger } = require('./logger');
|
||||
|
||||
const EXIT_GRACE_MS = 2000;
|
||||
|
||||
function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const logger = createLogger(path.join(__dirname, '..', 'log'));
|
||||
if (!args.port || !args.uuid || !args.registerEvent) {
|
||||
logger.error(`Ungueltige Startparameter: ${process.argv.slice(2).join(' ')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
process.on('uncaughtException', (error) => logger.error(error));
|
||||
process.on('unhandledRejection', (error) => logger.error(error));
|
||||
|
||||
const host = new StreamDockHost(args);
|
||||
// Nur fuer Tests: PLAYTUBE_PIPE_NAMES="a,b" ersetzt die Standard-Pipe-Namen.
|
||||
const pipeNames = process.env.PLAYTUBE_PIPE_NAMES ? process.env.PLAYTUBE_PIPE_NAMES.split(',') : undefined;
|
||||
const client = new PlaytubeClient({ pipeNames });
|
||||
const controller = new Controller({ host, client, logger });
|
||||
controller.start();
|
||||
|
||||
host.on('open', () => logger.info(`Bei Stream Dock registriert (Port ${args.port})`));
|
||||
host.on('error', (error) => logger.warn(`WebSocket-Fehler: ${error.message}`));
|
||||
host.on('close', () => {
|
||||
// Stream Dock beendet Plugins, indem es die Verbindung schliesst - dann sauber aufraeumen.
|
||||
logger.info('Verbindung zu Stream Dock beendet');
|
||||
controller.stop();
|
||||
setTimeout(() => process.exit(0), EXIT_GRACE_MS).unref();
|
||||
});
|
||||
host.connect();
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,233 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Client fuer die lokale Fernsteuerung von Playtube (playtube/remote_control.py).
|
||||
*
|
||||
* Transport: Named Pipe \\.\pipe\Playtube.Remote.<Datenordner> - "Playtube" (installierte
|
||||
* Playtube.exe) bzw. "PlaytubeDev" (python main.py). Nur der angemeldete Benutzer darf
|
||||
* verbinden. Protokoll: eine JSON-Nachricht pro Zeile (UTF-8, "\n"), Verbindung bleibt offen:
|
||||
*
|
||||
* -> {"id": 1, "cmd": "play_pause", "target": "auto"}
|
||||
* <- {"id": 1, "ok": true}
|
||||
* <- {"id": 2, "ok": false, "error": "..."}
|
||||
*
|
||||
* Der Client verbindet sich selbststaendig (auch wenn Playtube erst spaeter startet) und
|
||||
* baut die Verbindung nach einem Playtube-Neustart wieder auf.
|
||||
*/
|
||||
|
||||
const net = require('net');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { EventEmitter } = require('events');
|
||||
|
||||
const PIPE_PREFIX = 'Playtube.Remote.';
|
||||
// Installierte Version zuerst, dann der Entwicklungsmodus; danach die Edge-Variante (WebView2).
|
||||
const PIPE_NAMES = ['Playtube', 'PlaytubeDev', 'PlaytubeEdge', 'PlaytubeEdgeDev'];
|
||||
const MAX_BUFFER_CHARS = 1 << 20;
|
||||
|
||||
class PlaytubeError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.name = 'PlaytubeError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
function pipePath(name, platform = process.platform) {
|
||||
const full = PIPE_PREFIX + name;
|
||||
return platform === 'win32' ? `\\\\.\\pipe\\${full}` : path.join(os.tmpdir(), full);
|
||||
}
|
||||
|
||||
class PlaytubeClient extends EventEmitter {
|
||||
/**
|
||||
* @param {object} [options]
|
||||
* @param {string[]} [options.pipeNames]
|
||||
* @param {string} [options.platform]
|
||||
* @param {Function} [options.connect] - Ersatz fuer net.connect (Tests)
|
||||
* @param {number} [options.requestTimeoutMs]
|
||||
* @param {number[]} [options.backoffMs]
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
super();
|
||||
this.pipeNames = options.pipeNames || PIPE_NAMES;
|
||||
this.platform = options.platform || process.platform;
|
||||
this.connectFn = options.connect || net.connect;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 3000;
|
||||
this.backoffMs = options.backoffMs || [300, 600, 1200, 2500, 5000];
|
||||
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
this.pipeName = null;
|
||||
this.running = false;
|
||||
|
||||
this._nextId = 1;
|
||||
this._pending = new Map();
|
||||
this._buffer = '';
|
||||
this._failedRounds = 0;
|
||||
this._retryTimer = null;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this._attempt(0);
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.running = false;
|
||||
clearTimeout(this._retryTimer);
|
||||
this._retryTimer = null;
|
||||
const socket = this.socket;
|
||||
this.socket = null;
|
||||
if (this.connected) {
|
||||
this.connected = false;
|
||||
this._rejectAll(new PlaytubeError('stopped', 'Client gestoppt'));
|
||||
}
|
||||
if (socket) socket.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schickt einen Befehl und wartet auf die Antwort.
|
||||
* @param {string} cmd
|
||||
* @param {object} [fields] - target / value / playlist (undefined-Werte werden weggelassen)
|
||||
* @returns {Promise<object>} die komplette Antwort ({ok: true, ...})
|
||||
*/
|
||||
request(cmd, fields = {}) {
|
||||
if (!this.connected || !this.socket) {
|
||||
return Promise.reject(new PlaytubeError('not_connected', 'Playtube ist nicht verbunden'));
|
||||
}
|
||||
const id = this._nextId++;
|
||||
const payload = { id, cmd };
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
if (value !== undefined && value !== null) payload[key] = value;
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this._pending.delete(id);
|
||||
reject(new PlaytubeError('timeout', `Keine Antwort von Playtube auf "${cmd}"`));
|
||||
}, this.requestTimeoutMs);
|
||||
this._pending.set(id, { resolve, reject, timer });
|
||||
this.socket.write(`${JSON.stringify(payload)}\n`, (error) => {
|
||||
if (error && this._pending.delete(id)) {
|
||||
clearTimeout(timer);
|
||||
reject(new PlaytubeError('write_failed', error.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async status() {
|
||||
const response = await this.request('status');
|
||||
if (!response.state) throw new PlaytubeError('bad_response', 'Status ohne "state"');
|
||||
return response.state;
|
||||
}
|
||||
|
||||
async listPlaylists() {
|
||||
const response = await this.request('list_playlists');
|
||||
return Array.isArray(response.playlists) ? response.playlists : [];
|
||||
}
|
||||
|
||||
playPlaylist(playlistId) {
|
||||
return this.request('play_playlist', { playlist: playlistId });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ intern
|
||||
|
||||
_attempt(index) {
|
||||
if (!this.running) return;
|
||||
if (index >= this.pipeNames.length) {
|
||||
this._scheduleRetry();
|
||||
return;
|
||||
}
|
||||
const name = this.pipeNames[index];
|
||||
const socket = this.connectFn(pipePath(name, this.platform));
|
||||
let opened = false;
|
||||
socket.setEncoding('utf8');
|
||||
socket.once('connect', () => {
|
||||
if (!this.running) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
opened = true;
|
||||
this.socket = socket;
|
||||
this.connected = true;
|
||||
this.pipeName = name;
|
||||
this._failedRounds = 0;
|
||||
this._buffer = '';
|
||||
this.emit('connected', name);
|
||||
});
|
||||
socket.on('data', (chunk) => {
|
||||
if (socket === this.socket) this._onData(chunk);
|
||||
});
|
||||
socket.on('error', () => {
|
||||
// Folgt immer ein 'close' - dort wird weitergemacht.
|
||||
});
|
||||
socket.on('close', () => {
|
||||
if (!opened) {
|
||||
this._attempt(index + 1);
|
||||
} else if (socket === this.socket) {
|
||||
this._onLost();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_onLost() {
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
this.pipeName = null;
|
||||
this._rejectAll(new PlaytubeError('disconnected', 'Verbindung zu Playtube getrennt'));
|
||||
this.emit('disconnected');
|
||||
this._failedRounds = 0;
|
||||
this._scheduleRetry();
|
||||
}
|
||||
|
||||
_scheduleRetry() {
|
||||
if (!this.running) return;
|
||||
const delay = this.backoffMs[Math.min(this._failedRounds, this.backoffMs.length - 1)];
|
||||
this._failedRounds += 1;
|
||||
this._retryTimer = setTimeout(() => this._attempt(0), delay);
|
||||
}
|
||||
|
||||
_onData(chunk) {
|
||||
this._buffer += chunk;
|
||||
let newline;
|
||||
while ((newline = this._buffer.indexOf('\n')) >= 0) {
|
||||
const line = this._buffer.slice(0, newline).trim();
|
||||
this._buffer = this._buffer.slice(newline + 1);
|
||||
if (line) this._onLine(line);
|
||||
}
|
||||
if (this._buffer.length > MAX_BUFFER_CHARS) {
|
||||
// Kein Zeilenende in Sicht: Gegenstelle verhaelt sich falsch -> Verbindung neu aufbauen.
|
||||
this._buffer = '';
|
||||
if (this.socket) this.socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
_onLine(line) {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(line);
|
||||
} catch {
|
||||
return; // kaputte Zeile ignorieren, naechste abwarten
|
||||
}
|
||||
const entry = this._pending.get(message.id);
|
||||
if (!entry) return;
|
||||
this._pending.delete(message.id);
|
||||
clearTimeout(entry.timer);
|
||||
if (message.ok) {
|
||||
entry.resolve(message);
|
||||
} else {
|
||||
entry.reject(new PlaytubeError('remote', message.error || 'Fehler in Playtube'));
|
||||
}
|
||||
}
|
||||
|
||||
_rejectAll(error) {
|
||||
for (const entry of this._pending.values()) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(error);
|
||||
}
|
||||
this._pending.clear();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { PlaytubeClient, PlaytubeError, pipePath, PIPE_NAMES, PIPE_PREFIX };
|
||||
Reference in New Issue
Block a user