@ywkrlerche/richardwho 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/app.js +928 -87
  2. package/config.js +0 -1
  3. package/games.json +1 -1
  4. package/index.html +121 -10
  5. package/logos/kh-100ng.webp +0 -0
  6. package/logos/kh-2048-multitask.webp +0 -0
  7. package/logos/kh-adrenalinechallenge.webp +0 -0
  8. package/logos/kh-align-4.webp +0 -0
  9. package/logos/kh-amidst-the-clouds.webp +0 -0
  10. package/logos/kh-angry-sharks.webp +0 -0
  11. package/logos/kh-avalanche.webp +0 -0
  12. package/logos/kh-battleforgondor.webp +0 -0
  13. package/logos/kh-blacholesquare.webp +0 -0
  14. package/logos/kh-blackknight.webp +0 -0
  15. package/logos/kh-boxhead2play.webp +0 -0
  16. package/logos/kh-btd4.webp +0 -0
  17. package/logos/kh-burger-and-frights.webp +0 -0
  18. package/logos/kh-canyondefense.webp +0 -0
  19. package/logos/kh-championarcher.webp +0 -0
  20. package/logos/kh-creativekillchamber.webp +0 -0
  21. package/logos/kh-csgo-clicker.webp +0 -0
  22. package/logos/kh-dante.webp +0 -0
  23. package/logos/kh-deal-or-no-deal.webp +0 -0
  24. package/logos/kh-deepest-sword.webp +0 -0
  25. package/logos/kh-defend-the-tank.webp +0 -0
  26. package/logos/kh-doge2048.webp +0 -0
  27. package/logos/kh-edgenotfound.webp +0 -0
  28. package/logos/kh-endlesswar3.webp +0 -0
  29. package/logos/kh-evolution.webp +0 -0
  30. package/logos/kh-exo.webp +0 -0
  31. package/logos/kh-fairsquares.webp +0 -0
  32. package/logos/kh-flappy-2048.webp +0 -0
  33. package/logos/kh-flashtetris.webp +0 -0
  34. package/logos/kh-flippy-fish.webp +0 -0
  35. package/logos/kh-froggys-battle.webp +0 -0
  36. package/logos/kh-gachalife.webp +0 -0
  37. package/logos/kh-generic-fishing-game.webp +0 -0
  38. package/logos/kh-geojump.webp +0 -0
  39. package/logos/kh-gimme-the-airpod.webp +0 -0
  40. package/logos/kh-google-snake.webp +0 -0
  41. package/logos/kh-hardware-tycoon.webp +0 -0
  42. package/logos/kh-hba.webp +0 -0
  43. package/logos/kh-hexempire.webp +0 -0
  44. package/logos/kh-hexgl.webp +0 -0
  45. package/logos/kh-hextris.webp +0 -0
  46. package/logos/kh-just-one-boss.webp +0 -0
  47. package/logos/kh-kittencannon.webp +0 -0
  48. package/logos/kh-mario.webp +0 -0
  49. package/logos/kh-marvinspectrum.webp +0 -0
  50. package/logos/kh-matrixrampage.webp +0 -0
  51. package/logos/kh-meme2048.webp +0 -0
  52. package/logos/kh-my-rusty-submarine.webp +0 -0
  53. package/logos/kh-noob-steve-parkour.webp +0 -0
  54. package/logos/kh-ns-shaft.webp +0 -0
  55. package/logos/kh-offlineparadise.webp +0 -0
  56. package/logos/kh-out-of-ctrl.webp +0 -0
  57. package/logos/kh-pandemic2.webp +0 -0
  58. package/logos/kh-particle-clicker.webp +0 -0
  59. package/logos/kh-poom.webp +0 -0
  60. package/package.json +1 -1
  61. package/style.css +125 -10
package/app.js CHANGED
@@ -293,7 +293,7 @@
293
293
  function startGameHtml(game, html) {
294
294
  if (currentLoad?.id !== game.id) return;
295
295
  if (game.src === "gn" && !game.embed) html = stripTracking(html);
296
- html = guardHistory(html);
296
+ html = guardHistory(pinCdn(html), game.base);
297
297
  const doc = freshFrame().contentDocument;
298
298
  doc.open();
299
299
  doc.write(html);
@@ -354,6 +354,16 @@
354
354
  }
355
355
 
356
356
  // The extra collection's launch files embed Google Analytics; remove it so players aren't tracked
357
+ // Many games load their files from other people's GitHub repos through jsDelivr using a branch
358
+ // (@main). jsDelivr refuses branch links into repos over 50 MB unless the file happens to be cached,
359
+ // so those games break at random. games.json's cdnPins maps "owner/repo@branch" to a fixed commit.
360
+ let cdnPins = {};
361
+ function pinCdn(html) {
362
+ return html.replace(/(cdn|fastly)\.jsdelivr\.net\/gh\/([\w.-]+\/[\w.-]+?)(?:@([\w.-]+))?\//g, (all, host, repo, ref) => {
363
+ const sha = cdnPins[`${repo}@${ref || ""}`];
364
+ return sha ? `${host}.jsdelivr.net/gh/${repo}@${sha}/` : all;
365
+ });
366
+ }
357
367
  function stripTracking(html) {
358
368
  return html
359
369
  .replace(/<script\b[^>]*googletagmanager\.com[^>]*>\s*<\/script>/gi, "")
@@ -367,9 +377,11 @@
367
377
  // Insert only at the very top of the file (after an optional doctype and <html> tag). Searching for the
368
378
  // first "<head>" anywhere is unsafe: many self-unpacking games keep their whole page inside a script string,
369
379
  // and inserting there cuts that string in half.
370
- function guardHistory(html) {
380
+ // Folder games (game.base): a <base> tag makes the page's images, scripts and sounds load from its folder
381
+ function guardHistory(html, base) {
371
382
  const top = html.match(/^(?\s*(?:<!--[\s\S]*?-->\s*)*(?:<!doctype[^>]*>)?\s*(?:<html\b[^>]*>)?)/i)[1];
372
- return top + HISTORY_GUARD + html.slice(top.length);
383
+ const baseTag = base ? `<base href="${base.replace(/"/g, "&quot;")}">` : "";
384
+ return top + baseTag + HISTORY_GUARD + html.slice(top.length);
373
385
  }
374
386
 
375
387
  function stopGame() {
@@ -394,11 +406,11 @@
394
406
  }
395
407
 
396
408
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
397
- const VIEW_ORDER = ["home", "games", "chat", "stats", "settings", "changelog"];
409
+ const VIEW_ORDER = ["home", "games", "chat", "stats", "live", "settings", "changelog"];
398
410
  let lastView = null;
399
411
  function viewFor(hash) {
400
412
  return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat"
401
- : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : "home";
413
+ : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : hash === "#live" ? "live" : "home";
402
414
  }
403
415
  // Switching pages: the old page slides out while the new one slides in (down the side bar = upward,
404
416
  // up the side bar = downward). Uses the browser's view transitions; older browsers just switch.
@@ -408,12 +420,14 @@
408
420
  !matchMedia("(prefers-reduced-motion: reduce)").matches;
409
421
  if (!animate) { routeNow(); after?.(); return; }
410
422
  document.documentElement.dataset.navDir = VIEW_ORDER.indexOf(next) < VIEW_ORDER.indexOf(lastView) ? "up" : "down";
411
- document.startViewTransition(() => { routeNow(); after?.(); });
423
+ const t = document.startViewTransition(() => { routeNow(); after?.(); });
424
+ t.ready.catch(() => {}); // a quick second click skips the first slide: harmless, so don't report it as an error
412
425
  }
413
426
  function routeNow() {
414
427
  const m = location.hash.match(/^#play\/(.+)$/);
415
428
  const game = m && byId.get(decodeURIComponent(m[1]));
416
429
  if (game) {
430
+ if (live.viewer) stopWatching(); // a game covers the Live page: stop the stream's sound too
417
431
  els.player.hidden = false;
418
432
  document.body.classList.add("playing");
419
433
  addRecent(game.id);
@@ -437,6 +451,9 @@
437
451
  lastView = view;
438
452
  $("view-stats").hidden = view !== "stats";
439
453
  $("view-changelog").hidden = view !== "changelog";
454
+ $("view-live").hidden = view !== "live";
455
+ if (view === "live") { openChat(); renderLive(); }
456
+ else if (live.viewer) stopWatching(); // leaving the Live page stops the stream (and its sound); Watch live rejoins
440
457
  if (view === "changelog") renderChangelog();
441
458
  placeChatBox();
442
459
  if (view === "settings") { renderSettings(); renderAdmin(); }
@@ -449,10 +466,13 @@
449
466
  if (location.hash === "#recent") requestAnimationFrame(() => els.recentBlock.scrollIntoView({ block: "start" }));
450
467
  }
451
468
  function play(id) { location.hash = `#play/${encodeURIComponent(id)}`; }
452
- function go(view) {
469
+ // instant: switch right away, no slide (used when typing on the home search moves you to Games,
470
+ // so the Games search box can take focus before the next key arrives)
471
+ function go(view, { instant = false } = {}) {
453
472
  const target = view === "home" ? "" : `#${view}`;
454
473
  if (location.hash !== target) history.pushState(null, "", target || location.pathname + location.search);
455
- route(() => { if (view !== "recent") window.scrollTo(0, 0); });
474
+ const after = () => { if (view !== "recent") window.scrollTo(0, 0); };
475
+ if (instant) { routeNow(); after(); } else route(after);
456
476
  }
457
477
  function goBack() {
458
478
  if (location.hash.startsWith("#play/")) history.length > 1 ? history.back() : (location.hash = "#games");
@@ -506,6 +526,20 @@
506
526
  // Newest first. Add an entry here with every publish; its version should match package.json.
507
527
  // Each has: new (features), games (added/removed/fixed games), fixes (bugs). Leave a list out if empty.
508
528
  const CHANGELOG = [
529
+ { version: "1.0.35", date: "2026-10-28",
530
+ new: ["🔴 Live streams: watch Richard live, with its own chat beside the stream", "Quote of the day on the front page, and you can submit your own",
531
+ "📸 Take a photo with your camera right in the chat", "Full-screen chat", "Chat titles: add a title next to your name",
532
+ "See how many people are in chat right now", "Chat starts fresh every day at 1:35 PM"],
533
+ fixes: ["Chat doesn't block messages anymore: swear words just get their middle letters hidden",
534
+ "Nicknames can be anything", "No cooldown between messages or photos"] },
535
+ { version: "1.0.34", date: "2026-10-27",
536
+ new: ["Send photos in chat: drag and drop, paste, or tap 📷", "Emoji picker and 230 animated stickers (😊 button)",
537
+ "🚩 Report messages: 3 reports hides a message", "Slow mode and chat lock when chat gets busy"],
538
+ games: ["55 new games, including Battle for Gondor, Black Knight, Deepest Sword, HexGL, Gacha Life, Pandemic 2, Kitten Cannon and Super Mario Bros"],
539
+ fixes: ["Much stronger chat filter: blocked messages aren't sent at all", "Nicknames can't use links or teacher titles (Mr., Ms., Teacher…)",
540
+ "Explicit photos are blocked automatically",
541
+ "Games that randomly said “won't load” (like Scratch Inc, Recoil and Cubefield) now load reliably",
542
+ "Smaller logo and search bar on the home page"] },
509
543
  { version: "1.0.33", date: "2026-10-23",
510
544
  new: ["What's new page: see every update, new games and bug fixes (you're on it!)"] },
511
545
  { version: "1.0.32", date: "2026-10-23",
@@ -1008,49 +1042,85 @@
1008
1042
  }
1009
1043
 
1010
1044
  // ---------- Censored chat room ----------
1011
- // Two layers: this filter (stars out swears, refuses links/personal info) and the database's own
1012
- // rules (see SETUP.md), which reject the same things even if someone skips this page's code.
1045
+ // Two layers: this filter (anything it catches is refused, never starred out and sent) and the
1046
+ // database's rules (tools/build-rules.js), which repeat the core checks for anyone who skips this page.
1047
+ // The owner can add more words from Settings → Tools; they arrive in chat.settings.words.
1013
1048
  const BAD_ANYWHERE = ["fuck", "shit", "bitch", "cunt", "nigg", "faggot", "fagot", "whore", "slut", "pussy",
1014
1049
  "penis", "vagina", "porn", "retard", "asshole", "bastard", "molest", "pedo", "dildo", "boob", "nazi", "hitler",
1015
- "kill yourself", "killyourself"];
1016
- const BAD_WHOLE_WORD = ["ass", "fag", "cum", "tit", "tits", "hoe", "kys", "sex", "nig", "dick", "cock", "rape",
1017
- "raped", "rapist", "raping", "damn", "piss", "crap", "wank", "twat", "prick"];
1018
- const LEET = { 0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", 8: "b", "@": "a", $: "s", "!": "i", "|": "i" };
1050
+ "kill yourself", "killyourself", "neck yourself", "chink", "chingchong", "kike", "wetback", "tranny", "raghead",
1051
+ "towelhead", "beaner", "jigaboo", "porch monkey", "heil", "white power", "whitepower", "kkk", "1488", "horny",
1052
+ "nudes", "onlyfans", "blowjob", "handjob", "masturbat", "orgasm", "boner", "hentai", "rule34", "jerk off",
1053
+ "jack off", "motherfuck", "dumbass", "jackass", "shoot up the school", "bomb the school"];
1054
+ const BAD_WHOLE_WORD = ["ass", "fag", "fags", "cum", "tit", "tits", "hoe", "hoes", "kys", "sex", "sexy", "nig", "dick",
1055
+ "dicks", "cock", "rape", "raped", "rapist", "raping", "damn", "piss", "crap", "wank", "twat", "prick", "spic",
1056
+ "gook", "coon", "nude", "naked", "thot", "milf", "r34", "stfu", "wtf", "gtfo", "slur", "simp"];
1057
+ // "I hate <group>" and similar: checked on the whole message
1058
+ const BAD_PHRASES = [
1059
+ /\bhate\s+(all\s+)?(the\s+)?(jews?|jewish|blacks?|black people|gays?|muslims?|mexicans?|asians?|chinese|indians?|whites?|white people|trans|lgbt\w*|immigrants?|arabs?|christians?)\b/,
1060
+ /\b(jews?|blacks?|gays?|muslims?|mexicans?|asians?|trans)\s+(are|r)\s+(bad|evil|trash|garbage|disgusting|animals|stupid|the worst|not human)\b/,
1061
+ /\b(go back to|deport)\s+(your|ur)\s+country\b/, /\bgas\s+the\b/, /\bdid nothing wrong\b/, /\bkill\s+(all|every)\b/,
1062
+ ];
1063
+ const LEET = { 0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", 8: "b", "@": "a", $: "s", "!": "i", "|": "i", "€": "e" };
1064
+ // Look-alike letters from other alphabets ("fυck", "ѕhit") folded to plain a–z
1065
+ const HOMOGLYPHS = { "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i", "ј": "j", "ѕ": "s",
1066
+ "к": "k", "м": "m", "н": "h", "т": "t", "в": "b", "ℓ": "l", "α": "a", "ε": "e", "ι": "i", "κ": "k", "ν": "v", "ο": "o",
1067
+ "ρ": "p", "τ": "t", "υ": "u", "χ": "x" };
1019
1068
  // Real words that happen to contain a filtered one
1020
- const SAFE_WORDS = ["scunthorpe", "shiitake", "cockpit", "peacock", "hancock", "dickens", "assassin", "cocktail", "therapist"];
1021
- const plain = (s) => s.toLowerCase().replace(/[0134578@$!|]/g, (c) => LEET[c] || c).replace(/[^a-z ]/g, "");
1069
+ const SAFE_WORDS = ["scunthorpe", "shiitake", "cockpit", "peacock", "hancock", "dickens", "assassin", "cocktail",
1070
+ "therapist", "raccoon", "cocoon", "tycoon", "class", "pass", "grass", "glass", "bass", "mass", "brass", "assist",
1071
+ "assignment", "assume", "classic", "cumulative", "document", "titan", "title", "titles", "sextant", "essex",
1072
+ "middlesex", "shitake", "hello", "night", "nigeria", "niger", "snigger", "analysis", "therapist"];
1073
+ const fold = (s) => s.normalize("NFKD").replace(/[̀-ͯ​-‏⁠]/g, "")
1074
+ .replace(/./gu, (c) => HOMOGLYPHS[c] || HOMOGLYPHS[c.toLowerCase()] || c);
1075
+ const plain = (s) => fold(s).toLowerCase().replace(/[0134578@$!|€]/g, (c) => LEET[c] || c).replace(/[^a-z ]/g, "");
1022
1076
  const squash = (s) => plain(s).replace(/(.)\1+/g, "$1"); // "fuuuck" -> "fuck"
1077
+ const tight = (s) => squash(s).replace(/ /g, "");
1078
+ function extraWords() {
1079
+ return String(chat.settings.words || "").split(/[\n,]+/).map((w) => plain(w).trim()).filter((w) => w.length >= 2);
1080
+ }
1023
1081
  function isBadWord(word) {
1024
- const p = plain(word).replace(/ /g, ""), w = squash(word).replace(/ /g, "");
1082
+ const p = plain(word).replace(/ /g, ""), w = tight(word);
1025
1083
  if (!w || SAFE_WORDS.includes(p)) return false;
1026
1084
  // whole-word list: check before and after squashing, since squashing turns "ass" into "as"
1027
1085
  return BAD_WHOLE_WORD.includes(p) || BAD_WHOLE_WORD.includes(w) ||
1028
- BAD_ANYWHERE.some((b) => w.includes(squash(b).replace(/ /g, "")));
1086
+ [...BAD_ANYWHERE, ...extraWords()].some((b) => w.includes(tight(b)));
1029
1087
  }
1030
- // Returns { text } (with swears starred out) or { error } when the message can't be sent at all
1088
+ // Nothing is ever blocked: swear words just get their middle letters hidden ("f**k").
1089
+ // The owner's extra word list (Settings → Tools) is hidden the same way.
1090
+ function maskWord(w) {
1091
+ const letters = [...w];
1092
+ if (letters.length <= 2) return "*".repeat(letters.length);
1093
+ return letters[0] + "*".repeat(letters.length - 2) + letters[letters.length - 1];
1094
+ }
1095
+ function maskText(text) {
1096
+ return String(text).split(/(\s+)/).map((w) => (/\S/.test(w) && isBadWord(w) ? maskWord(w) : w)).join("");
1097
+ }
1098
+ // Returns { text } (masked) or { error } only when there's nothing to send
1031
1099
  function cleanMessage(raw) {
1032
- const text = raw.replace(/\s+/g, " ").trim();
1100
+ const text = String(raw).replace(/\s+/g, " ").trim();
1033
1101
  if (!text) return { error: "Type a message first." };
1034
- if (/(https?:|www\.|discord\.gg|\b[a-z0-9-]+\.(com|net|org|io|gg|xyz|co|me|tv|ly|app|dev|link)\b)/i.test(text)) return { error: "Links aren't allowed in chat." };
1035
- if (/\S+@\S+\.\S+/.test(text)) return { error: "Don't share email addresses." };
1036
- if (/(\d[\s().-]*){7,}/.test(text)) return { error: "Don't share phone numbers." };
1037
- const masked = text.split(" ").map((w) => (isBadWord(w) ? "*".repeat(w.length) : w)).join(" ");
1038
- // spaced-out tricks like "f u c k" survive word-by-word checks; catch them on the whole line
1039
- const joined = squash(masked.split(" ").filter((w) => !SAFE_WORDS.includes(plain(w))).join(" ")).replace(/ /g, "");
1040
- if (BAD_ANYWHERE.some((b) => joined.includes(squash(b).replace(/ /g, "")))) return { error: "That message was blocked." };
1041
- return { text: masked };
1102
+ return { text: maskText(text).slice(0, 300) };
1042
1103
  }
1104
+ // Names can be anything up to 16 characters. (The admin code is longer than that, so a mistyped code is
1105
+ // refused instead of being posted as someone's name.) "Richard" stays the owner's.
1043
1106
  function cleanName(raw) {
1044
- // Refuse (don't silently strip) other characters: a wrong or not-yet-saved admin code like "Code123!"
1045
- // must never be posted as a nickname
1046
- if (/[^\w .-]/.test(raw)) return { error: "Nicknames can only use letters, numbers, spaces, . _ and -." };
1047
- const name = raw.replace(/\s+/g, " ").trim().slice(0, 16);
1048
- if (name.length < 2) return { error: "Pick a nickname (2–16 letters)." };
1049
- if (name.split(/[ ._-]/).some(isBadWord) || isBadWord(name.replace(/[ ._-]/g, ""))) return { error: "Pick a different nickname." };
1050
- return { name };
1051
- }
1052
-
1053
- const chat = { started: false, uid: null, lastSent: 0, admin: false, triedName: "" };
1107
+ const name = String(raw).replace(/\s+/g, " ").trim();
1108
+ if (!name) return { error: "Pick a nickname." };
1109
+ if ([...name].length > 16) return { error: "Nicknames can be up to 16 characters." };
1110
+ return { name: maskText(name) };
1111
+ }
1112
+
1113
+ const chat = {
1114
+ started: false, uid: null, lastSent: 0, admin: false, triedName: "",
1115
+ settings: {}, // owner's live settings: slowMode (s), locked, words
1116
+ mutedUntil: 0, banned: false,
1117
+ flags: {}, // message key -> number of people who reported it
1118
+ lastText: "", lastTextAt: 0,
1119
+ room: "main", // "main" (the Chat page / beside games) or "live" (beside the live stream)
1120
+ };
1121
+ const HIDE_AFTER_REPORTS = Infinity;
1122
+ // Each room keeps its own messages, typing and "in chat" list; names, bans, mutes and settings are shared
1123
+ function roomPath(x) { return chat.room === "live" ? `live/chat/${x}` : `chat/${x}`; } // reports are switched off: nothing is hidden automatically
1054
1124
  const ADMIN_NAME = "Richard"; // what the admin's messages show as (reserved: the database refuses it from non-admins)
1055
1125
  function setAdminName() {
1056
1126
  $("chat-name").value = ADMIN_NAME;
@@ -1080,6 +1150,7 @@
1080
1150
  chat.started = true;
1081
1151
  $("chat-form").hidden = false;
1082
1152
  $("chat-name").value = store.get("rug-chat-name", "");
1153
+ $("chat-title").value = store.get("rug-chat-title", "");
1083
1154
  chatNote("Connecting…");
1084
1155
  try {
1085
1156
  await ensureUser(app);
@@ -1088,39 +1159,166 @@
1088
1159
  return;
1089
1160
  }
1090
1161
  if (chat.admin) setAdminName();
1162
+ if (!$("view-live").hidden) renderLive(); // now we know whether this is the owner (Go live panel)
1091
1163
  chatNote("");
1092
1164
  const log = $("chat-log");
1093
1165
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1166
+ const db = app.database();
1167
+ watchChatState(db);
1168
+ listenRoom(db);
1169
+ watchChatReset(db);
1170
+ }
1171
+
1172
+ // Show the current room's messages (called again when the chat moves between the Chat page and Live)
1173
+ // The chat starts fresh every day at 1:35 PM (by this browser's clock): only messages sent since the most
1174
+ // recent 1:35 PM show. Messages over a day old are deleted from the database by whoever has the chat open.
1175
+ const CHAT_RESET = { hour: 13, minute: 35 };
1176
+ function lastChatReset(now = new Date()) {
1177
+ const t = new Date(now.getFullYear(), now.getMonth(), now.getDate(), CHAT_RESET.hour, CHAT_RESET.minute);
1178
+ if (t > now) t.setDate(t.getDate() - 1);
1179
+ return t.getTime();
1180
+ }
1181
+ function watchChatReset(db) {
1182
+ clearInterval(chat.resetTimer);
1183
+ chat.resetTimer = setInterval(() => {
1184
+ if (lastChatReset() !== chat.resetAt) { listenRoom(db); sweepOldMessages(db); } // it's 1:35: clear the screen
1185
+ }, 15000);
1186
+ sweepOldMessages(db);
1187
+ }
1188
+ async function sweepOldMessages(db) {
1189
+ const dayAgo = Date.now() - 86400000;
1190
+ for (const path of ["chat/messages", "live/chat/messages"]) {
1191
+ try {
1192
+ const old = await db.ref(path).orderByChild("ts").endAt(dayAgo).limitToFirst(200).once("value");
1193
+ const changes = {};
1194
+ old.forEach((c) => { changes[`${path}/${c.key}`] = null; });
1195
+ if (Object.keys(changes).length) await db.ref().update(changes);
1196
+ } catch { /* older rules, or someone else already swept */ }
1197
+ }
1198
+ }
1199
+ function listenRoom(db) {
1200
+ const log = $("chat-log"), room = chat.room;
1201
+ log.innerHTML = `<p class="chat-empty" id="chat-empty">${room === "live" ? "No messages yet. Say hi to the stream!" : "No messages yet. Say hi!"}</p>`;
1202
+ $("chat-text").placeholder = room === "live" ? "Chat with the stream…" : "Say something… (drop a photo here)";
1094
1203
  if (chat.ref) chat.ref.off(); // reconnecting (signed in/out): drop the old listener so messages don't double
1095
- const ref = chat.ref = app.database().ref("chat/messages").orderByChild("ts").limitToLast(60);
1204
+ chat.resetAt = lastChatReset();
1205
+ const ref = chat.ref = db.ref(roomPath("messages")).orderByChild("ts").startAt(chat.resetAt).limitToLast(60);
1096
1206
  ref.on("child_added", (snap) => {
1097
1207
  const m = snap.val();
1098
- if (!m || typeof m.text !== "string") return;
1208
+ const div = renderMessage(snap.key, m);
1209
+ if (!div) return;
1099
1210
  $("chat-empty")?.remove();
1100
1211
  const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;
1101
- const t = new Date(m.ts || Date.now());
1102
- const div = document.createElement("div");
1103
- div.className = "chat-msg" + (m.uid === chat.uid ? " me" : "");
1104
- div.dataset.key = snap.key;
1105
- div.dataset.uid = m.uid || "";
1106
- // filter again on display, in case anything slipped past older rules
1107
- const shown = cleanMessage(m.text).text || "[removed]";
1108
- const mention = m.uid !== chat.uid && mentionsMe(m.text);
1109
- if (mention) div.classList.add("mention");
1110
- const body = escapeHtml(shown).replace(/(^|\s)@([\w.-]{2,16})/g, '$1<span class="at">@$2</span>');
1111
- div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}<span class="who" title="Mention">${escapeHtml(m.name || "?")}</span>${body}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
1112
- `<button class="mod" type="button" data-mod="delete" title="Delete message">🗑</button><button class="mod" type="button" data-mod="ban" title="Ban this person">🚫</button>`;
1113
1212
  log.appendChild(div);
1114
1213
  while (log.children.length > 80) log.firstChild.remove();
1115
1214
  if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight;
1116
- noteNewMessage(m, mention);
1215
+ // pictures load after they're added; keep the view pinned to the bottom when they do
1216
+ div.querySelector("img")?.addEventListener("load", () => { if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight; }, { once: true });
1217
+ if (room === "main") noteNewMessage(m, div.classList.contains("mention")); // the unread dot is for the regular chat
1117
1218
  });
1118
- // Deleted by an admin: disappears for everyone
1219
+ // Deleted (by its sender or the owner): disappears for everyone
1119
1220
  ref.on("child_removed", (snap) => {
1120
1221
  log.querySelector(`[data-key="${CSS.escape(snap.key)}"]`)?.remove();
1121
1222
  if (!log.querySelector(".chat-msg")) log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1122
1223
  });
1123
- startTypingWatch(app.database());
1224
+ startTypingWatch(db);
1225
+ watchHere(db);
1226
+ updateHere();
1227
+ }
1228
+ async function switchRoom(room) {
1229
+ if (room === chat.room) return;
1230
+ stopTyping();
1231
+ typing.ref = null;
1232
+ if (hereOn && hereRef) hereRef.remove().catch(() => {});
1233
+ hereOn = false;
1234
+ hereRef = null;
1235
+ chat.room = room;
1236
+ if (!chat.started || !chat.uid) return;
1237
+ const app = await getFirebase();
1238
+ if (app) listenRoom(app.database());
1239
+ }
1240
+
1241
+ // One chat row: text, a sticker or a photo, plus its buttons (shown by CSS for who may use them)
1242
+ const STICKER_URL = (code) => `https://fonts.gstatic.com/s/e/notoemoji/latest/${code}/512.webp`;
1243
+ function renderMessage(key, m) {
1244
+ if (!m || typeof m.name !== "string") return null;
1245
+ let body;
1246
+ if (typeof m.text === "string") {
1247
+ // mask again on display, so words added to the owner's list later get hidden in old messages too
1248
+ body = escapeHtml(maskText(m.text)).replace(/(^|\s)@([\w-]{2,16})/g, '$1<span class="at">@$2</span>');
1249
+ } else if (typeof m.sticker === "string" && STICKERS.includes(m.sticker)) {
1250
+ body = `<img class="chat-sticker" src="${STICKER_URL(m.sticker)}" alt="sticker" width="96" height="96" loading="lazy">`; } else if (typeof m.img === "string" && /^data:image\/(webp|jpeg);base64,[A-Za-z0-9+/=]+$/.test(m.img)) {
1251
+ body = `<button class="chat-photo-btn" type="button" data-act="view" title="Open photo"><img class="chat-photo" src="${m.img}" alt="Photo from ${escapeHtml(m.name)}" loading="lazy"></button>`;
1252
+ } else return null;
1253
+ const t = new Date(m.ts || Date.now());
1254
+ const div = document.createElement("div");
1255
+ const mine = m.uid === chat.uid;
1256
+ div.className = "chat-msg" + (mine ? " me" : "") + (m.img ? " photo" : "") + (m.sticker ? " sticker" : "");
1257
+ div.dataset.key = key;
1258
+ div.dataset.uid = m.uid || "";
1259
+ div.dataset.name = m.name;
1260
+ if (typeof m.text === "string") div.dataset.text = m.text;
1261
+ if (!mine && typeof m.text === "string" && mentionsMe(m.text)) div.classList.add("mention");
1262
+ const title = typeof m.title === "string" && m.title.trim() ? `<span class="chat-title-pill">${escapeHtml(maskText(m.title))}</span>` : "";
1263
+ div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}${title}<span class="who" title="Mention">${escapeHtml(maskText(m.name))}</span>` +
1264
+ `${body}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
1265
+ `<span class="msg-acts">` +
1266
+ `<button class="mod act-delete" type="button" data-act="delete" title="Delete message">🗑</button>` +
1267
+ (mine ? "" : `<button class="mod owner-only" type="button" data-act="purge" title="Delete everything this person sent">🧹</button>` +
1268
+ `<button class="mod owner-only" type="button" data-act="mute" title="Mute this person">🔇</button>` +
1269
+ `<button class="mod owner-only" type="button" data-act="ban" title="Ban this person">🚫</button>`) +
1270
+ `<span class="flag-count owner-only" title="Reports"></span></span>`;
1271
+ applyFlags(div);
1272
+ return div;
1273
+ }
1274
+ function applyFlags(div) {
1275
+ const n = chat.flags[div.dataset.key] || 0;
1276
+ div.classList.toggle("flagged", n >= HIDE_AFTER_REPORTS);
1277
+ const c = div.querySelector(".flag-count");
1278
+ if (c) c.textContent = n ? `🚩${n}` : "";
1279
+ }
1280
+
1281
+ // Live chat state: owner settings (slow mode, lock, extra words), my mute/ban, and report counts
1282
+ function watchChatState(db) {
1283
+ db.ref("chat/settings").on("value", (s) => {
1284
+ chat.settings = s.val() || {};
1285
+ updateChatStatus();
1286
+ if (chat.admin) fillChatTools();
1287
+ $("chat-log").querySelectorAll(".chat-msg").forEach((row) => { // newly blocked words: hide those messages now
1288
+ const t = row.dataset.text;
1289
+ if (t && !cleanMessage(t).text) row.remove();
1290
+ });
1291
+ }, () => {});
1292
+ db.ref(`chat/mutes/${chat.uid}`).on("value", (s) => { chat.mutedUntil = Number(s.val()?.until) || 0; updateChatStatus(); }, () => {});
1293
+ db.ref(`chat/banned/${chat.uid}`).on("value", (s) => { chat.banned = s.exists(); updateChatStatus(); }, () => {});
1294
+ db.ref("chat/flags").on("value", (s) => {
1295
+ chat.flags = {};
1296
+ s.forEach((c) => { chat.flags[c.key] = c.numChildren(); });
1297
+ $("chat-log").querySelectorAll(".chat-msg").forEach(applyFlags);
1298
+ if (chat.admin) renderReported();
1299
+ }, () => {});
1300
+ clearInterval(chat.statusTimer);
1301
+ chat.statusTimer = setInterval(updateChatStatus, 15000); // mutes run out on their own
1302
+ }
1303
+ // Why this browser can't post right now (or "" if it can)
1304
+ function blockedReason() {
1305
+ if (chat.admin) return "";
1306
+ if (chat.banned) return "You've been banned from sending messages. You can still read.";
1307
+ if (chat.mutedUntil > Date.now()) return `You're muted for ${fmtWait(chat.mutedUntil - Date.now())}.`;
1308
+ if (chat.settings.locked) return "Chat is locked right now. You can still read.";
1309
+ return "";
1310
+ }
1311
+ function fmtWait(ms) {
1312
+ const m = Math.ceil(ms / 60000);
1313
+ return m >= 60 * 24 ? `${Math.round(m / 1440)} day${m >= 2880 ? "s" : ""}` : m >= 60 ? `${Math.round(m / 60)} hour${m >= 120 ? "s" : ""}` : `${m} minute${m === 1 ? "" : "s"}`;
1314
+ }
1315
+ function slowSeconds() { return chat.admin ? 0 : Number(chat.settings.slowMode) || 0; } // no cooldown unless the owner turns on slow mode
1316
+ function updateChatStatus() {
1317
+ const why = blockedReason();
1318
+ ["chat-text", "chat-send", "emoji-btn", "photo-btn", "cam-btn"].forEach((id) => { if ($(id)) $(id).disabled = !!why; });
1319
+ const slow = Number(chat.settings.slowMode) || 0;
1320
+ $("chat-status").textContent = why || (chat.settings.locked ? "🔒 Chat is locked (only you can post)" : slow ? `🐢 Slow mode: one message every ${slow}s` : "");
1321
+ $("chat-status").classList.toggle("err", !!why);
1124
1322
  }
1125
1323
 
1126
1324
  // ---------- "X is typing…" ----------
@@ -1134,7 +1332,10 @@
1134
1332
  }
1135
1333
  function startTypingWatch(db) {
1136
1334
  db.ref(".info/serverTimeOffset").on("value", (s) => { typing.offset = s.val() || 0; });
1137
- db.ref("chat/typing").on("value", (snap) => { typing.others = snap.val() || {}; renderTyping(); }, () => {});
1335
+ typing.watchRef?.off();
1336
+ typing.others = {};
1337
+ typing.watchRef = db.ref(roomPath("typing"));
1338
+ typing.watchRef.on("value", (snap) => { typing.others = snap.val() || {}; renderTyping(); }, () => {});
1138
1339
  clearInterval(typing.timer);
1139
1340
  typing.timer = setInterval(renderTyping, 1000);
1140
1341
  }
@@ -1155,7 +1356,7 @@
1155
1356
  if (!app) return;
1156
1357
  typing.sentAt = Date.now();
1157
1358
  if (!typing.ref) {
1158
- typing.ref = app.database().ref(`chat/typing/${chat.uid}`);
1359
+ typing.ref = app.database().ref(roomPath(`typing/${chat.uid}`));
1159
1360
  typing.ref.onDisconnect().remove();
1160
1361
  }
1161
1362
  typing.ref.set({ name, ts: window.firebase.database.ServerValue.TIMESTAMP }).catch(() => {});
@@ -1183,26 +1384,88 @@
1183
1384
  box.focus();
1184
1385
  }
1185
1386
 
1186
- // ---------- Admin tools (chat) ----------
1187
- async function adminAction(e) {
1188
- const btn = e.target.closest("[data-mod]");
1387
+ // ---------- Message buttons: report (everyone), delete (yours, or any for the owner), owner tools ----------
1388
+ const MUTE_CHOICES = [["10 minutes", 10 * 60e3], ["1 hour", 60 * 60e3], ["1 day", 24 * 60 * 60e3], ["1 week", 7 * 24 * 60 * 60e3]];
1389
+ async function chatAction(e) {
1390
+ const btn = e.target.closest("[data-act]");
1189
1391
  if (!btn) return;
1190
1392
  const row = btn.closest(".chat-msg");
1191
- const mine = row.dataset.uid && row.dataset.uid === chat.uid;
1192
- if (!chat.admin && !(mine && btn.dataset.mod === "delete")) return; // everyone may delete their own
1393
+ const act = btn.dataset.act, uid = row.dataset.uid, name = row.dataset.name, key = row.dataset.key;
1394
+ if (act === "view") { openPhoto(row.querySelector("img").src); return; }
1395
+ const mine = uid && uid === chat.uid;
1193
1396
  const db = (await getFirebase()).database();
1194
1397
  try {
1195
- if (btn.dataset.mod === "delete") {
1196
- await db.ref(`chat/messages/${row.dataset.key}`).remove();
1197
- } else if (btn.dataset.mod === "ban" && row.dataset.uid && row.dataset.uid !== chat.uid) {
1198
- if (!confirm("Ban this person from chat? They'll still be able to read.")) return;
1199
- await db.ref(`chat/banned/${row.dataset.uid}`).set(true);
1200
- chatNote("Banned. Their old messages stay until you delete them.");
1398
+ if (act === "report" && !mine) {
1399
+ await db.ref(`chat/flags/${key}/${chat.uid}`).set(true);
1400
+ chatNote(`Reported. Messages with ${HIDE_AFTER_REPORTS} reports are hidden until the owner looks at them.`);
1401
+ } else if (act === "delete" && (mine || chat.admin)) {
1402
+ await db.ref().update({ [roomPath(`messages/${key}`)]: null });
1403
+ } else if (!chat.admin || mine) {
1404
+ return;
1405
+ } else if (act === "purge") {
1406
+ if (!confirm(`Delete every message from “${name}”? This can't be undone.`)) return;
1407
+ const n = await purgeUser(db, uid);
1408
+ chatNote(`Deleted ${n} message${n === 1 ? "" : "s"} from ${name}.`);
1409
+ } else if (act === "mute") {
1410
+ const ms = await pickMute(btn, name);
1411
+ if (!ms) return;
1412
+ await db.ref(`chat/mutes/${uid}`).set({ until: Date.now() + ms, name });
1413
+ chatNote(`${name} is muted for ${fmtWait(ms)}.`);
1414
+ } else if (act === "ban") {
1415
+ if (!confirm(`Ban “${name}” from chat? They can still read. You can unban them in Settings → Tools.`)) return;
1416
+ const alsoDelete = confirm(`Also delete everything “${name}” sent?`);
1417
+ await db.ref(`chat/banned/${uid}`).set({ name, ts: Date.now() });
1418
+ const n = alsoDelete ? await purgeUser(db, uid) : 0;
1419
+ chatNote(`Banned ${name}${alsoDelete ? ` and deleted ${n} message${n === 1 ? "" : "s"}` : ""}.`);
1201
1420
  }
1202
1421
  } catch {
1203
- chatNote("That didn't work.", true);
1422
+ chatNote("That didn't work. Try again.", true);
1204
1423
  }
1205
1424
  }
1425
+ // Every message a person sent (and the reports on them), gone in one write
1426
+ async function purgeUser(db, uid) {
1427
+ const snap = await db.ref(roomPath("messages")).orderByChild("uid").equalTo(uid).once("value");
1428
+ const changes = {};
1429
+ snap.forEach((c) => { changes[roomPath(`messages/${c.key}`)] = null; });
1430
+ if (Object.keys(changes).length) await db.ref().update(changes);
1431
+ return snap.numChildren();
1432
+ }
1433
+ // Small menu under the 🔇 button: how long to mute
1434
+ function pickMute(anchor, name) {
1435
+ document.querySelector(".mute-menu")?.remove();
1436
+ return new Promise((done) => {
1437
+ const menu = document.createElement("div");
1438
+ menu.className = "mute-menu";
1439
+ menu.setAttribute("role", "menu");
1440
+ menu.innerHTML = `<p>Mute ${escapeHtml(name)} for…</p>` + MUTE_CHOICES.map(([label, ms]) => `<button type="button" role="menuitem" data-ms="${ms}">${label}</button>`).join("") +
1441
+ `<button type="button" role="menuitem" data-ms="0" class="cancel">Cancel</button>`;
1442
+ document.body.appendChild(menu);
1443
+ const r = anchor.getBoundingClientRect();
1444
+ menu.style.left = `${Math.min(innerWidth - menu.offsetWidth - 8, Math.max(8, r.left - 60))}px`;
1445
+ menu.style.top = `${Math.min(innerHeight - menu.offsetHeight - 8, r.bottom + 6)}px`;
1446
+ menu.querySelector("button").focus();
1447
+ const close = (ms) => { menu.remove(); document.removeEventListener("pointerdown", outside, true); done(ms); };
1448
+ const outside = (ev) => { if (!menu.contains(ev.target)) close(0); };
1449
+ menu.addEventListener("click", (ev) => { const b = ev.target.closest("[data-ms]"); if (b) close(Number(b.dataset.ms)); });
1450
+ menu.addEventListener("keydown", (ev) => { if (ev.key === "Escape") close(0); });
1451
+ setTimeout(() => document.addEventListener("pointerdown", outside, true));
1452
+ });
1453
+ }
1454
+ // Full-size photo viewer
1455
+ function openPhoto(src) {
1456
+ const wrap = document.createElement("div");
1457
+ wrap.className = "photo-viewer";
1458
+ wrap.setAttribute("role", "dialog");
1459
+ wrap.setAttribute("aria-label", "Photo");
1460
+ wrap.innerHTML = `<img alt="Chat photo"><button class="wheel-x" type="button" aria-label="Close">✕</button>`;
1461
+ wrap.querySelector("img").src = src;
1462
+ const close = () => { wrap.remove(); document.removeEventListener("keydown", esc, true); };
1463
+ const esc = (ev) => { if (ev.key === "Escape") { ev.stopPropagation(); close(); } };
1464
+ wrap.addEventListener("click", (ev) => { if (ev.target === wrap || ev.target.closest(".wheel-x")) close(); });
1465
+ document.addEventListener("keydown", esc, true);
1466
+ document.body.appendChild(wrap);
1467
+ wrap.querySelector(".wheel-x").focus();
1468
+ }
1206
1469
 
1207
1470
  // The Tools section only exists for a browser that entered the code; everyone else never sees it
1208
1471
  async function renderAdmin() {
@@ -1214,7 +1477,88 @@
1214
1477
  $("admin-leave").hidden = !on;
1215
1478
  $("admin-tools-row").hidden = !on;
1216
1479
  $("admin-reports").hidden = !on;
1217
- if (on) watchReports(); else unwatchReports();
1480
+ $("admin-chat-tools").hidden = !on;
1481
+ $("admin-quotes").hidden = !on;
1482
+ if (on) { watchQuoteAdmin(); renderQuoteAdmin(); }
1483
+ if (on) { watchReports(); watchPunished(app.database()); fillChatTools(); renderReported(); }
1484
+ else unwatchReports();
1485
+ }
1486
+
1487
+ // ---------- Owner chat tools (Settings → Tools) ----------
1488
+ function fillChatTools() {
1489
+ const slow = String(Number(chat.settings.slowMode) || 0);
1490
+ $("mod-slow").value = [...$("mod-slow").options].some((o) => o.value === slow) ? slow : "0";
1491
+ $("mod-lock").checked = !!chat.settings.locked;
1492
+ if (document.activeElement !== $("mod-words")) $("mod-words").value = chat.settings.words || "";
1493
+ }
1494
+ async function saveChatSetting(field, value, okMsg) {
1495
+ try {
1496
+ await (await getFirebase()).database().ref(`chat/settings/${field}`).set(value);
1497
+ if (okMsg) $("mod-words-msg").textContent = okMsg;
1498
+ } catch {
1499
+ $("mod-words-msg").textContent = "Couldn't save. Are the new database rules published?";
1500
+ }
1501
+ }
1502
+ // Messages people reported, newest reports first, with keep / delete / delete-all buttons
1503
+ async function renderReported() {
1504
+ if (!chat.admin) return;
1505
+ const keys = Object.keys(chat.flags).filter((k) => chat.flags[k] > 0);
1506
+ $("reported-count").textContent = keys.length ? `(${keys.length})` : "";
1507
+ if (!keys.length) { $("reported-list").innerHTML = `<p class="none">Nothing reported.</p>`; return; }
1508
+ const db = (await getFirebase()).database();
1509
+ const rows = await Promise.all(keys.map(async (k) => ({ key: k, m: (await db.ref(`chat/messages/${k}`).once("value")).val() })));
1510
+ const stale = rows.filter((r) => !r.m).map((r) => r.key);
1511
+ if (stale.length) db.ref().update(Object.fromEntries(stale.map((k) => [`chat/flags/${k}`, null]))).catch(() => {}); // message already gone
1512
+ const live = rows.filter((r) => r.m);
1513
+ $("reported-list").innerHTML = !live.length ? `<p class="none">Nothing reported.</p>` : live.map(({ key, m }) => {
1514
+ const what = m.text ? escapeHtml(m.text) : m.sticker ? "[sticker]" : `<img class="report-thumb" src="${m.img}" alt="Reported photo">`;
1515
+ return `<div class="report" data-key="${escapeHtml(key)}" data-uid="${escapeHtml(m.uid || "")}" data-name="${escapeHtml(m.name)}"><span class="kind broken">🚩 ${chat.flags[key]}</span>` +
1516
+ `<div class="body"><span class="game">${escapeHtml(m.name)}</span><div class="note">${what}</div></div>` +
1517
+ `<button class="mod" type="button" data-rep="keep" title="Keep it: clear the reports">Keep</button>` +
1518
+ `<button class="mod" type="button" data-rep="delete" title="Delete this message">🗑</button>` +
1519
+ `<button class="mod" type="button" data-rep="purge" title="Delete everything this person sent">🧹</button></div>`;
1520
+ }).join("");
1521
+ }
1522
+ // Muted and banned people, with undo buttons
1523
+ let punishedWatched = false;
1524
+ function watchPunished(db) {
1525
+ if (punishedWatched) return;
1526
+ punishedWatched = true;
1527
+ const lists = { mutes: {}, banned: {} };
1528
+ const draw = () => {
1529
+ const rows = [
1530
+ ...Object.entries(lists.banned).map(([uid, v]) => ({ uid, kind: "banned", name: v?.name || "Someone", note: "Banned" })),
1531
+ ...Object.entries(lists.mutes).filter(([, v]) => v?.until > Date.now())
1532
+ .map(([uid, v]) => ({ uid, kind: "mutes", name: v.name || "Someone", note: `Muted for ${fmtWait(v.until - Date.now())} more` })),
1533
+ ];
1534
+ $("punished-list").innerHTML = !rows.length ? `<p class="none">Nobody.</p>` : rows.map((r) =>
1535
+ `<div class="report" data-uid="${escapeHtml(r.uid)}" data-kind="${r.kind}"><div class="body"><span class="game">${escapeHtml(r.name)}</span><div class="meta">${r.note}</div></div>` +
1536
+ `<button class="mod" type="button" data-undo>${r.kind === "banned" ? "Unban" : "Unmute"}</button></div>`).join("");
1537
+ };
1538
+ ["mutes", "banned"].forEach((k) => db.ref(`chat/${k}`).on("value", (s) => { lists[k] = s.val() || {}; draw(); }, () => { punishedWatched = false; }));
1539
+ }
1540
+ function bindChatTools() {
1541
+ $("mod-slow").addEventListener("change", () => saveChatSetting("slowMode", Number($("mod-slow").value)));
1542
+ $("mod-lock").addEventListener("change", () => saveChatSetting("locked", $("mod-lock").checked));
1543
+ $("mod-words-save").addEventListener("click", () => {
1544
+ const words = $("mod-words").value.split(/[\n,]+/).map((w) => w.trim()).filter(Boolean).join("\n").slice(0, 4000);
1545
+ saveChatSetting("words", words, `Saved ${words ? words.split("\n").length : 0} word${words.split("\n").length === 1 ? "" : "s"} ✓`);
1546
+ });
1547
+ $("reported-list").addEventListener("click", async (e) => {
1548
+ const b = e.target.closest("[data-rep]"), row = b?.closest(".report");
1549
+ if (!row || !chat.admin) return;
1550
+ const db = (await getFirebase()).database(), key = row.dataset.key;
1551
+ try {
1552
+ if (b.dataset.rep === "keep") await db.ref(`chat/flags/${key}`).remove();
1553
+ if (b.dataset.rep === "delete") await db.ref().update({ [`chat/messages/${key}`]: null, [`chat/flags/${key}`]: null });
1554
+ if (b.dataset.rep === "purge" && confirm(`Delete every message from “${row.dataset.name}”?`)) await purgeUser(db, row.dataset.uid);
1555
+ } catch {}
1556
+ renderReported();
1557
+ });
1558
+ $("punished-list").addEventListener("click", async (e) => {
1559
+ const row = e.target.closest("[data-undo]")?.closest(".report");
1560
+ if (row && chat.admin) try { await (await getFirebase()).database().ref(`chat/${row.dataset.kind}/${row.dataset.uid}`).remove(); } catch {}
1561
+ });
1218
1562
  }
1219
1563
 
1220
1564
  // ---------- Report a broken game / request a game ----------
@@ -1346,7 +1690,7 @@
1346
1690
  }
1347
1691
 
1348
1692
  function bindAdmin() {
1349
- $("chat-log").addEventListener("click", adminAction);
1693
+ $("chat-log").addEventListener("click", chatAction);
1350
1694
  $("admin-leave").addEventListener("click", async () => {
1351
1695
  try { await (await getFirebase()).database().ref(`chat/admins/${chat.uid}`).remove(); } catch {}
1352
1696
  chat.admin = false;
@@ -1357,8 +1701,8 @@
1357
1701
  await renderAdmin();
1358
1702
  });
1359
1703
  $("admin-clear").addEventListener("click", async () => {
1360
- if (!chat.admin || !confirm("Delete every chat message for everyone?")) return;
1361
- try { await (await getFirebase()).database().ref("chat/messages").remove(); }
1704
+ if (!chat.admin || !confirm("Delete every chat message for everyone (regular chat and live chat)?")) return;
1705
+ try { await (await getFirebase()).database().ref().update({ "chat/messages": null, "live/chat/messages": null }); } // both rooms
1362
1706
  catch { alert("Couldn't clear the chat."); }
1363
1707
  });
1364
1708
  }
@@ -1377,44 +1721,505 @@
1377
1721
  if (!$("chat-text").value.trim()) return;
1378
1722
  }
1379
1723
  }
1380
- const n = chat.admin ? { name: ADMIN_NAME } : cleanName(rawName);
1381
- if (n.error) { chatNote(n.error, true); $("chat-name").focus(); return; }
1382
- if (!chat.admin && n.name.toLowerCase() === ADMIN_NAME.toLowerCase()) { chatNote("That name is taken.", true); return; }
1383
1724
  const m = cleanMessage($("chat-text").value);
1384
1725
  if (m.error) { chatNote(m.error, true); return; }
1385
- const wait = 3000 - (Date.now() - chat.lastSent);
1386
- if (wait > 0) { chatNote(`Slow down. Wait ${Math.ceil(wait / 1000)}s.`, true); return; }
1726
+ if (await postMessage({ text: m.text })) {
1727
+ $("chat-text").value = "";
1728
+ stopTyping();
1729
+ }
1730
+ }
1731
+ // Checks shared by text, stickers and photos; returns { name } or null (after showing why)
1732
+ function chatSender() {
1733
+ const why = blockedReason();
1734
+ if (why) { chatNote(why, true); return null; }
1735
+ const n = chat.admin ? { name: ADMIN_NAME } : cleanName($("chat-name").value.trim());
1736
+ if (n.error) { chatNote(n.error, true); $("chat-name").focus(); return null; }
1737
+ if (!chat.admin && n.name.toLowerCase() === ADMIN_NAME.toLowerCase()) { chatNote("That name is taken.", true); return null; }
1738
+ const wait = slowSeconds() * 1000 - (Date.now() - chat.lastSent);
1739
+ if (wait > 0) { chatNote(`Slow down. Wait ${Math.ceil(wait / 1000)}s.`, true); return null; }
1740
+ return n;
1741
+ }
1742
+ async function postMessage(fields) {
1743
+ const app = await getFirebase();
1744
+ if (!app || !chat.uid) return false;
1745
+ const n = chatSender();
1746
+ if (!n) return false;
1387
1747
  if (!chat.admin) store.set("rug-chat-name", n.name); // never save the admin code as a remembered name
1748
+ const title = maskText($("chat-title").value.replace(/\s+/g, " ").trim()).slice(0, 20);
1749
+ store.set("rug-chat-title", title);
1388
1750
  const db = app.database();
1389
- const key = db.ref("chat/messages").push().key;
1751
+ const key = db.ref(roomPath("messages")).push().key;
1390
1752
  const TS = window.firebase.database.ServerValue.TIMESTAMP;
1391
1753
  chat.lastSent = Date.now();
1392
1754
  try {
1393
1755
  await db.ref().update({
1394
- [`chat/messages/${key}`]: { name: n.name, text: m.text, ts: TS, uid: chat.uid, ...(chat.admin ? { admin: true } : {}) },
1756
+ [roomPath(`messages/${key}`)]: { name: n.name, ts: TS, uid: chat.uid, ...fields, ...(title ? { title } : {}), ...(chat.admin ? { admin: true } : {}) },
1395
1757
  [`chat/last/${chat.uid}`]: TS,
1396
1758
  });
1397
- $("chat-text").value = "";
1398
- stopTyping();
1399
1759
  stats.bump("chatSent");
1400
1760
  chatNote("");
1761
+ return true;
1762
+ } catch {
1763
+ chatNote(blockedReason() || "Didn't send. Try again.", true);
1764
+ return false;
1765
+ }
1766
+ }
1767
+
1768
+ // ---------- Quote of the day ----------
1769
+ // Anyone can submit (quotes/pending, readable only by the owner). The owner approves them into
1770
+ // quotes/approved; the bar at the top shows one of those, a different one each day.
1771
+ const quotes = { approved: [], pending: [], sentAt: 0 };
1772
+ function dayNumber() { const d = new Date(); return Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() / 86400000); }
1773
+ function showQuoteOfDay() {
1774
+ const list = quotes.approved;
1775
+ const q = list.length ? list[dayNumber() % list.length] : null;
1776
+ $("quote-text").textContent = q ? maskText(q.text) : "No quote yet. Be the first to submit one!";
1777
+ $("quote-text").classList.toggle("is-empty", !q);
1778
+ $("quote-by").textContent = q?.by ? `— ${maskText(q.by)}` : "";
1779
+ }
1780
+ async function startQuotes() {
1781
+ const app = await getFirebase();
1782
+ if (!app) return;
1783
+ app.database().ref("quotes/approved").orderByKey().on("value", (s) => {
1784
+ quotes.approved = [];
1785
+ s.forEach((c) => { const v = c.val(); if (v && typeof v.text === "string") quotes.approved.push({ key: c.key, ...v }); });
1786
+ showQuoteOfDay();
1787
+ if (chat.admin) renderQuoteAdmin();
1788
+ }, () => {});
1789
+ }
1790
+ function openQuoteForm() {
1791
+ $("quote-input").value = ""; $("quote-author").value = ""; $("quote-msg").textContent = "";
1792
+ $("quote-msg").classList.remove("err");
1793
+ $("quote-wrap").hidden = false;
1794
+ $("quote-input").focus();
1795
+ }
1796
+ function closeQuoteForm() { $("quote-wrap").hidden = true; }
1797
+ async function sendQuote(e) {
1798
+ e.preventDefault();
1799
+ const text = $("quote-input").value.replace(/\s+/g, " ").trim(), by = $("quote-author").value.replace(/\s+/g, " ").trim();
1800
+ const say = (t, err) => { $("quote-msg").textContent = t; $("quote-msg").classList.toggle("err", !!err); };
1801
+ if (text.length < 3) return say("Type the quote first.", true);
1802
+ if (Date.now() - quotes.sentAt < 60000) return say("You just sent one. Try again in a minute.", true);
1803
+ const app = await getFirebase();
1804
+ if (!app) return say("Quotes aren't switched on for this site.", true);
1805
+ try {
1806
+ const user = chat.uid ? { uid: chat.uid } : await ensureUser(app);
1807
+ const db = app.database(), TS = window.firebase.database.ServerValue.TIMESTAMP;
1808
+ await db.ref().update({
1809
+ [`quotes/pending/${db.ref("quotes/pending").push().key}`]: { text: text.slice(0, 140), ...(by ? { by: by.slice(0, 30) } : {}), uid: user.uid, ts: TS },
1810
+ [`quotes/last/${user.uid}`]: TS,
1811
+ });
1812
+ quotes.sentAt = Date.now();
1813
+ closeQuoteForm();
1814
+ toast("Thanks! Richard will look at your quote.");
1401
1815
  } catch {
1402
- chatNote("Message blocked (filtered word, or sending too fast).", true);
1816
+ say("Couldn't send. Try again in a minute.", true);
1403
1817
  }
1404
1818
  }
1819
+ // Owner: pending submissions (approve / delete) and the approved list (delete)
1820
+ let quotesPendingRef = null;
1821
+ async function watchQuoteAdmin() {
1822
+ const app = await getFirebase();
1823
+ if (!app || !chat.admin || quotesPendingRef) return;
1824
+ quotesPendingRef = app.database().ref("quotes/pending");
1825
+ quotesPendingRef.on("value", (s) => {
1826
+ const list = [];
1827
+ s.forEach((c) => { list.push({ key: c.key, ...c.val() }); });
1828
+ quotes.pending = list.reverse();
1829
+ renderQuoteAdmin();
1830
+ }, () => { quotesPendingRef = null; });
1831
+ }
1832
+ function renderQuoteAdmin() {
1833
+ const row = (q, pending) => `<div class="report" data-key="${escapeHtml(q.key)}"><div class="body"><span class="game">“${escapeHtml(q.text)}”</span>` +
1834
+ `${q.by ? `<div class="meta">— ${escapeHtml(q.by)}</div>` : ""}</div>` +
1835
+ (pending ? `<button class="mod" type="button" data-q="approve">✓ Approve</button>` : "") +
1836
+ `<button class="mod" type="button" data-q="${pending ? "delete" : "unapprove"}" title="Delete">🗑</button></div>`;
1837
+ const p = quotes.pending;
1838
+ $("quotes-count").textContent = p.length ? `(${p.length})` : "";
1839
+ $("quotes-pending").innerHTML = p.length ? p.map((q) => row(q, true)).join("") : `<p class="none">No new submissions.</p>`;
1840
+ $("quotes-approved").innerHTML = quotes.approved.length ? quotes.approved.map((q) => row(q, false)).join("") : `<p class="none">None yet.</p>`;
1841
+ }
1842
+ function bindQuotes() {
1843
+ $("quote-submit-btn").addEventListener("click", openQuoteForm);
1844
+ $("quote-form").addEventListener("submit", sendQuote);
1845
+ $("quote-close").addEventListener("click", closeQuoteForm);
1846
+ $("quote-cancel").addEventListener("click", closeQuoteForm);
1847
+ $("quote-wrap").addEventListener("click", (e) => { if (e.target === $("quote-wrap")) closeQuoteForm(); });
1848
+ const act = async (e) => {
1849
+ const b = e.target.closest("[data-q]"), row = b?.closest(".report");
1850
+ if (!row || !chat.admin) return;
1851
+ const db = (await getFirebase()).database(), key = row.dataset.key;
1852
+ try {
1853
+ if (b.dataset.q === "approve") {
1854
+ const q = quotes.pending.find((x) => x.key === key);
1855
+ await db.ref().update({ [`quotes/approved/${key}`]: { text: q.text, ...(q.by ? { by: q.by } : {}) }, [`quotes/pending/${key}`]: null });
1856
+ } else if (b.dataset.q === "delete") await db.ref(`quotes/pending/${key}`).remove();
1857
+ else if (b.dataset.q === "unapprove" && confirm("Remove this quote from the rotation?")) await db.ref(`quotes/approved/${key}`).remove();
1858
+ } catch { alert("That didn't work. Are the new database rules published?"); }
1859
+ };
1860
+ $("quotes-pending").addEventListener("click", act);
1861
+ $("quotes-approved").addEventListener("click", act);
1862
+ }
1863
+
1864
+ // ---------- Live stream ----------
1865
+ // The owner streams their screen (with its sound), camera and mic straight to each viewer's browser
1866
+ // (WebRTC). The database only carries the connection set-up messages:
1867
+ // live/state { on, screen, cam, ts } (stream ids, so viewers know which video is which)
1868
+ // live/viewers/<id> { join, offer, answer, oice/*, vice/* } one entry per watching browser
1869
+ // Each viewer gets its own copy of the stream from the owner's computer, so a handful of viewers is
1870
+ // fine; dozens would need a streaming server.
1871
+ const ICE = { iceServers: [{ urls: ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"] }] };
1872
+ const live = { state: null, streams: null, peers: new Map(), viewer: null, audioCtx: null };
1873
+ async function startLiveWatch() {
1874
+ const app = await getFirebase();
1875
+ if (!app) return;
1876
+ app.database().ref("live/state").on("value", (s) => {
1877
+ const st = s.val();
1878
+ const wasOn = !!live.state;
1879
+ live.state = st && st.on ? st : null;
1880
+ document.querySelector('.rail-btn[data-nav="live"]').classList.toggle("is-live", !!live.state);
1881
+ if (live.state && !wasOn && !live.streams) toast("🔴 Richard is live! Open Live in the side bar to watch.");
1882
+ if (!live.state) stopWatching();
1883
+ if (!$("view-live").hidden) renderLive();
1884
+ }, () => {});
1885
+ }
1886
+ function renderLive() {
1887
+ const on = !!live.state, mine = !!live.streams;
1888
+ $("live-pill").hidden = !on;
1889
+ $("live-owner").hidden = !chat.admin;
1890
+ $("live-go").textContent = mine ? "■ End stream" : "🔴 Go live";
1891
+ $("live-lede").textContent = mine ? "You're live. Everyone on the site can watch."
1892
+ : on ? "Richard is live right now." : "Nobody's live right now. When Richard goes live, it shows up here.";
1893
+ $("live-overlay").hidden = mine || !!live.viewer;
1894
+ $("live-overlay-text").textContent = on ? "Richard is live" : "Not live right now";
1895
+ $("live-watch").hidden = !on || mine;
1896
+ updateViewerCount();
1897
+ }
1898
+
1899
+ // -- owner side --
1900
+ async function goLive() {
1901
+ if (live.streams) { await endLive(); return; }
1902
+ const useScreen = $("live-use-screen").checked, useCam = $("live-use-cam").checked, useMic = $("live-use-mic").checked;
1903
+ if (!useScreen && !useCam) { toast("Pick Screen or Camera (or both)."); return; }
1904
+ try {
1905
+ const screen = useScreen ? await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 30 }, audio: true }) : null;
1906
+ const cam = useCam || useMic ? await navigator.mediaDevices.getUserMedia({ video: useCam ? { width: 640, height: 360 } : false, audio: useMic }) : null;
1907
+ // one sound track: the screen's sound and the mic mixed together
1908
+ live.audioCtx = new AudioContext();
1909
+ const mix = live.audioCtx.createMediaStreamDestination();
1910
+ for (const src of [screen, cam]) if (src?.getAudioTracks().length) live.audioCtx.createMediaStreamSource(new MediaStream(src.getAudioTracks())).connect(mix);
1911
+ const mainVideo = screen ? screen.getVideoTracks() : cam ? cam.getVideoTracks() : [];
1912
+ const screenOut = new MediaStream([...mainVideo, ...mix.stream.getAudioTracks()]);
1913
+ const camOut = screen && cam?.getVideoTracks().length ? new MediaStream(cam.getVideoTracks()) : null;
1914
+ live.streams = { screenOut, camOut, raw: [screen, cam].filter(Boolean) };
1915
+ // preview what you're sending (muted, so no echo)
1916
+ $("live-screen").srcObject = screenOut;
1917
+ $("live-cam").srcObject = camOut;
1918
+ $("live-cam").hidden = !camOut;
1919
+ screen?.getVideoTracks()[0]?.addEventListener("ended", endLive); // "Stop sharing" in the browser bar
1920
+ const db = (await getFirebase()).database();
1921
+ await db.ref("live/viewers").remove();
1922
+ db.ref("live/state").onDisconnect().remove();
1923
+ db.ref("live/viewers").onDisconnect().remove();
1924
+ await db.ref("live/state").set({ on: true, main: screenOut.id, cam: camOut ? camOut.id : null, ts: window.firebase.database.ServerValue.TIMESTAMP });
1925
+ db.ref("live/viewers").on("child_added", (s) => connectViewer(db, s.key));
1926
+ db.ref("live/viewers").on("child_removed", (s) => { live.peers.get(s.key)?.close(); live.peers.delete(s.key); updateViewerCount(); });
1927
+ renderLive();
1928
+ } catch (err) {
1929
+ console.warn(err);
1930
+ live.streams?.raw.forEach((m) => m.getTracks().forEach((t) => t.stop()));
1931
+ live.streams = null;
1932
+ toast("Couldn't start the stream (screen, camera or mic was blocked).");
1933
+ }
1934
+ }
1935
+ function updateViewerCount() { $("live-viewers").textContent = live.streams ? `${live.peers.size} watching` : ""; }
1936
+ async function connectViewer(db, id) {
1937
+ if (!live.streams || live.peers.has(id)) return;
1938
+ const pc = new RTCPeerConnection(ICE);
1939
+ live.peers.set(id, pc);
1940
+ updateViewerCount();
1941
+ const { screenOut, camOut } = live.streams;
1942
+ screenOut.getTracks().forEach((t) => pc.addTrack(t, screenOut));
1943
+ camOut?.getTracks().forEach((t) => pc.addTrack(t, camOut));
1944
+ const ref = db.ref(`live/viewers/${id}`);
1945
+ pc.onicecandidate = (e) => { if (e.candidate) ref.child("oice").push(JSON.stringify(e.candidate)); };
1946
+ pc.onconnectionstatechange = () => { if (["failed", "closed"].includes(pc.connectionState)) { live.peers.delete(id); updateViewerCount(); } };
1947
+ const offer = await pc.createOffer();
1948
+ await pc.setLocalDescription(offer);
1949
+ await ref.child("offer").set({ type: offer.type, sdp: offer.sdp });
1950
+ ref.child("answer").on("value", async (s) => { const a = s.val(); if (a && !pc.currentRemoteDescription) await pc.setRemoteDescription(a).catch(() => {}); });
1951
+ ref.child("vice").on("child_added", (s) => { pc.addIceCandidate(JSON.parse(s.val())).catch(() => {}); });
1952
+ }
1953
+ async function endLive() {
1954
+ const db = (await getFirebase())?.database();
1955
+ if (db) { db.ref("live/viewers").off(); await db.ref("live/state").remove().catch(() => {}); await db.ref("live/viewers").remove().catch(() => {}); }
1956
+ live.peers.forEach((pc) => pc.close());
1957
+ live.peers.clear();
1958
+ live.streams?.raw.forEach((m) => m.getTracks().forEach((t) => t.stop()));
1959
+ live.streams = null;
1960
+ live.audioCtx?.close().catch(() => {});
1961
+ live.audioCtx = null;
1962
+ $("live-screen").srcObject = null; $("live-cam").srcObject = null; $("live-cam").hidden = true;
1963
+ renderLive();
1964
+ }
1965
+
1966
+ // -- viewer side --
1967
+ async function watchLive() {
1968
+ if (!live.state || live.viewer) return;
1969
+ const app = await getFirebase();
1970
+ const user = chat.uid ? { uid: chat.uid } : await ensureUser(app);
1971
+ const ref = app.database().ref(`live/viewers/${user.uid}`);
1972
+ const pc = new RTCPeerConnection(ICE);
1973
+ live.viewer = { pc, ref };
1974
+ pc.ontrack = (e) => {
1975
+ const stream = e.streams[0];
1976
+ if (!stream) return;
1977
+ const isCam = !!live.state?.cam && stream.id === live.state.cam;
1978
+ const el = isCam ? $("live-cam") : $("live-screen");
1979
+ if (el.srcObject !== stream) el.srcObject = stream;
1980
+ if (isCam) { $("live-cam").hidden = false; return; }
1981
+ // sound needs a tap first on some browsers: try with sound, else start muted and offer the button
1982
+ el.muted = false;
1983
+ el.play().catch(() => { el.muted = true; el.play().catch(() => {}); $("live-unmute").hidden = false; });
1984
+ };
1985
+ pc.onicecandidate = (e) => { if (e.candidate) ref.child("vice").push(JSON.stringify(e.candidate)); };
1986
+ pc.onconnectionstatechange = () => {
1987
+ if (pc.connectionState === "failed") { toast("Couldn't connect to the stream (your network may block it)."); stopWatching(); renderLive(); }
1988
+ };
1989
+ await ref.remove().catch(() => {});
1990
+ ref.onDisconnect().remove();
1991
+ await ref.set({ join: window.firebase.database.ServerValue.TIMESTAMP });
1992
+ ref.child("offer").on("value", async (s) => {
1993
+ const o = s.val();
1994
+ if (!o || pc.currentRemoteDescription) return;
1995
+ await pc.setRemoteDescription(o);
1996
+ const ans = await pc.createAnswer();
1997
+ await pc.setLocalDescription(ans);
1998
+ await ref.child("answer").set({ type: ans.type, sdp: ans.sdp });
1999
+ });
2000
+ ref.child("oice").on("child_added", (s) => { pc.addIceCandidate(JSON.parse(s.val())).catch(() => {}); });
2001
+ renderLive();
2002
+ }
2003
+ function stopWatching() {
2004
+ if (!live.viewer) return;
2005
+ const { pc, ref } = live.viewer;
2006
+ ref.child("offer").off();
2007
+ ref.child("oice").off();
2008
+ ref.remove().catch(() => {});
2009
+ pc.close();
2010
+ live.viewer = null;
2011
+ if (!live.streams) { $("live-screen").srcObject = null; $("live-cam").srcObject = null; $("live-cam").hidden = true; }
2012
+ $("live-unmute").hidden = true;
2013
+ }
2014
+ function bindLive() {
2015
+ $("live-go").addEventListener("click", goLive);
2016
+ $("live-watch").addEventListener("click", watchLive);
2017
+ $("live-unmute").addEventListener("click", () => { const v = $("live-screen"); v.muted = false; v.play().catch(() => {}); $("live-unmute").hidden = true; });
2018
+ window.addEventListener("pagehide", () => { if (live.streams) endLive(); });
2019
+ }
2020
+
2021
+ // ---------- Emoji picker and stickers ----------
2022
+ // Stickers are Google's Noto animated emoji (CC BY 4.0), sent by code so only these can ever appear.
2023
+ // Grouped into tabs in the picker; every code here was checked to exist on Google's server
2024
+ const STICKER_GROUPS = [
2025
+ ["😂", ["1f602", "1f923", "1f62d", "1f480", "1f973", "1f921", "1f60e", "1f92f", "1f97a", "1f911", "1f644", "1f60d", "1f622", "1f624", "1f976", "1f975", "1f60b", "1f634", "1f47b", "1f600", "1f601", "1f604", "1f605", "1f606", "1f609", "1f60a", "1f607", "1f970", "1f618", "1f61c", "1f92a", "1f92d", "1f92b", "1f914", "1f928", "1f610", "1f611", "1f636", "1f60f", "1f612", "1f62c", "1f925", "1f60c", "1f614", "1f62a", "1f924", "1f637", "1f912", "1f915", "1f922", "1f927", "1f635", "1f920", "1f913", "1f9d0", "1f615", "1f61f", "1f641", "1f62e", "1f62f", "1f632", "1f633", "1f628", "1f630", "1f625", "1f631", "1f616", "1f623", "1f61e", "1f613", "1f629", "1f62b", "1f971", "1f620", "1f621", "1f92c", "1f608", "1f47f", "1f4a9", "1f47d", "1f916", "1f63a", "1f638", "1f639", "1f63b", "1f63f", "1f640", "1f648", "1f649", "1f64a"]],
2026
+ ["👍", ["1f44d", "1f44f", "1f64f", "1f4aa", "1f918", "2764_fe0f", "1f9e0", "1f440", "1f48b", "1f498", "1f494", "1f4a5", "1f4ab", "1f44b", "1f44c", "1f90c", "270c_fe0f", "1f91e", "1f91f", "1f919", "1f44a", "1f91b", "1f64c", "1f450", "1f932", "1f91d", "1f485", "1f933", "1f441_fe0f", "1f483"]],
2027
+ ["🐶", ["1f40d", "1f431", "1f98a", "1f43b", "1f43c", "1f981", "1f42e", "1f438", "1f427", "1f426", "1f985", "1f989", "1f987", "1f43a", "1f984", "1f41d", "1f98b", "1f40c", "1f41e", "1f422", "1f996", "1f995", "1f419", "1f988", "1f42c", "1f433", "1f40a", "1f998", "1f415", "1f413", "1f9a9", "1f407", "1f43f_fe0f", "1f994"]],
2028
+ ["🌈", ["1f340", "1f335", "1f339", "1f337", "1f308", "26a1", "2744_fe0f", "2603_fe0f", "1f30a", "1f30b", "1f30d", "2b50", "2604_fe0f", "1f30c"]],
2029
+ ["🍕", ["1f34e", "1f349", "1f353", "1f951", "1f33d", "1f37f", "1f354", "1f355", "1f32d", "1f32e", "1f942", "1f37e", "1f379", "2615", "1f382", "1f369", "1f36a"]],
2030
+ ["🏆", ["1f3c6", "1f389", "26bd", "1f3c0", "26be", "1f3be", "1f3b3", "1f3af", "1f3b2", "1f3b8", "1f3b7", "1f941", "1f3ac", "1f388", "1f381", "1f38a", "1f386", "1f383", "1f947", "1f3c1"]],
2031
+ ["🚀", ["1f680", "1f525", "1f4af", "1f31f", "1f697", "1f6b2", "1f6f8", "2708_fe0f", "1f6a8", "1f4bb", "1f4f8", "1f48e", "1f514", "1f4a1", "1f50b", "23f0", "231b", "2705", "274c", "2757", "2753", "1f198", "1f4ac", "1f5ff", "1f47e"]],
2032
+ ];
2033
+ const STICKERS = STICKER_GROUPS.flatMap(([, list]) => list);
2034
+ const EMOJI_GROUPS = [
2035
+ ["😀", "😀😃😄😁😆😅😂🤣🥲😊😇🙂🙃😉😌😍🥰😘😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬😮‍💨🤥😴🤤😪😮😯😲🥱😳🥺😢😭😤😠😡🤯😱😨😰🥶🥵😵‍💫🤠🥳😎🤓🧐😈👻💀☠️🤡💩🤖👽"],
2036
+ ["👍", "👍👎👏🙌👐🤝🙏✌️🤞🤟🤘👌🤌🤏👈👉👆👇☝️✋🤚🖐️👋🤙💪🫡🫶"],
2037
+ ["❤️", "❤️🧡💛💚💙💜🖤🤍🤎💔❣️💕💞💓💗💖💘💝💯💢💥💫💦💨🔥✨⭐🌟⚡"],
2038
+ ["🎮", "🎮🕹️🏆🥇🥈🥉🎯🎲🧩♟️⚽🏀🏈⚾🎾🏐🏉🎱🏓🏒⛳🛹🏁🚗🏎️🚀✈️👾"],
2039
+ ["🍕", "🍕🍔🍟🌭🌮🌯🍿🍩🍪🎂🍰🧁🍫🍬🍭🍦🍉🍓🍌🍎🥤🧃☕🧋"],
2040
+ ["🐶", "🐶🐱🐭🐹🐰🦊🐻🐼🐨🐯🦁🐮🐷🐸🐵🙈🙉🙊🐔🐧🐦🐤🦆🦅🦉🐺🐗🐴🦄🐝🐛🦋🐌🐞🐢🐍🦖🐙🦈🐬🐳"],
2041
+ ];
2042
+ function buildPicker() {
2043
+ const seg = (s) => [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s)].map((x) => x.segment);
2044
+ $("picker-tabs").innerHTML = EMOJI_GROUPS.map(([icon], i) => `<button type="button" role="tab" data-tab="${i}" aria-selected="${i === 0}" title="Emoji">${icon}</button>`).join("") +
2045
+ `<button type="button" role="tab" data-tab="stickers" aria-selected="false" class="tab-stickers">Stickers</button>`;
2046
+ const showTab = (tab) => {
2047
+ $("picker-tabs").querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", b.dataset.tab === String(tab)));
2048
+ $("picker-grid").className = "picker-grid" + (tab === "stickers" ? " stickers" : "");
2049
+ $("picker-grid").innerHTML = tab === "stickers"
2050
+ ? STICKER_GROUPS.map(([icon, list]) => `<p class="picker-head">${icon}</p>` +
2051
+ list.map((c) => `<button type="button" data-sticker="${c}" title="Send sticker"><img src="${STICKER_URL(c)}" alt="" width="56" height="56" loading="lazy"></button>`).join("")).join("")
2052
+ : seg(EMOJI_GROUPS[tab][1]).map((e) => `<button type="button" data-emoji="${e}">${e}</button>`).join("");
2053
+ };
2054
+ showTab(0);
2055
+ $("picker-tabs").addEventListener("click", (e) => { const b = e.target.closest("[data-tab]"); if (b) showTab(/^\d+$/.test(b.dataset.tab) ? Number(b.dataset.tab) : b.dataset.tab); });
2056
+ $("picker-grid").addEventListener("click", async (e) => {
2057
+ const em = e.target.closest("[data-emoji]"), st = e.target.closest("[data-sticker]");
2058
+ if (em) insertAtCursor($("chat-text"), em.dataset.emoji);
2059
+ if (st && await postMessage({ sticker: st.dataset.sticker })) togglePicker(false);
2060
+ });
2061
+ }
2062
+ function insertAtCursor(input, text) {
2063
+ const s = input.selectionStart ?? input.value.length, e = input.selectionEnd ?? s;
2064
+ if (input.value.length + text.length > input.maxLength) return;
2065
+ input.value = input.value.slice(0, s) + text + input.value.slice(e);
2066
+ input.selectionStart = input.selectionEnd = s + text.length;
2067
+ input.focus();
2068
+ }
2069
+ function togglePicker(open = $("picker").hidden) {
2070
+ if (open && !$("picker-grid").children.length) buildPicker();
2071
+ $("picker").hidden = !open;
2072
+ $("emoji-btn").setAttribute("aria-expanded", open);
2073
+ }
2074
+
2075
+ // ---------- Photos: drag and drop, paste, or 📷 ----------
2076
+ // Posted straight away (no review). Before sending, a nudity detector (NSFW.js, runs in this browser)
2077
+ // checks the picture; the photo is re-drawn, which also strips hidden data like location, and shrunk to ≤ ~100 KB.
2078
+ let nsfwModel = null;
2079
+ function loadNsfw() {
2080
+ if (!nsfwModel) {
2081
+ nsfwModel = (async () => {
2082
+ await loadScript("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.22.0/dist/tf.min.js");
2083
+ await loadScript("https://cdn.jsdelivr.net/npm/nsfwjs@4.2.1/dist/browser/nsfwjs.min.js");
2084
+ return window.nsfwjs.load("https://cdn.jsdelivr.net/gh/infinitered/nsfwjs@v4.2.1/models/mobilenet_v2/model.json", { size: 224 });
2085
+ })().catch((err) => { nsfwModel = null; throw err; });
2086
+ }
2087
+ return nsfwModel;
2088
+ }
2089
+ async function sendPhoto(file) {
2090
+ if (!file || !/^image\//.test(file.type)) { chatNote("That isn't a picture.", true); return; }
2091
+ if (file.size > 20 * 1048576) { chatNote("That picture is too big (20 MB max).", true); return; }
2092
+ if (!chatSender()) return; // banned, muted, locked, no nickname, too fast: say so before the slow part
2093
+ chatNote("Checking photo…");
2094
+ $("photo-btn").disabled = true;
2095
+ try {
2096
+ const bmp = await createImageBitmap(file);
2097
+ let verdict;
2098
+ try {
2099
+ const model = await loadNsfw();
2100
+ const c = document.createElement("canvas");
2101
+ c.width = c.height = 224;
2102
+ c.getContext("2d").drawImage(bmp, 0, 0, 224, 224);
2103
+ verdict = Object.fromEntries((await model.classify(c)).map((p) => [p.className, p.probability]));
2104
+ } catch {
2105
+ chatNote("Couldn't check that photo, so it wasn't sent. Try again in a moment.", true);
2106
+ return;
2107
+ }
2108
+ // the one check that stays: nude photos aren't sent (the chat is full of kids)
2109
+ if ((verdict.Porn || 0) > 0.35 || (verdict.Hentai || 0) > 0.35 || (verdict.Sexy || 0) > 0.6) {
2110
+ chatNote("That photo can't be sent here.", true);
2111
+ return;
2112
+ }
2113
+ const img = await shrinkPhoto(bmp);
2114
+ if (await postMessage({ img })) chatNote("");
2115
+ } catch {
2116
+ chatNote("Couldn't read that picture.", true);
2117
+ } finally {
2118
+ $("photo-btn").disabled = !!blockedReason();
2119
+ $("photo-input").value = "";
2120
+ }
2121
+ }
2122
+ async function shrinkPhoto(bmp) {
2123
+ for (const [side, q] of [[720, 0.72], [600, 0.62], [480, 0.55], [360, 0.5]]) {
2124
+ const k = Math.min(1, side / Math.max(bmp.width, bmp.height));
2125
+ const c = document.createElement("canvas");
2126
+ c.width = Math.round(bmp.width * k); c.height = Math.round(bmp.height * k);
2127
+ c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height);
2128
+ let url = c.toDataURL("image/webp", q);
2129
+ if (!url.startsWith("data:image/webp")) url = c.toDataURL("image/jpeg", q); // Safari: no WebP encoder
2130
+ if (url.length <= 140000) return url;
2131
+ }
2132
+ throw new Error("too big");
2133
+ }
2134
+ // ---------- 📸 Take a photo with the camera ----------
2135
+ // Live preview → snapshot (mirrored like a selfie) → "Send to chat" goes through sendPhoto, so it gets
2136
+ // the same nude-photo check and shrinking as any other photo.
2137
+ let camStream = null;
2138
+ async function openCamera() {
2139
+ if (!chatSender()) return; // banned, muted, no nickname…: say so first
2140
+ $("cam-msg").textContent = "";
2141
+ showCamShot(false);
2142
+ $("cam-wrap").hidden = false;
2143
+ try {
2144
+ camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user", width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false });
2145
+ $("cam-video").srcObject = camStream;
2146
+ } catch {
2147
+ $("cam-msg").textContent = "Couldn't open your camera. Allow camera access in the browser and try again.";
2148
+ $("cam-msg").classList.add("err");
2149
+ }
2150
+ }
2151
+ function showCamShot(taken) {
2152
+ $("cam-video").hidden = taken; $("cam-shot").hidden = !taken;
2153
+ $("cam-snap").hidden = taken; $("cam-retake").hidden = !taken; $("cam-send").hidden = !taken;
2154
+ }
2155
+ function snapCamera() {
2156
+ const v = $("cam-video"), c = $("cam-shot");
2157
+ if (!v.videoWidth) return;
2158
+ c.width = v.videoWidth; c.height = v.videoHeight;
2159
+ const g = c.getContext("2d");
2160
+ g.translate(c.width, 0); g.scale(-1, 1); // mirror, matching the preview
2161
+ g.drawImage(v, 0, 0);
2162
+ showCamShot(true);
2163
+ }
2164
+ function closeCamera() {
2165
+ camStream?.getTracks().forEach((t) => t.stop());
2166
+ camStream = null;
2167
+ $("cam-video").srcObject = null;
2168
+ $("cam-wrap").hidden = true;
2169
+ }
2170
+ function sendCamPhoto() {
2171
+ $("cam-shot").toBlob((blob) => {
2172
+ closeCamera();
2173
+ if (blob) sendPhoto(new File([blob], "camera.jpg", { type: "image/jpeg" }));
2174
+ }, "image/jpeg", 0.9);
2175
+ }
2176
+ function bindChatExtras() {
2177
+ $("cam-btn").addEventListener("click", openCamera);
2178
+ $("cam-snap").addEventListener("click", snapCamera);
2179
+ $("cam-retake").addEventListener("click", () => showCamShot(false));
2180
+ $("cam-send").addEventListener("click", sendCamPhoto);
2181
+ $("cam-close").addEventListener("click", closeCamera);
2182
+ $("cam-wrap").addEventListener("click", (e) => { if (e.target === $("cam-wrap")) closeCamera(); });
2183
+ $("emoji-btn").addEventListener("click", () => togglePicker());
2184
+ $("chat-full-btn").addEventListener("click", () => setChatFull(!$("chat-box").classList.contains("full")));
2185
+ document.addEventListener("pointerdown", (e) => {
2186
+ if (!$("picker").hidden && !e.target.closest("#picker, #emoji-btn")) togglePicker(false);
2187
+ });
2188
+ $("picker").addEventListener("keydown", (e) => { if (e.key === "Escape") { togglePicker(false); $("emoji-btn").focus(); } });
2189
+ $("photo-btn").addEventListener("click", () => $("photo-input").click());
2190
+ $("photo-input").addEventListener("change", () => sendPhoto($("photo-input").files[0]));
2191
+ const box = $("chat-box");
2192
+ let depth = 0;
2193
+ box.addEventListener("dragenter", (e) => { if ([...e.dataTransfer.types].includes("Files")) { e.preventDefault(); depth++; box.classList.add("dropping"); } });
2194
+ box.addEventListener("dragover", (e) => { if ([...e.dataTransfer.types].includes("Files")) e.preventDefault(); });
2195
+ box.addEventListener("dragleave", () => { if (--depth <= 0) { depth = 0; box.classList.remove("dropping"); } });
2196
+ box.addEventListener("drop", (e) => {
2197
+ e.preventDefault(); depth = 0; box.classList.remove("dropping");
2198
+ sendPhoto([...e.dataTransfer.files].find((f) => f.type.startsWith("image/")));
2199
+ });
2200
+ $("chat-text").addEventListener("paste", (e) => {
2201
+ const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith("image/"));
2202
+ if (f) { e.preventDefault(); sendPhoto(f); }
2203
+ });
2204
+ }
1405
2205
 
1406
2206
  // ---------- Chat beside a game, and the unread dot ----------
1407
2207
  // There's one chat box: it sits on the Chat page, or in the player's side dock while that's open.
1408
2208
  const CHAT_SEEN_KEY = "rug-chat-seen", CHAT_DOCK_KEY = "rug-chat-dock";
1409
2209
  function dockOpen() { return !els.player.hidden && store.get(CHAT_DOCK_KEY, false); }
1410
- function chatShowing() { return dockOpen() || (els.player.hidden && !$("view-chat").hidden); }
2210
+ function liveShowing() { return els.player.hidden && !$("view-live").hidden; }
2211
+ function chatShowing() { return dockOpen() || (els.player.hidden && !$("view-chat").hidden) || liveShowing(); }
1411
2212
  function placeChatBox() {
1412
2213
  const docked = dockOpen();
1413
2214
  $("chat-dock").hidden = !docked;
1414
2215
  $("dock-btn").setAttribute("aria-pressed", docked);
1415
- const home = docked ? $("chat-dock") : $("view-chat");
2216
+ // the one chat box sits beside a game, beside the live stream, or on the Chat page
2217
+ const home = docked ? $("chat-dock") : liveShowing() ? $("live-chat") : $("view-chat");
2218
+ switchRoom(liveShowing() && !docked ? "live" : "main");
1416
2219
  if ($("chat-box").parentNode !== home) home.appendChild($("chat-box"));
2220
+ if (!chatShowing() && $("chat-box").classList.contains("full")) setChatFull(false);
1417
2221
  if (chatShowing()) markChatSeen();
2222
+ updateHere();
1418
2223
  }
1419
2224
  function toggleDock(open = !store.get(CHAT_DOCK_KEY, false)) {
1420
2225
  store.set(CHAT_DOCK_KEY, open);
@@ -1429,6 +2234,34 @@
1429
2234
  else if (mention) b.classList.add("has-mention");
1430
2235
  });
1431
2236
  }
2237
+ // "N in chat right now": chat/here/<id> exists while this browser has the chat open (or the live stream)
2238
+ let hereRef = null, hereOn = false;
2239
+ async function updateHere() {
2240
+ const want = chatShowing();
2241
+ if (want === hereOn || !chat.uid) return;
2242
+ const app = await getFirebase();
2243
+ if (!app) return;
2244
+ hereOn = want;
2245
+ hereRef ||= app.database().ref(roomPath(`here/${chat.uid}`));
2246
+ if (want) { hereRef.onDisconnect().remove(); hereRef.set(true).catch(() => {}); }
2247
+ else hereRef.remove().catch(() => {});
2248
+ }
2249
+ function watchHere(db) {
2250
+ chat.hereWatch?.off();
2251
+ chat.hereWatch = db.ref(roomPath("here"));
2252
+ const where = chat.room === "live" ? "watching" : "in chat";
2253
+ chat.hereWatch.on("value", (s) => {
2254
+ const n = s.numChildren();
2255
+ $("chat-here-n").textContent = n <= 1 ? `Just you ${where}` : `${n} ${where} right now`;
2256
+ }, () => { $("chat-here-n").textContent = ""; });
2257
+ }
2258
+ // Full-screen chat: the chat box covers the whole page (Esc or the button leaves)
2259
+ function setChatFull(on) {
2260
+ $("chat-box").classList.toggle("full", on);
2261
+ document.body.classList.toggle("chat-full", on);
2262
+ $("chat-full-btn").textContent = on ? "✕ Exit full screen" : "⛶ Full screen";
2263
+ if (on) $("chat-text").focus();
2264
+ }
1432
2265
  function markChatSeen() {
1433
2266
  if (chat.newest) store.set(CHAT_SEEN_KEY, chat.newest);
1434
2267
  setUnread(false);
@@ -1476,6 +2309,8 @@
1476
2309
  const keys = CFG.panicKeys || ["`", "]"];
1477
2310
  if (keys.includes(e.key)) { e.preventDefault(); panic(); return; }
1478
2311
  if (!$("report-wrap").hidden) { if (e.key === "Escape") closeReport(); return; }
2312
+ if (!$("cam-wrap").hidden) { if (e.key === "Escape") closeCamera(); return; }
2313
+ if (e.key === "Escape" && $("chat-box").classList.contains("full")) { setChatFull(false); return; }
1479
2314
  if (!$("wheel-wrap").hidden) {
1480
2315
  if (e.key === "Escape") closeWheel();
1481
2316
  else if (e.key === " " && wheel.spinning) { e.preventDefault(); finishWheel(); } // space skips
@@ -1548,8 +2383,9 @@
1548
2383
  els.search.value = els.homeInput.value;
1549
2384
  els.homeInput.value = "";
1550
2385
  setTag("All");
1551
- go("games");
2386
+ go("games", { instant: true });
1552
2387
  els.search.focus();
2388
+ els.search.setSelectionRange(els.search.value.length, els.search.value.length); // keep typing at the end
1553
2389
  renderGrid();
1554
2390
  };
1555
2391
  els.homeInput.addEventListener("input", () => { if (els.homeInput.value.trim()) fromHome(); });
@@ -1726,13 +2562,17 @@
1726
2562
  $("chat-text").addEventListener("blur", stopTyping);
1727
2563
  $("chat-log").addEventListener("click", mentionFromName);
1728
2564
  bindAdmin();
2565
+ bindChatTools();
2566
+ bindChatExtras();
2567
+ bindQuotes();
2568
+ bindLive();
1729
2569
  bindReports();
1730
2570
  startAnalytics();
1731
2571
  startPresence();
1732
2572
  // Listen to chat from the start so the chat buttons can show a dot for new messages.
1733
2573
  // First visit: only messages from now on count as new.
1734
2574
  if (store.get(CHAT_SEEN_KEY, null) === null) store.set(CHAT_SEEN_KEY, Date.now());
1735
- if (CFG.firebase) openChat();
2575
+ if (CFG.firebase) { openChat(); startQuotes(); startLiveWatch(); }
1736
2576
  // long enough to read a joke or two (skipped when the loading screen is off)
1737
2577
  const minShow = new Promise((r) => setTimeout(r, settings.boot !== false ? 1500 : 0));
1738
2578
  const update = newerVersionUrl(2500);
@@ -1741,6 +2581,7 @@
1741
2581
  const data = await res.json();
1742
2582
  games = data.games.slice().sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
1743
2583
  byId = new Map(games.map((g) => [g.id, g]));
2584
+ cdnPins = data.cdnPins || {};
1744
2585
  } catch (err) {
1745
2586
  console.error(err);
1746
2587
  els.homeSub.textContent = "Couldn't load the game list. Try refreshing.";