atagen

malice

public
Star0
Watch0
ba90983cec2eb8367c17aef8b5f937543c803672
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/api.tsTypescript164 lines8.2 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 type { EventContext, EventContextPage, MemberSummary, RoomSummary } from './types';
4
import type { Emote } from './emotes';
5
import type { MentionKey, MentionsBoundary, MentionsPage, SavedMentionContext } from './mentions-model';
6
export { mentionKey, parseMentionsPage, parseSavedMentionContext, parseMentionsUpdate } from './mentions-model';
7
export type { MentionKey, MentionReason, MentionCaptureState, MentionEntry, MentionCoverage, MentionGap, MentionsBoundary, MentionsPage, SavedMentionContext, MentionsUpdate } from './mentions-model';
8
import { formatBody } from './markdown';
9
import { mentionedUserIds, type Mention } from './mentions';
10
import { HttpTransport } from './transport-http';
11
import { parseSearchPage, scopeWire, type SearchPage, type SearchScope } from './search-model';
12
import type { CommandRequest, SendKind, SessionInfo, Transport, VerifyAction } from './transport';
13
export type { HistoryRequest } from './transport';
14
import { createDeviceTransport } from 'malice:device-transport';
15
16
import { ApiError } from './transport';
17
export { ApiError } from './transport';
18
export type { SessionInfo, SoftLogout, VerifyAction } from './transport';
19
20
function createTransport(): Transport {
21
  if (import.meta.env.VITE_MALICE_TARGET === 'device') return createDeviceTransport();
22
  return new HttpTransport();
23
}
24
25
const transport: Transport = createTransport();
26
27
export function getSession(): Promise<SessionInfo> {
28
  return transport.getSession();
29
}
30
31
export function login(homeserver: string, username: string, password: string): Promise<{ user_id: string }> {
32
  return transport.login(homeserver, username, password);
33
}
34
35
export function logout(): Promise<void> {
36
  return transport.logout();
37
}
38
39
export function getRooms(): Promise<{ rooms: RoomSummary[] }> {
40
  return transport.getRooms();
41
}
42
43
export const openRoom = (room_id: string) => transport.openRoom(room_id);
44
export const closeRoom = (room_id: string) => transport.closeRoom(room_id);
45
export const sendMessage = (
46
  room_id: string,
47
  body: string,
48
  reply_to: string | null = null,
49
  mentions: Mention[] = [],
50
  kind: SendKind = 'text',
51
  emotes: Emote[] = [],
52
  thread_root: string | null = null
53
) => transport.sendMessage(room_id, body, formatBody(body, mentions, true, emotes), reply_to, mentionedUserIds(mentions), kind, thread_root);
54
export const runCommand = (request: CommandRequest) => transport.command(request);
55
export const uploadAvatar = (file: File) => transport.uploadAvatar(file);
56
export const uploadRoomAvatar = (room_id: string, file: File) => transport.uploadRoomAvatar(room_id, file);
57
export const uploadMedia = (file: File) => transport.uploadMedia(file);
58
export const paginateRoom = (room_id: string, thread_root: string | null = null) => transport.paginateRoom(room_id, thread_root);
59
export const eventContext = (room_id: string, event_id: string, limit?: number): Promise<EventContext> =>
60
  transport.eventContext(room_id, event_id, limit);
61
export const eventContextBefore = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
62
  transport.eventContextBefore(room_id, event_id, from, limit);
63
export const eventContextAfter = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
64
  transport.eventContextAfter(room_id, event_id, from, limit);
65
export const mentionsPage = (cursor: string | null = null, limit = 50): Promise<MentionsPage> => transport.mentionsPage(cursor, limit);
66
export const mentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.mentionContext(room_id, event_id);
67
export const retryMentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.retryMentionContext(room_id, event_id);
68
export const setMentionsRead = (keys: MentionKey[], read: boolean) => transport.setMentionsRead(keys, read);
69
export const markMentionsReadThrough = (boundary: MentionsBoundary) => transport.markMentionsReadThrough(boundary);
70
export const recoverMentions = () => transport.recoverMentions();
71
export async function searchMessages(query: string, scope: SearchScope, cursor: string | null = null, limit = 30): Promise<SearchPage> {
72
  let raw: unknown;
73
  try {
74
    raw = await transport.command({ op: 'search', query, scope: scopeWire(scope), cursor, limit });
75
  } catch (e) {
76
    if (e instanceof ApiError && (e.status === 400 || e.status === 422)) throw new ApiError(400, "Search isn't available yet");
77
    throw e;
78
  }
79
  const page = parseSearchPage(raw);
80
  if (!page) throw new ApiError(502, 'Invalid search response');
81
  return page;
82
}
83
export const startRecentHistory = (room_id: string): Promise<void> => transport.startRecentHistory(room_id);
84
export const fillHistoryGap = (room_id: string, gap_id: string): Promise<void> => transport.fillHistoryGap(room_id, gap_id);
85
export const setTyping = (room_id: string, typing: boolean) => transport.setTyping(room_id, typing);
86
export const getAccountData = (eventType: string) => transport.getAccountData(eventType);
87
export const getUrlPreview = (room_id: string, url: string) => transport.getUrlPreview(room_id, url);
88
export const setAccountData = (eventType: string, content: Record<string, unknown>) =>
89
  transport.setAccountData(eventType, content);
90
91
export function joinRoom(room: string): Promise<{ room_id: string }> {
92
  return transport.joinRoom(room);
93
}
94
95
export function createRoom(name: string, topic?: string): Promise<{ room_id: string }> {
96
  return transport.createRoom(name, topic);
97
}
98
99
export const leaveRoom = (room_id: string) => transport.leaveRoom(room_id);
100
export const reactToMessage = (room_id: string, event_id: string, key: string, shortcode?: string, thread_root: string | null = null) =>
101
  transport.reactToMessage(room_id, event_id, key, shortcode, thread_root);
102
export const editMessage = (room_id: string, event_id: string, body: string, mentions: Mention[] = [], emotes: Emote[] = [], thread_root: string | null = null) =>
103
  transport.editMessage(room_id, event_id, body, formatBody(body, mentions, true, emotes), mentionedUserIds(mentions), thread_root);
104
export const markRead = (room_id: string, event_id: string, thread_root: string | null = null) => transport.markRead(room_id, event_id, thread_root);
105
106
export function getMembers(room_id: string): Promise<{ members: MemberSummary[] }> {
107
  return transport.getMembers(room_id);
108
}
109
110
/** Same URL shape in both builds: the hosted server and the device service worker both answer it. */
111
export function mediaUrl(mxc: string | null, size = 256): string | null {
112
  if (!mxc) return null;
113
  return `/api/media?mxc=${encodeURIComponent(mxc)}&size=${Math.max(16, Math.min(512, Math.round(size)))}`;
114
}
115
116
export function messageMediaUrl(mediaId: string, size: 'Thumbnail' | 'Full'): string {
117
  return `/api/message-media?media_id=${encodeURIComponent(mediaId)}&size=${size}`;
118
}
119
120
export function getProfile(): Promise<{ display_name: string | null; avatar_url: string | null }> {
121
  return transport.getProfile();
122
}
123
124
export function getSpaceChildren(room_id: string): Promise<{ room_ids: string[] }> {
125
  return transport.getSpaceChildren(room_id);
126
}
127
128
export function getEncryption(): Promise<{ state: unknown; verification: unknown }> {
129
  return transport.getEncryption();
130
}
131
132
export function recoverEncryption(recovery_key: string): Promise<void> {
133
  return transport.recoverEncryption(recovery_key);
134
}
135
136
export function startVerification(): Promise<void> {
137
  return transport.startVerification();
138
}
139
140
export function verifyEncryption(action: VerifyAction): Promise<void> {
141
  return transport.verifyEncryption(action);
142
}
143
144
export function uploadAttachment(
145
  room_id: string,
146
  file: File,
147
  caption: string | null = null,
148
  reply_to: string | null = null,
149
  mentions: Mention[] = [],
150
  emotes: Emote[] = [],
151
  thread_root: string | null = null
152
): Promise<void> {
153
  return transport.uploadAttachment(room_id, file, {
154
    caption,
155
    formatted_caption: caption ? formatBody(caption, mentions, true, emotes) : null,
156
    reply_to,
157
    mentions: mentionedUserIds(mentions),
158
    thread_root
159
  });
160
}
161
162
export function subscribeEvents(onEvent: (data: string) => void, onDisconnect: () => void): () => void {
163
  return transport.subscribeEvents(onEvent, onDisconnect);
164
}