From c9702dded7bc16ba99c6f41db0f277ed23ed6cf6 Mon Sep 17 00:00:00 2001 From: Cynthia Foxwell Date: Thu, 26 May 2022 22:58:31 -0600 Subject: [PATCH] plant that actually works --- src/modules/utsuholights.js | 46 ++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/src/modules/utsuholights.js b/src/modules/utsuholights.js index 33ba5cb..1aa16d9 100644 --- a/src/modules/utsuholights.js +++ b/src/modules/utsuholights.js @@ -49,17 +49,51 @@ utsuholights.callback = async function (msg, line, hex, bri) { }; hf.registerCommand(utsuholights); +const JPEG_HEADER = Buffer.from([ + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, +]); + +async function fetchPlant() { + const res = await fetch("https://nuclear.utsuho.rocks/plant/"); + const boundary = res.headers + .get("Content-Type") + .split(";")[1] + .trim() + .replace("boundary=", "--"); + let buffer = Buffer.alloc(0); + + let searchForNextBoundary = false; + return await new Promise((resolve) => { + res.body.on("data", function (data) { + if (!searchForNextBoundary) { + if (data.toString().startsWith(boundary)) { + buffer = Buffer.concat([buffer, data]); + searchForNextBoundary = true; + } + } else if (searchForNextBoundary) { + if (data.toString().startsWith(boundary)) { + res.body.end(); + const length = Number( + buffer.toString().match(/Content-Length:.*?(\d+)/)[1] + ); + const headerOffset = buffer.indexOf(JPEG_HEADER); + const data = buffer.slice(headerOffset, headerOffset + length); + + resolve(data); + } else { + buffer = Buffer.concat([buffer, data]); + } + } + }); + }); +} + const plant = new Command("plant"); plant.category = CATEGORY; plant.helpText = "Plant cam"; plant.callback = async function () { try { - const image = Buffer.from( - await fetch("https://nuclear.utsuho.rocks/plant/").then((res) => - res.arrayBuffer() - ) - ); - return {file: {file: image, name: "plant.jpg"}}; + return {file: {file: await fetchPlant(), name: "plant.jpg"}}; } catch (err) { return "<:trollhollow:851301241417498704> where plant (Encountered an error getting plant cam)"; }