Debian Codegraph @

web/src/app/Api.js

raw
1 import {
2 fetchLinesIterator,
3 maybeWithAuth,
4 topicShortUrl,
5 topicUrl,
6 topicUrlAuth,
7 topicUrlJsonPoll,
8 topicUrlJsonPollWithSince,
9 webPushUrl,
10 } from "./utils";
11 import userManager from "./UserManager";
12 import { fetchOrThrow } from "./errors";
13
14 class Api {
15 async poll(baseUrl, topic, since) {
16 const user = await userManager.get(baseUrl);
17 const shortUrl = topicShortUrl(baseUrl, topic);
18 const url = since ? topicUrlJsonPollWithSince(baseUrl, topic, since) : topicUrlJsonPoll(baseUrl, topic);
19 const messages = [];
20 const headers = maybeWithAuth({}, user);
21 console.log(`[Api] Polling ${url}`);
22 for await (const line of fetchLinesIterator(url, headers)) {
23 const message = JSON.parse(line);
24 if (message.id) {
25 console.log(`[Api, ${shortUrl}] Received message ${line}`);
26 messages.push(message);
27 }
28 }
29 return messages;
30 }
31
32 async publish(baseUrl, topic, message, options) {
33 const user = await userManager.get(baseUrl);
34 console.log(`[Api] Publishing message to ${topicUrl(baseUrl, topic)}`);
35 const headers = {};
36 const body = {
37 topic,
38 message,
39 ...options,
40 };
41 await fetchOrThrow(baseUrl, {
42 method: "PUT",
43 body: JSON.stringify(body),
44 headers: maybeWithAuth(headers, user),
45 });
46 }
47
48 /**
49 * Publishes to a topic using XMLHttpRequest (XHR), and returns a Promise with the active request.
50 * Unfortunately, fetch() does not support a progress hook, which is why XHR has to be used.
51 *
52 * Firefox XHR bug:
53 * Firefox has a bug(?), which returns 0 and "" for all fields of the XHR response in the case of an error,
54 * so we cannot determine the exact error. It also sometimes complains about CORS violations, even when the
55 * correct headers are clearly set. It's quite the odd behavior.
56 *
57 * There is an example, and the bug report here:
58 * - https://bugzilla.mozilla.org/show_bug.cgi?id=1733755
59 * - https://gist.github.com/binwiederhier/627f146d1959799be207ad8c17a8f345
60 */
61 publishXHR(url, body, headers, onProgress) {
62 console.log(`[Api] Publishing message to ${url}`);
63 const xhr = new XMLHttpRequest();
64 const send = new Promise((resolve, reject) => {
65 xhr.open("PUT", url);
66 if (body.type) {
67 xhr.overrideMimeType(body.type);
68 }
69 for (const [key, value] of Object.entries(headers)) {
70 xhr.setRequestHeader(key, value);
71 }
72 xhr.upload.addEventListener("progress", onProgress);
73 xhr.addEventListener("readystatechange", () => {
74 if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
75 console.log(`[Api] Publish successful (HTTP ${xhr.status})`, xhr.response);
76 resolve(xhr.response);
77 } else if (xhr.readyState === 4) {
78 // Firefox bug; see description above!
79 console.log(`[Api] Publish failed (HTTP ${xhr.status})`, xhr.responseText);
80 let errorText;
81 try {
82 const error = JSON.parse(xhr.responseText);
83 if (error.code && error.error) {
84 errorText = `Error ${error.code}: ${error.error}`;
85 }
86 } catch (e) {
87 // Nothing
88 }
89 xhr.abort();
90 reject(errorText ?? "An error occurred");
91 }
92 });
93 xhr.send(body);
94 });
95 send.abort = () => {
96 console.log(`[Api] Publish aborted by user`);
97 xhr.abort();
98 };
99 return send;
100 }
101
102 async topicAuth(baseUrl, topic, user) {
103 const url = topicUrlAuth(baseUrl, topic);
104 console.log(`[Api] Checking auth for ${url}`);
105 const response = await fetch(url, {
106 headers: maybeWithAuth({}, user),
107 });
108 if (response.status >= 200 && response.status <= 299) {
109 return true;
110 }
111 if (response.status === 401 || response.status === 403) {
112 // See server/server.go
113 return false;
114 }
115 throw new Error(`Unexpected server response ${response.status}`);
116 }
117
118 async updateWebPush(pushSubscription, topics) {
119 const user = await userManager.get(config.base_url);
120 const url = webPushUrl(config.base_url);
121 console.log(`[Api] Updating Web Push subscription`, { url, topics, endpoint: pushSubscription.endpoint });
122 const serializedSubscription = JSON.parse(JSON.stringify(pushSubscription)); // Ugh ... https://stackoverflow.com/a/40525434/1440785
123 await fetchOrThrow(url, {
124 method: "POST",
125 headers: maybeWithAuth({}, user),
126 body: JSON.stringify({
127 endpoint: serializedSubscription.endpoint,
128 auth: serializedSubscription.keys.auth,
129 p256dh: serializedSubscription.keys.p256dh,
130 topics,
131 }),
132 });
133 }
134
135 async deleteWebPush(pushSubscription) {
136 const user = await userManager.get(config.base_url);
137 const url = webPushUrl(config.base_url);
138 console.log(`[Api] Deleting Web Push subscription`, { url, endpoint: pushSubscription.endpoint });
139 await fetchOrThrow(url, {
140 method: "DELETE",
141 headers: maybeWithAuth({}, user),
142 body: JSON.stringify({
143 endpoint: pushSubscription.endpoint,
144 }),
145 });
146 }
147 }
148
149 const api = new Api();
150 export default api;