forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspaces.ts
More file actions
251 lines (215 loc) · 7.7 KB
/
spaces.ts
File metadata and controls
251 lines (215 loc) · 7.7 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
// Spaces API
// Implements: https://spec.matrix.org/v1.12/client-server-api/#spaces
//
// Spaces are a way to organize rooms into hierarchical groups
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
const app = new Hono<AppEnv>();
// ============================================
// Types
// ============================================
interface SpaceChild {
room_id: string;
room_type?: string;
name?: string;
topic?: string;
canonical_alias?: string;
num_joined_members: number;
avatar_url?: string;
join_rule?: string;
world_readable: boolean;
guest_can_join: boolean;
children_state: any[];
}
// ============================================
// Endpoints
// ============================================
// GET /_matrix/client/v1/rooms/:roomId/hierarchy - Get space hierarchy
app.get('/_matrix/client/v1/rooms/:roomId/hierarchy', requireAuth(), async (c) => {
// Note: userId could be used for permission checks in future
void c.get('userId');
const roomId = c.req.param('roomId');
const db = c.env.DB;
// Check if room exists
const room = await db.prepare(`
SELECT room_id FROM rooms WHERE room_id = ?
`).bind(roomId).first();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
// Get pagination params
// Note: 'from' pagination param reserved for future use
void c.req.query('from');
const limit = Math.min(parseInt(c.req.query('limit') || '50'), 100);
const maxDepth = parseInt(c.req.query('max_depth') || '1');
const suggestedOnly = c.req.query('suggested_only') === 'true';
// Get space children from m.space.child state events
const childEvents = await db.prepare(`
SELECT rs.state_key, e.content
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.space.child'
`).bind(roomId).all<{ state_key: string; content: string }>();
const rooms: SpaceChild[] = [];
// Add the space itself first
const spaceInfo = await getRoomInfo(db, roomId, c.env.SERVER_NAME);
if (spaceInfo) {
rooms.push({
...spaceInfo,
children_state: childEvents.results.map(ce => ({
type: 'm.space.child',
state_key: ce.state_key,
content: JSON.parse(ce.content),
sender: '', // Would need to fetch from event
origin_server_ts: 0,
})),
});
}
// Process each child
for (const child of childEvents.results) {
const childRoomId = child.state_key;
try {
const content = JSON.parse(child.content);
// Skip if suggested_only and not suggested
if (suggestedOnly && !content.suggested) {
continue;
}
// Skip if content has empty via array (deleted child)
if (!content.via || content.via.length === 0) {
continue;
}
// Get child room info
const childInfo = await getRoomInfo(db, childRoomId, c.env.SERVER_NAME);
if (childInfo) {
// Get grandchildren if within depth
let childrenState: any[] = [];
if (maxDepth > 1) {
const grandchildEvents = await db.prepare(`
SELECT rs.state_key, e.content
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.space.child'
`).bind(childRoomId).all<{ state_key: string; content: string }>();
childrenState = grandchildEvents.results.map(gce => ({
type: 'm.space.child',
state_key: gce.state_key,
content: JSON.parse(gce.content),
}));
}
rooms.push({
...childInfo,
children_state: childrenState,
});
}
} catch {
// Skip invalid child entries
}
}
return c.json({
rooms: rooms.slice(0, limit),
next_batch: rooms.length > limit ? rooms[limit - 1].room_id : undefined,
});
});
// Helper function to get room info
async function getRoomInfo(
db: D1Database,
roomId: string,
_serverName: string
): Promise<SpaceChild | null> {
// Get room
const room = await db.prepare(`
SELECT room_id, is_public FROM rooms WHERE room_id = ?
`).bind(roomId).first<{ room_id: string; is_public: number }>();
if (!room) {
return null;
}
// Get room name
const nameEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.name'
`).bind(roomId).first<{ content: string }>();
// Get room topic
const topicEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.topic'
`).bind(roomId).first<{ content: string }>();
// Get canonical alias
const aliasEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.canonical_alias'
`).bind(roomId).first<{ content: string }>();
// Get avatar
const avatarEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.avatar'
`).bind(roomId).first<{ content: string }>();
// Get join rule
const joinRuleEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.join_rules'
`).bind(roomId).first<{ content: string }>();
// Get room type (for spaces)
const createEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.create'
`).bind(roomId).first<{ content: string }>();
// Get member count
const memberCount = await db.prepare(`
SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'join'
`).bind(roomId).first<{ count: number }>();
// Get history visibility
const historyEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.history_visibility'
`).bind(roomId).first<{ content: string }>();
// Get guest access
const guestEvent = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.guest_access'
`).bind(roomId).first<{ content: string }>();
let roomType: string | undefined;
if (createEvent) {
try {
const content = JSON.parse(createEvent.content);
roomType = content.type;
} catch {}
}
let historyVisibility = 'shared';
if (historyEvent) {
try {
const content = JSON.parse(historyEvent.content);
historyVisibility = content.history_visibility;
} catch {}
}
let guestAccess = 'forbidden';
if (guestEvent) {
try {
const content = JSON.parse(guestEvent.content);
guestAccess = content.guest_access;
} catch {}
}
return {
room_id: roomId,
room_type: roomType,
name: nameEvent ? JSON.parse(nameEvent.content).name : undefined,
topic: topicEvent ? JSON.parse(topicEvent.content).topic : undefined,
canonical_alias: aliasEvent ? JSON.parse(aliasEvent.content).alias : undefined,
num_joined_members: memberCount?.count || 0,
avatar_url: avatarEvent ? JSON.parse(avatarEvent.content).url : undefined,
join_rule: joinRuleEvent ? JSON.parse(joinRuleEvent.content).join_rule : 'invite',
world_readable: historyVisibility === 'world_readable',
guest_can_join: guestAccess === 'can_join',
children_state: [],
};
}
export default app;