refactor: use Buffer.read* to parse payload

This commit is contained in:
sup39 2024-02-03 15:35:14 +09:00
parent 22f1b6e236
commit d9572b1d10
Signed by: sup39
GPG key ID: 111C00916C1641E5

View file

@ -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);
}