Run eslint autofixes

This commit is contained in:
nimbleghost 2023-05-24 09:03:28 +02:00
parent f558b4dbe9
commit 8319f1cf26
32 changed files with 394 additions and 435 deletions

View file

@ -1,3 +1,4 @@
import i18n from "i18next";
import {
accountBillingPortalUrl,
accountBillingSubscriptionUrl,
@ -17,7 +18,6 @@ import {
} from "./utils";
import session from "./Session";
import subscriptionManager from "./SubscriptionManager";
import i18n from "i18next";
import prefs from "./Prefs";
import routes from "../components/routes";
import { fetchOrThrow, UnauthorizedError } from "./errors";
@ -66,13 +66,13 @@ class AccountApi {
async create(username, password) {
const url = accountUrl(config.base_url);
const body = JSON.stringify({
username: username,
password: password,
username,
password,
});
console.log(`[AccountApi] Creating user account ${url}`);
await fetchOrThrow(url, {
method: "POST",
body: body,
body,
});
}
@ -97,7 +97,7 @@ class AccountApi {
method: "DELETE",
headers: withBearerAuth({}, session.token()),
body: JSON.stringify({
password: password,
password,
}),
});
}
@ -118,7 +118,7 @@ class AccountApi {
async createToken(label, expires) {
const url = accountTokenUrl(config.base_url);
const body = {
label: label,
label,
expires: expires > 0 ? Math.floor(Date.now() / 1000) + expires : 0,
};
console.log(`[AccountApi] Creating user access token ${url}`);
@ -132,8 +132,8 @@ class AccountApi {
async updateToken(token, label, expires) {
const url = accountTokenUrl(config.base_url);
const body = {
token: token,
label: label,
token,
label,
};
if (expires > 0) {
body.expires = Math.floor(Date.now() / 1000) + expires;
@ -171,7 +171,7 @@ class AccountApi {
await fetchOrThrow(url, {
method: "PATCH",
headers: withBearerAuth({}, session.token()),
body: body,
body,
});
}
@ -179,13 +179,13 @@ class AccountApi {
const url = accountSubscriptionUrl(config.base_url);
const body = JSON.stringify({
base_url: baseUrl,
topic: topic,
topic,
});
console.log(`[AccountApi] Adding user subscription ${url}: ${body}`);
const response = await fetchOrThrow(url, {
method: "POST",
headers: withBearerAuth({}, session.token()),
body: body,
body,
});
const subscription = await response.json(); // May throw SyntaxError
console.log(`[AccountApi] Subscription`, subscription);
@ -196,14 +196,14 @@ class AccountApi {
const url = accountSubscriptionUrl(config.base_url);
const body = JSON.stringify({
base_url: baseUrl,
topic: topic,
topic,
...payload,
});
console.log(`[AccountApi] Updating user subscription ${url}: ${body}`);
const response = await fetchOrThrow(url, {
method: "PATCH",
headers: withBearerAuth({}, session.token()),
body: body,
body,
});
const subscription = await response.json(); // May throw SyntaxError
console.log(`[AccountApi] Subscription`, subscription);
@ -230,8 +230,8 @@ class AccountApi {
method: "POST",
headers: withBearerAuth({}, session.token()),
body: JSON.stringify({
topic: topic,
everyone: everyone,
topic,
everyone,
}),
});
}
@ -272,11 +272,11 @@ class AccountApi {
async upsertBillingSubscription(method, tier, interval) {
const url = accountBillingSubscriptionUrl(config.base_url);
const response = await fetchOrThrow(url, {
method: method,
method,
headers: withBearerAuth({}, session.token()),
body: JSON.stringify({
tier: tier,
interval: interval,
tier,
interval,
}),
});
return await response.json(); // May throw SyntaxError
@ -309,7 +309,7 @@ class AccountApi {
headers: withBearerAuth({}, session.token()),
body: JSON.stringify({
number: phoneNumber,
channel: channel,
channel,
}),
});
}
@ -322,7 +322,7 @@ class AccountApi {
headers: withBearerAuth({}, session.token()),
body: JSON.stringify({
number: phoneNumber,
code: code,
code,
}),
});
}

View file

@ -18,7 +18,7 @@ class Api {
const messages = [];
const headers = maybeWithAuth({}, user);
console.log(`[Api] Polling ${url}`);
for await (let line of fetchLinesIterator(url, headers)) {
for await (const line of fetchLinesIterator(url, headers)) {
const message = JSON.parse(line);
if (message.id) {
console.log(`[Api, ${shortUrl}] Received message ${line}`);
@ -33,8 +33,8 @@ class Api {
console.log(`[Api] Publishing message to ${topicUrl(baseUrl, topic)}`);
const headers = {};
const body = {
topic: topic,
message: message,
topic,
message,
...options,
};
await fetchOrThrow(baseUrl, {
@ -60,7 +60,7 @@ class Api {
publishXHR(url, body, headers, onProgress) {
console.log(`[Api] Publishing message to ${url}`);
const xhr = new XMLHttpRequest();
const send = new Promise(function (resolve, reject) {
const send = new Promise((resolve, reject) => {
xhr.open("PUT", url);
if (body.type) {
xhr.overrideMimeType(body.type);
@ -106,7 +106,8 @@ class Api {
});
if (response.status >= 200 && response.status <= 299) {
return true;
} else if (response.status === 401 || response.status === 403) {
}
if (response.status === 401 || response.status === 403) {
// See server/server.go
return false;
}

View file

@ -77,7 +77,7 @@ class Connection {
close() {
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Closing connection`);
const socket = this.ws;
const retryTimeout = this.retryTimeout;
const { retryTimeout } = this;
if (socket !== null) {
socket.close();
}
@ -110,6 +110,7 @@ class Connection {
export class ConnectionState {
static Connected = "connected";
static Connecting = "connecting";
}

View file

@ -55,12 +55,12 @@ class ConnectionManager {
// Create and add new connections
subscriptionsWithUsersAndConnectionId.forEach((subscription) => {
const subscriptionId = subscription.id;
const connectionId = subscription.connectionId;
const { connectionId } = subscription;
const added = !this.connections.get(connectionId);
if (added) {
const baseUrl = subscription.baseUrl;
const topic = subscription.topic;
const user = subscription.user;
const { baseUrl } = subscription;
const { topic } = subscription;
const { user } = subscription;
const since = subscription.last;
const connection = new Connection(
connectionId,
@ -112,9 +112,8 @@ class ConnectionManager {
}
}
const makeConnectionId = async (subscription, user) => {
return user ? hashCode(`${subscription.id}|${user.username}|${user.password ?? ""}|${user.token ?? ""}`) : hashCode(`${subscription.id}`);
};
const makeConnectionId = async (subscription, user) =>
user ? hashCode(`${subscription.id}|${user.username}|${user.password ?? ""}|${user.token ?? ""}`) : hashCode(`${subscription.id}`);
const connectionManager = new ConnectionManager();
export default connectionManager;

View file

@ -25,8 +25,8 @@ class SubscriptionManager {
}
const subscription = {
id: topicUrl(baseUrl, topic),
baseUrl: baseUrl,
topic: topic,
baseUrl,
topic,
mutedUntil: 0,
last: null,
internal: internal || false,
@ -39,14 +39,14 @@ class SubscriptionManager {
console.log(`[SubscriptionManager] Syncing subscriptions from remote`, remoteSubscriptions);
// Add remote subscriptions
let remoteIds = []; // = topicUrl(baseUrl, topic)
const remoteIds = []; // = topicUrl(baseUrl, topic)
for (let i = 0; i < remoteSubscriptions.length; i++) {
const remote = remoteSubscriptions[i];
const local = await this.add(remote.base_url, remote.topic, false);
const reservation = remoteReservations?.find((r) => remote.base_url === config.base_url && remote.topic === r.topic) || null;
await this.update(local.id, {
displayName: remote.display_name, // May be undefined
reservation: reservation, // May be null!
reservation, // May be null!
});
remoteIds.push(local.id);
}
@ -63,12 +63,12 @@ class SubscriptionManager {
}
async updateState(subscriptionId, state) {
db.subscriptions.update(subscriptionId, { state: state });
db.subscriptions.update(subscriptionId, { state });
}
async remove(subscriptionId) {
await db.subscriptions.delete(subscriptionId);
await db.notifications.where({ subscriptionId: subscriptionId }).delete();
await db.notifications.where({ subscriptionId }).delete();
}
async first() {
@ -140,7 +140,7 @@ class SubscriptionManager {
}
async deleteNotifications(subscriptionId) {
await db.notifications.where({ subscriptionId: subscriptionId }).delete();
await db.notifications.where({ subscriptionId }).delete();
}
async markNotificationRead(notificationId) {
@ -148,24 +148,24 @@ class SubscriptionManager {
}
async markNotificationsRead(subscriptionId) {
await db.notifications.where({ subscriptionId: subscriptionId, new: 1 }).modify({ new: 0 });
await db.notifications.where({ subscriptionId, new: 1 }).modify({ new: 0 });
}
async setMutedUntil(subscriptionId, mutedUntil) {
await db.subscriptions.update(subscriptionId, {
mutedUntil: mutedUntil,
mutedUntil,
});
}
async setDisplayName(subscriptionId, displayName) {
await db.subscriptions.update(subscriptionId, {
displayName: displayName,
displayName,
});
}
async setReservation(subscriptionId, reservation) {
await db.subscriptions.update(subscriptionId, {
reservation: reservation,
reservation,
});
}

View file

@ -1,4 +1,4 @@
const config = window.config;
const { config } = window;
// The backend returns an empty base_url for the config struct,
// so the frontend (hey, that's us!) can use the current location.

View file

@ -48,6 +48,7 @@ export class UnauthorizedError extends Error {
export class UserExistsError extends Error {
static CODE = 40901; // errHTTPConflictUserExists
constructor() {
super("Username already exists");
}
@ -55,6 +56,7 @@ export class UserExistsError extends Error {
export class TopicReservedError extends Error {
static CODE = 40902; // errHTTPConflictTopicReserved
constructor() {
super("Topic already reserved");
}
@ -62,6 +64,7 @@ export class TopicReservedError extends Error {
export class AccountCreateLimitReachedError extends Error {
static CODE = 42906; // errHTTPTooManyRequestsLimitAccountCreation
constructor() {
super("Account creation limit reached");
}
@ -69,6 +72,7 @@ export class AccountCreateLimitReachedError extends Error {
export class IncorrectPasswordError extends Error {
static CODE = 40026; // errHTTPBadRequestIncorrectPasswordConfirmation
constructor() {
super("Password incorrect");
}

View file

@ -1,3 +1,4 @@
import { Base64 } from "js-base64";
import { rawEmojis } from "./emojis";
import beep from "../sounds/beep.mp3";
import juntos from "../sounds/juntos.mp3";
@ -7,7 +8,6 @@ import dadum from "../sounds/dadum.mp3";
import pop from "../sounds/pop.mp3";
import popSwoosh from "../sounds/pop-swoosh.mp3";
import config from "./config";
import { Base64 } from "js-base64";
export const topicUrl = (baseUrl, topic) => `${baseUrl}/${topic}`;
export const topicUrlWs = (baseUrl, topic) =>
@ -33,9 +33,7 @@ export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
export const expandUrl = (url) => [`https://${url}`, `http://${url}`];
export const expandSecureUrl = (url) => `https://${url}`;
export const validUrl = (url) => {
return url.match(/^https?:\/\/.+/);
};
export const validUrl = (url) => url.match(/^https?:\/\/.+/);
export const validTopic = (topic) => {
if (disallowedTopic(topic)) {
@ -44,14 +42,13 @@ export const validTopic = (topic) => {
return topic.match(/^([-_a-zA-Z0-9]{1,64})$/); // Regex must match Go & Android app!
};
export const disallowedTopic = (topic) => {
return config.disallowed_topics.includes(topic);
};
export const disallowedTopic = (topic) => config.disallowed_topics.includes(topic);
export const topicDisplayName = (subscription) => {
if (subscription.displayName) {
return subscription.displayName;
} else if (subscription.baseUrl === config.base_url) {
}
if (subscription.baseUrl === config.base_url) {
return subscription.topic;
}
return topicShortUrl(subscription.baseUrl, subscription.topic);
@ -67,7 +64,7 @@ rawEmojis.forEach((emoji) => {
const toEmojis = (tags) => {
if (!tags) return [];
else return tags.filter((tag) => tag in emojis).map((tag) => emojis[tag]);
return tags.filter((tag) => tag in emojis).map((tag) => emojis[tag]);
};
export const formatTitleWithDefault = (m, fallback) => {
@ -81,33 +78,31 @@ export const formatTitle = (m) => {
const emojiList = toEmojis(m.tags);
if (emojiList.length > 0) {
return `${emojiList.join(" ")} ${m.title}`;
} else {
return m.title;
}
return m.title;
};
export const formatMessage = (m) => {
if (m.title) {
return m.message;
} else {
const emojiList = toEmojis(m.tags);
if (emojiList.length > 0) {
return `${emojiList.join(" ")} ${m.message}`;
} else {
return m.message;
}
}
const emojiList = toEmojis(m.tags);
if (emojiList.length > 0) {
return `${emojiList.join(" ")} ${m.message}`;
}
return m.message;
};
export const unmatchedTags = (tags) => {
if (!tags) return [];
else return tags.filter((tag) => !(tag in emojis));
return tags.filter((tag) => !(tag in emojis));
};
export const maybeWithAuth = (headers, user) => {
if (user && user.password) {
return withBasicAuth(headers, user.username, user.password);
} else if (user && user.token) {
}
if (user && user.token) {
return withBearerAuth(headers, user.token);
}
return headers;
@ -121,30 +116,22 @@ export const maybeWithBearerAuth = (headers, token) => {
};
export const withBasicAuth = (headers, username, password) => {
headers["Authorization"] = basicAuth(username, password);
headers.Authorization = basicAuth(username, password);
return headers;
};
export const basicAuth = (username, password) => {
return `Basic ${encodeBase64(`${username}:${password}`)}`;
};
export const basicAuth = (username, password) => `Basic ${encodeBase64(`${username}:${password}`)}`;
export const withBearerAuth = (headers, token) => {
headers["Authorization"] = bearerAuth(token);
headers.Authorization = bearerAuth(token);
return headers;
};
export const bearerAuth = (token) => {
return `Bearer ${token}`;
};
export const bearerAuth = (token) => `Bearer ${token}`;
export const encodeBase64 = (s) => {
return Base64.encode(s);
};
export const encodeBase64 = (s) => Base64.encode(s);
export const encodeBase64Url = (s) => {
return Base64.encodeURI(s);
};
export const encodeBase64Url = (s) => Base64.encodeURI(s);
export const maybeAppendActionErrors = (message, notification) => {
const actionErrors = (notification.actions ?? [])
@ -153,13 +140,13 @@ export const maybeAppendActionErrors = (message, notification) => {
.join("\n");
if (actionErrors.length === 0) {
return message;
} else {
return `${message}\n\n${actionErrors}`;
}
return `${message}\n\n${actionErrors}`;
};
export const shuffle = (arr) => {
let j, x;
let j;
let x;
for (let index = arr.length - 1; index > 0; index--) {
j = Math.floor(Math.random() * (index + 1));
x = arr[index];
@ -169,12 +156,11 @@ export const shuffle = (arr) => {
return arr;
};
export const splitNoEmpty = (s, delimiter) => {
return s
export const splitNoEmpty = (s, delimiter) =>
s
.split(delimiter)
.map((x) => x.trim())
.filter((x) => x !== "");
};
/** Non-cryptographic hash function, see https://stackoverflow.com/a/8831937/1440785 */
export const hashCode = async (s) => {
@ -182,21 +168,18 @@ export const hashCode = async (s) => {
for (let i = 0; i < s.length; i++) {
const char = s.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32bit integer
hash &= hash; // Convert to 32bit integer
}
return hash;
};
export const formatShortDateTime = (timestamp) => {
return new Intl.DateTimeFormat("default", {
export const formatShortDateTime = (timestamp) =>
new Intl.DateTimeFormat("default", {
dateStyle: "short",
timeStyle: "short",
}).format(new Date(timestamp * 1000));
};
export const formatShortDate = (timestamp) => {
return new Intl.DateTimeFormat("default", { dateStyle: "short" }).format(new Date(timestamp * 1000));
};
export const formatShortDate = (timestamp) => new Intl.DateTimeFormat("default", { dateStyle: "short" }).format(new Date(timestamp * 1000));
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return "0 bytes";
@ -204,13 +187,14 @@ export const formatBytes = (bytes, decimals = 2) => {
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
};
export const formatNumber = (n) => {
if (n === 0) {
return n;
} else if (n % 1000 === 0) {
}
if (n % 1000 === 0) {
return `${n / 1000}k`;
}
return n.toLocaleString();
@ -267,7 +251,7 @@ export const playSound = async (id) => {
export async function* fetchLinesIterator(fileURL, headers) {
const utf8Decoder = new TextDecoder("utf-8");
const response = await fetch(fileURL, {
headers: headers,
headers,
});
const reader = response.body.getReader();
let { value: chunk, done: readerDone } = await reader.read();
@ -277,12 +261,12 @@ export async function* fetchLinesIterator(fileURL, headers) {
let startIndex = 0;
for (;;) {
let result = re.exec(chunk);
const result = re.exec(chunk);
if (!result) {
if (readerDone) {
break;
}
let remainder = chunk.substr(startIndex);
const remainder = chunk.substr(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
startIndex = re.lastIndex = 0;