Debian Codegraph @

web/src/app/utils.js

raw
1 import beep from "../sounds/beep.mp3";
2 import juntos from "../sounds/juntos.mp3";
3 import pristine from "../sounds/pristine.mp3";
4 import ding from "../sounds/ding.mp3";
5 import dadum from "../sounds/dadum.mp3";
6 import pop from "../sounds/pop.mp3";
7 import popSwoosh from "../sounds/pop-swoosh.mp3";
8 import config from "./config";
9 import emojisMapped from "./emojisMapped";
10 import { THEME, DATE_FORMAT, TIME_FORMAT } from "./Prefs";
11
12 export const tiersUrl = (baseUrl) => `${baseUrl}/v1/tiers`;
13 export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
14 export const expandUrl = (url) => [`https://${url}`, `http://${url}`];
15 export const expandSecureUrl = (url) => `https://${url}`;
16 export const topicUrl = (baseUrl, topic) => `${baseUrl}/${topic}`;
17 export const topicUrlWs = (baseUrl, topic) =>
18 `${topicUrl(baseUrl, topic)}/ws`.replaceAll("https://", "wss://").replaceAll("http://", "ws://");
19 export const topicUrlJson = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/json`;
20 export const topicUrlJsonPoll = (baseUrl, topic) => `${topicUrlJson(baseUrl, topic)}?poll=1`;
21 export const topicUrlJsonPollWithSince = (baseUrl, topic, since) => `${topicUrlJson(baseUrl, topic)}?poll=1&since=${since}`;
22 export const topicUrlAuth = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/auth`;
23 export const topicShortUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));
24 export const webPushUrl = (baseUrl) => `${baseUrl}/v1/webpush`;
25 export const accountUrl = (baseUrl) => `${baseUrl}/v1/account`;
26 export const accountLoginUrl = (baseUrl) => `${baseUrl}/v1/account/login`;
27 export const accountPasswordUrl = (baseUrl) => `${baseUrl}/v1/account/password`;
28 export const accountTokenUrl = (baseUrl) => `${baseUrl}/v1/account/token`;
29 export const accountSettingsUrl = (baseUrl) => `${baseUrl}/v1/account/settings`;
30 export const accountSubscriptionUrl = (baseUrl) => `${baseUrl}/v1/account/subscription`;
31 export const accountReservationUrl = (baseUrl) => `${baseUrl}/v1/account/reservation`;
32 export const accountReservationSingleUrl = (baseUrl, topic) => `${baseUrl}/v1/account/reservation/${topic}`;
33 export const accountBillingSubscriptionUrl = (baseUrl) => `${baseUrl}/v1/account/billing/subscription`;
34 export const accountBillingPortalUrl = (baseUrl) => `${baseUrl}/v1/account/billing/portal`;
35 export const accountPhoneUrl = (baseUrl) => `${baseUrl}/v1/account/phone`;
36 export const accountPhoneVerifyUrl = (baseUrl) => `${baseUrl}/v1/account/phone/verify`;
37 export const accountEmailUrl = (baseUrl) => `${baseUrl}/v1/account/email`;
38 export const accountEmailVerifyUrl = (baseUrl) => `${baseUrl}/v1/account/email/verify`;
39 export const accountEmailPrimaryUrl = (baseUrl) => `${baseUrl}/v1/account/email/primary`;
40 export const accountEmailResendUrl = (baseUrl) => `${baseUrl}/v1/account/email/resend`;
41 export const accountPasswordResetRequestUrl = (baseUrl) => `${baseUrl}/v1/account/password/reset/request`;
42 export const accountPasswordResetUrl = (baseUrl) => `${baseUrl}/v1/account/password/reset`;
43
44 export const validUrl = (url) => url.match(/^https?:\/\/.+/);
45
46 export const disallowedTopic = (topic) => config.disallowed_topics.includes(topic);
47
48 export const validTopic = (topic) => {
49 if (disallowedTopic(topic)) {
50 return false;
51 }
52 return topic.match(/^([-_a-zA-Z0-9]{1,64})$/); // Regex must match Go & Android app!
53 };
54
55 export const topicDisplayName = (subscription) => {
56 if (subscription.displayName) {
57 return subscription.displayName;
58 }
59 if (subscription.baseUrl === config.base_url) {
60 return subscription.topic;
61 }
62 return topicShortUrl(subscription.baseUrl, subscription.topic);
63 };
64
65 export const unmatchedTags = (tags) => {
66 if (!tags) return [];
67 return tags.filter((tag) => !(tag in emojisMapped));
68 };
69
70 export const encodeBase64 = (s) => {
71 const bytes = new TextEncoder().encode(s);
72 let binary = "";
73 for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
74 return btoa(binary);
75 };
76
77 export const encodeBase64Url = (s) => encodeBase64(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
78
79 export const bearerAuth = (token) => `Bearer ${token}`;
80
81 export const basicAuth = (username, password) => `Basic ${encodeBase64(`${username}:${password}`)}`;
82
83 export const withBearerAuth = (headers, token) => ({ ...headers, Authorization: bearerAuth(token) });
84
85 export const maybeWithBearerAuth = (headers, token) => {
86 if (token) {
87 return withBearerAuth(headers, token);
88 }
89 return headers;
90 };
91
92 export const withBasicAuth = (headers, username, password) => ({
93 ...headers,
94 Authorization: basicAuth(username, password),
95 });
96
97 export const maybeWithAuth = (headers, user) => {
98 if (user?.password) {
99 return withBasicAuth(headers, user.username, user.password);
100 }
101 if (user?.token) {
102 return withBearerAuth(headers, user.token);
103 }
104 return headers;
105 };
106
107 export const maybeActionErrors = (notification) => {
108 const actionErrors = (notification.actions ?? [])
109 .map((action) => action.error)
110 .filter((action) => !!action)
111 .join("\n");
112 if (actionErrors.length === 0) {
113 return undefined;
114 }
115 return actionErrors;
116 };
117
118 export const shuffle = (arr) => {
119 const returnArr = [...arr];
120
121 for (let index = returnArr.length - 1; index > 0; index -= 1) {
122 const j = Math.floor(Math.random() * (index + 1));
123 [returnArr[index], returnArr[j]] = [returnArr[j], returnArr[index]];
124 }
125
126 return returnArr;
127 };
128
129 export const splitNoEmpty = (s, delimiter) =>
130 s
131 .split(delimiter)
132 .map((x) => x.trim())
133 .filter((x) => x !== "");
134
135 /** Non-cryptographic hash function, see https://stackoverflow.com/a/8831937/1440785 */
136 export const hashCode = (s) => {
137 let hash = 0;
138 for (let i = 0; i < s.length; i += 1) {
139 const char = s.charCodeAt(i);
140 // eslint-disable-next-line no-bitwise
141 hash = (hash << 5) - hash + char;
142 // eslint-disable-next-line no-bitwise
143 hash &= hash; // Convert to 32bit integer
144 }
145 return hash;
146 };
147
148 /**
149 * convert `i18n.language` style str (e.g.: `en_US`) to kebab-case (e.g.: `en-US`),
150 * which is expected by `<html lang>` and `Intl.DateTimeFormat`. Falls back to "en"
151 * if the input is missing or not a string.
152 */
153 export const getKebabCaseLangStr = (language) => (typeof language === "string" && language.length > 0 ? language.replace(/_/g, "-") : "en");
154
155 // Date/time display is intentionally NOT tied to the UI translation language; it follows the
156 // dedicated dateFormat/timeFormat prefs (see Prefs.js). SYSTEM modes pass no locale to Intl so it
157 // uses the browser's default (the user's OS region/format settings). DMY/MDY force the day/month
158 // order; ISO8601 forces an unambiguous, locale-independent and always-24-hour format. The clock
159 // (12h/24h) is chosen independently via timeFormat. All variants render local time.
160 const pad2 = (n) => String(n).padStart(2, "0");
161
162 // Per-format date builders (only ISO zero-pads; the rest drop leading zeros). The router below
163 // (formatDate) picks one of these for a fixed-order format, or falls back to the browser locale.
164 const formatDateIso = (date) => `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
165 const formatDateDmy = (date) => `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
166 const formatDateDmyDot = (date) => `${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()}`;
167 const formatDateMdy = (date) => `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
168
169 // ISO date-time is always YYYY-MM-DD HH:mm (24-hour), independent of the timeFormat pref.
170 const formatDateTimeIso = (date) => `${formatDateIso(date)} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
171
172 // undefined lets the locale decide the clock; true/false force a 12- or 24-hour clock. Passing
173 // hour12: undefined to Intl is equivalent to omitting it (and avoids an object spread that would
174 // otherwise widen the sibling dateStyle/timeStyle string literals).
175 const hour12For = (timeFormat) => {
176 if (timeFormat === TIME_FORMAT.H12) return true;
177 if (timeFormat === TIME_FORMAT.H24) return false;
178 return undefined;
179 };
180
181 // The date router: delegates to a fixed-order builder, or falls back to the browser locale (SYSTEM).
182 export const formatDate = (timestamp, dateFormat = DATE_FORMAT.SYSTEM) => {
183 const date = new Date(timestamp * 1000);
184 switch (dateFormat) {
185 case DATE_FORMAT.ISO8601:
186 return formatDateIso(date);
187 case DATE_FORMAT.DMY:
188 return formatDateDmy(date);
189 case DATE_FORMAT.DMY_DOT:
190 return formatDateDmyDot(date);
191 case DATE_FORMAT.MDY:
192 return formatDateMdy(date);
193 default:
194 return new Intl.DateTimeFormat(undefined, { dateStyle: "short" }).format(date);
195 }
196 };
197
198 export const formatTime = (timestamp, timeFormat = TIME_FORMAT.SYSTEM) =>
199 new Intl.DateTimeFormat(undefined, {
200 timeStyle: "short",
201 hour12: hour12For(timeFormat),
202 }).format(new Date(timestamp * 1000));
203
204 export const formatDateTime = (timestamp, dateFormat = DATE_FORMAT.SYSTEM, timeFormat = TIME_FORMAT.SYSTEM) => {
205 if (dateFormat === DATE_FORMAT.ISO8601) {
206 return formatDateTimeIso(new Date(timestamp * 1000));
207 }
208 if ([DATE_FORMAT.DMY, DATE_FORMAT.DMY_DOT, DATE_FORMAT.MDY].includes(dateFormat)) {
209 return `${formatDate(timestamp, dateFormat)} ${formatTime(timestamp, timeFormat)}`;
210 }
211 return new Intl.DateTimeFormat(undefined, {
212 dateStyle: "short",
213 timeStyle: "short",
214 hour12: hour12For(timeFormat),
215 }).format(new Date(timestamp * 1000));
216 };
217
218 export const formatShortDuration = (ms, language) => {
219 const seconds = Math.round(ms / 1000);
220 const units = [
221 { unit: "year", s: 31536000 },
222 { unit: "month", s: 2592000 },
223 { unit: "week", s: 604800 },
224 { unit: "day", s: 86400 },
225 { unit: "hour", s: 3600 },
226 { unit: "minute", s: 60 },
227 { unit: "second", s: 1 },
228 ];
229 const match = units.find((u) => seconds >= u.s) ?? units[units.length - 1];
230 const value = Math.round(seconds / match.s);
231 // [lang, "en"] makes Intl fall back to English for well-formed-but-unsupported tags;
232 // the try/catch covers malformed tags (RangeError) so the web app never crashes here.
233 try {
234 return new Intl.NumberFormat([getKebabCaseLangStr(language), "en"], {
235 style: "unit",
236 unit: match.unit,
237 unitDisplay: "long",
238 }).format(value);
239 } catch {
240 return new Intl.NumberFormat("en", { style: "unit", unit: match.unit, unitDisplay: "long" }).format(value);
241 }
242 };
243
244 export const formatBytes = (bytes, decimals = 2) => {
245 if (bytes === 0) return "0 bytes";
246 const k = 1024;
247 const dm = decimals < 0 ? 0 : decimals;
248 const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
249 const i = Math.floor(Math.log(bytes) / Math.log(k));
250 return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
251 };
252
253 export const formatNumber = (n) => {
254 if (n === 0) {
255 return n;
256 }
257 if (n % 1000 === 0) {
258 return `${n / 1000}k`;
259 }
260 return n.toLocaleString();
261 };
262
263 export const formatPrice = (n) => {
264 if (n % 100 === 0) {
265 return `$${n / 100}`;
266 }
267 return `$${(n / 100).toPrecision(2)}`;
268 };
269
270 export const openUrl = (url) => {
271 window.open(url, "_blank", "noreferrer");
272 };
273
274 export const sounds = {
275 ding: {
276 file: ding,
277 label: "Ding",
278 },
279 juntos: {
280 file: juntos,
281 label: "Juntos",
282 },
283 pristine: {
284 file: pristine,
285 label: "Pristine",
286 },
287 dadum: {
288 file: dadum,
289 label: "Dadum",
290 },
291 pop: {
292 file: pop,
293 label: "Pop",
294 },
295 "pop-swoosh": {
296 file: popSwoosh,
297 label: "Pop swoosh",
298 },
299 beep: {
300 file: beep,
301 label: "Beep",
302 },
303 };
304
305 export const playSound = async (id) => {
306 const audio = new Audio(sounds[id].file);
307 return audio.play();
308 };
309
310 // From: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
311 // eslint-disable-next-line func-style
312 export async function* fetchLinesIterator(fileURL, headers) {
313 const utf8Decoder = new TextDecoder("utf-8");
314 const response = await fetch(fileURL, {
315 headers,
316 });
317 const reader = response.body.getReader();
318 let { value: chunk, done: readerDone } = await reader.read();
319 chunk = chunk ? utf8Decoder.decode(chunk) : "";
320
321 const re = /\n|\r|\r\n/gm;
322 let startIndex = 0;
323
324 for (;;) {
325 const result = re.exec(chunk);
326 if (!result) {
327 if (readerDone) {
328 break;
329 }
330 const remainder = chunk.substr(startIndex);
331 // eslint-disable-next-line no-await-in-loop
332 ({ value: chunk, done: readerDone } = await reader.read());
333 chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
334 startIndex = 0;
335 re.lastIndex = 0;
336 // eslint-disable-next-line no-continue
337 continue;
338 }
339 yield chunk.substring(startIndex, result.index);
340 startIndex = re.lastIndex;
341 }
342 if (startIndex < chunk.length) {
343 yield chunk.substr(startIndex); // last line didn't end in a newline char
344 }
345 }
346
347 export const randomAlphanumericString = (len) => {
348 const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
349 let id = "";
350 for (let i = 0; i < len; i += 1) {
351 // eslint-disable-next-line no-bitwise
352 id += alphabet[(Math.random() * alphabet.length) | 0];
353 }
354 return id;
355 };
356
357 export const urlB64ToUint8Array = (base64String) => {
358 const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
359 const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
360
361 const rawData = window.atob(base64);
362 const outputArray = new Uint8Array(rawData.length);
363
364 for (let i = 0; i < rawData.length; i += 1) {
365 outputArray[i] = rawData.charCodeAt(i);
366 }
367 return outputArray;
368 };
369
370 export const darkModeEnabled = (prefersDarkMode, themePreference) => {
371 switch (themePreference) {
372 case THEME.DARK:
373 return true;
374
375 case THEME.LIGHT:
376 return false;
377
378 case THEME.SYSTEM:
379 default:
380 return prefersDarkMode;
381 }
382 };
383
384 // Canvas-based favicon with a red notification dot when there are unread messages
385 let faviconCanvas;
386 let faviconOriginalIcon;
387
388 const loadFaviconIcon = () =>
389 new Promise((resolve) => {
390 if (faviconOriginalIcon) {
391 resolve(faviconOriginalIcon);
392 return;
393 }
394 const img = new Image();
395 img.onload = () => {
396 faviconOriginalIcon = img;
397 resolve(img);
398 };
399 img.onerror = () => resolve(null);
400 // Use PNG instead of ICO — .ico files can't be reliably drawn to canvas in all browsers
401 img.src = "/static/images/ntfy.png";
402 });
403
404 export const updateFavicon = async (count) => {
405 const size = 32;
406 const img = await loadFaviconIcon();
407 if (!img) {
408 return;
409 }
410
411 if (!faviconCanvas) {
412 faviconCanvas = document.createElement("canvas");
413 faviconCanvas.width = size;
414 faviconCanvas.height = size;
415 }
416
417 const ctx = faviconCanvas.getContext("2d");
418 ctx.clearRect(0, 0, size, size);
419 ctx.drawImage(img, 0, 0, size, size);
420
421 if (count > 0) {
422 const dotRadius = 5;
423 const borderWidth = 2;
424 const dotX = size - dotRadius - borderWidth + 1;
425 const dotY = size - dotRadius - borderWidth + 1;
426
427 // Transparent border: erase a ring around the dot so the icon doesn't bleed into it
428 ctx.save();
429 ctx.globalCompositeOperation = "destination-out";
430 ctx.beginPath();
431 ctx.arc(dotX, dotY, dotRadius + borderWidth, 0, 2 * Math.PI);
432 ctx.fill();
433 ctx.restore();
434
435 // Red dot
436 ctx.beginPath();
437 ctx.arc(dotX, dotY, dotRadius, 0, 2 * Math.PI);
438 ctx.fillStyle = "#dc3545";
439 ctx.fill();
440 }
441
442 const link = document.querySelector("link[rel='icon']");
443 if (link) {
444 link.href = faviconCanvas.toDataURL("image/png");
445 }
446 };
447
448 // Matches a URL whose scheme is NOT in the safe list (https, mailto, ...). A scheme
449 // (RFC 3986: [a-z][a-z0-9+.-]*) can't contain a slash, query, or hash, so a colon later
450 // in the path/query (e.g. foo?x=a:b) is never mistaken for a protocol separator. Relative
451 // URLs have no scheme and never match. This strips javascript:/data:/vbscript:/... so React
452 // never has to block a javascript: URL at render time -- which it does loudly, throwing an
453 // uncaught error.
454 const unsafeUrlProtocol = /^\s*(?!(?:https?|ftps?|ircs?|mailto|xmpp|tel):)[a-z][a-z0-9+.-]*:/i;
455
456 // Returns the URL unchanged if it uses a safe protocol or is relative, otherwise "".
457 export const sanitizeUrl = (url) => (url && unsafeUrlProtocol.test(url) ? "" : url || "");
458
459 export const copyToClipboard = (text) => {
460 if (navigator.clipboard && window.isSecureContext) {
461 return navigator.clipboard.writeText(text);
462 }
463 // Fallback to the older method if clipboard API is not supported (or on HTTP)
464 const textarea = document.createElement("textarea");
465 textarea.value = text;
466 textarea.setAttribute("readonly", ""); // Avoid mobile keyboards from popping up
467 textarea.style.position = "fixed"; // Avoid scroll jump
468 textarea.style.left = "-9999px";
469 document.body.appendChild(textarea);
470 textarea.focus();
471 textarea.select();
472 document.execCommand("copy");
473 document.body.removeChild(textarea);
474 return Promise.resolve();
475 };