All files / server text0wnz.js

28.16% Statements 40/142
15% Branches 12/80
25% Functions 4/16
27.33% Lines 38/139

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279  3x 3x       3x 3x   3x 3x 3x   3x 1x 1x 1x     1x 1x 1x       1x     3x         3x 1x 1x     1x           1x 1x                     1x     1x         1x 1x             1x 1x 1x               1x       1x                 3x                                           3x               3x               3x                                       3x               3x                                                                                                                                                                                       3x                                                  
import path from 'path';
import { existsSync, mkdirSync } from 'fs';
import { readFile, writeFile } from 'fs';
import { load, save } from './fileio.js';
import { callout, sanitize, createTimestampedFilename } from './utils.js';
 
const SESSION_DIR = path.resolve('./sessions');
const userList = {};
let imageData;
let chat = [];
let debug = false;
let sessionName = 'joint'; // Default session name
 
const initialize = config => {
	sessionName = config.sessionName;
	debug = config.debug || false;
	Iif (debug) {
		console.log('* Initializing text0wnz with session name:', sessionName);
	}
	Eif (!existsSync(SESSION_DIR)) {
		mkdirSync(SESSION_DIR, { recursive: true });
		Iif (debug) {
			console.log('* Creating session directory:', SESSION_DIR);
		}
	}
	loadSession();
};
 
const log = msg => {
	const logMsg = sanitize(msg, 100, false);
	debug ? callout(logMsg) : console.log(`* ${logMsg}`);
};
 
const loadSession = () => {
	const chatFile = path.join(SESSION_DIR, `${sessionName}.json`);
	const binFile = path.join(SESSION_DIR, `${sessionName}.bin`);
 
	// Validate and sanitize file paths
	Iif (!chatFile.startsWith(SESSION_DIR) || !binFile.startsWith(SESSION_DIR)) {
		console.error('[Error] Invalid session file path');
		return;
	}
 
	// Load chat history
	readFile(chatFile, 'utf8', (err, data) => {
		Iif (!err) {
			try {
				chat = JSON.parse(data).chat;
				if (debug) {
					console.log('* Loaded chat history from:', chatFile);
				}
			} catch (parseErr) {
				console.error('[Error] parsing chat file:', sanitize(parseErr));
				chat = [];
			}
		} else {
			Iif (debug) {
				console.log('* No existing chat file found, starting with empty chat');
			}
			chat = [];
		}
	});
 
	// Load or create canvas data
	load(binFile, loadedImageData => {
		Iif (loadedImageData !== undefined) {
			imageData = loadedImageData;
			if (debug) {
				console.log('* Loaded canvas data from:', binFile);
			}
		} else {
			// create default
			const c = 80;
			const r = 50;
			imageData = {
				columns: c,
				rows: r,
				data: new Uint16Array(c * r),
				iceColors: false,
				letterSpacing: false,
				fontName: 'CP437 8x16', // Default font
			};
			Iif (debug) {
				console.log(`* Created default canvas: `, c + 'x' + r);
			}
			// Save the new session file
			save(binFile, imageData, () => {
				if (debug) {
					console.log('* Created new session file:', binFile);
				}
			});
		}
	});
};
 
const sendToAll = (clients, msg) => {
	const message = JSON.stringify(msg);
	let suffix = 'client';
	if (clients.size > 1) {
		suffix += 's';
	}
	if (debug) {
		console.log('[Broadcasting]', sanitize(msg[0]), 'to', clients.size, suffix);
	}
 
	clients.forEach(client => {
		try {
			if (client.readyState === 1) {
				// WebSocket.OPEN
				client.send(message);
			}
		} catch (e) {
			console.error('[Error] sending to client:', sanitize(e));
		}
	});
};
 
const saveSessionWithTimestamp = callback => {
	const binTime = path.join(
		SESSION_DIR,
		createTimestampedFilename(sessionName, 'bin'),
	);
	save(binTime, imageData, callback);
};
 
const saveSession = callback => {
	const chatFile = path.join(SESSION_DIR, `${sessionName}.json`);
	const binFile = path.join(SESSION_DIR, `${sessionName}.bin`);
	writeFile(chatFile, JSON.stringify({ chat: chat }), () => {
		save(binFile, imageData, callback);
	});
};
 
const getStart = sessionID => {
	if (!imageData) {
		console.error('! ImageData not initialized');
		return JSON.stringify(['error', 'Server not ready']);
	}
	return JSON.stringify([
		'start',
		{
			columns: imageData.columns,
			rows: imageData.rows,
			letterSpacing: imageData.letterSpacing,
			iceColors: imageData.iceColors,
			fontName: imageData.fontName || 'CP437 8x16', // Include font with fallback
			chat: chat,
		},
		sessionID,
		userList,
	]);
};
 
const getImageData = () => {
	if (!imageData) {
		console.error('! ImageData not initialized');
		return { data: new Uint16Array(0) };
	}
	return imageData;
};
 
const message = (msg, sessionID, clients) => {
	if (!imageData) {
		console.error('! ImageData not initialized, ignoring message');
		return;
	}
 
	switch (msg[0]) {
		case 'join': {
			const handle = sanitize(msg[1], 100, false);
			log(`${handle} has joined`);
			userList[sessionID] = handle;
			msg[1] = handle;
			msg.push(sessionID);
			break;
		}
		case 'nick': {
			const oldHandle = sanitize(
				userList[sessionID] || 'Anonymous',
				100,
				false,
			);
			const newHandle = sanitize(msg[1], 100, false);
			console.log(
				`> ${oldHandle.replace(/\n|\r/g, '')} is now ${newHandle.replace(/\n|\r/g, '')}`,
			);
			userList[sessionID] = newHandle;
			msg[1] = newHandle;
			msg.push(sessionID);
			break;
		}
		case 'chat': {
			const handle = sanitize(userList[sessionID] || 'Anonymous', 100, false);
			const chatText = sanitize(msg[1], 140, false);
			msg.splice(1, 0, handle);
			msg[2] = chatText;
			chat.push([handle, chatText]);
			if (chat.length > 128) {
				chat.shift();
			}
			break;
		}
		case 'draw':
			msg[1].forEach(block => {
				imageData.data[block >> 16] = block & 0xffff;
			});
			break;
		case 'resize':
			if (msg[1] && msg[1].columns && msg[1].rows) {
				console.log(
					'[Server] Set canvas size:',
					`${Number(msg[1].columns)}x${Number(msg[1].rows)}`,
				);
				imageData.columns = msg[1].columns;
				imageData.rows = msg[1].rows;
				// Resize the data array
				const newSize = msg[1].columns * msg[1].rows;
				const newData = new Uint16Array(newSize);
				const copyLength = Math.min(imageData.data.length, newSize);
				for (let i = 0; i < copyLength; i++) {
					newData[i] = imageData.data[i];
				}
				imageData.data = newData;
			}
			break;
		case 'fontChange':
			if (msg[1] && Object.hasOwn(msg[1], 'fontName')) {
				console.log('[Server] updated font');
				imageData.fontName = msg[1].fontName;
			}
			break;
		case 'iceColorsChange':
			if (msg[1] && Object.hasOwn(msg[1], 'iceColors')) {
				console.log('[Server] updated ice colors');
				imageData.iceColors =
					typeof msg[1].iceColors === 'boolean' ? msg[1].iceColors : false;
			}
			break;
		case 'letterSpacingChange':
			if (msg[1] && Object.hasOwn(msg[1], 'letterSpacing')) {
				console.log('[Server] updated letter spacing');
				imageData.letterSpacing =
					typeof msg[1].letterSpacing === 'boolean'
						? msg[1].letterSpacing
						: false;
			}
			break;
		default:
			break;
	}
	sendToAll(clients, msg);
};
 
const closeSession = (sessionID, clients) => {
	if (userList[sessionID] !== undefined) {
		log(`${sanitize(userList[sessionID], 100, false)} has quit.`);
		delete userList[sessionID];
	}
	sendToAll(clients, ['part', sessionID]);
};
export {
	initialize,
	saveSessionWithTimestamp,
	saveSession,
	getStart,
	getImageData,
	message,
	closeSession,
};
export default {
	initialize,
	saveSessionWithTimestamp,
	saveSession,
	getStart,
	getImageData,
	message,
	closeSession,
};