Add ESLint (#941)

* Add eslint, switch to lint-staged for precommit

* Fix all ESLint errors

* Update GH workflow to check prettier and eslint
This commit is contained in:
Madeline
2023-01-20 18:10:47 +11:00
committed by GitHub
parent 0c815fde91
commit 084dc0be08
157 changed files with 1905 additions and 668 deletions
@@ -16,7 +16,7 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Router, Response, Request } from "express";
import { Router } from "express";
const router: Router = Router();
// TODO:
+1 -1
View File
@@ -92,7 +92,7 @@ router.patch(
"/",
route({ body: "ChannelModifySchema", permission: "MANAGE_CHANNELS" }),
async (req: Request, res: Response) => {
var payload = req.body as ChannelModifySchema;
const payload = req.body as ChannelModifySchema;
const { channel_id } = req.params;
if (payload.icon)
payload.icon = await handleFile(
@@ -86,7 +86,6 @@ router.get(
"/",
route({ permission: "MANAGE_CHANNELS" }),
async (req: Request, res: Response) => {
const { user_id } = req;
const { channel_id } = req.params;
const channel = await Channel.findOneOrFail({
where: { id: channel_id },
@@ -30,7 +30,6 @@ import {
Snowflake,
uploadFile,
MessageCreateSchema,
DiscordApiErrors,
} from "@fosscord/util";
import { Router, Response, Request } from "express";
import multer from "multer";
@@ -59,7 +58,7 @@ router.patch(
}),
async (req: Request, res: Response) => {
const { message_id, channel_id } = req.params;
var body = req.body as MessageCreateSchema;
let body = req.body as MessageCreateSchema;
const message = await Message.findOneOrFail({
where: { id: message_id, channel_id },
@@ -85,6 +84,7 @@ router.patch(
const new_message = await handleMessage({
...message,
// TODO: should message_reference be overridable?
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
message_reference: message.message_reference,
...body,
@@ -127,7 +127,7 @@ router.put(
}),
async (req: Request, res: Response) => {
const { channel_id, message_id } = req.params;
var body = req.body as MessageCreateSchema;
const body = req.body as MessageCreateSchema;
const attachments: Attachment[] = [];
const rights = await getRights(req.user_id);
@@ -171,7 +171,7 @@ router.put(
const embeds = body.embeds || [];
if (body.embed) embeds.push(body.embed);
let message = await handleMessage({
const message = await handleMessage({
...body,
type: 0,
pinned: false,
@@ -197,7 +197,10 @@ router.put(
channel.save(),
]);
postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
// no await as it shouldnt block the message send function and silently catch error
postHandleMessage(message).catch((e) =>
console.error("[Message] post-message handler failed", e),
);
return res.json(message);
},
@@ -165,13 +165,13 @@ router.put(
x.emoji.name === emoji.name,
);
if (!already_added) req.permission!.hasThrow("ADD_REACTIONS");
if (!already_added) req.permission?.hasThrow("ADD_REACTIONS");
if (emoji.id) {
const external_emoji = await Emoji.findOneOrFail({
where: { id: emoji.id },
});
if (!already_added) req.permission!.hasThrow("USE_EXTERNAL_EMOJIS");
if (!already_added) req.permission?.hasThrow("USE_EXTERNAL_EMOJIS");
emoji.animated = external_emoji.animated;
emoji.name = external_emoji.name;
}
@@ -214,7 +214,8 @@ router.delete(
"/:emoji/:user_id",
route({}),
async (req: Request, res: Response) => {
var { message_id, channel_id, user_id } = req.params;
let { user_id } = req.params;
const { message_id, channel_id } = req.params;
const emoji = getEmoji(req.params.emoji);
@@ -50,7 +50,7 @@ router.post(
const rights = await getRights(req.user_id);
rights.hasThrow("SELF_DELETE_MESSAGES");
let superuser = rights.has("MANAGE_MESSAGES");
const superuser = rights.has("MANAGE_MESSAGES");
const permission = await getPermission(
req.user_id,
channel?.guild_id,
@@ -31,23 +31,16 @@ import {
Snowflake,
uploadFile,
Member,
Role,
MessageCreateSchema,
ReadState,
DiscordApiErrors,
getRights,
Rights,
Reaction,
User,
} from "@fosscord/util";
import { HTTPError } from "lambert-server";
import {
handleMessage,
postHandleMessage,
route,
getIpAdress,
} from "@fosscord/api";
import { handleMessage, postHandleMessage, route } from "@fosscord/api";
import multer from "multer";
import { yellow } from "picocolors";
import { FindManyOptions, LessThan, MoreThan } from "typeorm";
import { FindManyOptions, FindOperator, LessThan, MoreThan } from "typeorm";
import { URL } from "url";
const router: Router = Router();
@@ -93,7 +86,7 @@ router.get("/", async (req: Request, res: Response) => {
if (limit < 1 || limit > 100)
throw new HTTPError("limit must be between 1 and 100", 422);
var halfLimit = Math.floor(limit / 2);
const halfLimit = Math.floor(limit / 2);
const permissions = await getPermission(
req.user_id,
@@ -103,7 +96,9 @@ router.get("/", async (req: Request, res: Response) => {
permissions.hasThrow("VIEW_CHANNEL");
if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]);
var query: FindManyOptions<Message> & { where: { id?: any } } = {
const query: FindManyOptions<Message> & {
where: { id?: FindOperator<string> | FindOperator<string>[] };
} = {
order: { timestamp: "DESC" },
take: limit,
where: { channel_id },
@@ -140,23 +135,21 @@ router.get("/", async (req: Request, res: Response) => {
const endpoint = Config.get().cdn.endpointPublic;
return res.json(
messages.map((x: any) => {
(x.reactions || []).forEach((x: any) => {
// @ts-ignore
if ((x.user_ids || []).includes(req.user_id)) x.me = true;
// @ts-ignore
delete x.user_ids;
messages.map((x: Partial<Message>) => {
(x.reactions || []).forEach((y: Partial<Reaction>) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
if ((y.user_ids || []).includes(req.user_id)) y.me = true;
delete y.user_ids;
});
// @ts-ignore
if (!x.author)
x.author = {
x.author = User.create({
id: "4",
discriminator: "0000",
username: "Fosscord Ghost",
public_flags: "0",
avatar: null,
};
x.attachments?.forEach((y: any) => {
public_flags: 0,
});
x.attachments?.forEach((y: Attachment) => {
// dynamically set attachment proxy_url in case the endpoint changed
const uri = y.proxy_url.startsWith("http")
? y.proxy_url
@@ -168,7 +161,7 @@ router.get("/", async (req: Request, res: Response) => {
/**
Some clients ( discord.js ) only check if a property exists within the response,
which causes erorrs when, say, the `application` property is `null`.
which causes errors when, say, the `application` property is `null`.
**/
// for (var curr in x) {
@@ -216,7 +209,7 @@ router.post(
}),
async (req: Request, res: Response) => {
const { channel_id } = req.params;
var body = req.body as MessageCreateSchema;
const body = req.body as MessageCreateSchema;
const attachments: Attachment[] = [];
const channel = await Channel.findOneOrFail({
@@ -244,7 +237,7 @@ router.post(
}
if (!req.rights.has(Rights.FLAGS.BYPASS_RATE_LIMITS)) {
var limits = Config.get().limits;
const limits = Config.get().limits;
if (limits.absoluteRate.register.enabled) {
const count = await Message.count({
where: {
@@ -269,7 +262,7 @@ router.post(
}
const files = (req.files as Express.Multer.File[]) ?? [];
for (var currFile of files) {
for (const currFile of files) {
try {
const file = await uploadFile(
`/attachments/${channel.id}`,
@@ -279,13 +272,13 @@ router.post(
Attachment.create({ ...file, proxy_url: file.url }),
);
} catch (error) {
return res.status(400).json({ message: error!.toString() });
return res.status(400).json({ message: error?.toString() });
}
}
const embeds = body.embeds || [];
if (body.embed) embeds.push(body.embed);
let message = await handleMessage({
const message = await handleMessage({
...body,
type: 0,
pinned: false,
@@ -304,7 +297,7 @@ router.post(
// Only one recipients should be closed here, since in group DMs the recipient is deleted not closed
await Promise.all(
channel.recipients!.map((recipient) => {
channel.recipients?.map((recipient) => {
if (recipient.closed) {
recipient.closed = false;
return Promise.all([
@@ -318,7 +311,7 @@ router.post(
}),
]);
}
}),
}) || [],
);
}
@@ -332,6 +325,7 @@ router.post(
});
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
message.member.roles = message.member.roles
.filter((x) => x.id != x.guild_id)
@@ -362,7 +356,10 @@ router.post(
channel.save(),
]);
postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
// no await as it shouldnt block the message send function and silently catch error
postHandleMessage(message).catch((e) =>
console.error("[Message] post-message handler failed", e),
);
return res.json(message);
},
@@ -43,7 +43,7 @@ router.put(
const { channel_id, overwrite_id } = req.params;
const body = req.body as ChannelPermissionOverwriteSchema;
var channel = await Channel.findOneOrFail({
const channel = await Channel.findOneOrFail({
where: { id: channel_id },
});
if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
@@ -56,22 +56,24 @@ router.put(
throw new HTTPError("user not found", 404);
} else throw new HTTPError("type not supported", 501);
//@ts-ignore
var overwrite: ChannelPermissionOverwrite =
let overwrite: ChannelPermissionOverwrite | undefined =
channel.permission_overwrites?.find((x) => x.id === overwrite_id);
if (!overwrite) {
// @ts-ignore
overwrite = {
id: overwrite_id,
type: body.type,
allow: "0",
deny: "0",
};
channel.permission_overwrites!.push(overwrite);
channel.permission_overwrites?.push(overwrite);
}
overwrite.allow = String(
req.permission!.bitfield & (BigInt(body.allow) || BigInt("0")),
(req.permission?.bitfield || 0n) &
(BigInt(body.allow) || BigInt("0")),
);
overwrite.deny = String(
req.permission!.bitfield & (BigInt(body.deny) || BigInt("0")),
(req.permission?.bitfield || 0n) &
(BigInt(body.deny) || BigInt("0")),
);
await Promise.all([
@@ -99,7 +101,7 @@ router.delete(
});
if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
channel.permission_overwrites = channel.permission_overwrites!.filter(
channel.permission_overwrites = channel.permission_overwrites?.filter(
(x) => x.id === overwrite_id,
);
+3 -5
View File
@@ -21,13 +21,11 @@ import {
ChannelPinsUpdateEvent,
Config,
emitEvent,
getPermission,
Message,
MessageUpdateEvent,
DiscordApiErrors,
} from "@fosscord/util";
import { Router, Request, Response } from "express";
import { HTTPError } from "lambert-server";
import { route } from "@fosscord/api";
const router: Router = Router();
@@ -43,7 +41,7 @@ router.put(
});
// * in dm channels anyone can pin messages -> only check for guilds
if (message.guild_id) req.permission!.hasThrow("MANAGE_MESSAGES");
if (message.guild_id) req.permission?.hasThrow("MANAGE_MESSAGES");
const pinned_count = await Message.count({
where: { channel: { id: channel_id }, pinned: true },
@@ -83,7 +81,7 @@ router.delete(
const channel = await Channel.findOneOrFail({
where: { id: channel_id },
});
if (channel.guild_id) req.permission!.hasThrow("MANAGE_MESSAGES");
if (channel.guild_id) req.permission?.hasThrow("MANAGE_MESSAGES");
const message = await Message.findOneOrFail({
where: { id: message_id },
@@ -120,7 +118,7 @@ router.get(
async (req: Request, res: Response) => {
const { channel_id } = req.params;
let pins = await Message.find({
const pins = await Message.find({
where: { channel_id: channel_id, pinned: true },
});
+4 -4
View File
@@ -19,10 +19,9 @@
import { HTTPError } from "lambert-server";
import { route } from "@fosscord/api";
import { isTextChannel } from "./messages";
import { FindManyOptions, Between, Not } from "typeorm";
import { FindManyOptions, Between, Not, FindOperator } from "typeorm";
import {
Channel,
Config,
emitEvent,
getPermission,
getRights,
@@ -69,7 +68,9 @@ router.post(
// TODO: send the deletion event bite-by-bite to prevent client stress
var query: FindManyOptions<Message> & { where: { id?: any } } = {
const query: FindManyOptions<Message> & {
where: { id?: FindOperator<string> };
} = {
order: { id: "ASC" },
// take: limit,
where: {
@@ -93,7 +94,6 @@ router.post(
};
const messages = await Message.find(query);
const endpoint = Config.get().cdn.endpointPublic;
if (messages.length == 0) {
res.sendStatus(304);
@@ -41,7 +41,7 @@ router.put("/:user_id", route({}), async (req: Request, res: Response) => {
if (channel.type !== ChannelType.GROUP_DM) {
const recipients = [
...channel.recipients!.map((r) => r.user_id),
...(channel.recipients?.map((r) => r.user_id) || []),
user_id,
].unique();
@@ -51,11 +51,11 @@ router.put("/:user_id", route({}), async (req: Request, res: Response) => {
);
return res.status(201).json(new_channel);
} else {
if (channel.recipients!.map((r) => r.user_id).includes(user_id)) {
if (channel.recipients?.map((r) => r.user_id).includes(user_id)) {
throw DiscordApiErrors.INVALID_RECIPIENT; //TODO is this the right error?
}
channel.recipients!.push(
channel.recipients?.push(
Recipient.create({ channel_id: channel_id, user_id: user_id }),
);
await channel.save();
@@ -95,7 +95,7 @@ router.delete("/:user_id", route({}), async (req: Request, res: Response) => {
)
throw DiscordApiErrors.MISSING_PERMISSIONS;
if (!channel.recipients!.map((r) => r.user_id).includes(user_id)) {
if (!channel.recipients?.map((r) => r.user_id).includes(user_id)) {
throw DiscordApiErrors.INVALID_RECIPIENT; //TODO is this the right error?
}
@@ -55,10 +55,10 @@ router.post(
const webhook_count = await Webhook.count({ where: { channel_id } });
const { maxWebhooks } = Config.get().limits.channel;
if (webhook_count > maxWebhooks)
if (maxWebhooks && webhook_count > maxWebhooks)
throw DiscordApiErrors.MAXIMUM_WEBHOOKS.withParams(maxWebhooks);
var { avatar, name } = req.body as WebhookCreateSchema;
let { avatar, name } = req.body as WebhookCreateSchema;
name = trimSpecial(name);
// TODO: move this