atagen

malice

public
Star0
Watch0
5d6f6e2eb5a5d86815495c9f47587b55de1e3ba3
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/api.tsTypescript217 lines10.8 KB
1
// Backend-agnostic API surface. Every call forwards to whichever transport
2
// this build was compiled for, hosted (fetch + SSE) or on-device (worker).
3
import { parseEventContextPage, parseEventContextSession } from './types';
4
import type { EventContextPage, EventContextSession, MemberSummary, RoomSummary } from './types';
5
import type { Emote } from './emotes';
6
import type { MentionKey, MentionsBoundary, MentionsPage, SavedMentionContext } from './mentions-model';
7
export { mentionKey, parseMentionsPage, parseSavedMentionContext, parseMentionsUpdate } from './mentions-model';
8
export type { MentionKey, MentionReason, MentionCaptureState, MentionEntry, MentionCoverage, MentionGap, MentionsBoundary, MentionsPage, SavedMentionContext, MentionsUpdate } from './mentions-model';
9
import { formatBody } from './markdown';
10
import { mentionedUserIds, type Mention } from './mentions';
11
import { HttpTransport } from './transport-http';
12
import { parseSearchPage, parseSearchSession, scopeWire, type SearchPage, type SearchScope, type SearchSession } from './search-model';
13
import type { CommandRequest, SendKind, SessionInfo, Transport, VerifyAction } from './transport';
14
export type { HistoryRequest } from './transport';
15
import { createDeviceTransport } from 'malice:device-transport';
16
17
import { ApiError } from './transport';
18
import { isRecord } from './guards';
19
export { ApiError } from './transport';
20
export type { SessionInfo, SoftLogout, VerifyAction } from './transport';
21
22
function createTransport(): Transport {
23
  if (import.meta.env.VITE_MALICE_TARGET === 'device') return createDeviceTransport();
24
  return new HttpTransport();
25
}
26
27
const transport: Transport = createTransport();
28
29
export function getSession(): Promise<SessionInfo> {
30
  return transport.getSession();
31
}
32
33
export function login(homeserver: string, username: string, password: string): Promise<{ user_id: string }> {
34
  return transport.login(homeserver, username, password);
35
}
36
37
export function logout(): Promise<void> {
38
  return transport.logout();
39
}
40
41
export function getRooms(): Promise<{ rooms: RoomSummary[] }> {
42
  return transport.getRooms();
43
}
44
45
export const openRoom = (room_id: string) => transport.openRoom(room_id);
46
export const closeRoom = (room_id: string) => transport.closeRoom(room_id);
47
export const sendMessage = (
48
  room_id: string,
49
  body: string,
50
  reply_to: string | null = null,
51
  mentions: Mention[] = [],
52
  kind: SendKind = 'text',
53
  emotes: Emote[] = [],
54
  thread_root: string | null = null
55
) => transport.sendMessage(room_id, body, formatBody(body, mentions, true, emotes), reply_to, mentionedUserIds(mentions), kind, thread_root);
56
export const runCommand = (request: CommandRequest) => transport.command(request);
57
export const uploadAvatar = (file: File) => transport.uploadAvatar(file);
58
export const uploadRoomAvatar = (room_id: string, file: File) => transport.uploadRoomAvatar(room_id, file);
59
export const uploadMedia = (file: File) => transport.uploadMedia(file);
60
export const paginateRoom = (room_id: string, thread_root: string | null = null) => transport.paginateRoom(room_id, thread_root);
61
export async function eventContext(room_id: string, event_id: string, limit = 20): Promise<EventContextSession> {
62
  const parsed = parseEventContextSession(
63
    await transport.command({ op: 'event_context', room_id, event_id, before_limit: limit, after_limit: limit })
64
  );
65
  if (!parsed) throw new ApiError(502, 'Invalid event context response');
66
  return parsed;
67
}
68
async function eventContextPage(op: 'event_context_before' | 'event_context_after', context_id: string, token: string, limit: number): Promise<EventContextPage> {
69
  const parsed = parseEventContextPage(await transport.command({ op, context_id, token, limit }));
70
  if (!parsed) throw new ApiError(502, 'Invalid event context page response');
71
  return parsed;
72
}
73
export const eventContextBefore = (context_id: string, token: string, limit = 20): Promise<EventContextPage> =>
74
  eventContextPage('event_context_before', context_id, token, limit);
75
export const eventContextAfter = (context_id: string, token: string, limit = 20): Promise<EventContextPage> =>
76
  eventContextPage('event_context_after', context_id, token, limit);
77
export async function closeEventContext(context_id: string): Promise<void> {
78
  await transport.command({ op: 'close_event_context', context_id });
79
}
80
export const mentionsPage = (cursor: string | null = null, limit = 50): Promise<MentionsPage> => transport.mentionsPage(cursor, limit);
81
export const mentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.mentionContext(room_id, event_id);
82
export const retryMentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.retryMentionContext(room_id, event_id);
83
export const setMentionsRead = (keys: MentionKey[], read: boolean) => transport.setMentionsRead(keys, read);
84
export const markMentionsReadThrough = (boundary: MentionsBoundary) => transport.markMentionsReadThrough(boundary);
85
export const recoverMentions = () => transport.recoverMentions();
86
export async function searchMessages(query: string, scope: SearchScope, limit = 30): Promise<SearchSession> {
87
  const session = parseSearchSession(await transport.command({ op: 'search', query, scope: scopeWire(scope), limit }));
88
  if (!session) throw new ApiError(502, 'Invalid search response');
89
  return session;
90
}
91
export async function searchMore(search_id: string, cursor: string, limit = 30): Promise<SearchPage> {
92
  const page = parseSearchPage(await transport.command({ op: 'search_more', search_id, cursor, limit }));
93
  if (!page) throw new ApiError(502, 'Invalid search response');
94
  return page;
95
}
96
export async function closeSearch(search_id: string): Promise<void> {
97
  await transport.command({ op: 'close_search', search_id });
98
}
99
export async function retryRecentHistory(room_id: string): Promise<void> {
100
  await transport.command({ op: 'retry_recent_history', room_id });
101
}
102
export async function fillHistoryGap(room_id: string, gap_id: string): Promise<void> {
103
  await transport.command({ op: 'fill_history_gap', room_id, gap_id });
104
}
105
export async function openThreadList(room_id: string): Promise<void> {
106
  await transport.command({ op: 'open_thread_list', room_id });
107
}
108
export async function paginateThreadList(room_id: string, limit = 20): Promise<void> {
109
  await transport.command({ op: 'paginate_thread_list', room_id, limit });
110
}
111
export async function closeThreadList(room_id: string): Promise<void> {
112
  await transport.command({ op: 'close_thread_list', room_id });
113
}
114
export const setTyping = (room_id: string, typing: boolean) => transport.setTyping(room_id, typing);
115
export const getAccountData = (eventType: string) => transport.getAccountData(eventType);
116
export const getUrlPreview = (room_id: string, url: string) => transport.getUrlPreview(room_id, url);
117
export const setAccountData = (eventType: string, content: Record<string, unknown>) =>
118
  transport.setAccountData(eventType, content);
119
120
export function joinRoom(room: string): Promise<{ room_id: string }> {
121
  return transport.joinRoom(room);
122
}
123
124
export function createRoom(name: string, topic?: string): Promise<{ room_id: string }> {
125
  return transport.createRoom(name, topic);
126
}
127
128
export const leaveRoom = (room_id: string) => transport.leaveRoom(room_id);
129
export const reactToMessage = (room_id: string, event_id: string, key: string, shortcode?: string, thread_root: string | null = null) =>
130
  transport.reactToMessage(room_id, event_id, key, shortcode, thread_root);
131
export const editMessage = (room_id: string, event_id: string, body: string, mentions: Mention[] = [], emotes: Emote[] = [], thread_root: string | null = null) =>
132
  transport.editMessage(room_id, event_id, body, formatBody(body, mentions, true, emotes), mentionedUserIds(mentions), thread_root);
133
export const markRead = (room_id: string, event_id: string, thread_root: string | null = null) => transport.markRead(room_id, event_id, thread_root);
134
135
export function getMembers(room_id: string): Promise<{ members: MemberSummary[] }> {
136
  return transport.getMembers(room_id);
137
}
138
139
/** Same URL shape in both builds: the hosted server and the device service worker both answer it. */
140
export function mediaUrl(mxc: string | null, size = 256): string | null {
141
  if (!mxc) return null;
142
  return `/api/media?mxc=${encodeURIComponent(mxc)}&size=${Math.max(16, Math.min(512, Math.round(size)))}`;
143
}
144
145
export function messageMediaUrl(mediaId: string, size: 'Thumbnail' | 'Full'): string {
146
  return `/api/message-media?media_id=${encodeURIComponent(mediaId)}&size=${size}`;
147
}
148
149
export function getProfile(): Promise<{ display_name: string | null; avatar_url: string | null }> {
150
  return transport.getProfile();
151
}
152
153
export function getSpaceChildren(room_id: string): Promise<{ room_ids: string[] }> {
154
  return transport.getSpaceChildren(room_id);
155
}
156
157
export function getEncryption(): Promise<{ state: unknown; verification: unknown }> {
158
  return transport.getEncryption();
159
}
160
161
export function recoverEncryption(recovery_key: string): Promise<void> {
162
  return transport.recoverEncryption(recovery_key);
163
}
164
165
export type KeyBackupAction = 'enable_key_backup' | 'disable_key_backup';
166
167
export async function runKeyBackup(op: KeyBackupAction, deleteFromServer = false): Promise<void> {
168
  await transport.command(op === 'disable_key_backup' ? { op, delete_from_server: deleteFromServer } : { op });
169
}
170
171
export async function setupRecovery(op: 'enable_recovery' | 'reset_recovery_key', passphrase: string | null): Promise<string> {
172
  const reply = await transport.command({ op, passphrase });
173
  const key = isRecord(reply) ? reply['recovery_key'] : null;
174
  if (typeof key !== 'string' || !key) throw new Error('No recovery key returned');
175
  return key;
176
}
177
178
export const isBackupExists = (e: unknown): boolean => e instanceof ApiError && e.kind === 'key_backup_exists';
179
180
export async function disableRecovery(): Promise<void> {
181
  await transport.command({ op: 'disable_recovery' });
182
}
183
184
export async function verifyRecoveryKey(recovery_key: string): Promise<boolean> {
185
  const reply = await transport.command({ op: 'verify_recovery_key', recovery_key });
186
  return isRecord(reply) && reply['valid'] === true;
187
}
188
189
export function startVerification(): Promise<void> {
190
  return transport.startVerification();
191
}
192
193
export function verifyEncryption(action: VerifyAction): Promise<void> {
194
  return transport.verifyEncryption(action);
195
}
196
197
export function uploadAttachment(
198
  room_id: string,
199
  file: File,
200
  caption: string | null = null,
201
  reply_to: string | null = null,
202
  mentions: Mention[] = [],
203
  emotes: Emote[] = [],
204
  thread_root: string | null = null
205
): Promise<void> {
206
  return transport.uploadAttachment(room_id, file, {
207
    caption,
208
    formatted_caption: caption ? formatBody(caption, mentions, true, emotes) : null,
209
    reply_to,
210
    mentions: mentionedUserIds(mentions),
211
    thread_root
212
  });
213
}
214
215
export function subscribeEvents(onEvent: (data: string) => void, onDisconnect: () => void): () => void {
216
  return transport.subscribeEvents(onEvent, onDisconnect);
217
}