Web app, uhttpd shell CGI backend, installer, build script and dev server. README merged with the repository's project description. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1616 lines
68 KiB
Bash
Executable File
1616 lines
68 KiB
Bash
Executable File
#!/bin/sh
|
||
# Cabin Chat 3.0.0 - self-contained installer for OpenWrt / GL.iNet routers.
|
||
# Uses only what the firmware already ships (uhttpd, busybox, uci).
|
||
#
|
||
# sh install-cabinchat.sh install, or upgrade an existing install
|
||
# (keeps messages, photos and the port)
|
||
# sh install-cabinchat.sh -p 8090 install/upgrade on a specific port
|
||
# sh install-cabinchat.sh wipe delete all messages and photos
|
||
# sh install-cabinchat.sh uninstall remove Cabin Chat completely
|
||
#
|
||
# Generated by build.sh - edit www/ and installer.sh.in instead of this file.
|
||
|
||
VERSION="3.0.0"
|
||
APP=/www-chat
|
||
WEB=$APP/htdocs
|
||
DATA=$APP/data
|
||
RUN=/tmp/cabinchat
|
||
CLOCK=/etc/cabinchat.clock
|
||
DNSNAME=chat.lan
|
||
DEFAULT_PORT=8088
|
||
STAGE=/tmp/cabinchat-stage.$$
|
||
|
||
info() { echo ">> $*"; }
|
||
warn() { echo "WARNING: $*" >&2; }
|
||
die() { echo "ERROR: $*" >&2; rm -rf "$STAGE"; exit 1; }
|
||
usage() { sed -n '4,9p' "$0" | sed 's/^# \{0,1\}//'; }
|
||
|
||
listening() { netstat -tln 2>/dev/null | grep -qE "[:.]$1[[:space:]]"; }
|
||
|
||
configured_port() {
|
||
uci -q get uhttpd.chat.listen_http | tr ' ' '\n' | sed -n 's/.*:\([0-9][0-9]*\)$/\1/p' | head -n 1
|
||
}
|
||
|
||
remove_config() {
|
||
if uci -q get uhttpd.chat >/dev/null; then
|
||
uci delete uhttpd.chat
|
||
uci commit uhttpd
|
||
fi
|
||
for a in $(uci -q get dhcp.@dnsmasq[0].address); do
|
||
case $a in "/$DNSNAME/"*) uci del_list dhcp.@dnsmasq[0].address="$a" ;; esac
|
||
done
|
||
uci commit dhcp
|
||
[ -f /etc/sysupgrade.conf ] && sed -i "\#^$APP/\$#d" /etc/sysupgrade.conf
|
||
}
|
||
|
||
extract_payload() {
|
||
rm -rf "$STAGE"
|
||
mkdir -p "$STAGE" || die "cannot create $STAGE"
|
||
cat > "$STAGE/VERSION" <<'__CABINCHAT_EOF__'
|
||
3.0.0
|
||
__CABINCHAT_EOF__
|
||
mkdir -p "$STAGE/cgi-bin"
|
||
cat > "$STAGE/cgi-bin/chat" <<'__CABINCHAT_EOF__'
|
||
#!/bin/sh
|
||
# Cabin Chat backend - CGI script for uhttpd (OpenWrt) or devserver.py.
|
||
# Needs only POSIX sh + busybox tools.
|
||
#
|
||
# Layout (APP = /www-chat on the router, the project folder when developing):
|
||
# APP/htdocs/ web root: index.html, cgi-bin/chat, img/ (photos)
|
||
# APP/data/messages one message per line, 8 TAB-separated fields:
|
||
# id ts type from to re nick payload
|
||
# type t: payload = text
|
||
# type i: payload = "<file> <width> <height>" (file in img/)
|
||
# to: "*" = everyone, otherwise the recipient's public id
|
||
# re: id of the quoted message, 0 = none
|
||
# APP/data/seq last message id (never decreases)
|
||
# /tmp/cabinchat/ volatile state: presence, typing, event token, key cache
|
||
# data/ is outside the web root, so private messages can't be downloaded directly;
|
||
# photo file names contain a random part, so they can't be guessed.
|
||
#
|
||
# Identity: each browser keeps a random secret key (k, 32 hex). The server derives a
|
||
# public id from it (first 16 hex of its MD5). Only public ids are ever sent out.
|
||
#
|
||
# API
|
||
# GET chat?k=KEY&n=NICKHEX&since=ID&ev=TOKEN&w=1
|
||
# Long poll: if nothing changed since TOKEN, waits up to HOLD seconds.
|
||
# Reply: @now <TAB> lastid <TAB> token <TAB> my-public-id
|
||
# U <TAB> id <TAB> nickhex <TAB> last-seen (users seen in 24 h)
|
||
# W <TAB> id <TAB> to <TAB> ts (who is typing)
|
||
# messages with since < id <= lastid that this user may see
|
||
# POST chat?a=text&k=KEY&n=NICKHEX&to=*|ID&re=ID body: UTF-8 text
|
||
# POST chat?a=img&k=KEY&n=NICKHEX&to=*|ID&re=ID&w=W&h=H&r=RND body: JPEG
|
||
# POST chat?a=typing&k=KEY&n=NICKHEX&to=*|ID|- (- = stopped)
|
||
#
|
||
# Timestamps come from the router's clock; clients only show relative ages.
|
||
# To keep that clock sane after a power cut (no RTC, no NTP in the air), the
|
||
# script touches CLOCK in /etc every few minutes: OpenWrt's sysfixtime sets the
|
||
# clock at boot to the newest file time found in /etc.
|
||
|
||
KEEP=86400 # rolling window: 24 h
|
||
HOLD=25 # long-poll hold time, seconds
|
||
ONLINE=70 # seen within this many seconds = online (clients do the math)
|
||
TYPING=8 # a typing notice lives this long
|
||
MAX_TEXT=4000 # bytes per text message
|
||
MAX_IMG=400000 # bytes per photo (the client aims for ~100 kB)
|
||
MAX_DATA_KB=51200 # refuse new photos once img/ exceeds 50 MB
|
||
|
||
case $0 in */*) WEB=${0%/*}; WEB=${WEB%/*} ;; *) WEB=.. ;; esac
|
||
DATA=${CABINCHAT_DATA:-$WEB/../data}
|
||
IMG=$WEB/img
|
||
LOG=$DATA/messages
|
||
SEQ=$DATA/seq
|
||
RUN=${TMPDIR:-/tmp}/cabinchat
|
||
EV=$RUN/ev
|
||
LOCKDIR=$RUN/lock
|
||
CLOCK=${CABINCHAT_CLOCK-/etc/cabinchat.clock}
|
||
NOW=$(date +%s)
|
||
qs="&$QUERY_STRING&"
|
||
me=
|
||
|
||
# ---------------------------------------------------------------- helpers
|
||
hdr() { printf 'Status: %s\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n' "$1"; }
|
||
fail() { hdr "$1"; echo "$2"; exit 0; }
|
||
|
||
# get NAME -> $v (raw value from the query string, empty if missing)
|
||
get() { v=${qs#*"&$1="}; if [ "$v" = "$qs" ]; then v=; else v=${v%%&*}; fi; }
|
||
|
||
num() { case $1 in ''|*[!0-9]*) return 1 ;; esac; }
|
||
hex() { case $1 in ''|*[!0-9a-f]*) return 1 ;; esac; }
|
||
pubid() { hex "$1" && [ ${#1} -eq 16 ]; }
|
||
|
||
take_lock() {
|
||
i=0
|
||
while ! mkdir "$LOCKDIR" 2>/dev/null; do
|
||
i=$((i + 1))
|
||
[ $i -gt 50 ] && { rm -rf "$LOCKDIR"; i=0; } # stale lock
|
||
sleep 0.1 2>/dev/null || sleep 1
|
||
done
|
||
}
|
||
drop_lock() { rmdir "$LOCKDIR" 2>/dev/null; }
|
||
|
||
# something changed: wakes up every waiting long poll
|
||
bump() { echo "$NOW.$$" > "$EV"; }
|
||
|
||
read_body() {
|
||
if head -c 1 </dev/null >/dev/null 2>&1; then head -c "$cl"; else cat; fi
|
||
}
|
||
|
||
hash16() {
|
||
if command -v md5sum >/dev/null 2>&1; then printf '%s' "$1" | md5sum | cut -c 1-16
|
||
elif command -v md5 >/dev/null 2>&1; then printf '%s' "$1" | md5 -q | cut -c 1-16
|
||
else printf '%016x\n' "$(printf '%s' "$1" | cksum | cut -d ' ' -f 1)"
|
||
fi
|
||
}
|
||
|
||
# k -> $me (public id); cached in RAM so the hash runs once per browser
|
||
identify() {
|
||
get k; key=$v
|
||
hex "$key" && [ ${#key} -eq 32 ] || fail "400 Bad Request" "bad key"
|
||
[ -f "$RUN/keys/$key" ] && read -r me < "$RUN/keys/$key"
|
||
if ! pubid "$me"; then
|
||
me=$(hash16 "$key")
|
||
printf '%s\n' "$me" > "$RUN/keys/$key"
|
||
fi
|
||
}
|
||
|
||
# record that $me is here; wake everybody if that is news
|
||
seen_me() {
|
||
get n; nick=$v
|
||
hex "$nick" && [ ${#nick} -le 200 ] || nick=
|
||
[ -n "$nick" ] || return 0
|
||
f=$RUN/users/$me; ps=0; pn=
|
||
[ -f "$f" ] && read -r ps pn < "$f"
|
||
num "$ps" || ps=0
|
||
printf '%s %s\n' "$NOW" "$nick" > "$f"
|
||
if [ "$ps" -lt $((NOW - ONLINE + 20)) ] || [ "$pn" != "$nick" ]; then bump; fi
|
||
}
|
||
|
||
# a power cut can leave a half-written last line: make sure we start on a new one
|
||
ensure_nl() { [ -s "$LOG" ] && [ -n "$(tail -c 1 "$LOG")" ] && echo >> "$LOG"; }
|
||
|
||
next_id() {
|
||
id=$(cat "$SEQ" 2>/dev/null)
|
||
if ! num "$id"; then
|
||
id=$(tail -n 1 "$LOG" 2>/dev/null | cut -f 1)
|
||
num "$id" || id=0
|
||
fi
|
||
id=$((id + 1))
|
||
printf '%s\n' "$id" > "$SEQ.tmp" && mv "$SEQ.tmp" "$SEQ"
|
||
}
|
||
|
||
read_seq() { lastid=0; [ -f "$SEQ" ] && read -r lastid < "$SEQ"; num "$lastid" || lastid=0; }
|
||
|
||
needs_prune() {
|
||
[ -s "$LOG" ] || return 1
|
||
first=$(head -n 1 "$LOG" | cut -f 2)
|
||
num "$first" || return 0
|
||
[ "$first" -lt $((NOW - KEEP)) ]
|
||
}
|
||
|
||
# drop expired (and malformed) lines, delete their photos; call with lock held
|
||
prune() {
|
||
needs_prune || return 0
|
||
awk -F '\t' -v c=$((NOW - KEEP)) -v del="$DATA/.del" '
|
||
NF == 8 && $1 ~ /^[0-9]+$/ && $2 >= c { print; next }
|
||
$3 == "i" { split($8, a, " "); print a[1] > del }
|
||
' "$LOG" > "$LOG.tmp" && mv "$LOG.tmp" "$LOG"
|
||
if [ -f "$DATA/.del" ]; then
|
||
while IFS= read -r f; do
|
||
case $f in .*|*[!0-9a-f.-]*) ;; *.jpg) rm -f "$IMG/$f" ;; esac
|
||
done < "$DATA/.del"
|
||
rm -f "$DATA/.del"
|
||
fi
|
||
# photos whose message line never got written (power cut during upload)
|
||
find "$IMG" -type f -mtime +2 -exec rm -f {} \; 2>/dev/null
|
||
}
|
||
|
||
touch_clock() {
|
||
[ -n "$CLOCK" ] || return 0
|
||
last=$(cat "$CLOCK" 2>/dev/null); num "$last" || last=0
|
||
[ $((NOW - last)) -ge 300 ] || return 0
|
||
printf '%s\n' "$NOW" > "$CLOCK.tmp" && mv "$CLOCK.tmp" "$CLOCK"
|
||
}
|
||
|
||
append() { # type payload
|
||
ensure_nl
|
||
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$NOW" "$1" "$me" "$to" "$re" "$nick" "$2" >> "$LOG"
|
||
}
|
||
|
||
for d in "$DATA" "$IMG" "$RUN/keys" "$RUN/users" "$RUN/typing"; do
|
||
[ -d "$d" ] || mkdir -p "$d" || fail "500 Internal Server Error" "cannot create $d"
|
||
done
|
||
[ -f "$EV" ] || bump
|
||
|
||
# ---------------------------------------------------------------- POST
|
||
if [ "$REQUEST_METHOD" = POST ]; then
|
||
identify
|
||
seen_me
|
||
[ -n "$nick" ] || fail "400 Bad Request" "bad nick"
|
||
get a; act=$v
|
||
get to; to=$v
|
||
|
||
if [ "$act" = typing ]; then
|
||
case $to in
|
||
-) rm -f "$RUN/typing/$me" ;;
|
||
'*') printf '* %s\n' "$NOW" > "$RUN/typing/$me" ;;
|
||
*) pubid "$to" || fail "400 Bad Request" "bad recipient"
|
||
printf '%s %s\n' "$to" "$NOW" > "$RUN/typing/$me" ;;
|
||
esac
|
||
bump
|
||
hdr "200 OK"; echo ok
|
||
exit 0
|
||
fi
|
||
|
||
[ "$to" = '*' ] || pubid "$to" || fail "400 Bad Request" "bad recipient"
|
||
get re; re=$v; num "$re" || re=0
|
||
cl=${CONTENT_LENGTH:-0}; num "$cl" || cl=0
|
||
[ "$cl" -gt 0 ] || fail "400 Bad Request" "empty"
|
||
|
||
case $act in
|
||
text)
|
||
[ "$cl" -le $MAX_TEXT ] || fail "413 Payload Too Large" "message too long"
|
||
msg=$(read_body | tr '\t\r\n' ' ')
|
||
case $msg in *[![:space:]]*) ;; *) fail "400 Bad Request" "empty" ;; esac
|
||
take_lock; prune; next_id; append t "$msg"; drop_lock
|
||
;;
|
||
img)
|
||
[ "$cl" -le $MAX_IMG ] || fail "413 Payload Too Large" "photo too large"
|
||
used=$(du -sk "$IMG" 2>/dev/null | cut -f 1); num "$used" || used=0
|
||
[ "$used" -lt $MAX_DATA_KB ] || fail "507 Insufficient Storage" "storage full"
|
||
get w; w=$v; num "$w" || w=0
|
||
get h; h=$v; num "$h" || h=0
|
||
get r; rnd=$v
|
||
hex "$rnd" && [ ${#rnd} -eq 16 ] || fail "400 Bad Request" "bad r"
|
||
tmp=$IMG/.upload.$$
|
||
read_body > "$tmp"
|
||
size=$(wc -c < "$tmp"); size=$((size))
|
||
if [ "$size" -ne "$cl" ]; then rm -f "$tmp"; fail "400 Bad Request" "incomplete upload"; fi
|
||
if [ "$(head -c 3 "$tmp")" != "$(printf '\377\330\377')" ]; then
|
||
rm -f "$tmp"; fail "415 Unsupported Media Type" "JPEG expected"
|
||
fi
|
||
take_lock; prune; next_id
|
||
mv "$tmp" "$IMG/$id-$rnd.jpg"
|
||
append i "$id-$rnd.jpg $w $h"
|
||
drop_lock
|
||
;;
|
||
*) fail "400 Bad Request" "unknown action" ;;
|
||
esac
|
||
rm -f "$RUN/typing/$me"
|
||
bump
|
||
touch_clock
|
||
hdr "200 OK"; echo "$id"
|
||
exit 0
|
||
fi
|
||
|
||
# ---------------------------------------------------------------- GET (long poll)
|
||
identify
|
||
seen_me
|
||
get since; since=$v; num "$since" || since=0
|
||
get ev; cev=$v
|
||
get w; wait=$v
|
||
if needs_prune; then take_lock; prune; drop_lock; fi
|
||
read_seq
|
||
read -r ev < "$EV"
|
||
|
||
if [ "$wait" = 1 ] && [ "$cev" = "$ev" ] && [ "$since" -ge "$lastid" ]; then
|
||
# nothing new: hold the request until something changes or HOLD runs out.
|
||
# Only builtins (read) and sleep run in this loop.
|
||
if sleep 0.01 2>/dev/null; then step=0.5; loops=$((HOLD * 2)); else step=1; loops=$HOLD; fi
|
||
while [ $loops -gt 0 ]; do
|
||
sleep $step
|
||
read -r ev < "$EV"
|
||
[ "$ev" != "$cev" ] && break
|
||
loops=$((loops - 1))
|
||
done
|
||
NOW=$(date +%s)
|
||
read_seq
|
||
[ -n "$nick" ] && printf '%s %s\n' "$NOW" "$nick" > "$RUN/users/$me"
|
||
fi
|
||
|
||
touch_clock
|
||
hdr "200 OK"
|
||
printf '@%s\t%s\t%s\t%s\n' "$NOW" "$lastid" "$ev" "$me"
|
||
|
||
for f in "$RUN"/users/*; do
|
||
[ -f "$f" ] || continue
|
||
read -r s n < "$f"
|
||
num "$s" || continue
|
||
if [ "$s" -ge $((NOW - KEEP)) ]; then
|
||
printf 'U\t%s\t%s\t%s\n' "${f##*/}" "$n" "$s"
|
||
else
|
||
rm -f "$f"
|
||
fi
|
||
done
|
||
|
||
for f in "$RUN"/typing/*; do
|
||
[ -f "$f" ] || continue
|
||
p=${f##*/}
|
||
[ "$p" = "$me" ] && continue
|
||
read -r t ts < "$f"
|
||
num "$ts" || continue
|
||
[ "$ts" -ge $((NOW - TYPING)) ] || continue
|
||
case $t in '*'|"$me") printf 'W\t%s\t%s\t%s\n' "$p" "$t" "$ts" ;; esac
|
||
done
|
||
|
||
if [ "$since" -lt "$lastid" ] && [ -s "$LOG" ]; then
|
||
awk -F '\t' -v s="$since" -v l="$lastid" -v me="$me" '
|
||
NF == 8 && $1 ~ /^[0-9]+$/ && $1 + 0 > s + 0 && $1 + 0 <= l + 0 &&
|
||
($5 == "*" || $5 == me || $4 == me)
|
||
' "$LOG"
|
||
fi
|
||
__CABINCHAT_EOF__
|
||
cat > "$STAGE/index.html" <<'__CABINCHAT_EOF__'
|
||
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
|
||
<meta name="theme-color" content="#14171d">
|
||
<meta name="color-scheme" content="dark">
|
||
<meta name="mobile-web-app-capable" content="yes">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||
<title>Cabin Chat</title>
|
||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%9C%88%EF%B8%8F%3C/text%3E%3C/svg%3E">
|
||
<style>
|
||
:root{
|
||
--bg:#0e1014; --panel:#14171d; --panel2:#1d2129; --line:#252a34;
|
||
--text:#e8ecf2; --muted:#8b93a5; --accent:#3d7bfd; --mine:#2f6be6; --theirs:#1e232c;
|
||
--ok:#22c55e; --bad:#f05252;
|
||
--emoji:"Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif;
|
||
}
|
||
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
|
||
[hidden]{display:none!important}
|
||
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg);color:var(--text);
|
||
font:16px/1.38 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
|
||
button{font:inherit;color:inherit;cursor:pointer}
|
||
#app{position:fixed;left:0;right:0;top:0;height:100dvh;display:flex;will-change:transform;overflow:hidden}
|
||
#chat{position:relative;flex:1;min-width:0;display:flex;flex-direction:column}
|
||
|
||
/* avatars */
|
||
.avatar{position:relative;flex:none;width:44px;height:44px;border-radius:50%;display:grid;place-items:center;
|
||
font-weight:600;font-size:18px;color:#fff}
|
||
.avatar.group{background:linear-gradient(135deg,#3d7bfd,#8b5cf6);font:20px var(--emoji)}
|
||
.avatar .on{position:absolute;right:-1px;bottom:-1px;width:13px;height:13px;border-radius:50%;
|
||
background:var(--ok);border:2.5px solid var(--panel)}
|
||
header .avatar{width:38px;height:38px;font-size:16px}
|
||
|
||
/* people drawer (sidebar on wide screens) */
|
||
#people{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;background:var(--panel);
|
||
transform:translateX(-100%);transition:transform .25s ease;visibility:hidden}
|
||
#app.people #people{transform:none;visibility:visible}
|
||
.phead{display:flex;align-items:center;gap:10px;padding:calc(env(safe-area-inset-top) + 12px) 12px 12px 18px;
|
||
border-bottom:1px solid var(--line)}
|
||
.phead b{flex:1;font-size:21px}
|
||
#plist{flex:1;overflow-y:auto;overscroll-behavior:contain;padding:6px}
|
||
.psec{padding:14px 12px 5px;font-size:12px;font-weight:600;letter-spacing:.6px;text-transform:uppercase;color:var(--muted)}
|
||
.pitem{display:flex;align-items:center;gap:12px;width:100%;padding:9px 10px;border:0;border-radius:14px;
|
||
background:none;text-align:left}
|
||
.pitem:active,.pitem.active{background:var(--panel2)}
|
||
.pmain{flex:1;min-width:0}
|
||
.pname,.psub{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.pname{font-weight:600;font-size:15.5px}
|
||
.psub{font-size:13.5px;color:var(--muted)}
|
||
.psub.typing{color:var(--accent)}
|
||
.pside{display:flex;flex-direction:column;align-items:flex-end;gap:5px;min-height:38px}
|
||
.ptime{font-size:11.5px;color:var(--muted)}
|
||
.pbadge{min-width:20px;height:20px;padding:0 6px;border-radius:10px;background:var(--accent);color:#fff;
|
||
font-size:12px;line-height:20px;text-align:center}
|
||
.pnone{padding:8px 12px;color:var(--muted);font-size:14px}
|
||
.pfoot{display:flex;align-items:center;gap:10px;padding:10px 14px calc(10px + env(safe-area-inset-bottom));
|
||
border-top:1px solid var(--line)}
|
||
.pfoot .ver{flex:1;text-align:right;font-size:11.5px;color:#596173}
|
||
.chip{max-width:60%;border:0;border-radius:999px;padding:8px 14px;background:var(--panel2);font-size:14px;
|
||
white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
@media (min-width:760px){
|
||
#people{position:relative;inset:auto;width:310px;flex:none;transform:none;visibility:visible;border-right:1px solid var(--line)}
|
||
#peopleBtn,#closePeople{display:none!important}
|
||
}
|
||
|
||
/* header */
|
||
header{flex:none;display:flex;align-items:center;gap:10px;
|
||
padding:calc(env(safe-area-inset-top) + 9px) 14px 9px 6px;
|
||
background:rgba(20,23,29,.92);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);
|
||
border-bottom:1px solid var(--line);z-index:2}
|
||
@media (min-width:760px){ header{padding-left:16px} }
|
||
#peopleBtn{position:relative;width:42px;height:42px}
|
||
#peopleBadge{position:absolute;top:2px;right:0;min-width:18px;height:18px;padding:0 5px;border-radius:9px;
|
||
background:var(--accent);color:#fff;font-size:11px;line-height:18px;text-align:center}
|
||
.title{flex:1;min-width:0}
|
||
.title b{display:block;font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.status{display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--muted);white-space:nowrap;overflow:hidden}
|
||
.status.typing{color:var(--accent)}
|
||
.status.bad{color:var(--bad)}
|
||
|
||
/* messages */
|
||
#wrap{position:relative;flex:1;min-height:0}
|
||
#log{position:absolute;inset:0;overflow-y:auto;overscroll-behavior:contain;-webkit-overflow-scrolling:touch;
|
||
padding:10px 10px 8px}
|
||
.empty{color:var(--muted);text-align:center;margin-top:26vh;font-size:15px;line-height:1.6}
|
||
.row{display:flex;flex-direction:column;align-items:flex-start;margin-top:2px;touch-action:pan-y}
|
||
.row.first{margin-top:12px}
|
||
.row.mine{align-items:flex-end}
|
||
.name{font-size:12.5px;font-weight:600;margin:0 0 3px 12px}
|
||
.bubble{position:relative;max-width:min(80%,520px);padding:7px 12px 7px;border-radius:20px;
|
||
background:var(--theirs);overflow-wrap:anywhere;white-space:pre-wrap;transition:transform .2s,filter .2s}
|
||
.bubble.swiping{transition:none}
|
||
.bubble.sel{filter:brightness(1.3)}
|
||
.bubble.flash{animation:flash 1.4s ease}
|
||
@keyframes flash{0%,45%{box-shadow:0 0 0 3px var(--accent)}100%{box-shadow:0 0 0 3px transparent}}
|
||
@media (pointer:coarse){ .bubble,.bubble img{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none} }
|
||
.mine .bubble{background:var(--mine);color:#fff}
|
||
.row:not(.mine).last .bubble{border-bottom-left-radius:6px}
|
||
.row.mine.last .bubble{border-bottom-right-radius:6px}
|
||
.meta{float:right;margin:7px 0 -3px 10px;font-size:11px;line-height:1;color:var(--muted);white-space:nowrap}
|
||
.mine .meta{color:rgba(255,255,255,.72)}
|
||
.bubble.jumbo{background:none!important;padding:0 2px;font:44px/1.15 var(--emoji)}
|
||
.bubble.jumbo .meta{display:block;float:none;text-align:right;margin:2px 4px 0;font:11px/1 -apple-system,sans-serif;color:var(--muted)}
|
||
.bubble.media{padding:3px;line-height:0}
|
||
.media img.photo{display:block;width:min(280px,64vw);height:auto;min-height:60px;border-radius:17px;background:#0006;cursor:zoom-in}
|
||
.row.mine.last .media img.photo{border-bottom-right-radius:4px}
|
||
.row:not(.mine).last .media img.photo{border-bottom-left-radius:4px}
|
||
.media .meta{position:absolute;right:10px;bottom:9px;float:none;margin:0;padding:4px 7px;border-radius:10px;
|
||
background:rgba(0,0,0,.55);color:#fff}
|
||
.pending img.photo{opacity:.45}
|
||
.spin{position:absolute;inset:0;margin:auto;width:34px;height:34px;border-radius:50%;
|
||
border:3px solid rgba(255,255,255,.3);border-top-color:#fff;animation:spin 1s linear infinite}
|
||
@keyframes spin{to{transform:rotate(360deg)}}
|
||
|
||
/* quotes */
|
||
.quote{display:flex;align-items:center;gap:8px;margin:1px 0 6px;padding:5px 9px;border-left:3px solid var(--accent);
|
||
border-radius:8px;background:rgba(255,255,255,.06);font-size:13.5px;line-height:1.3;white-space:normal;cursor:pointer}
|
||
.quote .qt{min-width:0}
|
||
.quote b{display:block;font-size:12.5px}
|
||
.quote span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;color:var(--muted)}
|
||
.quote img{flex:none;width:36px;height:36px;object-fit:cover;border-radius:6px}
|
||
.quote.gone span{font-style:italic}
|
||
.mine .quote{background:rgba(255,255,255,.16);border-left-color:rgba(255,255,255,.8)}
|
||
.mine .quote b{color:#fff!important}
|
||
.mine .quote span{color:rgba(255,255,255,.82)}
|
||
.media .quote{margin:4px 4px 6px}
|
||
.bubble.hasq{min-width:min(200px,70vw)}
|
||
|
||
/* typing indicator */
|
||
#typingRow{display:flex;flex-direction:column;align-items:flex-start;margin-top:12px}
|
||
#typingRow .tn{font-size:12px;color:var(--muted);margin:0 0 3px 12px}
|
||
.dots{display:flex;gap:4px;padding:13px 14px;border-radius:20px;border-bottom-left-radius:6px;background:var(--theirs)}
|
||
.dots i{width:7px;height:7px;border-radius:50%;background:var(--muted);animation:blink 1.3s infinite}
|
||
.dots i:nth-child(2){animation-delay:.18s}
|
||
.dots i:nth-child(3){animation-delay:.36s}
|
||
@keyframes blink{0%,60%,100%{opacity:.35;transform:none}30%{opacity:1;transform:translateY(-3px)}}
|
||
|
||
#jump{position:absolute;right:14px;bottom:14px;width:44px;height:44px;border-radius:50%;
|
||
border:1px solid var(--line);background:var(--panel2);display:grid;place-items:center;
|
||
box-shadow:0 6px 20px rgba(0,0,0,.5)}
|
||
#jump svg{width:22px;height:22px}
|
||
#badge{position:absolute;top:-6px;right:-4px;min-width:20px;height:20px;padding:0 5px;border-radius:10px;
|
||
background:var(--accent);color:#fff;font-size:12px;line-height:20px;text-align:center}
|
||
|
||
/* composer */
|
||
footer{flex:none;background:var(--panel);border-top:1px solid var(--line);padding-bottom:env(safe-area-inset-bottom)}
|
||
#app.kb footer{padding-bottom:0}
|
||
#replyBar{display:flex;align-items:center;gap:8px;padding:8px 8px 0 14px}
|
||
#replyBar .rq{flex:1;min-width:0;padding:2px 10px;border-left:3px solid var(--accent);font-size:13.5px}
|
||
#replyBar b{display:block;font-size:13px;color:var(--accent)}
|
||
#replyBar span{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--muted)}
|
||
#bar{display:flex;align-items:flex-end;gap:8px;padding:8px 10px}
|
||
.field{flex:1;min-width:0;display:flex;align-items:center;min-height:44px;padding:3px;border-radius:24px;
|
||
background:var(--panel2);border:1px solid transparent;transition:border-color .2s}
|
||
.field:focus-within{border-color:#34405a}
|
||
.field input{flex:1;min-width:0;border:0;outline:0;background:transparent;color:var(--text);font-size:16px;padding:8px 4px}
|
||
.field input::placeholder{color:var(--muted)}
|
||
.icon{flex:none;width:38px;height:38px;border:0;border-radius:50%;background:transparent;color:var(--muted);
|
||
display:grid;place-items:center;padding:0}
|
||
.icon:active{background:rgba(255,255,255,.08)}
|
||
.icon svg{width:24px;height:24px}
|
||
.send{flex:none;width:46px;height:46px;border:0;border-radius:50%;background:var(--accent);color:#fff;
|
||
display:grid;place-items:center;padding:0;transition:transform .15s,opacity .2s}
|
||
.send svg{width:22px;height:22px;margin-left:2px}
|
||
.send:disabled{opacity:.35}
|
||
.send:not(:disabled):active{transform:scale(.92)}
|
||
|
||
/* emoji panel */
|
||
#emoji{height:0;overflow:hidden;transition:height .2s ease}
|
||
#emoji.open{height:290px}
|
||
#egrid{height:244px;overflow-y:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(46px,1fr));
|
||
align-content:start;padding:4px 8px}
|
||
#egrid button{height:46px;border:0;border-radius:12px;background:none;font:28px/1 var(--emoji);padding:0}
|
||
#egrid button:active{background:rgba(255,255,255,.08)}
|
||
.enone{grid-column:1/-1;color:var(--muted);text-align:center;padding-top:80px;font-size:14px}
|
||
#etabs{height:46px;display:flex;border-top:1px solid var(--line)}
|
||
#etabs button{flex:1;border:0;background:none;font:21px/1 var(--emoji);opacity:.4;transition:opacity .2s}
|
||
#etabs button.on{opacity:1}
|
||
|
||
/* message menu */
|
||
#menuBack{position:fixed;inset:0;z-index:8}
|
||
#menu{position:fixed;z-index:9;min-width:180px;padding:5px;border:1px solid var(--line);border-radius:14px;
|
||
background:#232833;box-shadow:0 12px 36px rgba(0,0,0,.6)}
|
||
#menu button{display:flex;align-items:center;gap:12px;width:100%;padding:11px 12px;border:0;border-radius:10px;
|
||
background:none;font-size:15px;text-align:left}
|
||
#menu button:hover,#menu button:active{background:rgba(255,255,255,.07)}
|
||
#menu svg{width:20px;height:20px;color:var(--muted)}
|
||
|
||
/* overlays */
|
||
#viewer{position:fixed;inset:0;z-index:10;background:rgba(0,0,0,.94);display:flex;align-items:center;justify-content:center;
|
||
padding:env(safe-area-inset-top) 0 env(safe-area-inset-bottom)}
|
||
#viewer img{max-width:100%;max-height:100%;object-fit:contain}
|
||
#modal{position:fixed;inset:0;z-index:11;background:rgba(5,6,9,.7);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);
|
||
display:flex;justify-content:center;align-items:flex-start;padding:16vh 20px 0}
|
||
.card{width:100%;max-width:360px;background:var(--panel);border:1px solid var(--line);border-radius:24px;padding:26px 22px 20px;
|
||
text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.6)}
|
||
.card .avatar{margin:0 auto 14px;width:58px;height:58px;font-size:30px}
|
||
.card h2{margin:0 0 6px;font-size:21px}
|
||
.card p{margin:0 0 18px;color:var(--muted);font-size:14.5px}
|
||
.card input{width:100%;font-size:17px;padding:13px 16px;border-radius:14px;border:1px solid var(--line);
|
||
background:var(--panel2);color:var(--text);outline:0;text-align:center}
|
||
.card input:focus{border-color:var(--accent)}
|
||
.primary{width:100%;margin-top:12px;padding:13px;border:0;border-radius:14px;background:var(--accent);color:#fff;font-weight:600;font-size:16px}
|
||
#toast{position:fixed;left:50%;top:calc(env(safe-area-inset-top) + 70px);z-index:12;transform:translate(-50%,-10px);
|
||
max-width:86vw;padding:10px 16px;border-radius:14px;background:#2a303b;color:var(--text);font-size:14px;
|
||
white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
|
||
box-shadow:0 8px 24px rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s,transform .25s}
|
||
#toast.show{opacity:1;transform:translate(-50%,0)}
|
||
#toast.click{pointer-events:auto;cursor:pointer}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div id="app">
|
||
<aside id="people">
|
||
<div class="phead">
|
||
<b>Chats</b>
|
||
<button class="icon" id="closePeople" aria-label="Close">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||
</button>
|
||
</div>
|
||
<div id="plist"></div>
|
||
<div class="pfoot">
|
||
<button class="chip" id="me" title="Change your name"></button>
|
||
<span class="ver" id="ver"></span>
|
||
</div>
|
||
</aside>
|
||
|
||
<section id="chat">
|
||
<header>
|
||
<button class="icon" id="peopleBtn" aria-label="Chats and people">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3.3"/><path d="M2.8 19.5c.6-3.3 3.1-5.3 6.2-5.3s5.6 2 6.2 5.3"/><path d="M15.5 5.6a3.2 3.2 0 0 1 0 6M17.6 14.6c1.9.6 3.2 2.3 3.6 4.9"/></svg>
|
||
<span id="peopleBadge" hidden></span>
|
||
</button>
|
||
<div id="hAvatar"></div>
|
||
<div class="title">
|
||
<b id="hTitle">Everyone</b>
|
||
<span class="status" id="hSub">Connecting…</span>
|
||
</div>
|
||
</header>
|
||
|
||
<main id="wrap">
|
||
<div id="log">
|
||
<div class="empty" id="empty"></div>
|
||
<div id="typingRow" hidden><span class="tn" id="typingName"></span><div class="dots"><i></i><i></i><i></i></div></div>
|
||
</div>
|
||
<button id="jump" hidden aria-label="Jump to newest">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M6 13l6 6 6-6"/></svg>
|
||
<span id="badge" hidden></span>
|
||
</button>
|
||
</main>
|
||
|
||
<footer>
|
||
<div id="replyBar" hidden>
|
||
<div class="rq"><b id="rName"></b><span id="rText"></span></div>
|
||
<button type="button" class="icon" id="rCancel" aria-label="Cancel reply">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M7 7l10 10M17 7L7 17"/></svg>
|
||
</button>
|
||
</div>
|
||
<form id="bar" autocomplete="off">
|
||
<div class="field">
|
||
<button type="button" class="icon" id="emojiBtn" aria-label="Emoji"></button>
|
||
<input id="msg" maxlength="1000" placeholder="Message" enterkeyhint="send" autocomplete="off" autocorrect="on">
|
||
<button type="button" class="icon" id="photoBtn" aria-label="Send a photo">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="3.5"/><circle cx="9" cy="10.5" r="1.7"/><path d="M21 15.5l-4.6-4.6a1.2 1.2 0 0 0-1.7 0L7 18.6"/></svg>
|
||
</button>
|
||
</div>
|
||
<button class="send" id="send" aria-label="Send" disabled>
|
||
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3.4 20.4c-.7.3-1.4-.4-1.1-1.1L5 12 2.3 4.7c-.3-.7.4-1.4 1.1-1.1l17.5 7.5c.8.3.8 1.5 0 1.8L3.4 20.4zM6.6 12.9l-2 5.2 13.1-6.1L4.6 5.9l2 5.2H12v1.8H6.6z"/></svg>
|
||
</button>
|
||
</form>
|
||
<input type="file" id="file" accept="image/*" hidden>
|
||
<div id="emoji"><div id="egrid"></div><div id="etabs"></div></div>
|
||
</footer>
|
||
</section>
|
||
</div>
|
||
|
||
<div id="menuBack" hidden></div>
|
||
<div id="menu" hidden>
|
||
<button data-act="reply"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M9 7L4 12l5 5"/><path d="M4 12h10a6 6 0 0 1 6 6v1"/></svg>Reply</button>
|
||
<button data-act="copy"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"><rect x="8" y="8" width="12" height="12" rx="2.5"/><path d="M16 8V6.5A2.5 2.5 0 0 0 13.5 4h-7A2.5 2.5 0 0 0 4 6.5v7A2.5 2.5 0 0 0 6.5 16H8"/></svg>Copy text</button>
|
||
</div>
|
||
|
||
<div id="viewer" hidden><img alt=""></div>
|
||
|
||
<div id="modal" hidden>
|
||
<form class="card" id="nameForm" autocomplete="off">
|
||
<div class="avatar group">✈️</div>
|
||
<h2 id="mTitle">Welcome aboard</h2>
|
||
<p>Pick a name your fellow passengers will see.</p>
|
||
<input id="nameIn" maxlength="24" placeholder="Your name" enterkeyhint="done">
|
||
<button class="primary">Join the chat</button>
|
||
</form>
|
||
</div>
|
||
|
||
<div id="toast"></div>
|
||
|
||
<script>
|
||
(() => {
|
||
'use strict';
|
||
|
||
/* ================================================================ basics */
|
||
const $ = id => document.getElementById(id);
|
||
const app = $('app'), log = $('log'), input = $('msg'), sendBtn = $('send'),
|
||
emojiPanel = $('emoji'), egrid = $('egrid'), etabs = $('etabs'), typingRow = $('typingRow');
|
||
const store = {
|
||
get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
|
||
set(k, v) { try { localStorage.setItem(k, v); } catch (e) {} }
|
||
};
|
||
const enc = new TextEncoder(), dec = new TextDecoder();
|
||
const toHex = s => Array.from(enc.encode(s), b => b.toString(16).padStart(2, '0')).join('');
|
||
const fromHex = h => { try { return dec.decode(new Uint8Array((h.match(/../g) || []).map(x => parseInt(x, 16)))); } catch (e) { return '?'; } };
|
||
const randHex = n => Array.from(crypto.getRandomValues(new Uint8Array(n)), b => b.toString(16).padStart(2, '0')).join('');
|
||
const clean = s => s.replace(/[\t\r\n]+/g, ' ').trim();
|
||
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
|
||
const touch = matchMedia('(pointer: coarse)').matches;
|
||
const wide = () => matchMedia('(min-width: 760px)').matches;
|
||
const KEEP = 86400, ONLINE = 70, TYPING_SHOW = 7;
|
||
const ALL = '*';
|
||
|
||
const ICON_SMILE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M8.3 14.2c.9 1.3 2.2 2 3.7 2s2.8-.7 3.7-2"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/></svg>';
|
||
const ICON_KBD = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="2.5" y="6" width="19" height="12" rx="2.5"/><path d="M6 10h.01M9 10h.01M12 10h.01M15 10h.01M18 10h.01M6 13h.01M18 13h.01M8.5 14.5h7"/></svg>';
|
||
|
||
// identity: a secret key stays in this browser; the server only ever shows a public id
|
||
let key = store.get('cc.key');
|
||
if (!/^[0-9a-f]{32}$/.test(key || '')) { key = randHex(16); store.set('cc.key', key); }
|
||
const legacyId = store.get('cc.uid'); // id used by version 2, to recognise own old messages
|
||
let nick = store.get('cc.nick') || '';
|
||
let me = ''; // public id, told by the server
|
||
|
||
/* ================================================================ state */
|
||
const msgs = new Map(); // id -> message (all conversations)
|
||
const convs = new Map(); // conversation key -> [messages]
|
||
const users = new Map(); // public id -> {nick, seen}
|
||
let typing = new Map(); // public id -> {to, ts}
|
||
let readMarks = {}; // conversation key -> last read id
|
||
try { readMarks = JSON.parse(store.get('cc.read') || '{}') || {}; } catch (e) {}
|
||
const firstVisit = !store.get('cc.read');
|
||
let conv = ALL; // the open conversation
|
||
let since = 0, ev = '', offset = 0, online = null, loaded = false;
|
||
let stick = true, unseen = 0, prev = null, replyTo = null;
|
||
|
||
/* ================================================================ time */
|
||
const serverNow = () => Date.now() / 1000 + offset;
|
||
function ago(ts) {
|
||
const s = Math.max(0, serverNow() - ts);
|
||
if (s < 45) return 'now';
|
||
const m = Math.round(s / 60);
|
||
if (m < 60) return m + 'm ago';
|
||
return Math.floor(m / 60) + 'h ' + String(m % 60).padStart(2, '0') + 'm ago';
|
||
}
|
||
const shortAgo = ts => ago(ts).replace(' ago', '');
|
||
|
||
/* ================================================================ people & conversations */
|
||
const isMine = m => m.from === me || (legacyId && m.from === legacyId);
|
||
const convOf = m => m.to === ALL ? ALL : (isMine(m) ? m.to : m.from);
|
||
const hue = u => { let h = 0; for (const c of u) h = (h * 31 + c.charCodeAt(0)) >>> 0; return h % 360; };
|
||
const nameColor = id => 'hsl(' + hue(id) + ' 75% 70%)';
|
||
const nickOf = id => (users.get(id) || {}).nick || '?';
|
||
const isOnline = id => { const u = users.get(id); return !!u && serverNow() - u.seen < ONLINE; };
|
||
const isTyping = (id, to) => { const t = typing.get(id); return !!t && t.to === to && serverNow() - t.ts < TYPING_SHOW; };
|
||
|
||
function avatar(id, small) {
|
||
const a = el('div', 'avatar');
|
||
if (id === ALL) { a.classList.add('group'); a.textContent = '👥'; return a; }
|
||
a.textContent = (Array.from(nickOf(id).trim())[0] || '?').toUpperCase();
|
||
a.style.background = 'hsl(' + hue(id) + ' 42% 34%)';
|
||
if (isOnline(id)) a.appendChild(el('span', 'on'));
|
||
return a;
|
||
}
|
||
|
||
function typersIn(c) { // names typing in conversation c
|
||
const out = [];
|
||
for (const [id, t] of typing) {
|
||
if (serverNow() - t.ts >= TYPING_SHOW) continue;
|
||
if (c === ALL ? t.to === ALL : (id === c && t.to === me)) out.push(nickOf(id));
|
||
}
|
||
return out;
|
||
}
|
||
function typingText(names) {
|
||
if (!names.length) return '';
|
||
if (names.length === 1) return names[0] + ' is typing…';
|
||
if (names.length === 2) return names[0] + ' and ' + names[1] + ' are typing…';
|
||
return names.length + ' people are typing…';
|
||
}
|
||
|
||
const lastOf = c => { const a = convs.get(c); return a && a.length ? a[a.length - 1] : null; };
|
||
function unreadIn(c) {
|
||
const a = convs.get(c); if (!a) return 0;
|
||
const mark = readMarks[c] || 0; let n = 0;
|
||
for (let i = a.length - 1; i >= 0 && a[i].id > mark; i--) if (!isMine(a[i])) n++;
|
||
return n;
|
||
}
|
||
let saveReadTimer = 0;
|
||
function markRead(c) {
|
||
const last = lastOf(c);
|
||
if (!last || (readMarks[c] || 0) >= last.id) return;
|
||
readMarks[c] = last.id;
|
||
clearTimeout(saveReadTimer);
|
||
saveReadTimer = setTimeout(() => store.set('cc.read', JSON.stringify(readMarks)), 500);
|
||
}
|
||
function markReadIfSeen() { if (!document.hidden && stick && loaded) markRead(conv); }
|
||
|
||
const snippet = m => m.type === 'i' ? '📷 Photo' : (m.text.length > 120 ? m.text.slice(0, 120) + '…' : m.text);
|
||
|
||
/* ================================================================ message rendering */
|
||
let emojiOnly = null;
|
||
try { emojiOnly = new RegExp('^(?:\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}|\\u200d|\\ufe0f|\\s)+$', 'u'); } catch (e) {}
|
||
|
||
function parse(line) {
|
||
const f = line.split('\t');
|
||
if (f.length !== 8) return null;
|
||
const m = { id: +f[0], ts: +f[1], type: f[2], from: f[3], to: f[4], re: +f[5] || 0, nick: fromHex(f[6]) };
|
||
if (!(m.id > 0)) return null;
|
||
if (m.type === 'i') {
|
||
const p = f[7].split(' ');
|
||
m.file = p[0]; m.w = +p[1] || 0; m.h = +p[2] || 0;
|
||
if (!/^\d+(-[0-9a-f]{16})?\.jpg$/.test(m.file)) return null;
|
||
} else m.text = f[7];
|
||
return m;
|
||
}
|
||
|
||
function metaEl(ts) { const s = el('span', 'meta', ago(ts)); s.dataset.ts = ts; return s; }
|
||
|
||
function photoEl(src, w, h, cls) {
|
||
const im = new Image();
|
||
im.alt = 'Photo'; im.decoding = 'async'; im.loading = 'lazy'; im.draggable = false;
|
||
if (cls) im.className = cls;
|
||
if (w && h) im.style.aspectRatio = w + ' / ' + h;
|
||
im.onload = () => { if (stick) toBottom(); };
|
||
im.src = src;
|
||
return im;
|
||
}
|
||
|
||
function quoteEl(reId) {
|
||
const q = msgs.get(reId), d = el('div', 'quote');
|
||
d.dataset.re = reId;
|
||
const t = el('div', 'qt');
|
||
if (!q) { d.classList.add('gone'); t.append(el('b', null, ''), el('span', null, 'Message no longer available')); }
|
||
else {
|
||
if (q.type === 'i') d.appendChild(photoEl('img/' + q.file, 0, 0));
|
||
const b = el('b', null, isMine(q) ? 'You' : q.nick);
|
||
b.style.color = isMine(q) ? 'var(--accent)' : nameColor(q.from);
|
||
t.append(b, el('span', null, snippet(q)));
|
||
}
|
||
d.appendChild(t);
|
||
return d;
|
||
}
|
||
|
||
function render(m) {
|
||
const mine = isMine(m);
|
||
const grouped = prev && prev.row.isConnected && prev.from === m.from && Math.abs(m.ts - prev.ts) < 300;
|
||
const row = el('div', 'row last' + (mine ? ' mine' : '') + (grouped ? '' : ' first'));
|
||
if (grouped) prev.row.classList.remove('last');
|
||
if (!grouped && !mine && conv === ALL) {
|
||
const n = el('div', 'name', m.nick);
|
||
n.style.color = nameColor(m.from);
|
||
row.appendChild(n);
|
||
}
|
||
const b = el('div', 'bubble');
|
||
b.dataset.id = m.id;
|
||
if (m.re) { b.classList.add('hasq'); b.appendChild(quoteEl(m.re)); }
|
||
if (m.type === 'i') {
|
||
b.classList.add('media');
|
||
b.append(photoEl('img/' + m.file, m.w, m.h, 'photo'), metaEl(m.ts));
|
||
} else {
|
||
if (!m.re && emojiOnly && m.text.length <= 16 && emojiOnly.test(m.text)) b.classList.add('jumbo');
|
||
b.append(el('span', null, m.text), metaEl(m.ts));
|
||
}
|
||
row.appendChild(b);
|
||
row.dataset.ts = m.ts;
|
||
log.insertBefore(row, typingRow);
|
||
prev = { from: m.from, ts: m.ts, row };
|
||
$('empty').hidden = true;
|
||
}
|
||
|
||
function emptyText() {
|
||
return conv === ALL ? 'No messages yet.\nSay hi to everyone 👋'
|
||
: 'This is your private chat with ' + nickOf(conv) + '.\nOnly the two of you can see it.';
|
||
}
|
||
|
||
function renderConv() {
|
||
for (const r of log.querySelectorAll('.row')) r.remove();
|
||
prev = null;
|
||
for (const m of convs.get(conv) || []) render(m);
|
||
const e = $('empty');
|
||
e.textContent = emptyText(); e.style.whiteSpace = 'pre-line';
|
||
e.hidden = !!log.querySelector('.row');
|
||
stick = true; unseen = 0; updateJump();
|
||
toBottom();
|
||
}
|
||
|
||
function updateAges() {
|
||
for (const m of log.querySelectorAll('.meta[data-ts]')) m.textContent = ago(+m.dataset.ts);
|
||
}
|
||
|
||
// rolling 24 h window on the client as well
|
||
function expire() {
|
||
const cut = serverNow() - KEEP;
|
||
let changed = false;
|
||
for (const [id, m] of msgs) {
|
||
if (m.ts >= cut) continue;
|
||
msgs.delete(id); changed = true;
|
||
const a = convs.get(convOf(m));
|
||
if (a) { const i = a.indexOf(m); if (i >= 0) a.splice(i, 1); }
|
||
}
|
||
if (changed) {
|
||
for (const row of log.querySelectorAll('.row[data-ts]')) { if (+row.dataset.ts < cut) row.remove(); else break; }
|
||
$('empty').hidden = !!log.querySelector('.row');
|
||
}
|
||
}
|
||
|
||
/* ================================================================ header, people list, typing */
|
||
let listSig = '';
|
||
function refreshUI() {
|
||
// header
|
||
const sub = $('hSub');
|
||
let text, cls = '';
|
||
if (online === false) { text = 'Reconnecting…'; cls = 'bad'; }
|
||
else if (conv === ALL) {
|
||
const t = typingText(typersIn(ALL));
|
||
if (t) { text = t; cls = 'typing'; }
|
||
else { let n = 1; for (const id of users.keys()) if (id !== me && isOnline(id)) n++; text = online ? n + ' online' : 'Connecting…'; }
|
||
} else if (isTyping(conv, me)) { text = 'typing…'; cls = 'typing'; }
|
||
else if (isOnline(conv)) text = 'online';
|
||
else { const u = users.get(conv); text = u && u.seen ? 'last seen ' + ago(u.seen) : 'offline'; }
|
||
sub.textContent = text; sub.className = 'status ' + cls;
|
||
$('hTitle').textContent = conv === ALL ? 'Everyone' : nickOf(conv);
|
||
const ha = $('hAvatar'); ha.textContent = ''; ha.appendChild(avatar(conv));
|
||
|
||
// typing bubble at the bottom of the open chat
|
||
const names = typersIn(conv);
|
||
const wasHidden = typingRow.hidden;
|
||
typingRow.hidden = !names.length;
|
||
$('typingName').textContent = conv === ALL && names.length ? names.join(', ') : '';
|
||
$('typingName').hidden = conv !== ALL;
|
||
if (wasHidden !== typingRow.hidden && stick) toBottom();
|
||
|
||
// unread badge on the people button: messages waiting in other chats
|
||
let others = 0, total = 0;
|
||
for (const c of convs.keys()) { const n = unreadIn(c); total += n; if (c !== conv) others += n; }
|
||
$('peopleBadge').hidden = !others;
|
||
$('peopleBadge').textContent = others > 99 ? '99+' : others;
|
||
document.title = document.hidden && total ? '(' + total + ') Cabin Chat' : 'Cabin Chat';
|
||
|
||
renderList();
|
||
}
|
||
|
||
function peopleIds() {
|
||
const ids = new Set();
|
||
for (const id of users.keys()) ids.add(id);
|
||
for (const c of convs.keys()) if (c !== ALL) ids.add(c);
|
||
for (const m of convs.get(ALL) || []) ids.add(m.from);
|
||
ids.delete(me); ids.delete(ALL); if (legacyId) ids.delete(legacyId);
|
||
return [...ids];
|
||
}
|
||
function activity(id) {
|
||
const u = users.get(id), l = lastOf(id);
|
||
return Math.max(u ? u.seen : 0, l ? l.ts : 0);
|
||
}
|
||
|
||
function renderList() {
|
||
const ids = peopleIds().sort((a, b) => (isOnline(b) - isOnline(a)) || (activity(b) - activity(a)));
|
||
const rows = [ALL, ...ids].map(c => {
|
||
const last = lastOf(c), n = unreadIn(c);
|
||
let sub, typ = false;
|
||
if (c === ALL) {
|
||
const t = typingText(typersIn(ALL));
|
||
if (t) { sub = t; typ = true; }
|
||
else sub = last ? (isMine(last) ? 'You' : last.nick) + ': ' + snippet(last) : 'Group chat with everyone';
|
||
} else if (isTyping(c, me)) { sub = 'typing…'; typ = true; }
|
||
else if (last) sub = (isMine(last) ? 'You: ' : '') + snippet(last);
|
||
else sub = isOnline(c) ? 'online' : (users.get(c) && users.get(c).seen ? 'last seen ' + ago(users.get(c).seen) : 'offline');
|
||
return { c, name: c === ALL ? 'Everyone' : nickOf(c), sub, typ, n, time: last ? shortAgo(last.ts) : '', on: c !== ALL && isOnline(c) };
|
||
});
|
||
const sig = conv + JSON.stringify(rows);
|
||
if (sig === listSig) return;
|
||
listSig = sig;
|
||
|
||
const list = $('plist'); list.textContent = '';
|
||
rows.forEach((r, i) => {
|
||
if (i === 1) list.appendChild(el('div', 'psec', 'People'));
|
||
const b = el('button', 'pitem' + (r.c === conv ? ' active' : ''));
|
||
b.type = 'button';
|
||
b.dataset.conv = r.c;
|
||
const main = el('div', 'pmain');
|
||
main.append(el('div', 'pname', r.name), el('div', 'psub' + (r.typ ? ' typing' : ''), r.sub));
|
||
const side = el('div', 'pside');
|
||
side.appendChild(el('span', 'ptime', r.time));
|
||
if (r.n) side.appendChild(el('span', 'pbadge', r.n > 99 ? '99+' : r.n));
|
||
b.append(avatar(r.c), main, side);
|
||
list.appendChild(b);
|
||
});
|
||
if (rows.length === 1) list.appendChild(el('div', 'pnone', 'Nobody else here yet. People show up as soon as they open the chat.'));
|
||
}
|
||
|
||
$('plist').addEventListener('click', e => {
|
||
const b = e.target.closest('.pitem');
|
||
if (b) openConv(b.dataset.conv);
|
||
});
|
||
|
||
function openConv(c) {
|
||
if (c !== conv) {
|
||
stopTyping();
|
||
conv = c;
|
||
store.set('cc.conv', c);
|
||
cancelReply();
|
||
renderConv();
|
||
input.placeholder = c === ALL ? 'Message everyone' : 'Message ' + nickOf(c);
|
||
listSig = '';
|
||
}
|
||
closePeople();
|
||
markReadIfSeen();
|
||
refreshUI();
|
||
}
|
||
|
||
/* drawer: on phones the people list slides over the chat; the back button closes it */
|
||
function openPeople() {
|
||
if (wide() || app.classList.contains('people')) return;
|
||
app.classList.add('people');
|
||
history.pushState({ cc: 'people' }, '');
|
||
}
|
||
function closePeople() {
|
||
if (!app.classList.contains('people')) return;
|
||
app.classList.remove('people');
|
||
if (history.state && history.state.cc === 'people') history.back();
|
||
}
|
||
addEventListener('popstate', () => app.classList.remove('people'));
|
||
$('peopleBtn').addEventListener('click', openPeople);
|
||
$('closePeople').addEventListener('click', closePeople);
|
||
|
||
/* ================================================================ scrolling & keyboard */
|
||
function toBottom() { log.scrollTop = log.scrollHeight; }
|
||
function updateJump() {
|
||
$('jump').hidden = stick;
|
||
$('badge').hidden = !unseen;
|
||
$('badge').textContent = unseen > 99 ? '99+' : unseen;
|
||
}
|
||
log.addEventListener('scroll', () => {
|
||
const s = log.scrollHeight - log.scrollTop - log.clientHeight < 70;
|
||
if (s !== stick) { stick = s; if (s) { unseen = 0; markReadIfSeen(); refreshUI(); } updateJump(); }
|
||
if (menuOpen) closeMenu();
|
||
}, { passive: true });
|
||
$('jump').addEventListener('click', () => { stick = true; unseen = 0; toBottom(); updateJump(); markReadIfSeen(); refreshUI(); });
|
||
|
||
// keep the layout above the soft keyboard (iOS ignores interactive-widget)
|
||
let fullH = 0;
|
||
function fit() {
|
||
const vv = window.visualViewport;
|
||
if (!vv) return;
|
||
fullH = Math.max(fullH, vv.height);
|
||
app.style.height = vv.height + 'px';
|
||
app.style.transform = vv.offsetTop ? 'translateY(' + vv.offsetTop + 'px)' : '';
|
||
app.classList.toggle('kb', vv.height < fullH - 120);
|
||
if (stick) toBottom();
|
||
}
|
||
if (window.visualViewport) {
|
||
visualViewport.addEventListener('resize', fit);
|
||
visualViewport.addEventListener('scroll', fit);
|
||
addEventListener('orientationchange', () => { fullH = 0; setTimeout(fit, 300); });
|
||
fit();
|
||
}
|
||
|
||
/* ================================================================ network: long poll */
|
||
let ctrl = null, kicked = false, wake = null, fails = 0;
|
||
const nap = ms => new Promise(r => { const t = setTimeout(r, ms); wake = () => { clearTimeout(t); r(); }; });
|
||
|
||
function kick() { // restart the long poll right now
|
||
kicked = true;
|
||
if (ctrl) ctrl.abort();
|
||
if (wake) wake();
|
||
}
|
||
|
||
function setOnline(v) { if (v !== online) { online = v; refreshUI(); } }
|
||
|
||
function resetAll() {
|
||
msgs.clear(); convs.clear(); since = 0; ev = '';
|
||
renderConv();
|
||
}
|
||
|
||
function addMessage(m) {
|
||
if (msgs.has(m.id)) return false;
|
||
msgs.set(m.id, m);
|
||
const c = convOf(m);
|
||
if (!convs.has(c)) convs.set(c, []);
|
||
convs.get(c).push(m);
|
||
if (!isMine(m) && !users.has(m.from)) users.set(m.from, { nick: m.nick, seen: 0 });
|
||
if (!isMine(m)) typing.delete(m.from);
|
||
return true;
|
||
}
|
||
|
||
function handle(text) {
|
||
const lines = text.split('\n');
|
||
lines.pop(); // '' or a half-written line
|
||
const h = (lines.shift() || '').split('\t');
|
||
if (h.length < 4 || h[0][0] !== '@') throw new Error('bad response');
|
||
offset = +h[0].slice(1) - Date.now() / 1000;
|
||
const last = +h[1];
|
||
me = h[3];
|
||
if (last < since) { resetAll(); return; } // chat was wiped on the router
|
||
ev = h[2];
|
||
|
||
const fresh = [];
|
||
typing = new Map();
|
||
for (const l of lines) {
|
||
if (l[0] === 'U') {
|
||
const [, id, n, s] = l.split('\t');
|
||
if (id !== me) users.set(id, { nick: fromHex(n) || '?', seen: +s });
|
||
} else if (l[0] === 'W') {
|
||
const [, id, to, ts] = l.split('\t');
|
||
typing.set(id, { to, ts: +ts });
|
||
} else {
|
||
const m = parse(l);
|
||
if (m && addMessage(m)) fresh.push(m);
|
||
}
|
||
}
|
||
since = last;
|
||
|
||
if (!loaded) { // first answer: build everything
|
||
loaded = true;
|
||
if (firstVisit) { for (const c of convs.keys()) markRead(c); }
|
||
if (conv !== ALL && !peopleIds().includes(conv)) conv = ALL;
|
||
input.placeholder = conv === ALL ? 'Message everyone' : 'Message ' + nickOf(conv);
|
||
renderConv();
|
||
} else if (fresh.length) {
|
||
let here = 0, theirs = 0;
|
||
for (const m of fresh) {
|
||
if (convOf(m) === conv) { render(m); here++; if (!isMine(m)) theirs++; }
|
||
else if (!isMine(m)) notify(m);
|
||
}
|
||
if (here) { if (stick) toBottom(); else { unseen += theirs; updateJump(); } }
|
||
}
|
||
markReadIfSeen();
|
||
}
|
||
|
||
async function pollOnce() {
|
||
ctrl = new AbortController();
|
||
kicked = false;
|
||
const watchdog = setTimeout(() => ctrl.abort(), 40000); // dead connection (router reboot, WiFi drop)
|
||
try {
|
||
const url = 'cgi-bin/chat?k=' + key + '&n=' + toHex(nick) + '&since=' + since + '&ev=' + ev + '&w=' + (ev ? 1 : 0);
|
||
const r = await fetch(url, { cache: 'no-store', signal: ctrl.signal });
|
||
if (!r.ok) throw new Error(r.status);
|
||
handle(await r.text());
|
||
fails = 0;
|
||
setOnline(true);
|
||
} catch (e) {
|
||
if (!kicked) { fails++; if (fails > 1) setOnline(false); }
|
||
} finally {
|
||
clearTimeout(watchdog);
|
||
}
|
||
updateAges(); refreshUI();
|
||
if (kicked) return 0;
|
||
if (fails) return Math.min(10000, 1000 * fails);
|
||
return document.hidden ? 3000 : 0; // background: fewer wake-ups
|
||
}
|
||
|
||
async function loop() {
|
||
for (;;) {
|
||
const d = await pollOnce();
|
||
if (d) await nap(d);
|
||
wake = null;
|
||
}
|
||
}
|
||
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (!document.hidden) { markReadIfSeen(); refreshUI(); kick(); } // a frozen tab's request may be dead
|
||
});
|
||
|
||
const postUrl = (act, extra) =>
|
||
'cgi-bin/chat?a=' + act + '&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(conv) + (extra || '');
|
||
|
||
/* ================================================================ typing notices */
|
||
let typingSent = 0, typingConv = null;
|
||
function sendTyping(to) {
|
||
fetch('cgi-bin/chat?a=typing&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(to), { method: 'POST' }).catch(() => {});
|
||
}
|
||
function onTyping() {
|
||
const now = Date.now();
|
||
if (input.value.trim()) {
|
||
if (now - typingSent > 3000 || typingConv !== conv) { typingSent = now; typingConv = conv; sendTyping(conv); }
|
||
} else stopTyping();
|
||
}
|
||
function stopTyping() {
|
||
if (typingSent && Date.now() - typingSent < 9000) sendTyping('-');
|
||
typingSent = 0; typingConv = null;
|
||
}
|
||
|
||
/* ================================================================ sending */
|
||
async function sendText() {
|
||
const m = clean(input.value).slice(0, 1000);
|
||
if (!m) return;
|
||
const re = replyTo;
|
||
input.value = ''; updateSend(); cancelReply();
|
||
typingSent = 0; typingConv = null; // the server clears our typing notice
|
||
try {
|
||
const r = await fetch(postUrl('text', re ? '&re=' + re : ''), { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: m });
|
||
if (!r.ok) throw new Error();
|
||
} catch (e) {
|
||
if (!input.value) { input.value = m; updateSend(); if (re) setReply(re); }
|
||
toast('Message not sent – are you on the chat WiFi?');
|
||
}
|
||
stick = true;
|
||
}
|
||
|
||
function loadImage(file) {
|
||
return new Promise((res, rej) => {
|
||
const url = URL.createObjectURL(file), img = new Image();
|
||
img.onload = () => { URL.revokeObjectURL(url); res(img); };
|
||
img.onerror = () => { URL.revokeObjectURL(url); rej(new Error('Can’t read this image format')); };
|
||
img.src = url;
|
||
});
|
||
}
|
||
|
||
// scale down + re-encode as JPEG until it fits into ~100 kB
|
||
async function shrink(file, target = 100 * 1024) {
|
||
const img = await loadImage(file); // browsers apply EXIF rotation here
|
||
const W = img.naturalWidth, H = img.naturalHeight;
|
||
const c = document.createElement('canvas'), ctx = c.getContext('2d');
|
||
let max = 1280, q = 0.8, blob = null;
|
||
for (let i = 0; i < 12; i++) {
|
||
const s = Math.min(1, max / Math.max(W, H));
|
||
c.width = Math.max(1, Math.round(W * s)); c.height = Math.max(1, Math.round(H * s));
|
||
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, c.width, c.height);
|
||
ctx.drawImage(img, 0, 0, c.width, c.height);
|
||
blob = await new Promise(r => c.toBlob(r, 'image/jpeg', q));
|
||
if (!blob) throw new Error('Could not process the photo');
|
||
if (blob.size <= target) break;
|
||
if (q > 0.55) q -= 0.1; else max = Math.round(max * 0.8);
|
||
}
|
||
return { blob, w: c.width, h: c.height };
|
||
}
|
||
|
||
function pendingRow(blob, w, h) {
|
||
const row = el('div', 'row mine last first');
|
||
const b = el('div', 'bubble media pending');
|
||
const url = URL.createObjectURL(blob);
|
||
b.append(photoEl(url, w, h, 'photo'), el('div', 'spin'));
|
||
row.appendChild(b);
|
||
log.insertBefore(row, typingRow);
|
||
$('empty').hidden = true;
|
||
stick = true; toBottom();
|
||
return () => { row.remove(); URL.revokeObjectURL(url); };
|
||
}
|
||
|
||
async function sendPhoto(file) {
|
||
let done = null;
|
||
const re = replyTo;
|
||
cancelReply();
|
||
try {
|
||
const { blob, w, h } = await shrink(file);
|
||
done = pendingRow(blob, w, h);
|
||
const extra = '&w=' + w + '&h=' + h + '&r=' + randHex(8) + (re ? '&re=' + re : '');
|
||
const r = await fetch(postUrl('img', extra), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: blob });
|
||
if (!r.ok) throw new Error(r.status === 507 ? 'Chat storage is full' : 'Photo upload failed (' + r.status + ')');
|
||
} catch (e) {
|
||
toast(e.message && !/fetch|network|load/i.test(e.message) ? e.message : 'Photo not sent – are you on the chat WiFi?');
|
||
}
|
||
if (done) setTimeout(done, 400); // the real message arrives through the long poll
|
||
stick = true;
|
||
}
|
||
|
||
$('photoBtn').addEventListener('click', () => $('file').click());
|
||
$('file').addEventListener('change', () => {
|
||
const f = $('file').files[0];
|
||
$('file').value = '';
|
||
if (f) sendPhoto(f);
|
||
});
|
||
|
||
function openViewer(src) { $('viewer').firstElementChild.src = src; $('viewer').hidden = false; }
|
||
$('viewer').addEventListener('click', () => { $('viewer').hidden = true; });
|
||
addEventListener('keydown', e => { if (e.key === 'Escape') { $('viewer').hidden = true; closeMenu(); cancelReply(); } });
|
||
|
||
/* ================================================================ replies (quotes) */
|
||
function setReply(id) {
|
||
const m = msgs.get(id);
|
||
if (!m) return;
|
||
replyTo = id;
|
||
$('rName').textContent = 'Reply to ' + (isMine(m) ? 'yourself' : m.nick);
|
||
$('rText').textContent = snippet(m);
|
||
$('replyBar').hidden = false;
|
||
input.focus();
|
||
if (stick) setTimeout(toBottom, 50);
|
||
}
|
||
function cancelReply() { replyTo = null; $('replyBar').hidden = true; }
|
||
$('rCancel').addEventListener('mousedown', e => e.preventDefault());
|
||
$('rCancel').addEventListener('click', cancelReply);
|
||
|
||
function jumpTo(id) {
|
||
const b = log.querySelector('.bubble[data-id="' + id + '"]');
|
||
if (!b) { toast('That message is no longer here'); return; }
|
||
b.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
b.classList.remove('flash'); void b.offsetWidth; b.classList.add('flash');
|
||
}
|
||
|
||
// message menu: long press (touch), right click (mouse), swipe right = quick reply
|
||
let menuOpen = null, menuAt = 0, swipe = null, swallowClick = false;
|
||
function openMenu(b) {
|
||
const m = msgs.get(+b.dataset.id);
|
||
if (!m) return;
|
||
closeMenu();
|
||
menuOpen = b; menuAt = Date.now();
|
||
b.classList.add('sel');
|
||
if (navigator.vibrate) try { navigator.vibrate(12); } catch (e) {}
|
||
const menu = $('menu');
|
||
menu.querySelector('[data-act="copy"]').hidden = m.type !== 't';
|
||
$('menuBack').hidden = false; menu.hidden = false;
|
||
const r = b.getBoundingClientRect(), mw = menu.offsetWidth, mh = menu.offsetHeight;
|
||
let x = isMine(m) ? r.right - mw : r.left, y = r.bottom + 6;
|
||
if (y + mh > innerHeight - 10) y = r.top - mh - 6;
|
||
menu.style.left = Math.max(8, Math.min(x, innerWidth - mw - 8)) + 'px';
|
||
menu.style.top = Math.max(8, y) + 'px';
|
||
}
|
||
function closeMenu() {
|
||
if (!menuOpen) return;
|
||
menuOpen.classList.remove('sel');
|
||
menuOpen = null;
|
||
$('menu').hidden = true; $('menuBack').hidden = true;
|
||
}
|
||
$('menuBack').addEventListener('click', () => { if (Date.now() - menuAt > 450) closeMenu(); }); // ignore the finger lifting after a long press
|
||
$('menuBack').addEventListener('contextmenu', e => { e.preventDefault(); closeMenu(); });
|
||
$('menu').addEventListener('click', e => {
|
||
const b = e.target.closest('button');
|
||
if (!b || !menuOpen) return;
|
||
const m = msgs.get(+menuOpen.dataset.id);
|
||
closeMenu();
|
||
if (!m) return;
|
||
if (b.dataset.act === 'reply') setReply(m.id);
|
||
if (b.dataset.act === 'copy') copyText(m.text);
|
||
});
|
||
|
||
function copyText(t) {
|
||
const ta = el('textarea');
|
||
ta.value = t; ta.setAttribute('readonly', '');
|
||
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0';
|
||
document.body.appendChild(ta);
|
||
ta.select(); ta.setSelectionRange(0, t.length);
|
||
let ok = false;
|
||
try { ok = document.execCommand('copy'); } catch (e) {}
|
||
ta.remove();
|
||
if (!ok && navigator.clipboard) navigator.clipboard.writeText(t).then(() => toast('Copied'), () => toast('Copy not supported here'));
|
||
else toast(ok ? 'Copied' : 'Copy not supported here');
|
||
}
|
||
|
||
log.addEventListener('pointerdown', e => {
|
||
const b = e.target.closest('.bubble[data-id]');
|
||
swallowClick = false;
|
||
if (!b || e.button > 0) return;
|
||
swipe = { b, x: e.clientX, y: e.clientY, mode: null, dx: 0,
|
||
timer: e.pointerType === 'mouse' ? 0 : setTimeout(() => {
|
||
if (swipe && !swipe.mode) { swipe.mode = 'press'; swallowClick = true; openMenu(b); }
|
||
}, 480) };
|
||
});
|
||
log.addEventListener('pointermove', e => {
|
||
if (!swipe) return;
|
||
const dx = e.clientX - swipe.x, dy = e.clientY - swipe.y;
|
||
if (!swipe.mode) {
|
||
if (Math.abs(dy) > 10 || dx < -10) return endSwipe();
|
||
if (dx > 14 && e.pointerType !== 'mouse') { swipe.mode = 'swipe'; clearTimeout(swipe.timer); swipe.b.classList.add('swiping'); }
|
||
}
|
||
if (swipe.mode === 'swipe') {
|
||
swipe.dx = Math.max(0, Math.min(90, dx));
|
||
swipe.b.style.transform = 'translateX(' + swipe.dx + 'px)';
|
||
}
|
||
});
|
||
function endSwipe() {
|
||
if (!swipe) return;
|
||
clearTimeout(swipe.timer);
|
||
if (swipe.mode === 'swipe') {
|
||
swipe.b.classList.remove('swiping');
|
||
swipe.b.style.transform = '';
|
||
swallowClick = true;
|
||
if (swipe.dx > 60) setReply(+swipe.b.dataset.id);
|
||
}
|
||
swipe = null;
|
||
}
|
||
log.addEventListener('pointerup', endSwipe);
|
||
log.addEventListener('pointercancel', endSwipe);
|
||
log.addEventListener('contextmenu', e => {
|
||
const b = e.target.closest('.bubble[data-id]');
|
||
if (!b) return;
|
||
e.preventDefault();
|
||
if (!menuOpen) openMenu(b);
|
||
});
|
||
log.addEventListener('click', e => {
|
||
if (swallowClick) { swallowClick = false; e.preventDefault(); e.stopPropagation(); return; }
|
||
const q = e.target.closest('.quote[data-re]');
|
||
if (q) { jumpTo(+q.dataset.re); return; }
|
||
const im = e.target.closest('img.photo');
|
||
if (im && im.closest('.bubble[data-id]')) openViewer(im.src);
|
||
}, true);
|
||
|
||
/* ================================================================ notifications for other chats */
|
||
let toastTimer = 0;
|
||
function toast(t, onClick) {
|
||
const e = $('toast');
|
||
e.textContent = t;
|
||
e.classList.add('show');
|
||
e.classList.toggle('click', !!onClick);
|
||
e.onclick = onClick ? () => { e.classList.remove('show'); onClick(); } : null;
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => e.classList.remove('show'), onClick ? 4500 : 3200);
|
||
}
|
||
function notify(m) {
|
||
if (document.hidden) return;
|
||
const where = m.to === ALL ? m.nick + ' in Everyone' : m.nick;
|
||
const c = convOf(m);
|
||
toast('💬 ' + where + ': ' + snippet(m), () => openConv(c));
|
||
}
|
||
|
||
/* ================================================================ emoji */
|
||
const EMOJI = [
|
||
['🕘', ''],
|
||
['😀', '😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 😚 😋 😛 😜 🤪 😝 🤑 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 🤥 😌 😔 😪 🤤 😴 😷 🤒 🤕 🤢 🤮 🥵 🥶 🥴 😵 🤯 🤠 🥳 😎 🤓 🧐 😕 😟 🙁 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬 😈 💀 💩 🤡 👻 👽 🤖'],
|
||
['👍', '👋 🤚 ✋ 🖖 👌 🤏 ✌️ 🤞 🤟 🤘 🤙 👈 👉 👆 👇 ☝️ 👍 👎 ✊ 👊 🤛 🤜 👏 🙌 👐 🤲 🤝 🙏 💪 ❤️ 🧡 💛 💚 💙 💜 🖤 🤍 💔 ❣️ 💕 💞 💓 💗 💖 💘 💝 🙈 🙉 🙊'],
|
||
['✈️', '✈️ 🛫 🛬 🛩️ 💺 🚁 🧳 🛂 🛃 🌍 🌎 🌏 🗺️ 🏝️ 🏖️ 🏔️ 🌋 🗽 🗼 🏰 🚗 🚕 🚌 🚆 🚢 ⛵ 🚀 🛸 🌅 🌄 🌃 🌌 ☁️ ⛅ 🌤️ 🌧️ ⛈️ 🌩️ 🌈 ☀️ 🌙 ⭐ 🌟 ❄️ 🌊'],
|
||
['🍔', '☕ 🍵 🧃 🥤 🍺 🍻 🥂 🍷 🥃 🍸 🍹 🍾 🍔 🍟 🍕 🌭 🥪 🌮 🌯 🥗 🍝 🍜 🍣 🍱 🥟 🍩 🍪 🎂 🍰 🧁 🍫 🍬 🍭 🍿 🥨 🥐 🧀 🍎 🍌 🍇 🍓 🍉 🍒 🥑 🌶️'],
|
||
['🎉', '🎉 🎊 🎈 🎁 🏆 🥇 ⚽ 🏀 🎮 🎲 🎯 🎧 🎵 🎶 🎬 📸 📷 📱 💻 ⌚ 🔋 🔌 💡 📖 ✏️ 📝 📌 🔑 🛏️ 🧸 💤 🎤 🎸 🧩 ♟️'],
|
||
['✅', '✅ ❌ ❓ ❗ 💯 🔥 ✨ 💥 💫 💦 💨 🆗 🆒 🆕 🆘 ⚠️ 🚫 ⛔ 📵 🔇 🔔 ⏰ ⏳ ➡️ ⬅️ ⬆️ ⬇️ 🔁 ➕ ➖ ✖️ 💲 ♻️ 🟢 🟡 🔴']
|
||
];
|
||
let recent = (store.get('cc.recent') || '').split(' ').filter(Boolean);
|
||
let emojiTab = -1;
|
||
|
||
EMOJI.forEach(([icon], i) => {
|
||
const b = el('button', null, icon);
|
||
b.type = 'button';
|
||
b.setAttribute('aria-label', i ? 'Category' : 'Recently used');
|
||
b.addEventListener('click', () => showTab(i));
|
||
etabs.appendChild(b);
|
||
});
|
||
|
||
function showTab(i) {
|
||
emojiTab = i;
|
||
[...etabs.children].forEach((b, j) => b.classList.toggle('on', i === j));
|
||
egrid.textContent = '';
|
||
const list = i === 0 ? recent : EMOJI[i][1].split(' ');
|
||
if (!list.length) egrid.appendChild(el('div', 'enone', 'Emoji you use will show up here'));
|
||
for (const e of list) { const b = el('button', null, e); b.type = 'button'; egrid.appendChild(b); }
|
||
egrid.scrollTop = 0;
|
||
}
|
||
|
||
egrid.addEventListener('mousedown', e => e.preventDefault()); // keep the cursor
|
||
egrid.addEventListener('click', e => {
|
||
const b = e.target.closest('button');
|
||
if (!b) return;
|
||
const em = b.textContent;
|
||
const st = input.selectionStart ?? input.value.length, en = input.selectionEnd ?? st;
|
||
input.setRangeText(em, st, en, 'end');
|
||
updateSend(); onTyping();
|
||
recent = [em, ...recent.filter(x => x !== em)].slice(0, 40);
|
||
store.set('cc.recent', recent.join(' '));
|
||
});
|
||
|
||
function setEmoji(open) {
|
||
emojiPanel.classList.toggle('open', open);
|
||
$('emojiBtn').innerHTML = open ? ICON_KBD : ICON_SMILE;
|
||
$('emojiBtn').setAttribute('aria-label', open ? 'Keyboard' : 'Emoji');
|
||
if (open) {
|
||
if (touch) input.blur();
|
||
if (emojiTab < 0) showTab(recent.length ? 0 : 1);
|
||
}
|
||
setTimeout(() => { if (stick) toBottom(); }, 230);
|
||
}
|
||
$('emojiBtn').innerHTML = ICON_SMILE;
|
||
for (const id of ['emojiBtn', 'photoBtn', 'send']) $(id).addEventListener('mousedown', e => e.preventDefault());
|
||
$('emojiBtn').addEventListener('click', () => {
|
||
const open = !emojiPanel.classList.contains('open');
|
||
setEmoji(open);
|
||
if (!open || !touch) input.focus();
|
||
});
|
||
input.addEventListener('focus', () => { if (touch && emojiPanel.classList.contains('open')) setEmoji(false); });
|
||
|
||
/* ================================================================ composer */
|
||
function updateSend() { sendBtn.disabled = !input.value.trim(); }
|
||
input.addEventListener('input', () => { updateSend(); onTyping(); });
|
||
$('bar').addEventListener('submit', e => { e.preventDefault(); sendText(); });
|
||
|
||
/* ================================================================ name */
|
||
function askName(first) {
|
||
$('mTitle').textContent = first ? 'Welcome aboard' : 'Change your name';
|
||
$('nameForm').querySelector('.primary').textContent = first ? 'Join the chat' : 'Save';
|
||
$('nameIn').value = nick;
|
||
$('modal').hidden = false;
|
||
setTimeout(() => $('nameIn').focus(), 60);
|
||
}
|
||
$('nameForm').addEventListener('submit', e => {
|
||
e.preventDefault();
|
||
const n = clean($('nameIn').value).slice(0, 24);
|
||
if (!n) { $('nameIn').focus(); return; }
|
||
const first = !nick;
|
||
nick = n; store.set('cc.nick', n);
|
||
$('me').textContent = n;
|
||
$('modal').hidden = true;
|
||
$('nameIn').blur();
|
||
if (first) loop(); else kick(); // tell everybody the new name
|
||
});
|
||
$('modal').addEventListener('click', e => { if (e.target === $('modal') && nick) $('modal').hidden = true; });
|
||
$('me').addEventListener('click', () => askName(false));
|
||
|
||
fetch('VERSION', { cache: 'no-store' }).then(r => r.ok ? r.text() : '')
|
||
.then(v => { v = v.trim(); if (/^[\w.\-]{1,20}$/.test(v)) $('ver').textContent = 'Cabin Chat v' + v; }).catch(() => {});
|
||
|
||
/* ================================================================ start */
|
||
conv = store.get('cc.conv') || ALL;
|
||
renderConv();
|
||
refreshUI();
|
||
setInterval(() => { expire(); refreshUI(); }, 1000); // typing / online state expire on their own
|
||
setInterval(updateAges, 15000);
|
||
if (nick) { $('me').textContent = nick; loop(); } else askName(true);
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|
||
__CABINCHAT_EOF__
|
||
[ -f "$STAGE/index.html" ] && [ -f "$STAGE/cgi-bin/chat" ] && [ -f "$STAGE/VERSION" ] \
|
||
|| die "installer payload is incomplete"
|
||
}
|
||
|
||
# version 2 lines (6 fields) -> version 3 (8 fields: + recipient "*" and no quote)
|
||
migrate_messages() {
|
||
[ -s "$DATA/messages" ] || return 0
|
||
awk -F '\t' 'BEGIN { OFS = "\t" }
|
||
NF == 6 { print $1, $2, $3, $4, "*", 0, $5, $6; next }
|
||
NF == 8 { print }' "$DATA/messages" > "$DATA/messages.new" &&
|
||
mv "$DATA/messages.new" "$DATA/messages"
|
||
}
|
||
|
||
# ------------------------------------------------------------------ install
|
||
do_install() {
|
||
[ -x /usr/sbin/uhttpd ] || die "uhttpd is not installed.
|
||
With internet access run: opkg update && opkg install uhttpd
|
||
then run this installer again."
|
||
|
||
LANIP=$(uci -q get network.lan.ipaddr | cut -d/ -f1)
|
||
[ -n "$LANIP" ] || die "could not read the LAN IP (network.lan.ipaddr)"
|
||
|
||
OLDVER=
|
||
if [ -f "$APP/VERSION" ]; then
|
||
OLDVER=$(cat "$APP/VERSION")
|
||
elif [ -e "$APP/index.html" ] || uci -q get uhttpd.chat >/dev/null; then
|
||
OLDVER="1.x"
|
||
fi
|
||
OLDPORT=$(configured_port)
|
||
[ -n "$PORT" ] || PORT=${OLDPORT:-$DEFAULT_PORT}
|
||
case $PORT in ''|*[!0-9]*) die "invalid port: $PORT" ;; esac
|
||
if [ "$PORT" != "$OLDPORT" ] && listening "$PORT"; then
|
||
die "port $PORT is already in use - choose another one with -p <port>"
|
||
fi
|
||
|
||
if [ -n "$OLDVER" ]; then
|
||
info "upgrading Cabin Chat $OLDVER -> $VERSION"
|
||
else
|
||
info "installing Cabin Chat $VERSION"
|
||
fi
|
||
|
||
# unpack first: if anything is wrong with this file, nothing has been touched yet
|
||
extract_payload
|
||
|
||
if [ -n "$OLDVER" ]; then
|
||
info "removing the previous version (messages and photos are kept)"
|
||
fi
|
||
remove_config
|
||
mkdir -p "$APP" || die "cannot create $APP"
|
||
mkdir -p "$DATA"
|
||
# keep the photos aside (version 2 kept them in data/img, version 3 in htdocs/img)
|
||
KEEPIMG=$APP/.img-keep
|
||
mkdir -p "$KEEPIMG"
|
||
for d in "$WEB/img" "$DATA/img"; do
|
||
[ -d "$d" ] && mv "$d"/* "$KEEPIMG"/ 2>/dev/null
|
||
rm -rf "$d"
|
||
done
|
||
for f in "$APP"/* "$APP"/.[!.]*; do
|
||
[ -e "$f" ] || continue
|
||
case $f in "$DATA"|"$KEEPIMG") continue ;; esac
|
||
rm -rf "$f"
|
||
done
|
||
rm -rf /tmp/chat.log /tmp/chat.lock /tmp/cabinchat.lock # leftovers from versions 1 and 2
|
||
migrate_messages
|
||
|
||
info "installing files to $WEB"
|
||
mkdir -p "$WEB"
|
||
cp -R "$STAGE"/* "$WEB"/ || die "copying files failed"
|
||
rm -rf "$STAGE"
|
||
chmod 755 "$WEB"/cgi-bin/*
|
||
mkdir -p "$WEB/img"
|
||
mv "$KEEPIMG"/* "$WEB/img"/ 2>/dev/null
|
||
rm -rf "$KEEPIMG"
|
||
[ -f "$CLOCK" ] || date +%s > "$CLOCK"
|
||
|
||
info "configuring web server on $LANIP:$PORT"
|
||
uci set uhttpd.chat=uhttpd
|
||
uci add_list uhttpd.chat.listen_http="$LANIP:$PORT"
|
||
uci set uhttpd.chat.home="$WEB"
|
||
uci set uhttpd.chat.cgi_prefix='/cgi-bin'
|
||
uci set uhttpd.chat.index_page='index.html'
|
||
uci set uhttpd.chat.no_dirlists='1'
|
||
# long polling keeps one request per open chat waiting for up to 25 s
|
||
uci set uhttpd.chat.script_timeout='60'
|
||
uci set uhttpd.chat.network_timeout='60'
|
||
uci set uhttpd.chat.max_requests='100'
|
||
uci set uhttpd.chat.max_connections='100'
|
||
uci commit uhttpd
|
||
/etc/init.d/uhttpd enable
|
||
/etc/init.d/uhttpd restart
|
||
|
||
info "adding DNS name $DNSNAME"
|
||
uci add_list dhcp.@dnsmasq[0].address="/$DNSNAME/$LANIP"
|
||
uci commit dhcp
|
||
/etc/init.d/dnsmasq restart >/dev/null 2>&1
|
||
|
||
touch /etc/sysupgrade.conf
|
||
grep -qx "$APP/" /etc/sysupgrade.conf || echo "$APP/" >> /etc/sysupgrade.conf
|
||
|
||
sleep 1
|
||
listening "$PORT" || die "uhttpd is not listening on port $PORT - check: logread | grep uhttpd"
|
||
if command -v wget >/dev/null; then
|
||
case $(wget -q -O - "http://$LANIP:$PORT/cgi-bin/chat?k=00000000000000000000000000000000&since=0" 2>/dev/null | head -n 1) in
|
||
@*) info "self-test passed" ;;
|
||
*) warn "the chat backend did not answer as expected - check: logread | grep uhttpd" ;;
|
||
esac
|
||
fi
|
||
|
||
n=$(grep -c . "$DATA/messages" 2>/dev/null); n=${n:-0}
|
||
echo
|
||
info "Cabin Chat $VERSION is running ($n messages from the last 24 h kept)"
|
||
echo " http://$LANIP:$PORT"
|
||
echo " http://$DNSNAME:$PORT"
|
||
}
|
||
|
||
# ------------------------------------------------------------------ uninstall
|
||
do_uninstall() {
|
||
info "removing Cabin Chat"
|
||
remove_config
|
||
rm -rf "$APP" "$CLOCK" "$RUN" /tmp/chat.log /tmp/chat.lock /tmp/cabinchat.lock
|
||
/etc/init.d/uhttpd restart >/dev/null 2>&1
|
||
/etc/init.d/dnsmasq restart >/dev/null 2>&1
|
||
info "done"
|
||
}
|
||
|
||
do_wipe() {
|
||
[ -d "$APP" ] || die "Cabin Chat is not installed"
|
||
rm -rf "$DATA" "$WEB/img"
|
||
mkdir -p "$DATA" "$WEB/img"
|
||
# wake up waiting browsers so they notice the empty chat
|
||
[ -d "$RUN" ] && echo "wipe.$$" > "$RUN/ev"
|
||
info "all messages and photos deleted"
|
||
}
|
||
|
||
# ------------------------------------------------------------------ main
|
||
CMD=install
|
||
PORT=
|
||
while [ $# -gt 0 ]; do
|
||
case $1 in
|
||
-p|--port) [ -n "$2" ] || die "-p needs a port number"; PORT=$2; shift 2 ;;
|
||
[0-9]*) PORT=$1; shift ;;
|
||
install|upgrade) CMD=install; shift ;;
|
||
uninstall|remove) CMD=uninstall; shift ;;
|
||
wipe) CMD=wipe; shift ;;
|
||
-h|--help|help) usage; exit 0 ;;
|
||
*) usage; die "unknown argument: $1" ;;
|
||
esac
|
||
done
|
||
|
||
[ "$(id -u)" = "0" ] || die "please run as root"
|
||
command -v uci >/dev/null || die "uci not found - is this OpenWrt?"
|
||
|
||
case $CMD in
|
||
install) do_install ;;
|
||
uninstall) do_uninstall ;;
|
||
wipe) do_wipe ;;
|
||
esac
|