utils.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { Base64 } from "js-base64";
  2. import beep from "../sounds/beep.mp3";
  3. import juntos from "../sounds/juntos.mp3";
  4. import pristine from "../sounds/pristine.mp3";
  5. import ding from "../sounds/ding.mp3";
  6. import dadum from "../sounds/dadum.mp3";
  7. import pop from "../sounds/pop.mp3";
  8. import popSwoosh from "../sounds/pop-swoosh.mp3";
  9. import config from "./config";
  10. import emojisMapped from "./emojisMapped";
  11. export const tiersUrl = (baseUrl) => `${baseUrl}/v1/tiers`;
  12. export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
  13. export const expandUrl = (url) => [`https://${url}`, `http://${url}`];
  14. export const expandSecureUrl = (url) => `https://${url}`;
  15. export const topicUrl = (baseUrl, topic) => `${baseUrl}/${topic}`;
  16. export const topicUrlWs = (baseUrl, topic) =>
  17. `${topicUrl(baseUrl, topic)}/ws`.replaceAll("https://", "wss://").replaceAll("http://", "ws://");
  18. export const topicUrlJson = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/json`;
  19. export const topicUrlJsonPoll = (baseUrl, topic) => `${topicUrlJson(baseUrl, topic)}?poll=1`;
  20. export const topicUrlJsonPollWithSince = (baseUrl, topic, since) => `${topicUrlJson(baseUrl, topic)}?poll=1&since=${since}`;
  21. export const topicUrlAuth = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/auth`;
  22. export const topicShortUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));
  23. export const webPushUrl = (baseUrl) => `${baseUrl}/v1/webpush`;
  24. export const accountUrl = (baseUrl) => `${baseUrl}/v1/account`;
  25. export const accountPasswordUrl = (baseUrl) => `${baseUrl}/v1/account/password`;
  26. export const accountTokenUrl = (baseUrl) => `${baseUrl}/v1/account/token`;
  27. export const accountSettingsUrl = (baseUrl) => `${baseUrl}/v1/account/settings`;
  28. export const accountSubscriptionUrl = (baseUrl) => `${baseUrl}/v1/account/subscription`;
  29. export const accountReservationUrl = (baseUrl) => `${baseUrl}/v1/account/reservation`;
  30. export const accountReservationSingleUrl = (baseUrl, topic) => `${baseUrl}/v1/account/reservation/${topic}`;
  31. export const accountBillingSubscriptionUrl = (baseUrl) => `${baseUrl}/v1/account/billing/subscription`;
  32. export const accountBillingPortalUrl = (baseUrl) => `${baseUrl}/v1/account/billing/portal`;
  33. export const accountPhoneUrl = (baseUrl) => `${baseUrl}/v1/account/phone`;
  34. export const accountPhoneVerifyUrl = (baseUrl) => `${baseUrl}/v1/account/phone/verify`;
  35. export const validUrl = (url) => url.match(/^https?:\/\/.+/);
  36. export const disallowedTopic = (topic) => config.disallowed_topics.includes(topic);
  37. export const validTopic = (topic) => {
  38. if (disallowedTopic(topic)) {
  39. return false;
  40. }
  41. return topic.match(/^([-_a-zA-Z0-9]{1,64})$/); // Regex must match Go & Android app!
  42. };
  43. export const topicDisplayName = (subscription) => {
  44. if (subscription.displayName) {
  45. return subscription.displayName;
  46. }
  47. if (subscription.baseUrl === config.base_url) {
  48. return subscription.topic;
  49. }
  50. return topicShortUrl(subscription.baseUrl, subscription.topic);
  51. };
  52. export const unmatchedTags = (tags) => {
  53. if (!tags) return [];
  54. return tags.filter((tag) => !(tag in emojisMapped));
  55. };
  56. export const encodeBase64 = (s) => Base64.encode(s);
  57. export const encodeBase64Url = (s) => Base64.encodeURI(s);
  58. export const bearerAuth = (token) => `Bearer ${token}`;
  59. export const basicAuth = (username, password) => `Basic ${encodeBase64(`${username}:${password}`)}`;
  60. export const withBearerAuth = (headers, token) => ({ ...headers, Authorization: bearerAuth(token) });
  61. export const maybeWithBearerAuth = (headers, token) => {
  62. if (token) {
  63. return withBearerAuth(headers, token);
  64. }
  65. return headers;
  66. };
  67. export const withBasicAuth = (headers, username, password) => ({ ...headers, Authorization: basicAuth(username, password) });
  68. export const maybeWithAuth = (headers, user) => {
  69. if (user?.password) {
  70. return withBasicAuth(headers, user.username, user.password);
  71. }
  72. if (user?.token) {
  73. return withBearerAuth(headers, user.token);
  74. }
  75. return headers;
  76. };
  77. export const maybeAppendActionErrors = (message, notification) => {
  78. const actionErrors = (notification.actions ?? [])
  79. .map((action) => action.error)
  80. .filter((action) => !!action)
  81. .join("\n");
  82. if (actionErrors.length === 0) {
  83. return message;
  84. }
  85. return `${message}\n\n${actionErrors}`;
  86. };
  87. export const shuffle = (arr) => {
  88. const returnArr = [...arr];
  89. for (let index = returnArr.length - 1; index > 0; index -= 1) {
  90. const j = Math.floor(Math.random() * (index + 1));
  91. [returnArr[index], returnArr[j]] = [returnArr[j], returnArr[index]];
  92. }
  93. return returnArr;
  94. };
  95. export const splitNoEmpty = (s, delimiter) =>
  96. s
  97. .split(delimiter)
  98. .map((x) => x.trim())
  99. .filter((x) => x !== "");
  100. /** Non-cryptographic hash function, see https://stackoverflow.com/a/8831937/1440785 */
  101. export const hashCode = (s) => {
  102. let hash = 0;
  103. for (let i = 0; i < s.length; i += 1) {
  104. const char = s.charCodeAt(i);
  105. // eslint-disable-next-line no-bitwise
  106. hash = (hash << 5) - hash + char;
  107. // eslint-disable-next-line no-bitwise
  108. hash &= hash; // Convert to 32bit integer
  109. }
  110. return hash;
  111. };
  112. export const formatShortDateTime = (timestamp, language) =>
  113. new Intl.DateTimeFormat(language, {
  114. dateStyle: "short",
  115. timeStyle: "short",
  116. }).format(new Date(timestamp * 1000));
  117. export const formatShortDate = (timestamp, language) =>
  118. new Intl.DateTimeFormat(language, { dateStyle: "short" }).format(new Date(timestamp * 1000));
  119. export const formatBytes = (bytes, decimals = 2) => {
  120. if (bytes === 0) return "0 bytes";
  121. const k = 1024;
  122. const dm = decimals < 0 ? 0 : decimals;
  123. const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  124. const i = Math.floor(Math.log(bytes) / Math.log(k));
  125. return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
  126. };
  127. export const formatNumber = (n) => {
  128. if (n === 0) {
  129. return n;
  130. }
  131. if (n % 1000 === 0) {
  132. return `${n / 1000}k`;
  133. }
  134. return n.toLocaleString();
  135. };
  136. export const formatPrice = (n) => {
  137. if (n % 100 === 0) {
  138. return `$${n / 100}`;
  139. }
  140. return `$${(n / 100).toPrecision(2)}`;
  141. };
  142. export const openUrl = (url) => {
  143. window.open(url, "_blank", "noopener,noreferrer");
  144. };
  145. export const sounds = {
  146. ding: {
  147. file: ding,
  148. label: "Ding",
  149. },
  150. juntos: {
  151. file: juntos,
  152. label: "Juntos",
  153. },
  154. pristine: {
  155. file: pristine,
  156. label: "Pristine",
  157. },
  158. dadum: {
  159. file: dadum,
  160. label: "Dadum",
  161. },
  162. pop: {
  163. file: pop,
  164. label: "Pop",
  165. },
  166. "pop-swoosh": {
  167. file: popSwoosh,
  168. label: "Pop swoosh",
  169. },
  170. beep: {
  171. file: beep,
  172. label: "Beep",
  173. },
  174. };
  175. export const playSound = async (id) => {
  176. const audio = new Audio(sounds[id].file);
  177. return audio.play();
  178. };
  179. // From: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  180. // eslint-disable-next-line func-style
  181. export async function* fetchLinesIterator(fileURL, headers) {
  182. const utf8Decoder = new TextDecoder("utf-8");
  183. const response = await fetch(fileURL, {
  184. headers,
  185. });
  186. const reader = response.body.getReader();
  187. let { value: chunk, done: readerDone } = await reader.read();
  188. chunk = chunk ? utf8Decoder.decode(chunk) : "";
  189. const re = /\n|\r|\r\n/gm;
  190. let startIndex = 0;
  191. for (;;) {
  192. const result = re.exec(chunk);
  193. if (!result) {
  194. if (readerDone) {
  195. break;
  196. }
  197. const remainder = chunk.substr(startIndex);
  198. // eslint-disable-next-line no-await-in-loop
  199. ({ value: chunk, done: readerDone } = await reader.read());
  200. chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
  201. startIndex = 0;
  202. re.lastIndex = 0;
  203. // eslint-disable-next-line no-continue
  204. continue;
  205. }
  206. yield chunk.substring(startIndex, result.index);
  207. startIndex = re.lastIndex;
  208. }
  209. if (startIndex < chunk.length) {
  210. yield chunk.substr(startIndex); // last line didn't end in a newline char
  211. }
  212. }
  213. export const randomAlphanumericString = (len) => {
  214. const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  215. let id = "";
  216. for (let i = 0; i < len; i += 1) {
  217. // eslint-disable-next-line no-bitwise
  218. id += alphabet[(Math.random() * alphabet.length) | 0];
  219. }
  220. return id;
  221. };
  222. export const urlB64ToUint8Array = (base64String) => {
  223. const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  224. const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
  225. const rawData = window.atob(base64);
  226. const outputArray = new Uint8Array(rawData.length);
  227. for (let i = 0; i < rawData.length; i += 1) {
  228. outputArray[i] = rawData.charCodeAt(i);
  229. }
  230. return outputArray;
  231. };