eplace/src/rooms/canvas/index.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

2026-05-16 13:38:37 +02:00
import { authedAPIRequest } from "../../utils/auth";
2026-05-16 16:15:40 +02:00
/**
* @param {string} room
* @return {Promise<Object?>} The response Json object
*/
async function fetchCanvas(room) {
2026-05-16 13:38:37 +02:00
if (!room) {
console.error("Cannot fetch canvas of an undefined room");
return null;
}
const response = await authedAPIRequest("/rooms/" + room + "/canvas", {
method: "GET",
});
if (!response.ok) {
console.error("Could not retrieve room canvas: " + response.statusText);
console.debug(await response.text());
return null;
}
const res = await response.json();
console.debug(`Retrieved canvas for room ${room}:`);
2026-05-16 16:15:40 +02:00
// console.debug(res);
2026-05-16 13:38:37 +02:00
return res;
}
2026-05-16 16:15:40 +02:00
// Splits a string into fixed length substrings
String.prototype.chunk = function(size) {
return [].concat.apply([],
this.split('').map(function(x,i){ return i%size ? [] : this.slice(i,i+size) }, this)
)
}
// get the canvas of a room and deserialize it
async function getCanvas(room) {
const raw_pixels = await fetchCanvas(room);
if (!raw_pixels || !raw_pixels.pixels) {
console.error("Aborting canvas deserialization")
return null;
}
// Convert to a an array of strings representing binary (beurk)
let raw_binary_str = ""
for (let i = 0; i < raw_pixels.pixels.length; i++) {
raw_binary_str = raw_binary_str.concat(raw_pixels.pixels.charCodeAt(i).toString(2).padStart(8, "0"))
}
// console.debug(raw_binary_str)
// Chunk it to an array of fixed-length string (5)
let pixel_array = raw_binary_str.chunk(5)
if (pixel_array[pixel_array.length-1].length < 5)
pixel_array.pop()
// console.debug(pixel_array)
// Convert into numbers
pixel_array = pixel_array.map((pixel) => parseInt( pixel, 2 ))
// console.debug(pixel_array)
return pixel_array
}
2026-05-16 13:38:37 +02:00
// subscribe to the stream of a room
function subscribeToRoom() {}
2026-05-16 16:15:40 +02:00
2026-05-16 13:38:37 +02:00
// get the pixel info of a room
function getPixelInfo() {}
2026-05-16 16:15:40 +02:00
2026-05-16 13:38:37 +02:00
// place a pixel in a room
function placePixel() {}
export { getCanvas, subscribeToRoom, getPixelInfo, placePixel };