app.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. /*
  2. MeetRoom - Video conferencing WebApp
  3. author: tobychui / AI assisted
  4. Front-end for the mod/meetroom backend (src/meetroom.go). Media flows
  5. peer-to-peer over a WebRTC mesh; the ArozOS server only relays JSON
  6. signaling frames over /system/meetroom/ws and stores shared files.
  7. Connection model:
  8. - Each peer connection carries exactly one audio and one video
  9. transceiver, created up-front in sendrecv mode. Camera / screen
  10. tracks are attached with replaceTrack(), so toggling the camera
  11. or starting a screen share never needs SDP renegotiation.
  12. - The newcomer is always the offerer: on "welcome" it creates an
  13. offer to every existing peer; existing peers answer.
  14. Resilience:
  15. - An app-level ping/pong heartbeat detects half-dead sockets (e.g.
  16. a silently dropped network) and force-closes them.
  17. - When the signaling socket drops mid-meeting, the client keeps the
  18. room UI and local media alive and reconnects with capped
  19. exponential backoff. Reconnecting rejoins as a fresh peer, so the
  20. WebRTC mesh is rebuilt from the new "welcome" frame. If the room
  21. cannot be reached again within RECONNECT_WINDOW_MS (or no longer
  22. exists), the client gives up and returns to the lobby.
  23. */
  24. (function () {
  25. "use strict";
  26. var HEARTBEAT_INTERVAL_MS = 15000; //app-level ping cadence
  27. var HEARTBEAT_TIMEOUT_MS = 40000; //no pong for this long = dead socket
  28. var RECONNECT_WINDOW_MS = 60000; //give up reconnecting after this long
  29. var RECONNECT_MAX_DELAY_MS = 10000; //backoff cap between attempts
  30. var API = {
  31. create: "/system/meetroom/create",
  32. join: "/system/meetroom/join",
  33. info: "/system/meetroom/info",
  34. end: "/system/meetroom/end",
  35. ice: "/system/meetroom/iceservers",
  36. upload: "/system/meetroom/upload",
  37. attachfile: "/system/meetroom/attachfile",
  38. download: "/system/meetroom/download",
  39. ws: "/system/meetroom/ws"
  40. };
  41. //File extensions the chat renders inline as images; must match the
  42. //server-side raster whitelist (mod/sharedspace IsImageName)
  43. var IMAGE_EXTS = ["png", "jpg", "jpeg", "gif", "webp", "bmp"];
  44. var state = {
  45. ws: null,
  46. connected: false,
  47. myPeerId: -1,
  48. username: "",
  49. isHost: false,
  50. room: null, // {id, displayid, title, host, protected}
  51. password: "",
  52. peers: {}, // peerid -> peer record
  53. iceConfig: { iceServers: [{ urls: ["stun:stun.l.google.com:19302"] }] },
  54. localStream: null,
  55. camTrack: null,
  56. micTrack: null,
  57. screenStream: null,
  58. screenTrack: null,
  59. micOn: true,
  60. camOn: true,
  61. sharing: false,
  62. handRaised: false,
  63. handAt: {}, // peerid -> time (ms) the hand went up, for the raise queue order
  64. chatOpen: false,
  65. peopleOpen: false,
  66. statsOpen: false,
  67. unreadChat: 0,
  68. clockTimer: null,
  69. statsTimer: null,
  70. leaving: false,
  71. currentRoomId: "",
  72. reconnecting: false,
  73. reconnectDeadline: 0,
  74. reconnectAttempt: 0,
  75. reconnectTimer: null,
  76. heartbeatTimer: null,
  77. lastPong: 0
  78. };
  79. /* ================= Small helpers ================= */
  80. function $id(id) { return document.getElementById(id); }
  81. function escapeHtml(text) {
  82. var div = document.createElement("div");
  83. div.textContent = text;
  84. return div.innerHTML;
  85. }
  86. //For values placed inside HTML attributes: escapeHtml does not cover
  87. //quotes, so escape them explicitly to stay inside the attribute.
  88. function escapeAttr(text) {
  89. return escapeHtml(text).replace(/"/g, """).replace(/'/g, "'");
  90. }
  91. function formatBytes(bytes) {
  92. if (bytes < 1024) return bytes + " B";
  93. var units = ["KB", "MB", "GB"];
  94. var v = bytes;
  95. for (var i = 0; i < units.length; i++) {
  96. v = v / 1024;
  97. if (v < 1024 || i === units.length - 1) {
  98. return v.toFixed(1) + " " + units[i];
  99. }
  100. }
  101. }
  102. function copyText(text) {
  103. if (navigator.clipboard && navigator.clipboard.writeText) {
  104. navigator.clipboard.writeText(text);
  105. return;
  106. }
  107. var ta = document.createElement("textarea");
  108. ta.value = text;
  109. document.body.appendChild(ta);
  110. ta.select();
  111. document.execCommand("copy");
  112. document.body.removeChild(ta);
  113. }
  114. function showLobbyError(msg) {
  115. var box = $id("lobbyError");
  116. box.textContent = msg;
  117. box.style.display = msg ? "block" : "none";
  118. }
  119. function setWindowTitle(title) {
  120. document.title = title;
  121. if (typeof ao_module_setWindowTitle === "function") {
  122. try { ao_module_setWindowTitle(title); } catch (e) { }
  123. }
  124. }
  125. function isImageName(name) {
  126. var idx = name.lastIndexOf(".");
  127. if (idx < 0) return false;
  128. return IMAGE_EXTS.indexOf(name.substring(idx + 1).toLowerCase()) >= 0;
  129. }
  130. /* ================= Sound effects ================= */
  131. //Short synthesized chimes via WebAudio: no bundled audio assets needed.
  132. //The context is created lazily on the first join (a user gesture has
  133. //happened by then, so autoplay policies allow it).
  134. var audioCtx = null;
  135. function playChime(notes) {
  136. try {
  137. if (!audioCtx) {
  138. var Ctx = window.AudioContext || window.webkitAudioContext;
  139. if (!Ctx) return;
  140. audioCtx = new Ctx();
  141. }
  142. if (audioCtx.state === "suspended") {
  143. var resumed = audioCtx.resume();
  144. if (resumed && resumed.catch) resumed.catch(function () { });
  145. }
  146. var t = audioCtx.currentTime;
  147. notes.forEach(function (note) {
  148. var osc = audioCtx.createOscillator();
  149. var gain = audioCtx.createGain();
  150. osc.type = "sine";
  151. osc.frequency.value = note.freq;
  152. gain.gain.setValueAtTime(0.0001, t + note.at);
  153. gain.gain.linearRampToValueAtTime(0.12, t + note.at + 0.02);
  154. gain.gain.exponentialRampToValueAtTime(0.0001, t + note.at + note.len);
  155. osc.connect(gain);
  156. gain.connect(audioCtx.destination);
  157. osc.start(t + note.at);
  158. osc.stop(t + note.at + note.len + 0.05);
  159. });
  160. } catch (e) { }
  161. }
  162. function playJoinSound() {
  163. //Ascending two-note chime (C5 -> G5)
  164. playChime([
  165. { freq: 523.25, at: 0, len: 0.18 },
  166. { freq: 783.99, at: 0.13, len: 0.25 }
  167. ]);
  168. }
  169. function playLeaveSound() {
  170. //Descending two-note chime (E5 -> G4)
  171. playChime([
  172. { freq: 659.25, at: 0, len: 0.18 },
  173. { freq: 392.00, at: 0.13, len: 0.25 }
  174. ]);
  175. }
  176. function playHandSound() {
  177. //Gentle single note (A5) to flag a raised hand
  178. playChime([
  179. { freq: 880.00, at: 0, len: 0.22 }
  180. ]);
  181. }
  182. /* ================= Lobby actions ================= */
  183. $id("createBtn").addEventListener("click", function () {
  184. var btn = this;
  185. btn.classList.add("loading", "disabled");
  186. showLobbyError("");
  187. $.post(API.create, {
  188. title: $id("createTitle").value.trim(),
  189. password: $id("createPassword").value
  190. }, function (data) {
  191. btn.classList.remove("loading", "disabled");
  192. if (data.error !== undefined) {
  193. showLobbyError(data.error);
  194. return;
  195. }
  196. enterRoom(data.roomid, $id("createPassword").value);
  197. }, "json").fail(function () {
  198. btn.classList.remove("loading", "disabled");
  199. showLobbyError("Failed to create the meeting. Are you still logged in?");
  200. });
  201. });
  202. $id("joinBtn").addEventListener("click", function () {
  203. var btn = this;
  204. var roomid = $id("joinRoomId").value.trim();
  205. if (roomid === "") {
  206. showLobbyError("Please enter a meeting ID");
  207. return;
  208. }
  209. var password = $id("joinPassword").value;
  210. btn.classList.add("loading", "disabled");
  211. showLobbyError("");
  212. $.post(API.join, { roomid: roomid, password: password }, function (data) {
  213. btn.classList.remove("loading", "disabled");
  214. if (data.error !== undefined) {
  215. showLobbyError(data.error);
  216. return;
  217. }
  218. enterRoom(data.room.id, password);
  219. }, "json").fail(function () {
  220. btn.classList.remove("loading", "disabled");
  221. showLobbyError("Failed to join the meeting. Are you still logged in?");
  222. });
  223. });
  224. $id("joinRoomId").addEventListener("keyup", function (e) {
  225. if (e.key === "Enter") $id("joinPassword").focus();
  226. });
  227. $id("joinPassword").addEventListener("keyup", function (e) {
  228. if (e.key === "Enter") $id("joinBtn").click();
  229. });
  230. //Allow invite links of the form index.html#123456789
  231. if (location.hash.length > 1) {
  232. $id("joinRoomId").value = decodeURIComponent(location.hash.substring(1));
  233. }
  234. /* ================= Room setup ================= */
  235. function enterRoom(roomId, password) {
  236. state.password = password || "";
  237. state.leaving = false;
  238. fetch(API.ice).then(function (r) { return r.json(); }).then(function (cfg) {
  239. if (cfg && cfg.iceServers && cfg.iceServers.length > 0) {
  240. state.iceConfig = cfg;
  241. }
  242. }).catch(function () { }).then(function () {
  243. return acquireLocalMedia();
  244. }).then(function () {
  245. openSignalingSocket(roomId);
  246. });
  247. }
  248. //Try cam+mic, then mic only, then cam only; joining with no devices at
  249. //all is still allowed (view-only + chat + screen share).
  250. function acquireLocalMedia() {
  251. var constraints = [
  252. { video: true, audio: true },
  253. { audio: true },
  254. { video: true }
  255. ];
  256. var attempt = function (idx) {
  257. if (idx >= constraints.length) return Promise.resolve();
  258. return navigator.mediaDevices.getUserMedia(constraints[idx]).then(function (stream) {
  259. state.localStream = stream;
  260. state.micTrack = stream.getAudioTracks()[0] || null;
  261. state.camTrack = stream.getVideoTracks()[0] || null;
  262. }).catch(function () {
  263. return attempt(idx + 1);
  264. });
  265. };
  266. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  267. return Promise.resolve();
  268. }
  269. return attempt(0);
  270. }
  271. function openSignalingSocket(roomId) {
  272. state.currentRoomId = roomId;
  273. var proto = location.protocol === "https:" ? "wss://" : "ws://";
  274. var url = proto + location.host + API.ws +
  275. "?roomid=" + encodeURIComponent(roomId) +
  276. "&password=" + encodeURIComponent(state.password);
  277. var ws = new WebSocket(url);
  278. state.ws = ws;
  279. ws.onmessage = function (evt) {
  280. var msg;
  281. try { msg = JSON.parse(evt.data); } catch (e) { return; }
  282. handleServerMessage(msg);
  283. };
  284. ws.onclose = function () {
  285. stopHeartbeat();
  286. if (state.leaving) return;
  287. if (state.connected || state.reconnecting) {
  288. //Dropped mid-meeting (or a reconnect attempt failed):
  289. //keep the room alive and retry.
  290. beginReconnect();
  291. } else {
  292. showLobbyError("Could not join: the room may not exist or the password is wrong.");
  293. }
  294. };
  295. }
  296. function sendFrame(obj) {
  297. if (state.ws && state.ws.readyState === WebSocket.OPEN) {
  298. state.ws.send(JSON.stringify(obj));
  299. }
  300. }
  301. /* ================= Heartbeat & auto-reconnect ================= */
  302. function startHeartbeat() {
  303. stopHeartbeat();
  304. state.lastPong = Date.now();
  305. state.heartbeatTimer = setInterval(function () {
  306. if (Date.now() - state.lastPong > HEARTBEAT_TIMEOUT_MS) {
  307. //Half-dead socket: force-close so onclose starts reconnecting
  308. if (state.ws) { try { state.ws.close(); } catch (e) { } }
  309. return;
  310. }
  311. sendFrame({ type: "ping" });
  312. }, HEARTBEAT_INTERVAL_MS);
  313. }
  314. function stopHeartbeat() {
  315. if (state.heartbeatTimer) {
  316. clearInterval(state.heartbeatTimer);
  317. state.heartbeatTimer = null;
  318. }
  319. }
  320. function showReconnectBanner(show, text) {
  321. $id("reconnectBanner").style.display = show ? "" : "none";
  322. if (text) $id("reconnectText").textContent = text;
  323. }
  324. function beginReconnect() {
  325. if (!state.reconnecting) {
  326. //First drop: open the give-up window and freeze the mesh
  327. state.reconnecting = true;
  328. state.connected = false;
  329. state.reconnectDeadline = Date.now() + RECONNECT_WINDOW_MS;
  330. state.reconnectAttempt = 0;
  331. addSystemChat("Connection lost - trying to reconnect...");
  332. }
  333. scheduleReconnectAttempt();
  334. }
  335. function scheduleReconnectAttempt() {
  336. if (state.leaving || !state.reconnecting) return;
  337. if (Date.now() > state.reconnectDeadline) {
  338. giveUpReconnect("Connection to the meeting was lost and could not be re-established.");
  339. return;
  340. }
  341. state.reconnectAttempt++;
  342. var delay = Math.min(1000 * Math.pow(2, state.reconnectAttempt - 1), RECONNECT_MAX_DELAY_MS);
  343. showReconnectBanner(true, "Connection lost - reconnecting (attempt " + state.reconnectAttempt + ")...");
  344. state.reconnectTimer = setTimeout(tryReconnect, delay);
  345. }
  346. function tryReconnect() {
  347. if (state.leaving || !state.reconnecting) return;
  348. //Probe the room first: if the meeting ended (or was swept) while we
  349. //were offline there is nothing to reconnect to.
  350. fetch(API.info + "?roomid=" + encodeURIComponent(state.currentRoomId)).then(function (r) {
  351. return r.json();
  352. }).then(function (info) {
  353. if (state.leaving || !state.reconnecting) return;
  354. if (!info || info.exists === false) {
  355. giveUpReconnect("The meeting is no longer available.");
  356. return;
  357. }
  358. //Refresh the ICE config: built-in TURN credentials are
  359. //short-lived and may have expired while we were offline.
  360. fetch(API.ice).then(function (r) { return r.json(); }).then(function (cfg) {
  361. if (cfg && cfg.iceServers && cfg.iceServers.length > 0) {
  362. state.iceConfig = cfg;
  363. }
  364. }).catch(function () { }).then(function () {
  365. if (state.leaving || !state.reconnecting) return;
  366. openSignalingSocket(state.currentRoomId);
  367. });
  368. }).catch(function () {
  369. //Server unreachable: back off and retry within the window
  370. scheduleReconnectAttempt();
  371. });
  372. }
  373. function giveUpReconnect(msg) {
  374. state.reconnecting = false;
  375. state.leaving = true;
  376. cleanupRoom();
  377. showLobbyError(msg);
  378. }
  379. /* ================= Server messages ================= */
  380. function handleServerMessage(msg) {
  381. switch (msg.type) {
  382. case "welcome":
  383. var wasReconnect = state.reconnecting;
  384. state.reconnecting = false;
  385. if (state.reconnectTimer) {
  386. clearTimeout(state.reconnectTimer);
  387. state.reconnectTimer = null;
  388. }
  389. showReconnectBanner(false);
  390. state.connected = true;
  391. state.myPeerId = msg.peerid;
  392. state.username = msg.username;
  393. state.isHost = msg.isHost;
  394. state.room = msg.room;
  395. //Peer connections from before a drop are stale; rebuild the
  396. //mesh from scratch as the fresh peer the server sees us as.
  397. Object.keys(state.peers).forEach(function (peerId) {
  398. removePeer(peerId);
  399. });
  400. showRoomUI(wasReconnect);
  401. (msg.peers || []).forEach(function (peerInfo) {
  402. var peer = createPeerRecord(peerInfo);
  403. startOfferTo(peer);
  404. });
  405. startHeartbeat();
  406. broadcastState();
  407. updateParticipantCount();
  408. if (wasReconnect) {
  409. addSystemChat("Reconnected to the meeting");
  410. } else {
  411. playJoinSound();
  412. }
  413. break;
  414. case "pong":
  415. state.lastPong = Date.now();
  416. break;
  417. case "peer-join":
  418. createPeerRecord(msg.peer);
  419. addSystemChat(msg.peer.username + " joined the meeting");
  420. playJoinSound();
  421. broadcastState(); //let the newcomer learn our mute/cam state
  422. updateParticipantCount();
  423. refreshAttendance();
  424. break;
  425. case "peer-leave":
  426. removePeer(msg.peerid);
  427. addSystemChat(msg.username + (msg.kicked ? " was removed from the meeting" : " left the meeting"));
  428. playLeaveSound();
  429. updateParticipantCount();
  430. refreshAttendance();
  431. break;
  432. case "kicked":
  433. //The host removed us from the meeting. Stop reconnecting and
  434. //fall back to the lobby with a notice.
  435. state.leaving = true;
  436. cleanupRoom();
  437. showLobbyError("You have been removed from the meeting by the host.");
  438. break;
  439. case "signal":
  440. handleSignal(msg.from, msg.data);
  441. break;
  442. case "chat":
  443. addChatMessage(msg);
  444. break;
  445. case "file":
  446. addFileMessage(msg);
  447. break;
  448. case "state":
  449. updatePeerState(msg);
  450. break;
  451. case "attendance":
  452. renderAttendance(msg.records || []);
  453. break;
  454. case "room-closed":
  455. state.leaving = true;
  456. cleanupRoom();
  457. showLobbyError("The meeting has been ended by the host.");
  458. break;
  459. }
  460. }
  461. /* ================= Peer connections ================= */
  462. function createPeerRecord(info) {
  463. if (state.peers[info.peerid]) return state.peers[info.peerid];
  464. var peer = {
  465. info: info,
  466. pc: null,
  467. stream: new MediaStream(),
  468. senders: { audio: null, video: null },
  469. pendingCandidates: [],
  470. state: { audio: false, video: false, screen: false, hand: false }
  471. };
  472. state.peers[info.peerid] = peer;
  473. addVideoTile(info.peerid, info.username, false);
  474. return peer;
  475. }
  476. function buildPeerConnection(peer) {
  477. var pc = new RTCPeerConnection(state.iceConfig);
  478. peer.pc = pc;
  479. pc.onicecandidate = function (evt) {
  480. if (evt.candidate) {
  481. sendFrame({
  482. type: "signal",
  483. to: peer.info.peerid,
  484. data: { kind: "ice", candidate: evt.candidate }
  485. });
  486. }
  487. };
  488. pc.ontrack = function (evt) {
  489. peer.stream.addTrack(evt.track);
  490. attachStreamToTile(peer.info.peerid, peer.stream);
  491. };
  492. pc.onconnectionstatechange = function () {
  493. if (pc.connectionState === "failed") {
  494. try { pc.restartIce(); } catch (e) { }
  495. }
  496. };
  497. return pc;
  498. }
  499. function currentVideoTrack() {
  500. if (state.sharing && state.screenTrack) return state.screenTrack;
  501. return state.camTrack;
  502. }
  503. //Newcomer side: create both transceivers, attach local tracks, offer.
  504. function startOfferTo(peer) {
  505. var pc = buildPeerConnection(peer);
  506. var audioTx = pc.addTransceiver("audio", { direction: "sendrecv" });
  507. var videoTx = pc.addTransceiver("video", { direction: "sendrecv" });
  508. peer.senders.audio = audioTx.sender;
  509. peer.senders.video = videoTx.sender;
  510. if (state.micTrack) audioTx.sender.replaceTrack(state.micTrack);
  511. if (currentVideoTrack()) videoTx.sender.replaceTrack(currentVideoTrack());
  512. pc.createOffer().then(function (offer) {
  513. return pc.setLocalDescription(offer);
  514. }).then(function () {
  515. sendFrame({
  516. type: "signal",
  517. to: peer.info.peerid,
  518. data: { kind: "offer", sdp: pc.localDescription }
  519. });
  520. }).catch(function () { });
  521. }
  522. //Existing-member side: answer the newcomer's offer, reusing the
  523. //transceivers created by setRemoteDescription.
  524. function handleOffer(peer, sdp) {
  525. var pc = peer.pc || buildPeerConnection(peer);
  526. pc.setRemoteDescription(new RTCSessionDescription(sdp)).then(function () {
  527. pc.getTransceivers().forEach(function (tx) {
  528. var kind = tx.receiver && tx.receiver.track ? tx.receiver.track.kind : "";
  529. tx.direction = "sendrecv";
  530. if (kind === "audio") {
  531. peer.senders.audio = tx.sender;
  532. if (state.micTrack) tx.sender.replaceTrack(state.micTrack);
  533. } else if (kind === "video") {
  534. peer.senders.video = tx.sender;
  535. if (currentVideoTrack()) tx.sender.replaceTrack(currentVideoTrack());
  536. }
  537. });
  538. return pc.createAnswer();
  539. }).then(function (answer) {
  540. return pc.setLocalDescription(answer);
  541. }).then(function () {
  542. sendFrame({
  543. type: "signal",
  544. to: peer.info.peerid,
  545. data: { kind: "answer", sdp: pc.localDescription }
  546. });
  547. drainCandidates(peer);
  548. }).catch(function () { });
  549. }
  550. function handleSignal(fromPeerId, data) {
  551. if (!data || !data.kind) return;
  552. var peer = state.peers[fromPeerId];
  553. if (!peer) {
  554. //Offer can arrive before the peer-join broadcast is processed
  555. peer = createPeerRecord({ peerid: fromPeerId, username: "Guest", isHost: false });
  556. }
  557. if (data.kind === "offer") {
  558. handleOffer(peer, data.sdp);
  559. } else if (data.kind === "answer") {
  560. if (peer.pc) {
  561. peer.pc.setRemoteDescription(new RTCSessionDescription(data.sdp)).then(function () {
  562. drainCandidates(peer);
  563. }).catch(function () { });
  564. }
  565. } else if (data.kind === "ice") {
  566. if (peer.pc && peer.pc.remoteDescription) {
  567. peer.pc.addIceCandidate(new RTCIceCandidate(data.candidate)).catch(function () { });
  568. } else {
  569. peer.pendingCandidates.push(data.candidate);
  570. }
  571. }
  572. }
  573. function drainCandidates(peer) {
  574. var queued = peer.pendingCandidates;
  575. peer.pendingCandidates = [];
  576. queued.forEach(function (candidate) {
  577. peer.pc.addIceCandidate(new RTCIceCandidate(candidate)).catch(function () { });
  578. });
  579. }
  580. function removePeer(peerId) {
  581. var peer = state.peers[peerId];
  582. if (!peer) return;
  583. if (peer.pc) {
  584. try { peer.pc.close(); } catch (e) { }
  585. }
  586. delete state.peers[peerId];
  587. delete state.handAt[peerId];
  588. var tile = $id("tile-" + peerId);
  589. if (tile) tile.remove();
  590. }
  591. /* ================= Video tiles ================= */
  592. function addVideoTile(peerId, username, isLocal) {
  593. if ($id("tile-" + peerId)) return;
  594. var tile = document.createElement("div");
  595. tile.className = "video-tile no-video";
  596. tile.id = "tile-" + peerId;
  597. tile.innerHTML =
  598. '<video autoplay playsinline ' + (isLocal ? "muted" : "") + '></video>' +
  599. '<div class="tile-avatar">' + escapeHtml(username.substring(0, 1)) + '</div>' +
  600. '<div class="sharing-badge"><i class="desktop icon"></i> Sharing screen</div>' +
  601. '<div class="hand-badge" title="Hand raised"><i class="hand paper icon"></i></div>' +
  602. '<div class="tile-label">' +
  603. '<i class="microphone slash icon muted-icon" style="display:none;"></i>' +
  604. '<span class="label-name">' + escapeHtml(username) + (isLocal ? " (You)" : "") + '</span>' +
  605. '</div>';
  606. $id("videoGrid").appendChild(tile);
  607. }
  608. function attachStreamToTile(peerId, stream) {
  609. var tile = $id("tile-" + peerId);
  610. if (!tile) return;
  611. var video = tile.querySelector("video");
  612. if (video.srcObject !== stream) {
  613. video.srcObject = stream;
  614. }
  615. var p = video.play();
  616. if (p && p.catch) p.catch(function () { });
  617. }
  618. function setTileState(peerId, audioOn, videoOn, screenOn, handUp) {
  619. var tile = $id("tile-" + peerId);
  620. if (!tile) return;
  621. tile.classList.toggle("no-video", !videoOn);
  622. tile.classList.toggle("is-sharing", !!screenOn);
  623. tile.classList.toggle("hand-raised", !!handUp);
  624. tile.querySelector(".muted-icon").style.display = audioOn ? "none" : "";
  625. }
  626. function updatePeerState(msg) {
  627. var peer = state.peers[msg.from];
  628. if (!peer) return;
  629. var wasHandUp = peer.state.hand;
  630. //The first state frame from a peer is an initial sync (peers re-send
  631. //their state when anyone joins), so don't treat a hand already up as a
  632. //fresh raise - just reflect it on the tile.
  633. var firstSync = !peer.stateSynced;
  634. peer.stateSynced = true;
  635. peer.state = { audio: msg.audio, video: msg.video, screen: msg.screen, hand: !!msg.hand };
  636. setTileState(msg.from, msg.audio, msg.video, msg.screen, msg.hand);
  637. //Maintain the raise-hand queue order: stamp the first time we see a
  638. //hand up, clear it when lowered.
  639. if (msg.hand && !wasHandUp) {
  640. state.handAt[msg.from] = Date.now();
  641. } else if (!msg.hand) {
  642. delete state.handAt[msg.from];
  643. }
  644. if (msg.hand && !wasHandUp && !firstSync) {
  645. addSystemChat(peer.info.username + " raised their hand");
  646. playHandSound();
  647. }
  648. if (state.peopleOpen) refreshAttendance();
  649. }
  650. function updateParticipantCount() {
  651. $id("participantCount").textContent = String(Object.keys(state.peers).length + 1);
  652. }
  653. /* ================= Clock & meeting timer ================= */
  654. function pad2(n) { return n < 10 ? "0" + n : String(n); }
  655. //Render a second count as H:MM:SS, dropping the hours until they matter.
  656. function formatDuration(totalSeconds) {
  657. if (totalSeconds < 0) totalSeconds = 0;
  658. var h = Math.floor(totalSeconds / 3600);
  659. var m = Math.floor((totalSeconds % 3600) / 60);
  660. var s = totalSeconds % 60;
  661. return (h > 0 ? h + ":" + pad2(m) : pad2(m)) + ":" + pad2(s);
  662. }
  663. function tickClock() {
  664. var now = new Date();
  665. $id("systemClock").textContent = now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  666. if (state.room && state.room.createdat) {
  667. var elapsed = Math.floor(Date.now() / 1000) - state.room.createdat;
  668. $id("meetingElapsed").textContent = formatDuration(elapsed);
  669. }
  670. }
  671. function startClock() {
  672. stopClock();
  673. tickClock();
  674. state.clockTimer = setInterval(tickClock, 1000);
  675. }
  676. function stopClock() {
  677. if (state.clockTimer) {
  678. clearInterval(state.clockTimer);
  679. state.clockTimer = null;
  680. }
  681. }
  682. /* ================= Room UI ================= */
  683. function showRoomUI(isReconnect) {
  684. $id("lobby").style.display = "none";
  685. $id("room").style.display = "flex";
  686. $id("roomTitle").textContent = state.room.title;
  687. $id("roomIdText").textContent = state.room.displayid;
  688. $id("endBtn").style.display = state.isHost ? "" : "none";
  689. setWindowTitle("MeetRoom - " + state.room.title);
  690. //Local tile
  691. addVideoTile("local", state.username, true);
  692. if (state.localStream && !state.sharing) {
  693. attachStreamToTile("local", state.localStream);
  694. }
  695. if (!isReconnect) {
  696. //Keep the user's mute / camera choices across a reconnect
  697. state.micOn = !!state.micTrack;
  698. state.camOn = !!state.camTrack;
  699. }
  700. if (!state.micTrack) $id("micBtn").disabled = true;
  701. if (!state.camTrack) $id("camBtn").disabled = true;
  702. refreshControlButtons();
  703. refreshLocalTile();
  704. startClock();
  705. if (!isReconnect) {
  706. addSystemChat("You joined the meeting as " + state.username);
  707. }
  708. }
  709. function refreshLocalTile() {
  710. var videoOn = (state.camOn && !!state.camTrack) || state.sharing;
  711. setTileState("local", state.micOn && !!state.micTrack, videoOn, state.sharing, state.handRaised);
  712. }
  713. function refreshControlButtons() {
  714. var micBtn = $id("micBtn");
  715. micBtn.classList.toggle("ctrl-off", !(state.micOn && state.micTrack));
  716. micBtn.querySelector("i").className = (state.micOn && state.micTrack) ? "microphone icon" : "microphone slash icon";
  717. micBtn.querySelector("span").textContent = (state.micOn && state.micTrack) ? "Mute" : "Unmute";
  718. var camBtn = $id("camBtn");
  719. camBtn.classList.toggle("ctrl-off", !(state.camOn && state.camTrack));
  720. camBtn.querySelector("i").className = (state.camOn && state.camTrack) ? "video icon" : "video slash icon";
  721. var shareBtn = $id("shareBtn");
  722. shareBtn.classList.toggle("ctrl-active", state.sharing);
  723. shareBtn.querySelector("span").textContent = state.sharing ? "Stop" : "Share";
  724. var handBtn = $id("handBtn");
  725. handBtn.classList.toggle("ctrl-active", state.handRaised);
  726. handBtn.querySelector("i").className = state.handRaised ? "hand paper icon" : "hand paper outline icon";
  727. handBtn.querySelector("span").textContent = state.handRaised ? "Lower" : "Raise";
  728. }
  729. function broadcastState() {
  730. sendFrame({
  731. type: "state",
  732. audio: state.micOn && !!state.micTrack,
  733. video: (state.camOn && !!state.camTrack) || state.sharing,
  734. screen: state.sharing,
  735. hand: state.handRaised
  736. });
  737. }
  738. /* ================= Controls ================= */
  739. $id("micBtn").addEventListener("click", function () {
  740. if (!state.micTrack) return;
  741. state.micOn = !state.micOn;
  742. state.micTrack.enabled = state.micOn;
  743. refreshControlButtons();
  744. refreshLocalTile();
  745. broadcastState();
  746. });
  747. $id("camBtn").addEventListener("click", function () {
  748. if (!state.camTrack) return;
  749. state.camOn = !state.camOn;
  750. state.camTrack.enabled = state.camOn;
  751. refreshControlButtons();
  752. refreshLocalTile();
  753. broadcastState();
  754. });
  755. $id("shareBtn").addEventListener("click", function () {
  756. if (state.sharing) {
  757. stopScreenShare();
  758. } else {
  759. startScreenShare();
  760. }
  761. });
  762. $id("handBtn").addEventListener("click", function () {
  763. state.handRaised = !state.handRaised;
  764. if (state.handRaised) {
  765. state.handAt[state.myPeerId] = Date.now();
  766. } else {
  767. delete state.handAt[state.myPeerId];
  768. }
  769. refreshControlButtons();
  770. refreshLocalTile();
  771. broadcastState();
  772. if (state.peopleOpen) refreshAttendance();
  773. addSystemChat(state.handRaised ? "You raised your hand" : "You lowered your hand");
  774. if (state.handRaised) playHandSound();
  775. });
  776. function replaceOutgoingVideoTrack(track) {
  777. Object.keys(state.peers).forEach(function (peerId) {
  778. var peer = state.peers[peerId];
  779. if (peer.senders.video) {
  780. peer.senders.video.replaceTrack(track).catch(function () { });
  781. }
  782. });
  783. }
  784. function startScreenShare() {
  785. if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
  786. addSystemChat("Screen sharing is not supported by this browser");
  787. return;
  788. }
  789. navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }).then(function (stream) {
  790. state.screenStream = stream;
  791. state.screenTrack = stream.getVideoTracks()[0];
  792. state.sharing = true;
  793. state.screenTrack.onended = function () {
  794. if (state.sharing) stopScreenShare();
  795. };
  796. replaceOutgoingVideoTrack(state.screenTrack);
  797. //Preview the shared screen locally
  798. var preview = new MediaStream([state.screenTrack]);
  799. if (state.micTrack) preview.addTrack(state.micTrack);
  800. attachStreamToTile("local", preview);
  801. refreshControlButtons();
  802. refreshLocalTile();
  803. broadcastState();
  804. }).catch(function () { });
  805. }
  806. function stopScreenShare() {
  807. state.sharing = false;
  808. if (state.screenStream) {
  809. state.screenStream.getTracks().forEach(function (t) { t.stop(); });
  810. }
  811. state.screenStream = null;
  812. state.screenTrack = null;
  813. replaceOutgoingVideoTrack(state.camOn ? state.camTrack : null);
  814. if (state.localStream) {
  815. attachStreamToTile("local", state.localStream);
  816. }
  817. refreshControlButtons();
  818. refreshLocalTile();
  819. broadcastState();
  820. }
  821. /* ================= Invite dialog ================= */
  822. //Build a shareable link to this meeting. The lobby reads the room ID from
  823. //the URL hash on load (NormalizeRoomID strips the dashes), so the display
  824. //ID is fine to embed.
  825. function inviteLink() {
  826. return location.origin + location.pathname + "#" + state.room.displayid;
  827. }
  828. //Assemble the full invitation text, folding in the host's optional message.
  829. function buildInviteText() {
  830. var message = $id("inviteMessage").value.trim();
  831. var lines = [];
  832. if (message !== "") {
  833. lines.push(message, "");
  834. }
  835. lines.push("You're invited to a MeetRoom meeting" + (state.room.title ? ": " + state.room.title : ""));
  836. lines.push("Meeting ID: " + state.room.displayid);
  837. lines.push("Link: " + inviteLink());
  838. if (state.room.protected) {
  839. lines.push("(This meeting is password protected - the password will be shared separately.)");
  840. }
  841. return lines.join("\n");
  842. }
  843. function openInviteModal() {
  844. $id("inviteTitle").textContent = state.room.title || "Untitled meeting";
  845. $id("inviteId").textContent = state.room.displayid;
  846. $id("inviteLink").value = inviteLink();
  847. $id("invitePasswordNote").style.display = state.room.protected ? "" : "none";
  848. $id("inviteModal").style.display = "flex";
  849. }
  850. function closeInviteModal() {
  851. $id("inviteModal").style.display = "none";
  852. }
  853. //Flash a check mark on a copy button so the user sees the copy took
  854. function flashCopied(btn) {
  855. var icon = btn.querySelector("i");
  856. if (!icon || btn.dataset.flashing === "1") return;
  857. var original = icon.className;
  858. btn.dataset.flashing = "1";
  859. icon.className = "check icon";
  860. setTimeout(function () {
  861. icon.className = original;
  862. btn.dataset.flashing = "0";
  863. }, 1200);
  864. }
  865. $id("inviteBtn").addEventListener("click", openInviteModal);
  866. $id("inviteCloseBtn").addEventListener("click", closeInviteModal);
  867. $id("inviteModal").addEventListener("click", function (e) {
  868. //Click on the dimmed backdrop (not the card) closes the dialog
  869. if (e.target === this) closeInviteModal();
  870. });
  871. Array.prototype.forEach.call(document.querySelectorAll(".invite-copy-btn"), function (btn) {
  872. btn.addEventListener("click", function () {
  873. copyText(btn.dataset.copy === "link" ? inviteLink() : state.room.displayid);
  874. flashCopied(btn);
  875. });
  876. });
  877. $id("inviteCopyAllBtn").addEventListener("click", function () {
  878. copyText(buildInviteText());
  879. flashCopied(this);
  880. addSystemChat("Invitation copied to clipboard");
  881. });
  882. $id("roomIdTag").addEventListener("click", function () {
  883. copyText(state.room.displayid);
  884. addSystemChat("Meeting ID copied to clipboard");
  885. });
  886. $id("leaveBtn").addEventListener("click", function () {
  887. state.leaving = true;
  888. playLeaveSound();
  889. cleanupRoom();
  890. showLobbyError("");
  891. });
  892. $id("endBtn").addEventListener("click", function () {
  893. if (!confirm("End the meeting for all participants?")) return;
  894. sendFrame({ type: "end" });
  895. state.leaving = true;
  896. playLeaveSound();
  897. cleanupRoom();
  898. showLobbyError("");
  899. });
  900. window.addEventListener("beforeunload", function () {
  901. state.leaving = true;
  902. if (state.ws) { try { state.ws.close(); } catch (e) { } }
  903. });
  904. /* ================= Chat ================= */
  905. function toggleChat(open) {
  906. state.chatOpen = open;
  907. $id("chatPanel").style.display = open ? "flex" : "none";
  908. if (open) {
  909. if (state.peopleOpen) togglePeople(false);
  910. hideMessageToast();
  911. state.unreadChat = 0;
  912. $id("chatBadge").style.display = "none";
  913. $id("chatText").focus();
  914. scrollChat();
  915. }
  916. }
  917. $id("chatBtn").addEventListener("click", function () { toggleChat(!state.chatOpen); });
  918. $id("chatCloseBtn").addEventListener("click", function () { toggleChat(false); });
  919. /* ================= Participants & attendance ================= */
  920. function togglePeople(open) {
  921. state.peopleOpen = open;
  922. $id("peoplePanel").style.display = open ? "flex" : "none";
  923. if (open) {
  924. if (state.chatOpen) toggleChat(false);
  925. refreshAttendance();
  926. }
  927. }
  928. $id("peopleBtn").addEventListener("click", function () { togglePeople(!state.peopleOpen); });
  929. $id("peopleCloseBtn").addEventListener("click", function () { togglePeople(false); });
  930. //Host action: kick a participant. The list is re-rendered often, so the
  931. //click is handled by delegation on the stable container.
  932. $id("attendanceList").addEventListener("click", function (e) {
  933. var btn = e.target.closest ? e.target.closest(".kick-btn") : null;
  934. if (!btn) return;
  935. var peerId = parseInt(btn.dataset.peerid, 10);
  936. var name = btn.dataset.name || "this participant";
  937. if (isNaN(peerId)) return;
  938. if (!confirm("Remove " + name + " from the meeting?")) return;
  939. sendFrame({ type: "kick", to: peerId });
  940. });
  941. //Ask the server for the join/leave log; the reply arrives as an
  942. //"attendance" frame and lands in renderAttendance()
  943. function refreshAttendance() {
  944. if (!state.peopleOpen) return;
  945. sendFrame({ type: "attendance" });
  946. }
  947. function attendanceTime(unixTime) {
  948. return new Date(unixTime * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  949. }
  950. //Is the participant behind this present attendance record raising a hand?
  951. function recordHandRaised(record) {
  952. if (!record.present) return false;
  953. if (record.peerid === state.myPeerId) return state.handRaised;
  954. var peer = state.peers[record.peerid];
  955. return !!(peer && peer.state && peer.state.hand);
  956. }
  957. function attendanceEntry(record) {
  958. var entry = document.createElement("div");
  959. entry.className = "attendance-entry" + (record.present ? " present" : "");
  960. var times = record.present
  961. ? "joined " + attendanceTime(record.joinedat)
  962. : attendanceTime(record.joinedat) + " - " + attendanceTime(record.leftat);
  963. var isHostRecord = state.room && record.username === state.room.host;
  964. var handUp = recordHandRaised(record);
  965. //The host can remove any present participant other than themselves
  966. var canKick = state.isHost && record.present && !isHostRecord && record.peerid !== state.myPeerId;
  967. entry.innerHTML =
  968. '<i class="' + (record.present ? "user icon" : "sign-out icon") + '"></i>' +
  969. '<span class="attendee-name">' + escapeHtml(record.username) + '</span>' +
  970. (isHostRecord ? '<span class="host-tag">Host</span>' : "") +
  971. (handUp ? '<i class="hand paper icon hand-indicator" title="Hand raised"></i>' : "") +
  972. '<span class="attendee-times">' + escapeHtml(times) + '</span>' +
  973. (canKick
  974. ? '<button class="kick-btn" data-peerid="' + record.peerid + '" data-name="' + escapeAttr(record.username) + '" title="Remove from meeting"><i class="user times icon"></i></button>'
  975. : "");
  976. return entry;
  977. }
  978. //Build the raise-hand queue: everyone currently present with a hand up,
  979. //ordered by when they raised it (earliest first).
  980. function raisedHandQueue(present) {
  981. return present.filter(recordHandRaised).sort(function (a, b) {
  982. return (state.handAt[a.peerid] || 0) - (state.handAt[b.peerid] || 0);
  983. });
  984. }
  985. function handQueueEntry(record, position) {
  986. var entry = document.createElement("div");
  987. entry.className = "hand-queue-entry";
  988. var isSelf = record.peerid === state.myPeerId;
  989. entry.innerHTML =
  990. '<span class="hand-queue-pos">' + position + '</span>' +
  991. '<i class="hand paper icon hand-indicator"></i>' +
  992. '<span class="attendee-name">' + escapeHtml(record.username) + (isSelf ? " (You)" : "") + '</span>';
  993. return entry;
  994. }
  995. function renderAttendance(records) {
  996. var box = $id("attendanceList");
  997. box.innerHTML = "";
  998. var present = records.filter(function (r) { return r.present; });
  999. var past = records.filter(function (r) { return !r.present; });
  1000. //Raised-hand queue first, so the speaking order is front and centre
  1001. var raised = raisedHandQueue(present);
  1002. if (raised.length > 0) {
  1003. var groupHands = document.createElement("div");
  1004. groupHands.className = "attendance-group";
  1005. groupHands.textContent = "Raised hands (" + raised.length + ")";
  1006. box.appendChild(groupHands);
  1007. raised.forEach(function (record, i) { box.appendChild(handQueueEntry(record, i + 1)); });
  1008. }
  1009. var groupPresent = document.createElement("div");
  1010. groupPresent.className = "attendance-group";
  1011. groupPresent.textContent = "In meeting (" + present.length + ")";
  1012. box.appendChild(groupPresent);
  1013. present.forEach(function (record) { box.appendChild(attendanceEntry(record)); });
  1014. if (past.length > 0) {
  1015. var groupPast = document.createElement("div");
  1016. groupPast.className = "attendance-group";
  1017. groupPast.textContent = "Left the meeting (" + past.length + ")";
  1018. box.appendChild(groupPast);
  1019. past.forEach(function (record) { box.appendChild(attendanceEntry(record)); });
  1020. }
  1021. }
  1022. /* ================= Connection performance ================= */
  1023. function toggleStats(open) {
  1024. state.statsOpen = open;
  1025. $id("statsBtn").classList.toggle("ctrl-active", open);
  1026. $id("statsPanel").style.display = open ? "flex" : "none";
  1027. if (open) {
  1028. startStatsPolling();
  1029. } else {
  1030. stopStatsPolling();
  1031. }
  1032. }
  1033. $id("statsBtn").addEventListener("click", function () { toggleStats(!state.statsOpen); });
  1034. $id("statsCloseBtn").addEventListener("click", function () { toggleStats(false); });
  1035. //Let the user drag the floating stats window around the meeting. Uses
  1036. //pointer events so it works with both mouse and touch; the header keeps
  1037. //the pointer capture so dragging continues even if it briefly leaves it.
  1038. (function makeStatsDraggable() {
  1039. var panel = $id("statsPanel");
  1040. var handle = $id("statsHeader");
  1041. var dragging = false, startX = 0, startY = 0, startLeft = 0, startTop = 0;
  1042. handle.addEventListener("pointerdown", function (e) {
  1043. if (e.target.closest && e.target.closest(".stats-close")) return;
  1044. var parent = panel.offsetParent || panel.parentElement;
  1045. var rect = panel.getBoundingClientRect();
  1046. var pr = parent.getBoundingClientRect();
  1047. startLeft = rect.left - pr.left;
  1048. startTop = rect.top - pr.top;
  1049. startX = e.clientX;
  1050. startY = e.clientY;
  1051. //Switch from the CSS right-anchor to explicit left/top so drags move it
  1052. panel.style.left = startLeft + "px";
  1053. panel.style.top = startTop + "px";
  1054. panel.style.right = "auto";
  1055. dragging = true;
  1056. try { handle.setPointerCapture(e.pointerId); } catch (err) { }
  1057. e.preventDefault();
  1058. });
  1059. handle.addEventListener("pointermove", function (e) {
  1060. if (!dragging) return;
  1061. var parent = panel.offsetParent || panel.parentElement;
  1062. var maxL = Math.max(0, parent.clientWidth - panel.offsetWidth);
  1063. var maxT = Math.max(0, parent.clientHeight - panel.offsetHeight);
  1064. panel.style.left = Math.max(0, Math.min(startLeft + (e.clientX - startX), maxL)) + "px";
  1065. panel.style.top = Math.max(0, Math.min(startTop + (e.clientY - startY), maxT)) + "px";
  1066. });
  1067. var endDrag = function (e) {
  1068. if (!dragging) return;
  1069. dragging = false;
  1070. try { handle.releasePointerCapture(e.pointerId); } catch (err) { }
  1071. };
  1072. handle.addEventListener("pointerup", endDrag);
  1073. handle.addEventListener("pointercancel", endDrag);
  1074. })();
  1075. function startStatsPolling() {
  1076. stopStatsPolling();
  1077. collectAndRenderStats();
  1078. state.statsTimer = setInterval(collectAndRenderStats, 2000);
  1079. }
  1080. function stopStatsPolling() {
  1081. if (state.statsTimer) {
  1082. clearInterval(state.statsTimer);
  1083. state.statsTimer = null;
  1084. }
  1085. }
  1086. function formatBitrate(kbps) {
  1087. if (kbps >= 1000) return (kbps / 1000).toFixed(1) + " Mbps";
  1088. return kbps + " kbps";
  1089. }
  1090. //Reduce a peer connection's raw getStats() report to the handful of
  1091. //numbers worth showing, turning cumulative byte counters into a live
  1092. //bitrate by diffing against the previous sample.
  1093. function summarizePeerStats(peer, report) {
  1094. var now = (window.performance && performance.now) ? performance.now() : Date.now();
  1095. var bytesRecv = 0, bytesSent = 0, packetsRecv = 0, packetsLost = 0, rttMs = null;
  1096. report.forEach(function (r) {
  1097. if (r.type === "inbound-rtp" && !r.isRemote) {
  1098. bytesRecv += r.bytesReceived || 0;
  1099. packetsRecv += r.packetsReceived || 0;
  1100. packetsLost += r.packetsLost || 0;
  1101. } else if (r.type === "outbound-rtp" && !r.isRemote) {
  1102. bytesSent += r.bytesSent || 0;
  1103. } else if (r.type === "candidate-pair" && (r.nominated || r.state === "succeeded") &&
  1104. typeof r.currentRoundTripTime === "number") {
  1105. rttMs = Math.round(r.currentRoundTripTime * 1000);
  1106. }
  1107. });
  1108. var last = peer._lastStats;
  1109. var recvKbps = 0, sentKbps = 0;
  1110. if (last && now > last.t) {
  1111. var dt = (now - last.t) / 1000;
  1112. recvKbps = Math.max(0, Math.round((bytesRecv - last.bytesRecv) * 8 / 1000 / dt));
  1113. sentKbps = Math.max(0, Math.round((bytesSent - last.bytesSent) * 8 / 1000 / dt));
  1114. }
  1115. peer._lastStats = { t: now, bytesRecv: bytesRecv, bytesSent: bytesSent };
  1116. var totalPackets = packetsRecv + packetsLost;
  1117. return {
  1118. username: peer.info.username,
  1119. recvKbps: recvKbps,
  1120. sentKbps: sentKbps,
  1121. rttMs: rttMs,
  1122. lossPct: totalPackets > 0 ? (packetsLost / totalPackets) * 100 : 0
  1123. };
  1124. }
  1125. function collectAndRenderStats() {
  1126. if (!state.statsOpen) return;
  1127. var peerIds = Object.keys(state.peers);
  1128. var promises = peerIds.map(function (peerId) {
  1129. var peer = state.peers[peerId];
  1130. if (!peer.pc || !peer.pc.getStats) return Promise.resolve(null);
  1131. return peer.pc.getStats().then(function (report) {
  1132. return summarizePeerStats(peer, report);
  1133. }).catch(function () { return null; });
  1134. });
  1135. Promise.all(promises).then(function (results) {
  1136. renderStats(results.filter(function (r) { return r; }));
  1137. });
  1138. }
  1139. //Classify a link by round-trip time and loss so a colour can flag it
  1140. function linkQuality(s) {
  1141. if (s.rttMs === null) return "";
  1142. if (s.rttMs < 150 && s.lossPct < 2) return "good";
  1143. if (s.rttMs < 300 && s.lossPct < 5) return "fair";
  1144. return "poor";
  1145. }
  1146. function renderStats(list) {
  1147. var box = $id("statsBody");
  1148. if (!state.connected) {
  1149. box.innerHTML = '<div class="stats-empty">Not connected.</div>';
  1150. return;
  1151. }
  1152. if (list.length === 0) {
  1153. box.innerHTML = '<div class="stats-empty">No peer connections yet - stats appear once someone else joins.</div>';
  1154. return;
  1155. }
  1156. var totalRecv = 0, totalSent = 0;
  1157. list.forEach(function (s) { totalRecv += s.recvKbps; totalSent += s.sentKbps; });
  1158. var html = '<div class="stats-summary">' +
  1159. '<div class="stats-summary-item"><i class="download icon"></i><strong>' + formatBitrate(totalRecv) + '</strong><span>received</span></div>' +
  1160. '<div class="stats-summary-item"><i class="upload icon"></i><strong>' + formatBitrate(totalSent) + '</strong><span>sent</span></div>' +
  1161. '</div>';
  1162. list.forEach(function (s) {
  1163. var quality = linkQuality(s);
  1164. html += '<div class="stats-peer">' +
  1165. '<div class="stats-peer-name">' + escapeHtml(s.username) +
  1166. (quality ? '<span class="stats-quality ' + quality + '">' + quality + '</span>' : "") +
  1167. '</div>' +
  1168. '<div class="stats-peer-metrics">' +
  1169. '<span title="Receiving from this peer"><i class="download icon"></i>' + formatBitrate(s.recvKbps) + '</span>' +
  1170. '<span title="Sending to this peer"><i class="upload icon"></i>' + formatBitrate(s.sentKbps) + '</span>' +
  1171. '<span title="Round-trip time"><i class="stopwatch icon"></i>' + (s.rttMs === null ? "-" : s.rttMs + " ms") + '</span>' +
  1172. '<span title="Packet loss"><i class="exclamation triangle icon"></i>' + s.lossPct.toFixed(1) + '%</span>' +
  1173. '</div>' +
  1174. '</div>';
  1175. });
  1176. box.innerHTML = html;
  1177. }
  1178. /* ================= New message popup ================= */
  1179. var toastTimer = null;
  1180. function showMessageToast(title, body) {
  1181. if (state.chatOpen) return; //already reading the chat
  1182. var toast = $id("msgToast");
  1183. toast.querySelector(".toast-title span").textContent = title;
  1184. toast.querySelector(".toast-body").textContent = body;
  1185. toast.style.display = "block";
  1186. if (toastTimer) clearTimeout(toastTimer);
  1187. toastTimer = setTimeout(hideMessageToast, 6000);
  1188. }
  1189. function hideMessageToast() {
  1190. if (toastTimer) {
  1191. clearTimeout(toastTimer);
  1192. toastTimer = null;
  1193. }
  1194. $id("msgToast").style.display = "none";
  1195. }
  1196. $id("msgToast").addEventListener("click", function () {
  1197. hideMessageToast();
  1198. toggleChat(true);
  1199. });
  1200. function sendChat() {
  1201. var input = $id("chatText");
  1202. var text = input.value.trim();
  1203. if (text === "") return;
  1204. if (!state.ws || state.ws.readyState !== WebSocket.OPEN) {
  1205. //Keep the draft in the input so nothing is lost mid-reconnect
  1206. addSystemChat("Reconnecting - message not sent, please retry in a moment");
  1207. return;
  1208. }
  1209. sendFrame({ type: "chat", text: text });
  1210. input.value = "";
  1211. }
  1212. $id("chatSendBtn").addEventListener("click", sendChat);
  1213. $id("chatText").addEventListener("keyup", function (e) {
  1214. if (e.key === "Enter") sendChat();
  1215. });
  1216. function bumpUnread() {
  1217. if (state.chatOpen) return;
  1218. state.unreadChat++;
  1219. var badge = $id("chatBadge");
  1220. badge.textContent = state.unreadChat > 9 ? "9+" : String(state.unreadChat);
  1221. badge.style.display = "";
  1222. }
  1223. function appendChatNode(node) {
  1224. $id("chatMessages").appendChild(node);
  1225. scrollChat();
  1226. }
  1227. function scrollChat() {
  1228. var box = $id("chatMessages");
  1229. box.scrollTop = box.scrollHeight;
  1230. }
  1231. function chatTimestamp(unixTime) {
  1232. var d = unixTime ? new Date(unixTime * 1000) : new Date();
  1233. return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  1234. }
  1235. function addChatMessage(msg) {
  1236. var own = msg.from === state.myPeerId;
  1237. var node = document.createElement("div");
  1238. node.className = "chat-msg" + (own ? " own" : "");
  1239. node.innerHTML =
  1240. '<div class="msg-meta">' + escapeHtml(msg.username) + " - " + chatTimestamp(msg.time) + '</div>' +
  1241. '<div class="msg-body">' + escapeHtml(msg.text) + '</div>';
  1242. appendChatNode(node);
  1243. if (!own) {
  1244. bumpUnread();
  1245. showMessageToast(msg.username, msg.text);
  1246. }
  1247. }
  1248. function addFileMessage(msg) {
  1249. var own = msg.from === state.myPeerId;
  1250. var href = API.download +
  1251. "?roomid=" + encodeURIComponent(state.room.id) +
  1252. "&password=" + encodeURIComponent(state.password) +
  1253. "&fileid=" + encodeURIComponent(msg.fileid);
  1254. var node = document.createElement("div");
  1255. node.className = "chat-msg" + (own ? " own" : "");
  1256. //Images render inline so nobody has to download them; clicking the
  1257. //preview opens the full-size image in a new tab (inline=1 keeps the
  1258. //browser from forcing a download). Everything else stays a link.
  1259. var body;
  1260. if (isImageName(msg.name)) {
  1261. var inlineHref = href + "&inline=1";
  1262. body =
  1263. '<a target="_blank" rel="noopener" href="' + inlineHref + '" title="Open full size">' +
  1264. '<img class="chat-image" src="' + inlineHref + '" alt="' + escapeAttr(msg.name) + '">' +
  1265. '</a>' +
  1266. '<a class="file-link" href="' + href + '" download>' +
  1267. '<i class="download icon"></i>' + escapeHtml(msg.name) +
  1268. '</a> <span class="file-size">(' + formatBytes(msg.size) + ')</span>';
  1269. } else {
  1270. body =
  1271. '<a class="file-link" target="_blank" rel="noopener" href="' + href + '" download>' +
  1272. '<i class="file outline icon"></i>' + escapeHtml(msg.name) +
  1273. '</a> <span class="file-size">(' + formatBytes(msg.size) + ')</span>';
  1274. }
  1275. node.innerHTML =
  1276. '<div class="msg-meta">' + escapeHtml(msg.username) + " - " + chatTimestamp(msg.time) + '</div>' +
  1277. '<div class="msg-body">' + body + '</div>';
  1278. appendChatNode(node);
  1279. var preview = node.querySelector(".chat-image");
  1280. if (preview) {
  1281. //Keep the newest message visible once the preview finishes loading
  1282. preview.addEventListener("load", scrollChat);
  1283. }
  1284. if (!own) {
  1285. bumpUnread();
  1286. showMessageToast(msg.username, "Shared " + (isImageName(msg.name) ? "an image: " : "a file: ") + msg.name);
  1287. }
  1288. }
  1289. function addSystemChat(text) {
  1290. var node = document.createElement("div");
  1291. node.className = "chat-msg system";
  1292. node.innerHTML = '<div class="msg-body">' + escapeHtml(text) + '</div>';
  1293. appendChatNode(node);
  1294. }
  1295. /* ================= Attachments ================= */
  1296. function toggleAttachMenu(open) {
  1297. $id("attachMenu").style.display = open ? "block" : "none";
  1298. }
  1299. //The attach button opens a small menu: upload a local file, or pick a
  1300. //file the user already has in their ArozOS storage.
  1301. $id("attachBtn").addEventListener("click", function (e) {
  1302. e.stopPropagation();
  1303. toggleAttachMenu($id("attachMenu").style.display === "none");
  1304. });
  1305. //Any click elsewhere dismisses the menu
  1306. document.addEventListener("click", function () { toggleAttachMenu(false); });
  1307. $id("attachMenu").addEventListener("click", function (e) { e.stopPropagation(); });
  1308. $id("attachDeviceBtn").addEventListener("click", function () {
  1309. toggleAttachMenu(false);
  1310. $id("attachInput").click();
  1311. });
  1312. $id("attachArozosBtn").addEventListener("click", function () {
  1313. toggleAttachMenu(false);
  1314. if (typeof ao_module_openFileSelector !== "function") {
  1315. addSystemChat("ArozOS file picker is only available inside the ArozOS desktop");
  1316. return;
  1317. }
  1318. //ao_module_openFileSelector needs a window-scoped callback name; the
  1319. //selector hands back an array of {filepath, filename}.
  1320. ao_module_openFileSelector("meetroomArozFilesSelected", "user:/", "file", true);
  1321. });
  1322. //Called back by the ArozOS file selector (must live on window)
  1323. window.meetroomArozFilesSelected = function (files) {
  1324. if (!files || files.length === 0) return;
  1325. Array.prototype.forEach.call(files, function (f) {
  1326. attachArozosPath(f.filepath, f.filename);
  1327. });
  1328. };
  1329. //Stream a file that already lives in the user's ArozOS storage into the
  1330. //room without downloading it to the browser first: the server reads it
  1331. //straight from the user's file system (see /system/meetroom/attachfile).
  1332. function attachArozosPath(vpath, displayName) {
  1333. if (!state.ws || state.ws.readyState !== WebSocket.OPEN) {
  1334. addSystemChat("Reconnecting - please try sharing the file again in a moment");
  1335. return;
  1336. }
  1337. var name = displayName || vpath.split("/").pop();
  1338. var form = new FormData();
  1339. form.append("roomid", state.room.id);
  1340. form.append("password", state.password);
  1341. form.append("path", vpath);
  1342. $id("uploadStatus").style.display = "";
  1343. $id("uploadStatusText").textContent = "Sharing " + name + "...";
  1344. fetch(API.attachfile, { method: "POST", body: form }).then(function (r) {
  1345. return r.json();
  1346. }).then(function (data) {
  1347. $id("uploadStatus").style.display = "none";
  1348. if (data.error !== undefined) {
  1349. addSystemChat("Could not share " + name + ": " + data.error);
  1350. return;
  1351. }
  1352. sendFrame({ type: "file", fileid: data.fileid });
  1353. }).catch(function () {
  1354. $id("uploadStatus").style.display = "none";
  1355. addSystemChat("Could not share " + name);
  1356. });
  1357. }
  1358. //Upload a file (or pasted image blob) and announce it to the room
  1359. function uploadAndAnnounce(file, displayName) {
  1360. if (!file) return;
  1361. if (!state.ws || state.ws.readyState !== WebSocket.OPEN) {
  1362. addSystemChat("Reconnecting - please try sharing the file again in a moment");
  1363. return;
  1364. }
  1365. var name = displayName || file.name;
  1366. var form = new FormData();
  1367. form.append("roomid", state.room.id);
  1368. form.append("password", state.password);
  1369. form.append("file", file, name);
  1370. $id("uploadStatus").style.display = "";
  1371. $id("uploadStatusText").textContent = "Uploading " + name + "...";
  1372. fetch(API.upload, { method: "POST", body: form }).then(function (r) {
  1373. return r.json();
  1374. }).then(function (data) {
  1375. $id("uploadStatus").style.display = "none";
  1376. if (data.error !== undefined) {
  1377. addSystemChat("Upload failed: " + data.error);
  1378. return;
  1379. }
  1380. sendFrame({ type: "file", fileid: data.fileid });
  1381. }).catch(function () {
  1382. $id("uploadStatus").style.display = "none";
  1383. addSystemChat("Upload failed");
  1384. });
  1385. }
  1386. $id("attachInput").addEventListener("change", function () {
  1387. var file = this.files[0];
  1388. this.value = "";
  1389. uploadAndAnnounce(file);
  1390. });
  1391. //Ctrl+V in the meeting attaches a copied image (screenshot, copied
  1392. //picture, ...) to the chat
  1393. document.addEventListener("paste", function (e) {
  1394. if (!state.connected) return;
  1395. var items = (e.clipboardData && e.clipboardData.items) || [];
  1396. for (var i = 0; i < items.length; i++) {
  1397. if (items[i].kind !== "file" || items[i].type.indexOf("image/") !== 0) continue;
  1398. var blob = items[i].getAsFile();
  1399. if (!blob) continue;
  1400. e.preventDefault();
  1401. if (!state.chatOpen) toggleChat(true);
  1402. var ext = (items[i].type.split("/")[1] || "png").split("+")[0];
  1403. uploadAndAnnounce(blob, "pasted-image-" + Date.now() + "." + ext);
  1404. return;
  1405. }
  1406. });
  1407. /* ================= Teardown ================= */
  1408. function cleanupRoom() {
  1409. stopHeartbeat();
  1410. stopClock();
  1411. stopStatsPolling();
  1412. if (state.reconnectTimer) {
  1413. clearTimeout(state.reconnectTimer);
  1414. state.reconnectTimer = null;
  1415. }
  1416. state.reconnecting = false;
  1417. state.currentRoomId = "";
  1418. showReconnectBanner(false);
  1419. if (state.ws) {
  1420. var ws = state.ws;
  1421. state.ws = null;
  1422. try { ws.onclose = null; ws.close(); } catch (e) { }
  1423. }
  1424. Object.keys(state.peers).forEach(function (peerId) {
  1425. removePeer(peerId);
  1426. });
  1427. if (state.localStream) {
  1428. state.localStream.getTracks().forEach(function (t) { t.stop(); });
  1429. }
  1430. if (state.screenStream) {
  1431. state.screenStream.getTracks().forEach(function (t) { t.stop(); });
  1432. }
  1433. state.localStream = null;
  1434. state.camTrack = null;
  1435. state.micTrack = null;
  1436. state.screenStream = null;
  1437. state.screenTrack = null;
  1438. state.sharing = false;
  1439. state.handRaised = false;
  1440. state.handAt = {};
  1441. state.connected = false;
  1442. state.myPeerId = -1;
  1443. state.room = null;
  1444. state.password = "";
  1445. state.unreadChat = 0;
  1446. $id("videoGrid").innerHTML = "";
  1447. $id("chatMessages").innerHTML = "";
  1448. $id("attendanceList").innerHTML = "";
  1449. $id("chatBadge").style.display = "none";
  1450. $id("micBtn").disabled = false;
  1451. $id("camBtn").disabled = false;
  1452. hideMessageToast();
  1453. toggleChat(false);
  1454. togglePeople(false);
  1455. toggleStats(false);
  1456. //Return the floating stats window to its default corner for next time
  1457. var sp = $id("statsPanel");
  1458. sp.style.left = "";
  1459. sp.style.top = "";
  1460. sp.style.right = "";
  1461. closeInviteModal();
  1462. toggleAttachMenu(false);
  1463. $id("room").style.display = "none";
  1464. $id("lobby").style.display = "flex";
  1465. setWindowTitle("MeetRoom");
  1466. }
  1467. })();