add new chat logic and message service

This commit is contained in:
JCEEE
2026-08-05 11:20:27 +01:00
parent 3378e1dce7
commit fed2f32258
11 changed files with 1013 additions and 14 deletions
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-message-square"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>

After

Width:  |  Height:  |  Size: 305 B

+353
View File
@@ -0,0 +1,353 @@
<script lang="ts">
import { onMount } from 'svelte';
import { chatStore } from '$lib/stores/chat.svelte';
import { chatIcon, sendIcon } from './icons';
import { formatWeekday, formatHumanDate } from '$lib/format';
let { role = 'child' }: { role?: string } = $props();
let draft = $state('');
let sending = $state(false);
let error = $state('');
let container: HTMLDivElement | undefined = $state();
let idleTimer: ReturnType<typeof setTimeout> | undefined;
const isOwn = (msg: any) => msg.authorId === chatStore.actorId;
function scrollToBottom(instant = false) {
if (!container) return;
container.scrollTo({
top: container.scrollHeight,
behavior: instant ? 'auto' : 'smooth'
});
}
$effect(() => {
const n = chatStore.messages.length;
if (n > 0) {
const last = chatStore.messages[n - 1];
// Only auto-scroll when the newest message is ours, or on open.
if (isOwn(last) || chatStore.open) scrollToBottom(true);
}
});
async function send() {
const text = draft.trim();
if (!text || sending) return;
sending = true;
error = '';
draft = '';
clearIdle();
chatStore.setTyping(false).catch(() => {});
try {
await chatStore.send(text);
scrollToBottom(true);
} catch {
error = 'Could not send. Try again.';
} finally {
sending = false;
requestAnimationFrame(() => scrollToBottom(true));
}
}
function onInput() {
chatStore.setTyping(true).catch(() => {});
clearIdle();
idleTimer = setTimeout(() => {
chatStore.setTyping(false).catch(() => {});
}, 2500);
}
function clearIdle() {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = undefined;
}
function onClose() {
clearIdle();
chatStore.setTyping(false).catch(() => {});
chatStore.closeChat();
}
function insertMention(name: string) {
draft = draft.trimEnd();
draft = (draft ? draft + ' ' : '') + '@' + name + ' ';
}
// Render content, wrapping @mentions in a styled token.
function renderContent(text: string) {
const segs: { text: string; mention: boolean }[] = [];
const re = /(@[A-Za-z0-9_.-]+)/g;
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (m.index > last) segs.push({ text: text.slice(last, m.index), mention: false });
segs.push({ text: m[1], mention: true });
last = m.index + m[0].length;
}
if (last < text.length) segs.push({ text: text.slice(last), mention: false });
return segs;
}
onMount(() => {
requestAnimationFrame(() => scrollToBottom(true));
});
</script>
<div class="chat-panel" class:open={chatStore.open}>
<div class="chat-head">
<span class="chat-title">Family Chat</span>
<button class="chat-close" onclick={onClose} aria-label="Close chat"></button>
</div>
<div class="chat-messages" bind:this={container}>
{#if chatStore.messages.length === 0}
<p class="chat-empty">No messages yet. Say hi! 👋</p>
{:else}
{#each chatStore.messages as msg (msg.id)}
<div class="msg-row" class:own={isOwn(msg)}>
{#if !isOwn(msg)}
<span class="avatar" style="background:{msg.authorColor || '#6366f1'}">
{msg.authorName?.charAt(0).toUpperCase()}
</span>
{/if}
<div class="bubble-wrap">
{#if !isOwn(msg)}
<span class="msg-author">{msg.authorName}</span>
{/if}
<div class="bubble">
{#each renderContent(msg.content) as seg (msg.id + ':' + seg.text)}
{#if seg.mention}
<button class="mention" onclick={() => insertMention(seg.text.slice(1))}
>{seg.text}</button
>
{:else}
{seg.text}
{/if}
{/each}
<span class="msg-time">{formatWeekday(msg.createdAt)}</span>
</div>
</div>
</div>
{/each}
{/if}
</div>
<div class="chat-typing">
{#if chatStore.typingNames.length > 0}
<span class="typing-text">
{chatStore.typingNames.join(', ')}
{chatStore.typingNames.length === 1 ? 'is' : 'are'} typing…
</span>
{:else}
<span class="typing-text"></span>
{/if}
</div>
<div class="chat-composer">
{#if error}<div class="chat-error">{error}</div>{/if}
<input
type="text"
class="chat-input"
placeholder="Message the family…"
bind:value={draft}
oninput={onInput}
onkeydown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
send();
}
}}
disabled={sending}
/>
<button class="chat-send" onclick={send} disabled={sending || !draft.trim()} aria-label="Send">
{@html sendIcon}
</button>
</div>
</div>
<style>
.chat-panel {
position: fixed;
top: 0;
right: 0;
height: 100dvh;
width: 500px;
background: #fff;
border-left: 1px solid #e5e7eb;
display: flex;
flex-direction: column;
z-index: 110;
transform: translateX(100%);
transition: transform 0.25s ease;
box-shadow: -8px 0 24px rgba(0, 0, 0, 0.08);
}
.chat-panel.open {
transform: translateX(0);
}
/* Mobile: full-screen fixed layer. */
@media (max-width: 767.98px) {
.chat-panel {
width: 100vw;
}
}
.chat-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.85rem 1.25rem;
border-bottom: 1px solid #e5e7eb;
background: #4338ca;
color: #fff;
}
.chat-title {
font-weight: 700;
font-size: 1rem;
}
.chat-close {
background: none;
border: none;
color: #c7d2fe;
font-size: 1.1rem;
cursor: pointer;
padding: 0.25rem 0.5rem;
}
.chat-close:hover {
color: #fff;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.chat-empty {
color: #9ca3af;
text-align: center;
margin-top: 3rem;
}
.msg-row {
display: flex;
align-items: flex-end;
gap: 0.5rem;
}
.msg-row.own {
justify-content: flex-end;
}
.avatar {
width: 28px;
height: 28px;
border-radius: 50%;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: 700;
flex-shrink: 0;
}
.bubble-wrap {
max-width: 72%;
display: flex;
flex-direction: column;
}
.msg-row.own .bubble-wrap {
align-items: flex-end;
}
.msg-author {
font-size: 0.72rem;
color: #6b7280;
margin: 0 0 0.15rem 0.35rem;
font-weight: 600;
}
.bubble {
background: #f3f4f6;
border-radius: 14px;
border-bottom-left-radius: 4px;
padding: 0.5rem 0.75rem;
font-size: 0.9rem;
color: #111827;
line-height: 1.4;
word-break: break-word;
position: relative;
}
.msg-row.own .bubble {
background: #6366f1;
color: #fff;
border-bottom-left-radius: 14px;
border-bottom-right-radius: 4px;
}
.msg-time {
display: block;
font-size: 0.62rem;
color: #9ca3af;
margin-top: 0.25rem;
text-align: right;
text-transform: capitalize;
}
.msg-row.own .msg-time {
color: rgba(255, 255, 255, 0.7);
}
.mention {
background: #ede9fe;
color: #6d28d9;
border: none;
border-radius: 6px;
padding: 0 0.25rem;
font-weight: 600;
font-size: 0.85rem;
cursor: pointer;
}
.chat-typing {
min-height: 1.5rem;
padding: 0 1.25rem;
}
.typing-text {
font-size: 0.75rem;
color: #6b7280;
font-style: italic;
}
.chat-composer {
display: flex;
gap: 0.5rem;
padding: 0.75rem 1.25rem 1rem;
border-top: 1px solid #e5e7eb;
align-items: center;
}
.chat-error {
position: absolute;
bottom: 4.5rem;
color: #dc2626;
font-size: 0.75rem;
}
.chat-input {
flex: 1;
padding: 0.6rem 0.9rem;
border: 1px solid #d1d5db;
border-radius: 999px;
font-size: 0.9rem;
outline: none;
}
.chat-input:focus {
border-color: #6366f1;
}
.chat-send {
width: 40px;
height: 40px;
border-radius: 50%;
border: none;
background: #6366f1;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
flex-shrink: 0;
}
.chat-send:disabled {
opacity: 0.5;
cursor: default;
}
</style>
+2
View File
@@ -9,3 +9,5 @@ export const prefsIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="
export const chevronLeft = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg>'
export const chevronRight = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>'
export const bellIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>'
export const chatIcon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>'
export const sendIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>'
+1
View File
@@ -6,3 +6,4 @@ export { default as Card } from './Card.svelte';
export { default as CardGrid } from './CardGrid.svelte';
export { default as Button } from './Button.svelte';
export { default as Accordion } from './Accordion.svelte';
export { default as Chat } from './Chat.svelte';
+257
View File
@@ -0,0 +1,257 @@
import { pb } from '$lib/pocketbase';
import type { ChatMessage, TypingRow } from '$lib/types';
interface ChatInit {
famId: string;
actorId: string;
actorType: 'admin' | 'member';
actorName: string;
actorColor: string;
deviceToken?: string;
memberId?: string;
}
class ChatStore {
famId = $state('');
messages = $state<ChatMessage[]>([]);
typing = $state<Record<string, TypingRow>>({});
unread = $state(0);
open = $state(false);
initialized = $state(false);
actorId = $state('');
actorType = $state<'admin' | 'member'>('member');
actorName = $state('');
actorColor = $state('');
deviceToken = $state('');
memberId = $state('');
private unsubs: (() => void)[] = [];
private destroyed = false;
private initPromise: Promise<void> | null = null;
private lastSeenAt = 0;
private typingTimers = new Map<string, ReturnType<typeof setTimeout>>();
typingNames = $derived.by(() => {
const names: string[] = [];
for (const row of Object.values(this.typing)) {
if (row.actorId !== this.actorId) names.push(row.authorName);
}
return names;
});
async init(opts: ChatInit) {
this.famId = opts.famId;
this.actorId = opts.actorId;
this.actorType = opts.actorType;
this.actorName = opts.actorName;
this.actorColor = opts.actorColor;
this.deviceToken = opts.deviceToken || '';
this.memberId = opts.memberId || '';
if (this.initialized && this.famId === opts.famId) return;
if (this.initPromise) {
await this.initPromise;
if (this.initialized && this.famId === opts.famId) return;
}
this.cleanup();
this.destroyed = false;
this.lastSeenAt = Date.now();
this.initPromise = (async () => {
try {
// Last week + this week of history (custom createdAt field — the
// auto `created` field can't be filtered in this PB version).
const since = new Date(Date.now() - 14 * 86400000).toISOString();
const msgs = (await pb.collection('messages').getFullList({
filter: `famId = '${opts.famId}' && createdAt >= '${since}'`,
sort: 'createdAt'
})) as ChatMessage[];
this.messages = msgs;
this.initialized = true;
} catch (e) {
console.error('ChatStore.init failed:', e);
this.initPromise = null;
throw e;
}
await this.subscribe();
this.initPromise = null;
})();
return this.initPromise!;
}
private async subscribe() {
const msgSub = pb
.collection('messages')
.subscribe('*', (data: any) => {
if (this.destroyed) return;
this.onMessage(data.action, data.record);
})
.then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] messages subscribe failed:', err));
const typingSub = pb
.collection('chat_typing')
.subscribe('*', (data: any) => {
if (this.destroyed) return;
this.onTyping(data.action, data.record);
})
.then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] typing subscribe failed:', err));
await Promise.allSettled([msgSub, typingSub]);
}
private onMessage(action: string, record: ChatMessage) {
if (record.famId !== this.famId) return;
if (action === 'delete') {
this.messages = this.messages.filter((m) => m.id !== record.id);
return;
}
if (action === 'update') {
this.messages = this.messages.map((m) => (m.id === record.id ? { ...m, ...record } : m));
return;
}
// create
if (!this.messages.some((m) => m.id === record.id)) {
this.messages = [...this.messages, record].sort((a, b) =>
a.createdAt.localeCompare(b.createdAt)
);
}
// Stop showing their typing indicator once the message lands.
this.clearTyping(record.authorId);
if (record.authorId !== this.actorId && !this.open) {
this.unread++;
}
}
private onTyping(action: string, record: TypingRow) {
if (record.famId !== this.famId) return;
if (action === 'delete') {
this.removeTyping(record.actorId);
return;
}
if (!record.typing) {
this.removeTyping(record.actorId);
return;
}
this.typing = { ...this.typing, [record.actorId]: record };
const prev = this.typingTimers.get(record.actorId);
if (prev) clearTimeout(prev);
this.typingTimers.set(
record.actorId,
setTimeout(() => this.removeTyping(record.actorId), 5000)
);
}
private clearTyping(actorId: string) {
if (this.typing[actorId]) this.removeTyping(actorId);
}
private removeTyping(actorId: string) {
if (!this.typing[actorId]) return;
const next = { ...this.typing };
delete next[actorId];
this.typing = next;
const t = this.typingTimers.get(actorId);
if (t) clearTimeout(t);
this.typingTimers.delete(actorId);
}
// ── Writes via proxy ──
private async chatFetch(method: string, path: string, body?: unknown) {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.actorType === 'member' && this.deviceToken) {
headers['x-device-token'] = this.deviceToken;
headers['x-device-famid'] = this.famId;
}
const res = await fetch(path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `${method} ${path} failed`);
return data;
}
async send(content: string) {
const text = content.trim();
if (!text || !this.famId) return;
const temp: ChatMessage = {
id: 'temp-' + Date.now(),
famId: this.famId,
authorType: this.actorType,
authorId: this.actorId,
authorName: this.actorName,
authorColor: this.actorColor,
content: text,
createdAt: new Date().toISOString()
};
this.messages = [...this.messages, temp];
this.lastSeenAt = Date.now();
// Signal we stopped typing (message sent).
this.setTyping(false).catch(() => {});
try {
const saved = await this.chatFetch('POST', `/api/chat/${this.famId}/messages`, {
content: text
});
// SSE may have already delivered the real record via onMessage, so
// drop both the temp and any pre-existing copy of the saved id to
// avoid duplicate keys in the keyed each block.
this.messages = this.messages
.filter((m) => m.id !== temp.id && m.id !== saved.id)
.concat([{ ...saved, authorName: temp.authorName, authorColor: temp.authorColor }])
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
} catch (e) {
this.messages = this.messages.filter((m) => m.id !== temp.id);
console.error('Chat send failed:', e);
throw e;
}
}
private typingThrottle = 0;
async setTyping(typing: boolean) {
if (!this.famId) return;
const now = Date.now();
if (typing && now - this.typingThrottle < 1500) return;
this.typingThrottle = now;
try {
await this.chatFetch('POST', `/api/chat/${this.famId}/typing`, { typing });
} catch (e) {
console.error('Chat typing failed:', e);
}
}
toggle() {
this.open = !this.open;
if (this.open) {
this.unread = 0;
this.lastSeenAt = Date.now();
}
}
openChat() {
this.open = true;
this.unread = 0;
this.lastSeenAt = Date.now();
}
closeChat() {
this.open = false;
}
cleanup() {
this.destroyed = true;
for (const unsub of this.unsubs) unsub();
this.unsubs = [];
for (const t of this.typingTimers.values()) clearTimeout(t);
this.typingTimers.clear();
this.initialized = false;
}
}
export const chatStore = new ChatStore();
+22 -1
View File
@@ -74,7 +74,7 @@ export interface ChoreTemplate {
updated: string;
}
export interface AssignedChore {
export interface AssignedChore {
id: string;
famId: string;
memberId: string;
@@ -172,6 +172,27 @@ export interface Settings {
simulateEow?: boolean;
}
export interface ChatMessage {
id: string;
famId: string;
authorType: 'admin' | 'member';
authorId: string;
authorName: string;
authorColor?: string;
content: string;
createdAt: string;
}
export interface TypingRow {
id: string;
famId: string;
actorId: string;
actorType: 'admin' | 'member';
authorName: string;
authorColor?: string;
typing: boolean;
}
export interface Session {
famId: string;
userId: string;
+31 -1
View File
@@ -16,12 +16,40 @@ async function paydayCheck(famId: string, headers: Record<string, string>) {
} catch {}
}
async function resolveChatIdentity(
api: 'admin' | 'member',
opts: {
session?: { famId: string; userId: string };
deviceToken?: string;
famId?: string;
}
) {
try {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (api === 'admin' && opts.session) {
headers['x-session-famid'] = opts.session.famId;
headers['x-session-userid'] = opts.session.userId;
} else if (api === 'member' && opts.deviceToken && opts.famId) {
headers['x-device-token'] = opts.deviceToken;
headers['x-device-famid'] = opts.famId;
} else {
return null;
}
const res = await fetch(`${HONO_URL}/api/chat/me`, { headers });
if (!res.ok) return null;
return await res.json();
} catch {
return null;
}
}
export async function load(event) {
const session = event.locals.session || null;
const isParent = session !== null;
const deviceToken = event.cookies.get('device_token') || '';
let famId = '';
let chat: { famId: string; actor: any } | null = null;
if (isParent) {
famId = session.famId;
@@ -29,6 +57,7 @@ export async function load(event) {
'x-session-famid': session.famId,
'x-session-userid': session.userId
});
chat = await resolveChatIdentity('admin', { session });
} else if (deviceToken) {
try {
const res = await fetch(`${HONO_URL}/api/members/seasons`, {
@@ -44,8 +73,9 @@ export async function load(event) {
'x-device-token': deviceToken,
'x-device-famid': famId
});
chat = await resolveChatIdentity('member', { deviceToken, famId });
}
}
return { session, isParent, role: session?.role || 'child', famId };
return { session, isParent, role: session?.role || 'child', famId, chat, deviceToken };
}
+91 -5
View File
@@ -3,7 +3,9 @@
import { onMount } from 'svelte';
import { initPbFromCookie } from '$lib/pocketbase';
import { famStore } from '$lib/stores/fam.svelte';
import { Sidebar, TopNav, Footer } from '$lib/components';
import { chatStore } from '$lib/stores/chat.svelte';
import { Sidebar, TopNav, Footer, Chat } from '$lib/components';
import { chatIcon } from '$lib/components/icons';
import type { Session } from '$lib/types';
let { children, data } = $props();
@@ -24,7 +26,9 @@
const rewards = famStore.rewards;
if (!mounted) {
mounted = true;
prevClaimedIds = new Set(rewards.filter((r: any) => r.status === 'requested').map((r: any) => r.id));
prevClaimedIds = new Set(
rewards.filter((r: any) => r.status === 'requested').map((r: any) => r.id)
);
return;
}
for (const r of rewards) {
@@ -35,18 +39,39 @@
setTimeout(() => (claimToast = ''), 5000);
}
}
prevClaimedIds = new Set(rewards.filter((r: any) => r.status === 'requested').map((r: any) => r.id));
prevClaimedIds = new Set(
rewards.filter((r: any) => r.status === 'requested').map((r: any) => r.id)
);
});
onMount(() => {
initPbFromCookie();
if (page.data.famId) famStore.init(page.data.famId);
const chat = page.data.chat;
if (chat?.famId && chat?.actor) {
chatStore.init({
famId: chat.famId,
actorId: chat.actor.id,
actorType: chat.actor.type,
actorName: chat.actor.name,
actorColor: chat.actor.color || '#6366f1',
deviceToken: page.data.deviceToken || ''
});
}
});
</script>
<div class="app-shell">
<div class="layout-stage" class:chat-open={chatStore.open}>
<div class="app-shell">
<Sidebar {famName} session={data.session} {isParent} {role} />
<TopNav {role} seasons={famStore.seasons} />
<TopNav {role} seasons={famStore.seasons}>
<button class="chat-toggle" onclick={() => chatStore.toggle()} aria-label="Open chat">
{@html chatIcon}
{#if chatStore.unread > 0}
<span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span>
{/if}
</button>
</TopNav>
<main class="app-main">
{@render children()}
</main>
@@ -54,6 +79,12 @@
<div class="claim-toast">{claimToast}</div>
{/if}
<Footer />
</div>
{#if chatStore.open}
<button class="chat-backdrop" onclick={() => chatStore.closeChat()} aria-label="Close chat"
></button>
{/if}
<Chat {role} />
</div>
<style>
@@ -75,6 +106,28 @@
display: flex;
flex-direction: column;
background: whitesmoke;
width: 100%;
transition: transform 0.25s ease;
}
/* Desktop: slide the whole app-shell left to reveal the 500px chat on the right. */
@media (min-width: 768px) {
.layout-stage.chat-open .app-shell {
transform: translateX(-500px);
}
}
/* Mobile: chat covers the screen; app stays put under a dimmed backdrop. */
.chat-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
border: none;
z-index: 105;
display: none;
}
@media (max-width: 767.98px) {
.chat-backdrop {
display: block;
}
}
.app-main {
margin-left: 220px;
@@ -83,4 +136,37 @@
flex: 1;
transition: margin-left 0.2s;
}
.chat-toggle {
position: relative;
width: 40px;
height: 40px;
border: none;
border-radius: 10px;
background: #f3f4f6;
color: #374151;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.chat-toggle:hover {
background: #e5e7eb;
color: #4338ca;
}
.chat-badge {
position: absolute;
top: -4px;
right: -4px;
background: #10b981;
color: #fff;
font-size: 0.7rem;
font-weight: 700;
min-width: 18px;
height: 18px;
border-radius: 999px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 4px;
}
</style>
+37
View File
@@ -349,6 +349,43 @@ async function main() {
],
});
// Chat collections (global family messages + transient typing presence)
ids.messages = await createCollection(token, {
name: "messages",
type: "base",
listRule: "",
viewRule: "",
createRule: null,
updateRule: null,
deleteRule: null,
fields: [
rel("famId", ids.fams!, true),
select("authorType", ["admin", "member"], true),
text("authorId", true),
text("authorName", true),
text("authorColor"),
text("content", true),
],
});
ids.chat_typing = await createCollection(token, {
name: "chat_typing",
type: "base",
listRule: "",
viewRule: "",
createRule: null,
updateRule: null,
deleteRule: null,
fields: [
rel("famId", ids.fams!, true),
text("actorId", true),
select("actorType", ["admin", "member"], true),
text("authorName", true),
text("authorColor"),
bool("typing"),
],
});
console.log("\n✅ All collections created successfully");
console.log("Collection IDs:", ids);
}
+138
View File
@@ -2313,6 +2313,144 @@ app.post("/api/admin/:famId/debug/generate-data", requireAdmin, async (c) => {
}
});
// ── Chat ────────────────────────────────────────────────
// Resolve the acting user for a chat write. Admins authenticate via the
// httpOnly `session` cookie (parsed server-side) or explicit session headers
// (server-to-server); members via device token.
async function resolveChatActor(c: any) {
// Server-side admin (layout load forwards session headers).
const hsFamId = c.req.header("x-session-famid");
const hsUserId = c.req.header("x-session-userid");
if (hsFamId && hsUserId) {
const admins = await pb.getList(
"fam_admins",
`famId = '${hsFamId}' && userId = '${hsUserId}'`,
);
const admin = admins.items?.[0];
if (admin) {
return {
famId: hsFamId,
actor: {
id: admin.id,
type: "admin",
name: admin.name,
color: admin.color,
},
};
}
}
const cookieHeader = c.req.header("cookie") || "";
const cookieMatch = cookieHeader.match(/session=([^;]+)/);
if (cookieMatch) {
try {
const s = JSON.parse(decodeURIComponent(cookieMatch[1]));
if (s?.famId && s?.userId) {
const admins = await pb.getList(
"fam_admins",
`famId = '${s.famId}' && userId = '${s.userId}'`,
);
const admin = admins.items?.[0];
if (admin) {
return {
famId: s.famId,
actor: {
id: admin.id,
type: "admin",
name: admin.name,
color: admin.color,
},
};
}
}
} catch {}
}
const famId = c.req.header("x-device-famid");
const deviceToken = c.req.header("x-device-token");
if (famId && deviceToken) {
const hash = crypto.createHash("sha256").update(deviceToken).digest("hex");
const members = await pb.getList(
"members",
`famId = '${famId}' && deviceToken = '${hash}'`,
);
const member = members.items?.[0];
if (member) {
return {
famId,
actor: {
id: member.id,
type: "member",
name: member.name,
color: member.color,
},
};
}
}
return null;
}
app.post("/api/chat/:famId/messages", async (c) => {
try {
const auth = await resolveChatActor(c);
if (!auth) return c.json({ error: "Unauthorized" }, 401);
const { content } = await c.req.json();
if (!content || !content.trim()) {
return c.json({ error: "content required" }, 400);
}
const record = await pb.create("messages", {
famId: auth.famId,
authorType: auth.actor.type,
authorId: auth.actor.id,
authorName: auth.actor.name,
authorColor: auth.actor.color,
content: content.trim(),
createdAt: new Date().toISOString(),
});
return c.json(record);
} catch (err) {
return handleError(c, err);
}
});
app.post("/api/chat/:famId/typing", async (c) => {
try {
const auth = await resolveChatActor(c);
if (!auth) return c.json({ error: "Unauthorized" }, 401);
const { typing } = await c.req.json();
const existing = await pb.getList(
"chat_typing",
`famId = '${auth.famId}' && actorId = '${auth.actor.id}' && actorType = '${auth.actor.type}'`,
);
const row = {
famId: auth.famId,
actorId: auth.actor.id,
actorType: auth.actor.type,
authorName: auth.actor.name,
authorColor: auth.actor.color,
typing: !!typing,
};
if (existing.items?.length) {
await pb.update("chat_typing", existing.items[0].id, row);
} else {
await pb.create("chat_typing", row);
}
return c.json({ ok: true });
} catch (err) {
return handleError(c, err);
}
});
// Current user's chat identity (name, color, actorId) + famId.
app.get("/api/chat/me", async (c) => {
try {
const auth = await resolveChatActor(c);
if (!auth) return c.json({ error: "Unauthorized" }, 401);
return c.json({ famId: auth.famId, actor: auth.actor });
} catch (err) {
return handleError(c, err);
}
});
// ── Start server ─────────────────────────────────────────
const port = parseInt(process.env.PROXY_PORT || "3456", 10);
+73
View File
@@ -1383,5 +1383,78 @@ export async function migrate(): Promise<void> {
);
}
// ── 9. Create chat collections (messages + chat_typing) ──
const famsColChat = await getCollection("fams");
if (famsColChat) {
// 9a. messages
const msgsCol = await getCollection("messages");
if (!msgsCol) {
console.log("[migrate] Creating messages collection...");
await createCollection({
name: "messages",
type: "base",
listRule: "",
viewRule: "",
createRule: null,
updateRule: null,
deleteRule: null,
fields: [
{
name: "famId",
type: "relation",
required: true,
collectionId: famsColChat.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "authorType", type: "select", required: true, values: ["admin", "member"], maxSelect: 1 },
{ name: "authorId", type: "text", required: true },
{ name: "authorName", type: "text", required: true },
{ name: "authorColor", type: "text", required: false },
{ name: "content", type: "text", required: true },
{ name: "createdAt", type: "date", required: false },
],
});
} else {
console.log(` ↳ messages already exists`);
await updateCollection("messages", { listRule: "", viewRule: "" });
}
// 9b. chat_typing (transient presence rows, one per actor)
const typingCol = await getCollection("chat_typing");
if (!typingCol) {
console.log("[migrate] Creating chat_typing collection...");
await createCollection({
name: "chat_typing",
type: "base",
listRule: "",
viewRule: "",
createRule: null,
updateRule: null,
deleteRule: null,
fields: [
{
name: "famId",
type: "relation",
required: true,
collectionId: famsColChat.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "actorId", type: "text", required: true },
{ name: "actorType", type: "select", required: true, values: ["admin", "member"], maxSelect: 1 },
{ name: "authorName", type: "text", required: true },
{ name: "authorColor", type: "text", required: false },
{ name: "typing", type: "bool", required: false },
],
});
} else {
console.log(` ↳ chat_typing already exists`);
await updateCollection("chat_typing", { listRule: "", viewRule: "" });
}
} else {
console.log(` ↳ fams collection not found — chat collections deferred`);
}
console.log("[migrate] Done");
}