From d9572b1d1037f91d4a0bf36d0c62a2bc81eaaf18 Mon Sep 17 00:00:00 2001 From: sup39 Date: Sat, 3 Feb 2024 15:35:14 +0900 Subject: [PATCH] refactor: use `Buffer.read*` to parse payload --- index.js | 36 +++++++++++++++--------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/index.js b/index.js index 72644fd..bf4129a 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,7 @@ // ==UserScript== // @name sup-ytsync // @namespace https://forgejo.sup39.dev/sup39/sup-ytsync/ -// @version 2024-01-30 +// @version 2024-02-03 // @description A script to sync Youtube video progress with others via MQTT // @author sup39 // @match https://www.youtube.com/watch* @@ -65,9 +65,6 @@ }; } - // FIXME - const Buffer = /** @type{Buffer}*//**@type{any}*/(Uint8Array); - const videoId = new URLSearchParams(window.location.search).get('v'); if (videoId == null) return; @@ -92,12 +89,12 @@ const client = mqtt.connect(url, {username, password, clientId}); client.on('error', e => console.warn('Error occurs on MQTT connection:', e)); - /** @param {DataView} body */ - function parseTime(body) { - if (body.byteLength !== 8) { + /** @param {Buffer} payload */ + function parseTime(payload) { + if (payload.byteLength !== 8) { throw new Error('Invalid payload'); } - return body.getFloat64(0); + return payload.readDoubleBE(0); } client.on('connect', () => { @@ -106,12 +103,16 @@ const video = Video(videoElement, (command, state) => { const {currentTime: t} = state; console.debug(`Broadcast video sync command [${command}]`, t); - const payload = new Buffer(8); + const payload = new Uint8Array(8); new DataView(payload.buffer).setFloat64(0, t); - client.publish(`${topicPrefix}${clientId}/${command}`, payload); + client.publish( + `${topicPrefix}${clientId}/${command}`, + // FIXME + /**@type{Buffer}*/(/**@type{unknown}*/(payload)), + ); }); - client.on('message', (/**@type{string}*/topic, /**@type{Uint8Array}*/payload) => { + client.on('message', (topic, payload) => { if (!topic.startsWith(topicPrefix)) { return console.warn('Unexpected MQTT message', {topic, payload}); } @@ -119,21 +120,14 @@ // ignore command sent by self if (commander === clientId) return; - /** DataView of payload */ - const body = new DataView( - payload.buffer, - payload.byteOffset, - payload.byteLength, - ); - try { if (command === 'play') { - const t = parseTime(body); + const t = parseTime(payload); console.debug(`Received command [${command}]`, t); video.seek(t); video.play(); } else if (command === 'pause') { - const t = parseTime(body); + const t = parseTime(payload); console.debug(`Received command [${command}]`, t); video.seek(t); video.pause(); @@ -145,7 +139,7 @@ * => need to update current time */ if (video.isPaused) { - const t = parseTime(body); + const t = parseTime(payload); console.debug(`Received command [${command}]`, t); video.seek(t); }