forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpresence.ts
More file actions
279 lines (238 loc) · 8.03 KB
/
presence.ts
File metadata and controls
279 lines (238 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Presence API
// Implements: https://spec.matrix.org/v1.12/client-server-api/#presence
//
// Presence indicates whether users are online, offline, or unavailable.
// Status messages can also be set.
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
import { getServersInRoomsWithUser } from '../services/database';
const app = new Hono<AppEnv>();
// ============================================
// Constants
// ============================================
const PRESENCE_TIMEOUT = 5 * 60 * 1000; // 5 minutes - consider offline after this
// ============================================
// Endpoints
// ============================================
// PUT /_matrix/client/v3/presence/:userId/status - Set presence status
app.put('/_matrix/client/v3/presence/:userId/status', requireAuth(), async (c) => {
const requestingUserId = c.get('userId');
const targetUserId = c.req.param('userId');
const db = c.env.DB;
// Users can only set their own presence
if (requestingUserId !== targetUserId) {
return Errors.forbidden('Cannot set presence for other users').toResponse();
}
let body: { presence: string; status_msg?: string };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const { presence, status_msg } = body;
// Validate presence state
const validStates = ['online', 'offline', 'unavailable'];
if (!presence || !validStates.includes(presence)) {
return c.json({
errcode: 'M_INVALID_PARAM',
error: `Invalid presence state: ${presence}. Must be one of: ${validStates.join(', ')}`,
}, 400);
}
const now = Date.now();
// Store presence in D1
await db.prepare(`
INSERT INTO presence (user_id, presence, status_msg, last_active_ts)
VALUES (?, ?, ?, ?)
ON CONFLICT (user_id) DO UPDATE SET
presence = excluded.presence,
status_msg = excluded.status_msg,
last_active_ts = excluded.last_active_ts
`).bind(requestingUserId, presence, status_msg || null, now).run();
// Write-through to KV cache for fast reads (5 minute TTL)
await c.env.CACHE.put(
`presence:${requestingUserId}`,
JSON.stringify({
presence,
status_msg: status_msg || null,
last_active_ts: now,
}),
{ expirationTtl: 5 * 60 } // 5 minutes
);
// Queue outbound m.presence EDUs to federated servers
try {
const remoteServers = await getServersInRoomsWithUser(db, requestingUserId);
const localServer = c.env.SERVER_NAME;
const uniqueServers = [...new Set(remoteServers)].filter(s => s !== localServer);
for (const server of uniqueServers) {
const fedDO = c.env.FEDERATION.get(c.env.FEDERATION.idFromName(server));
await fedDO.fetch(new Request('http://internal/send-edu', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
destination: server,
edu_type: 'm.presence',
content: {
push: [{
user_id: requestingUserId,
presence,
status_msg: status_msg || undefined,
last_active_ago: 0,
currently_active: presence === 'online',
}],
},
}),
}));
}
} catch (err) {
console.warn('[presence] Failed to queue federation EDUs:', err);
}
return c.json({});
});
// GET /_matrix/client/v3/presence/:userId/status - Get presence status
app.get('/_matrix/client/v3/presence/:userId/status', requireAuth(), async (c) => {
const targetUserId = c.req.param('userId');
const db = c.env.DB;
// Check if target user exists
const user = await db.prepare(`
SELECT user_id FROM users WHERE user_id = ?
`).bind(targetUserId).first();
if (!user) {
return Errors.notFound('User not found').toResponse();
}
// Try KV cache first for faster reads
const cached = await c.env.CACHE.get(`presence:${targetUserId}`, 'json') as {
presence: string;
status_msg: string | null;
last_active_ts: number;
} | null;
let presence: {
presence: string;
status_msg: string | null;
last_active_ts: number;
} | null = cached;
// Fall back to D1 if not in cache
if (!presence) {
presence = await db.prepare(`
SELECT presence, status_msg, last_active_ts
FROM presence
WHERE user_id = ?
`).bind(targetUserId).first<{
presence: string;
status_msg: string | null;
last_active_ts: number;
}>();
}
if (!presence) {
// Default to offline if no presence set
return c.json({
presence: 'offline',
currently_active: false,
});
}
const now = Date.now();
const isActive = (now - presence.last_active_ts) < PRESENCE_TIMEOUT;
// If presence was set to online but they've been inactive, report as unavailable
let effectivePresence = presence.presence;
if (presence.presence === 'online' && !isActive) {
effectivePresence = 'unavailable';
}
return c.json({
presence: effectivePresence,
status_msg: presence.status_msg || undefined,
last_active_ago: now - presence.last_active_ts,
currently_active: isActive && presence.presence === 'online',
});
});
// ============================================
// Internal Helpers
// ============================================
// Get presence for multiple users (for sync)
// This function requires KVNamespace to be passed for caching
export async function getPresenceForUsers(
db: D1Database,
userIds: string[],
cache?: KVNamespace
): Promise<Record<string, {
presence: string;
status_msg?: string;
last_active_ago?: number;
currently_active?: boolean;
}>> {
if (userIds.length === 0) return {};
const now = Date.now();
const byUser: Record<string, {
presence: string;
status_msg?: string;
last_active_ago?: number;
currently_active?: boolean;
}> = {};
const uncachedUserIds: string[] = [];
// Try to get from KV cache first
if (cache) {
for (const userId of userIds) {
const cached = await cache.get(`presence:${userId}`, 'json') as {
presence: string;
status_msg: string | null;
last_active_ts: number;
} | null;
if (cached) {
const isActive = (now - cached.last_active_ts) < PRESENCE_TIMEOUT;
let effectivePresence = cached.presence;
if (cached.presence === 'online' && !isActive) {
effectivePresence = 'unavailable';
}
byUser[userId] = {
presence: effectivePresence,
status_msg: cached.status_msg || undefined,
last_active_ago: now - cached.last_active_ts,
currently_active: isActive && cached.presence === 'online',
};
} else {
uncachedUserIds.push(userId);
}
}
} else {
uncachedUserIds.push(...userIds);
}
// Fall back to D1 for uncached users
if (uncachedUserIds.length > 0) {
const placeholders = uncachedUserIds.map(() => '?').join(',');
const results = await db.prepare(`
SELECT user_id, presence, status_msg, last_active_ts
FROM presence
WHERE user_id IN (${placeholders})
`).bind(...uncachedUserIds).all<{
user_id: string;
presence: string;
status_msg: string | null;
last_active_ts: number;
}>();
for (const row of results.results) {
const isActive = (now - row.last_active_ts) < PRESENCE_TIMEOUT;
let effectivePresence = row.presence;
if (row.presence === 'online' && !isActive) {
effectivePresence = 'unavailable';
}
byUser[row.user_id] = {
presence: effectivePresence,
status_msg: row.status_msg || undefined,
last_active_ago: now - row.last_active_ts,
currently_active: isActive && row.presence === 'online',
};
}
}
return byUser;
}
// Update last active timestamp (call this on API activity)
export async function updateLastActive(
db: D1Database,
userId: string
): Promise<void> {
const now = Date.now();
await db.prepare(`
UPDATE presence SET last_active_ts = ? WHERE user_id = ?
`).bind(now, userId).run();
}
export default app;