atagen

malice

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