mirror of
https://github.com/spacebarchat/server.git
synced 2026-07-16 19:42:03 +00:00
replace all var with let (reduces warnings)
This commit is contained in:
@@ -44,7 +44,7 @@ function _generateName() {
|
||||
return `${prefix.random()}${suffix.random()}`;
|
||||
}
|
||||
|
||||
var token = JSON.parse(localStorage.getItem("token"));
|
||||
let token = JSON.parse(localStorage.getItem("token"));
|
||||
if (!token && location.pathname !== "/login" && location.pathname !== "/register") {
|
||||
fetch(`${window.GLOBAL_ENV.API_ENDPOINT}/auth/register`, {
|
||||
method: "POST",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// fosscord-login.css after login is successful, but not if you reload the page after logging in. This script is to remove fosscord-login.css in
|
||||
// that specific case.
|
||||
|
||||
var token = JSON.parse(localStorage.getItem("token"));
|
||||
let token = JSON.parse(localStorage.getItem("token"));
|
||||
if (!token && location.pathname !== "/login" && location.pathname !== "/register") {
|
||||
document.getElementById("logincss").remove();
|
||||
}
|
||||
|
||||
@@ -53,9 +53,9 @@
|
||||
);
|
||||
|
||||
setInterval(() => {
|
||||
var token = JSON.parse(localStorage.getItem("token"));
|
||||
let token = JSON.parse(localStorage.getItem("token"));
|
||||
if (token) {
|
||||
var logincss = document.querySelector('#logincss'),
|
||||
let logincss = document.querySelector('#logincss'),
|
||||
canRemove = logincss ? logincss: "";
|
||||
if(canRemove !== "") {
|
||||
document.querySelector("#logincss").remove();
|
||||
|
||||
@@ -11,7 +11,7 @@ const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
|
||||
const specification = JSON.parse(fs.readFileSync(openapiPath, { encoding: "utf8" }));
|
||||
|
||||
function combineSchemas(schemas) {
|
||||
var definitions = {};
|
||||
let definitions = {};
|
||||
|
||||
for (const name in schemas) {
|
||||
definitions = {
|
||||
|
||||
@@ -40,7 +40,7 @@ const Excluded = [
|
||||
];
|
||||
|
||||
function modify(obj) {
|
||||
for (var k in obj) {
|
||||
for (let k in obj) {
|
||||
if (typeof obj[k] === "object" && obj[k] !== null) {
|
||||
modify(obj[k]);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ function main() {
|
||||
let schemas = generator.getUserSymbols().filter((x) => (x.endsWith("Schema") || x.endsWith("Response")) && !Excluded.includes(x));
|
||||
console.log(schemas);
|
||||
|
||||
var definitions = {};
|
||||
let definitions = {};
|
||||
|
||||
for (const name of schemas) {
|
||||
const part = TJS.generateSchema(program, name, settings, [], generator);
|
||||
@@ -79,11 +79,11 @@ function main() {
|
||||
main();
|
||||
|
||||
function walk(dir) {
|
||||
var results = [];
|
||||
var list = fs.readdirSync(dir);
|
||||
let results = [];
|
||||
let list = fs.readdirSync(dir);
|
||||
list.forEach(function (file) {
|
||||
file = dir + "/" + file;
|
||||
var stat = fs.statSync(file);
|
||||
let stat = fs.statSync(file);
|
||||
if (stat && stat.isDirectory()) {
|
||||
/* Recurse into a subdirectory */
|
||||
results = results.concat(walk(file));
|
||||
|
||||
@@ -19,19 +19,19 @@ setInterval(() => {
|
||||
getUsers();
|
||||
}, 60 * 1000);
|
||||
async function generate() {
|
||||
var accounts = await JSON.parse(fs.readFileSync("accounts.json"));
|
||||
let accounts = await JSON.parse(fs.readFileSync("accounts.json"));
|
||||
console.log(accounts);
|
||||
var account = await register();
|
||||
let account = await register();
|
||||
accounts.push(account);
|
||||
fs.writeFileSync("accounts.json", JSON.stringify(accounts));
|
||||
console.log(accounts.length);
|
||||
var y = await login(account);
|
||||
let y = await login(account);
|
||||
sendMessage(y);
|
||||
}
|
||||
async function getUsers() {
|
||||
var accounts = await JSON.parse(fs.readFileSync("accounts.json"));
|
||||
let accounts = await JSON.parse(fs.readFileSync("accounts.json"));
|
||||
accounts.forEach(async (x) => {
|
||||
var y = await login(x);
|
||||
let y = await login(x);
|
||||
console.log(y);
|
||||
sendMessage(y);
|
||||
});
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
const fetch = require("node-fetch");
|
||||
const fs = require("fs");
|
||||
var config = require("./../../config.json");
|
||||
let config = require("./../../config.json");
|
||||
module.exports = login;
|
||||
async function login(account) {
|
||||
var body = {
|
||||
let body = {
|
||||
fingerprint: "805826570869932034.wR8vi8lGlFBJerErO9LG5NViJFw",
|
||||
login: account.email,
|
||||
password: account.password
|
||||
};
|
||||
var x = await fetch(config.url + "/auth/login", {
|
||||
let x = await fetch(config.url + "/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
const fetch = require("node-fetch");
|
||||
const fs = require("fs");
|
||||
var config = require("./../../config.json");
|
||||
let config = require("./../../config.json");
|
||||
module.exports = sendMessage;
|
||||
async function sendMessage(account) {
|
||||
var body = {
|
||||
let body = {
|
||||
fingerprint: "805826570869932034.wR8vi8lGlFBJerErO9LG5NViJFw",
|
||||
content: "Test",
|
||||
tts: false
|
||||
};
|
||||
var x = await fetch(config.url + "/channels/" + config["text-channel"] + "/messages", {
|
||||
let x = await fetch(config.url + "/channels/" + config["text-channel"] + "/messages", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
const fetch = require("node-fetch");
|
||||
const fs = require("fs");
|
||||
var config = require("./../../config.json");
|
||||
let config = require("./../../config.json");
|
||||
module.exports = generate;
|
||||
async function generate() {
|
||||
var mail = (Math.random() + 10).toString(36).substring(2);
|
||||
let mail = (Math.random() + 10).toString(36).substring(2);
|
||||
mail = mail + "." + (Math.random() + 10).toString(36).substring(2) + "@stresstest.com";
|
||||
var password =
|
||||
let password =
|
||||
(Math.random() * 69).toString(36).substring(-7) +
|
||||
(Math.random() * 69).toString(36).substring(-7) +
|
||||
(Math.random() * 69).toString(36).substring(-8);
|
||||
console.log(mail);
|
||||
console.log(password);
|
||||
var body = {
|
||||
let body = {
|
||||
fingerprint: "805826570869932034.wR8vi8lGlFBJerErO9LG5NViJFw",
|
||||
email: mail,
|
||||
username: "Fosscord Stress Test",
|
||||
@@ -22,7 +22,7 @@ async function generate() {
|
||||
gift_code_sku_id: null,
|
||||
captcha_key: null
|
||||
};
|
||||
var x = await fetch(config.url + "/auth/register", {
|
||||
let x = await fetch(config.url + "/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body)
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ export class FosscordServer extends Server {
|
||||
this.app.use(
|
||||
morgan("combined", {
|
||||
skip: (req, res) => {
|
||||
var skip = !(process.env["LOG_REQUESTS"]?.includes(res.statusCode.toString()) ?? false);
|
||||
let skip = !(process.env["LOG_REQUESTS"]?.includes(res.statusCode.toString()) ?? false);
|
||||
if (process.env["LOG_REQUESTS"]?.charAt(0) == "-") skip = !skip;
|
||||
return skip;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ type RateLimit = {
|
||||
expires_at: Date;
|
||||
};
|
||||
|
||||
var Cache = new Map<string, RateLimit>();
|
||||
let Cache = new Map<string, RateLimit>();
|
||||
const EventRateLimit = "RATELIMIT";
|
||||
|
||||
export default function rateLimit(opts: {
|
||||
@@ -52,10 +52,10 @@ export default function rateLimit(opts: {
|
||||
}
|
||||
|
||||
const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, "");
|
||||
var executor_id = getIpAdress(req);
|
||||
let executor_id = getIpAdress(req);
|
||||
if (!opts.onlyIp && req.user_id) executor_id = req.user_id;
|
||||
|
||||
var max_hits = opts.count;
|
||||
let max_hits = opts.count;
|
||||
if (opts.bot && req.user_bot) max_hits = opts.bot;
|
||||
if (opts.GET && ["GET", "OPTIONS", "HEAD"].includes(req.method)) max_hits = opts.GET;
|
||||
else if (opts.MODIFY && ["POST", "DELETE", "PATCH", "PUT"].includes(req.method)) max_hits = opts.MODIFY;
|
||||
@@ -165,7 +165,7 @@ export async function initRateLimits(app: Router) {
|
||||
|
||||
async function hitRoute(opts: { executor_id: string; bucket_id: string; max_hits: number; window: number; }) {
|
||||
const id = opts.executor_id + opts.bucket_id;
|
||||
var limit = Cache.get(id);
|
||||
let limit = Cache.get(id);
|
||||
if (!limit) {
|
||||
limit = {
|
||||
id: opts.bucket_id,
|
||||
@@ -183,7 +183,7 @@ async function hitRoute(opts: { executor_id: string; bucket_id: string; max_hits
|
||||
}
|
||||
|
||||
/*
|
||||
var ratelimit = await RateLimit.findOne({ id: opts.bucket_id, executor_id: opts.executor_id });
|
||||
let ratelimit = await RateLimit.findOne({ where: { id: opts.bucket_id, executor_id: opts.executor_id } });
|
||||
if (!ratelimit) {
|
||||
ratelimit = new RateLimit({
|
||||
id: opts.bucket_id,
|
||||
|
||||
@@ -73,7 +73,7 @@ export interface ChannelModifySchema {
|
||||
}
|
||||
|
||||
router.patch("/", route({ body: "ChannelModifySchema", permission: "MANAGE_CHANNELS" }), async (req: Request, res: Response) => {
|
||||
var payload = req.body as ChannelModifySchema;
|
||||
let payload = req.body as ChannelModifySchema;
|
||||
const { channel_id } = req.params;
|
||||
if (payload.icon) payload.icon = await handleFile(`/channel-icons/${channel_id}`, payload.icon);
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ const messageUpload = multer({
|
||||
|
||||
router.patch("/", route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }), 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 }, relations: ["attachments"] });
|
||||
|
||||
@@ -92,7 +92,7 @@ router.put(
|
||||
route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_BACKDATED_EVENTS" }),
|
||||
async (req: Request, res: Response) => {
|
||||
const { channel_id, message_id } = req.params;
|
||||
var body = req.body as MessageCreateSchema;
|
||||
let body = req.body as MessageCreateSchema;
|
||||
const attachments: Attachment[] = [];
|
||||
|
||||
const rights = await getRights(req.user_id);
|
||||
|
||||
@@ -145,7 +145,7 @@ router.put("/:emoji/:user_id", route({ permission: "READ_MESSAGE_HISTORY", right
|
||||
});
|
||||
|
||||
router.delete("/:emoji/:user_id", route({}), async (req: Request, res: Response) => {
|
||||
var { message_id, channel_id, user_id } = req.params;
|
||||
let { message_id, channel_id, user_id } = req.params;
|
||||
|
||||
const emoji = getEmoji(req.params.emoji);
|
||||
|
||||
|
||||
@@ -95,13 +95,13 @@ router.get("/", async (req: Request, res: Response) => {
|
||||
const limit = Number(req.query.limit) || 50;
|
||||
if (limit < 1 || limit > 100) throw new HTTPError("limit must be between 1 and 100", 422);
|
||||
|
||||
var halfLimit = Math.floor(limit / 2);
|
||||
let halfLimit = Math.floor(limit / 2);
|
||||
|
||||
const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
|
||||
permissions.hasThrow("VIEW_CHANNEL");
|
||||
if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]);
|
||||
|
||||
var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
|
||||
let query: FindManyOptions<Message> & { where: { id?: any; }; } = {
|
||||
order: { id: "DESC" },
|
||||
take: limit,
|
||||
where: { channel_id },
|
||||
@@ -148,7 +148,7 @@ router.get("/", async (req: Request, res: Response) => {
|
||||
which causes erorrs when, say, the `application` property is `null`.
|
||||
**/
|
||||
|
||||
for (var curr in x) {
|
||||
for (let curr in x) {
|
||||
if (x[curr] === null)
|
||||
delete x[curr];
|
||||
}
|
||||
@@ -189,7 +189,7 @@ router.post(
|
||||
route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }),
|
||||
async (req: Request, res: Response) => {
|
||||
const { channel_id } = req.params;
|
||||
var body = req.body as MessageCreateSchema;
|
||||
let body = req.body as MessageCreateSchema;
|
||||
const attachments: Attachment[] = [];
|
||||
|
||||
const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients", "recipients.user"] });
|
||||
@@ -198,7 +198,7 @@ router.post(
|
||||
}
|
||||
|
||||
const files = req.files as Express.Multer.File[] ?? [];
|
||||
for (var currFile of files) {
|
||||
for (let currFile of files) {
|
||||
try {
|
||||
const file = await uploadFile(`/attachments/${channel.id}`, currFile);
|
||||
attachments.push({ ...file, proxy_url: file.url });
|
||||
|
||||
@@ -25,7 +25,7 @@ router.put(
|
||||
const { channel_id, overwrite_id } = req.params;
|
||||
const body = req.body as ChannelPermissionOverwriteSchema;
|
||||
|
||||
var channel = await Channel.findOneOrFail({ id: channel_id });
|
||||
let channel = await Channel.findOneOrFail({ where: {id: channel_id} });
|
||||
if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
|
||||
|
||||
if (body.type === 0) {
|
||||
@@ -35,7 +35,7 @@ router.put(
|
||||
} else throw new HTTPError("type not supported", 501);
|
||||
|
||||
// @ts-ignore
|
||||
var overwrite: ChannelPermissionOverwrite = channel.permission_overwrites.find((x) => x.id === overwrite_id);
|
||||
let overwrite: ChannelPermissionOverwrite = channel.permission_overwrites.find((x) => x.id === overwrite_id);
|
||||
if (!overwrite) {
|
||||
// @ts-ignore
|
||||
overwrite = {
|
||||
|
||||
@@ -51,7 +51,7 @@ router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res:
|
||||
|
||||
// TODO: send the deletion event bite-by-bite to prevent client stress
|
||||
|
||||
var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
|
||||
let query: FindManyOptions<Message> & { where: { id?: any; }; } = {
|
||||
order: { id: "ASC" },
|
||||
// take: limit,
|
||||
where: {
|
||||
|
||||
@@ -31,7 +31,7 @@ router.post("/", route({ body: "WebhookCreateSchema", permission: "MANAGE_WEBHOO
|
||||
const { maxWebhooks } = Config.get().limits.channel;
|
||||
if (webhook_count > maxWebhooks) throw DiscordApiErrors.MAXIMUM_WEBHOOKS.withParams(maxWebhooks);
|
||||
|
||||
var { avatar, name } = req.body as { name: string; avatar?: string };
|
||||
let { avatar, name } = req.body as { name: string; avatar?: string };
|
||||
name = trimSpecial(name);
|
||||
if (name === "clyde") throw new HTTPError("Invalid name", 400);
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ const router = Router();
|
||||
|
||||
router.get("/", route({}), async (req: Request, res: Response) => {
|
||||
const { offset, limit, categories } = req.query;
|
||||
var showAllGuilds = Config.get().guild.discovery.showAllGuilds;
|
||||
var configLimit = Config.get().guild.discovery.limit;
|
||||
let showAllGuilds = Config.get().guild.discovery.showAllGuilds;
|
||||
let configLimit = Config.get().guild.discovery.limit;
|
||||
// ! this only works using SQL querys
|
||||
// TODO: implement this with default typeorm query
|
||||
// const guilds = await Guild.find({ where: { features: "DISCOVERABLE" } }); //, take: Math.abs(Number(limit)) });
|
||||
|
||||
@@ -10,7 +10,7 @@ router.get("/categories", route({}), async (req: Request, res: Response) => {
|
||||
|
||||
const { locale, primary_only } = req.query;
|
||||
|
||||
const out = primary_only ? await Categories.find() : await Categories.find({ where: `"is_primary" = "true"` });
|
||||
const out = primary_only ? await Categories.find() : await Categories.find({ where: {is_primary: true} });
|
||||
|
||||
res.send(out);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ const router = Router();
|
||||
|
||||
router.get("/", route({}), async (req: Request, res: Response) => {
|
||||
const { limit, personalization_disabled } = req.query;
|
||||
var showAllGuilds = Config.get().guild.discovery.showAllGuilds;
|
||||
let showAllGuilds = Config.get().guild.discovery.showAllGuilds;
|
||||
// ! this only works using SQL querys
|
||||
// TODO: implement this with default typeorm query
|
||||
// const guilds = await Guild.find({ where: { features: "DISCOVERABLE" } }); //, take: Math.abs(Number(limit)) });
|
||||
|
||||
@@ -8,7 +8,7 @@ const router = Router();
|
||||
// discord prefixes this route with /delete instead of using the delete method
|
||||
// docs are wrong https://discord.com/developers/docs/resources/guild#delete-guild
|
||||
router.post("/", route({}), async (req: Request, res: Response) => {
|
||||
var { guild_id } = req.params;
|
||||
let { guild_id } = req.params;
|
||||
|
||||
const guild = await Guild.findOneOrFail({ where: { id: guild_id }, select: ["owner_id"] });
|
||||
if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401);
|
||||
|
||||
@@ -55,7 +55,7 @@ router.patch("/", route({ body: "GuildUpdateSchema"}), async (req: Request, res:
|
||||
if (body.banner) body.banner = await handleFile(`/banners/${guild_id}`, body.banner);
|
||||
if (body.splash) body.splash = await handleFile(`/splashes/${guild_id}`, body.splash);
|
||||
|
||||
var guild = await Guild.findOneOrFail({
|
||||
let guild = await Guild.findOneOrFail({
|
||||
where: { id: guild_id },
|
||||
relations: ["emojis", "roles", "stickers"]
|
||||
});
|
||||
|
||||
@@ -62,19 +62,19 @@ router.put("/", route({}), async (req: Request, res: Response) => {
|
||||
// TODO: join others by controller
|
||||
}
|
||||
|
||||
var guild = await Guild.findOneOrFail({
|
||||
let guild = await Guild.findOneOrFail({
|
||||
where: { id: guild_id }
|
||||
});
|
||||
|
||||
var emoji = await Emoji.find({
|
||||
let emoji = await Emoji.find({
|
||||
where: { guild_id: guild_id }
|
||||
});
|
||||
|
||||
var roles = await Role.find({
|
||||
let roles = await Role.find({
|
||||
where: { guild_id: guild_id }
|
||||
});
|
||||
|
||||
var stickers = await Sticker.find({
|
||||
let stickers = await Sticker.find({
|
||||
where: { guild_id: guild_id }
|
||||
});
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ export interface MemberNickChangeSchema {
|
||||
}
|
||||
|
||||
router.patch("/", route({ body: "MemberNickChangeSchema" }), async (req: Request, res: Response) => {
|
||||
var { guild_id, member_id } = req.params;
|
||||
var permissionString: PermissionResolvable = "MANAGE_NICKNAMES";
|
||||
let { guild_id, member_id } = req.params;
|
||||
let permissionString: PermissionResolvable = "MANAGE_NICKNAMES";
|
||||
if (member_id === "@me") {
|
||||
member_id = req.user_id;
|
||||
permissionString = "CHANGE_NICKNAME";
|
||||
|
||||
@@ -6,16 +6,16 @@ const router = Router();
|
||||
|
||||
//Returns all inactive members, respecting role hierarchy
|
||||
export const inactiveMembers = async (guild_id: string, user_id: string, days: number, roles: string[] = []) => {
|
||||
var date = new Date();
|
||||
let date = new Date();
|
||||
date.setDate(date.getDate() - days);
|
||||
//Snowflake should have `generateFromTime` method? Or similar?
|
||||
var minId = BigInt(date.valueOf() - Snowflake.EPOCH) << BigInt(22);
|
||||
let minId = BigInt(date.valueOf() - Snowflake.EPOCH) << BigInt(22);
|
||||
|
||||
/**
|
||||
idea: ability to customise the cutoff variable
|
||||
possible candidates: public read receipt, last presence, last VC leave
|
||||
**/
|
||||
var members = await Member.find({
|
||||
let members = await Member.find({
|
||||
where: [
|
||||
{
|
||||
guild_id,
|
||||
@@ -54,7 +54,7 @@ export const inactiveMembers = async (guild_id: string, user_id: string, days: n
|
||||
router.get("/", route({}), async (req: Request, res: Response) => {
|
||||
const days = parseInt(req.query.days as string);
|
||||
|
||||
var roles = req.query.include_roles;
|
||||
let roles = req.query.include_roles;
|
||||
if (typeof roles === "string") roles = [roles]; //express will return array otherwise
|
||||
|
||||
const members = await inactiveMembers(req.params.guild_id, req.user_id, days, roles as string[]);
|
||||
@@ -72,7 +72,7 @@ export interface PruneSchema {
|
||||
router.post("/", route({ permission: "KICK_MEMBERS", right: "KICK_BAN_MEMBERS" }), async (req: Request, res: Response) => {
|
||||
const days = parseInt(req.body.days);
|
||||
|
||||
var roles = req.query.include_roles;
|
||||
let roles = req.query.include_roles;
|
||||
if (typeof roles === "string") roles = [roles];
|
||||
|
||||
const { guild_id } = req.params;
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface TemplateModifySchema {
|
||||
router.get("/", route({}), async (req: Request, res: Response) => {
|
||||
const { guild_id } = req.params;
|
||||
|
||||
var templates = await Template.find({ source_guild_id: guild_id });
|
||||
let templates = await Template.find({ where: { source_guild_id: guild_id } });
|
||||
|
||||
return res.json(templates);
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface VoiceStateUpdateSchema {
|
||||
|
||||
router.patch("/", route({ body: "VoiceStateUpdateSchema" }), async (req: Request, res: Response) => {
|
||||
const body = req.body as VoiceStateUpdateSchema;
|
||||
var { guild_id, user_id } = req.params;
|
||||
let { guild_id, user_id } = req.params;
|
||||
if (user_id === "@me") user_id = req.user_id;
|
||||
|
||||
const perms = await getPermission(req.user_id, guild_id, body.channel_id);
|
||||
|
||||
@@ -21,7 +21,7 @@ router.get("/", route({}), async (req: Request, res: Response) => {
|
||||
if (!guild.widget_enabled) throw new HTTPError("Widget Disabled", 404);
|
||||
|
||||
// Fetch existing widget invite for widget channel
|
||||
var invite = await Invite.findOne({ channel_id: guild.widget_channel_id });
|
||||
let invite = await Invite.findOne({ where: { channel_id: guild.widget_channel_id } });
|
||||
|
||||
if (guild.widget_channel_id && !invite) {
|
||||
// Create invite for channel if none exists
|
||||
|
||||
@@ -15,10 +15,10 @@ router.get("/", route({ test: { response: { body: "UserProfileResponse" } } }),
|
||||
if (req.params.id === "@me") req.params.id = req.user_id;
|
||||
const user = await User.getPublicUser(req.params.id, { relations: ["connected_accounts"] });
|
||||
|
||||
var mutual_guilds: object[] = [];
|
||||
var premium_guild_since;
|
||||
const requested_member = await Member.find( { id: req.params.id, })
|
||||
const self_member = await Member.find( { id: req.user_id, })
|
||||
let mutual_guilds: object[] = [];
|
||||
let premium_guild_since;
|
||||
const requested_member = await Member.find( { where: { id: req.params.id, } })
|
||||
const self_member = await Member.find( { where: { id: req.user_id, } })
|
||||
|
||||
for(const rmem of requested_member) {
|
||||
if(rmem.premium_since) {
|
||||
|
||||
@@ -16,7 +16,7 @@ export interface UserRelationsResponse {
|
||||
|
||||
|
||||
router.get("/", route({ test: { response: { body: "UserRelationsResponse" } } }), async (req: Request, res: Response) => {
|
||||
var mutual_relations: object[] = [];
|
||||
let mutual_relations: object[] = [];
|
||||
const requested_relations = await User.findOneOrFail({
|
||||
where: { id: req.params.id },
|
||||
relations: ["relationships"]
|
||||
@@ -29,7 +29,7 @@ router.get("/", route({ test: { response: { body: "UserRelationsResponse" } } })
|
||||
for(const rmem of requested_relations.relationships) {
|
||||
for(const smem of self_relations.relationships)
|
||||
if (rmem.to_id === smem.to_id && rmem.type === 1 && rmem.to_id !== req.user_id) {
|
||||
var relation_user = await User.getPublicUser(rmem.to_id)
|
||||
let relation_user = await User.getPublicUser(rmem.to_id)
|
||||
|
||||
mutual_relations.push({id: relation_user.id, username: relation_user.username, avatar: relation_user.avatar, discriminator: relation_user.discriminator, public_flags: relation_user.public_flags})
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ router.patch("/", route({ body: "UserModifySchema" }), async (req: Request, res:
|
||||
}
|
||||
|
||||
if(body.username){
|
||||
var check_username = body?.username?.replace(/\s/g, '');
|
||||
let check_username = body?.username?.replace(/\s/g, '');
|
||||
if(!check_username) {
|
||||
throw FieldErrors({
|
||||
username: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
|
||||
|
||||
@@ -129,7 +129,7 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ
|
||||
{ relations: ["relationships", "relationships.to"], select: userProjection }
|
||||
);
|
||||
|
||||
var relationship = user.relationships.find((x) => x.to_id === id);
|
||||
let relationship = user.relationships.find((x) => x.to_id === id);
|
||||
const friendRequest = friend.relationships.find((x) => x.to_id === req.user_id);
|
||||
|
||||
// TODO: you can add infinitely many blocked users (should this be prevented?)
|
||||
@@ -165,8 +165,8 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ
|
||||
const { maxFriends } = Config.get().limits.user;
|
||||
if (user.relationships.length >= maxFriends) throw DiscordApiErrors.MAXIMUM_FRIENDS.withParams(maxFriends);
|
||||
|
||||
var incoming_relationship = new Relationship({ nickname: undefined, type: RelationshipType.incoming, to: user, from: friend });
|
||||
var outgoing_relationship = new Relationship({
|
||||
let incoming_relationship = new Relationship({ nickname: undefined, type: RelationshipType.incoming, to: user, from: friend });
|
||||
let outgoing_relationship = new Relationship({
|
||||
nickname: undefined,
|
||||
type: RelationshipType.outgoing,
|
||||
to: friend,
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ config();
|
||||
import { FosscordServer } from "./Server";
|
||||
import cluster from "cluster";
|
||||
import os from "os";
|
||||
var cores = 1;
|
||||
let cores = 1;
|
||||
try {
|
||||
cores = Number(process.env.THREADS) || os.cpus().length;
|
||||
} catch {
|
||||
@@ -27,7 +27,7 @@ if (cluster.isMaster && process.env.NODE_ENV == "production") {
|
||||
cluster.fork();
|
||||
});
|
||||
} else {
|
||||
var port = Number(process.env.PORT) || 3001;
|
||||
let port = Number(process.env.PORT) || 3001;
|
||||
|
||||
const server = new FosscordServer({ port });
|
||||
server.start().catch(console.error);
|
||||
|
||||
@@ -102,11 +102,11 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
|
||||
throw new HTTPError("Empty messages are not allowed", 50006);
|
||||
}
|
||||
|
||||
var content = opts.content;
|
||||
var mention_channel_ids = [] as string[];
|
||||
var mention_role_ids = [] as string[];
|
||||
var mention_user_ids = [] as string[];
|
||||
var mention_everyone = false;
|
||||
let content = opts.content;
|
||||
let mention_channel_ids = [] as string[];
|
||||
let mention_role_ids = [] as string[];
|
||||
let mention_user_ids = [] as string[];
|
||||
let mention_everyone = false;
|
||||
|
||||
if (content) { // TODO: explicit-only mentions
|
||||
message.content = content.trim();
|
||||
@@ -144,7 +144,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
|
||||
|
||||
// TODO: cache link result in db
|
||||
export async function postHandleMessage(message: Message) {
|
||||
var links = message.content?.match(LINK_REGEX);
|
||||
let links = message.content?.match(LINK_REGEX);
|
||||
if (!links) return;
|
||||
|
||||
const data = { ...message };
|
||||
|
||||
@@ -87,7 +87,7 @@ const normalizeBody = (body: any = {}) => {
|
||||
};
|
||||
|
||||
export function route(opts: RouteOptions) {
|
||||
var validate: AnyValidateFunction<any> | undefined;
|
||||
let validate: AnyValidateFunction<any> | undefined;
|
||||
if (opts.body) {
|
||||
validate = ajv.getSchema(opts.body);
|
||||
if (!validate) throw new Error(`Body schema ${opts.body} not found`);
|
||||
|
||||
@@ -19,7 +19,7 @@ const blocklist: string[] = []; // TODO: update ones passwordblocklist is stored
|
||||
*/
|
||||
export function checkPassword(password: string): number {
|
||||
const { minLength, minNumbers, minUpperCase, minSymbols } = Config.get().register.password;
|
||||
var strength = 0;
|
||||
let strength = 0;
|
||||
|
||||
// checks for total password len
|
||||
if (password.length >= minLength - 1) {
|
||||
|
||||
@@ -23,10 +23,10 @@ export const ajv = new Ajv({
|
||||
});
|
||||
addFormats(ajv);
|
||||
|
||||
var token: string;
|
||||
var user: User;
|
||||
var guild: Guild;
|
||||
var channel: Channel;
|
||||
let token: string;
|
||||
let user: User;
|
||||
let guild: Guild;
|
||||
let channel: Channel;
|
||||
|
||||
const request = async (path: string, opts: any = {}): Promise<any> => {
|
||||
const response = await fetch(`http://localhost:3001/api${path}`, {
|
||||
@@ -41,7 +41,7 @@ const request = async (path: string, opts: any = {}): Promise<any> => {
|
||||
});
|
||||
if (response.status === 204) return;
|
||||
|
||||
var data = await response.text();
|
||||
let data = await response.text();
|
||||
try {
|
||||
data = JSON.parse(data);
|
||||
if (response.status >= 400) throw data;
|
||||
@@ -95,13 +95,13 @@ describe("Automatic unit tests with route description middleware", () => {
|
||||
}
|
||||
const urlPath =
|
||||
path.replace(":id", user.id).replace(":guild_id", guild.id).replace(":channel_id", channel.id) || route.test?.path;
|
||||
var validate: any;
|
||||
let validate: any;
|
||||
if (route.test.body) {
|
||||
validate = ajv.getSchema(route.test.body);
|
||||
if (!validate) return done(new Error(`Response schema ${route.test.body} not found`));
|
||||
}
|
||||
|
||||
var body = "";
|
||||
let body = "";
|
||||
let eventEmitted = Promise.resolve();
|
||||
|
||||
if (route.test.event) {
|
||||
|
||||
@@ -4,7 +4,7 @@ const WebSocket = require("ws");
|
||||
const endpoint = process.env.GATEWAY || "ws://localhost:3001";
|
||||
const connections = Number(process.env.CONNECTIONS) || 50;
|
||||
const token = process.env.TOKEN;
|
||||
var cores = 1;
|
||||
let cores = 1;
|
||||
try {
|
||||
cores = Number(process.env.THREADS) || os.cpus().length;
|
||||
} catch {
|
||||
@@ -12,7 +12,7 @@ try {
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
console.error("TOKEN env var missing");
|
||||
console.error("TOKEN env let missing");
|
||||
process.exit();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ config();
|
||||
import { execSync } from "child_process";
|
||||
|
||||
// TODO: add socket event transmission
|
||||
var cores = 1;
|
||||
let cores = 1;
|
||||
try {
|
||||
cores = Number(process.env.THREADS) || os.cpus().length;
|
||||
} catch {
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ export function initStats() {
|
||||
// osu.mem.info(),
|
||||
// osu.netstat.inOut(),
|
||||
// ]);
|
||||
// var networkUsage = "";
|
||||
// let networkUsage = "";
|
||||
// if (typeof network === "object") {
|
||||
// networkUsage = `| [Network]: in ${network.total.inputMb}mb | out ${network.total.outputMb}mb`;
|
||||
// }
|
||||
|
||||
@@ -35,8 +35,8 @@ router.post(
|
||||
Config.get()?.cdn.endpointPublic || "http://localhost:3003";
|
||||
|
||||
await storage.set(path, buffer);
|
||||
var width;
|
||||
var height;
|
||||
let width;
|
||||
let height;
|
||||
if (mimetype.includes("image")) {
|
||||
const dimensions = imageSize(buffer);
|
||||
if (dimensions) {
|
||||
|
||||
@@ -33,7 +33,7 @@ router.post(
|
||||
const { buffer, mimetype, size, originalname, fieldname } = req.file;
|
||||
const { user_id } = req.params;
|
||||
|
||||
var hash = crypto
|
||||
let hash = crypto
|
||||
.createHash("md5")
|
||||
.update(Snowflake.generate())
|
||||
.digest("hex");
|
||||
@@ -59,7 +59,7 @@ router.post(
|
||||
);
|
||||
|
||||
router.get("/:user_id", async (req: Request, res: Response) => {
|
||||
var { user_id } = req.params;
|
||||
let { user_id } = req.params;
|
||||
user_id = user_id.split(".")[0]; // remove .file extension
|
||||
const path = `avatars/${user_id}`;
|
||||
|
||||
@@ -74,7 +74,7 @@ router.get("/:user_id", async (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
router.get("/:user_id/:hash", async (req: Request, res: Response) => {
|
||||
var { user_id, hash } = req.params;
|
||||
let { user_id, hash } = req.params;
|
||||
hash = hash.split(".")[0]; // remove .file extension
|
||||
const path = `avatars/${user_id}/${hash}`;
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ router.post(
|
||||
const { buffer, mimetype, size, originalname, fieldname } = req.file;
|
||||
const { role_id } = req.params;
|
||||
|
||||
var hash = crypto
|
||||
let hash = crypto
|
||||
.createHash("md5")
|
||||
.update(Snowflake.generate())
|
||||
.digest("hex");
|
||||
@@ -58,7 +58,7 @@ router.post(
|
||||
);
|
||||
|
||||
router.get("/:role_id", async (req: Request, res: Response) => {
|
||||
var { role_id } = req.params;
|
||||
let { role_id } = req.params;
|
||||
//role_id = role_id.split(".")[0]; // remove .file extension
|
||||
const path = `role-icons/${role_id}`;
|
||||
|
||||
@@ -73,7 +73,7 @@ router.get("/:role_id", async (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
router.get("/:role_id/:hash", async (req: Request, res: Response) => {
|
||||
var { role_id, hash } = req.params;
|
||||
let { role_id, hash } = req.params;
|
||||
//hash = hash.split(".")[0]; // remove .file extension
|
||||
const path = `role-icons/${role_id}/${hash}`;
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import ExifTransformer = require("exif-be-gone");
|
||||
function getPath(path: string) {
|
||||
// STORAGE_LOCATION has a default value in start.ts
|
||||
const root = process.env.STORAGE_LOCATION || "../";
|
||||
var filename = join(root, path);
|
||||
let filename = join(root, path);
|
||||
|
||||
if (path.indexOf("\0") !== -1 || !filename.startsWith(root))
|
||||
throw new Error("invalid path");
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Close } from "./Close";
|
||||
import { Message } from "./Message";
|
||||
import { createDeflate } from "zlib";
|
||||
import { URL } from "url";
|
||||
var erlpack: any;
|
||||
let erlpack: any;
|
||||
try {
|
||||
erlpack = require("@yukikaze-bot/erlpack");
|
||||
} catch (error) {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CLOSECODES, OPCODES } from "../util/Constants";
|
||||
import { WebSocket, Payload } from "@fosscord/gateway";
|
||||
var erlpack: any;
|
||||
let erlpack: any;
|
||||
try {
|
||||
erlpack = require("@yukikaze-bot/erlpack");
|
||||
} catch (error) {}
|
||||
@@ -18,7 +18,7 @@ const PayloadSchema = {
|
||||
|
||||
export async function Message(this: WebSocket, buffer: WS.Data) {
|
||||
// TODO: compression
|
||||
var data: Payload;
|
||||
let data: Payload;
|
||||
|
||||
if (this.encoding === "etf" && buffer instanceof Buffer)
|
||||
data = erlpack.unpack(buffer);
|
||||
|
||||
@@ -41,7 +41,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
|
||||
|
||||
try {
|
||||
const { jwtSecret } = Config.get().security;
|
||||
var { decoded } = await checkToken(identify.token, jwtSecret); // will throw an error if invalid
|
||||
let { decoded } = await checkToken(identify.token, jwtSecret); // will throw an error if invalid
|
||||
} catch (error) {
|
||||
console.error("invalid token", error);
|
||||
return this.close(CLOSECODES.Authentication_failed);
|
||||
@@ -117,7 +117,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
|
||||
return this.close(CLOSECODES.Invalid_shard);
|
||||
}
|
||||
}
|
||||
var users: PublicUser[] = [];
|
||||
let users: PublicUser[] = [];
|
||||
|
||||
const merged_members = members.map((x: Member) => {
|
||||
return [
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Server } from "./Server";
|
||||
import { config } from "dotenv";
|
||||
config();
|
||||
|
||||
var port = Number(process.env.PORT);
|
||||
let port = Number(process.env.PORT);
|
||||
if (isNaN(port)) port = 3002;
|
||||
|
||||
const server = new Server({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
var erlpack: any;
|
||||
let erlpack: any;
|
||||
try {
|
||||
erlpack = require("@yukikaze-bot/erlpack");
|
||||
} catch (error) {
|
||||
|
||||
@@ -171,7 +171,7 @@ export class Channel extends BaseClass {
|
||||
if (!opts?.skipNameChecks) {
|
||||
const guild = await Guild.findOneOrFail({ id: channel.guild_id });
|
||||
if (!guild.features.includes("ALLOW_INVALID_CHANNEL_NAMES") && channel.name) {
|
||||
for (var character of InvisibleCharacters)
|
||||
for (let character of InvisibleCharacters)
|
||||
if (channel.name.includes(character))
|
||||
throw new HTTPError("Channel name cannot include invalid characters", 403);
|
||||
|
||||
|
||||
@@ -346,9 +346,9 @@ export class Guild extends BaseClass {
|
||||
});
|
||||
|
||||
for (const channel of body.channels?.sort((a, b) => (a.parent_id ? 1 : -1))) {
|
||||
var id = ids.get(channel.id) || Snowflake.generate();
|
||||
let id = ids.get(channel.id) || Snowflake.generate();
|
||||
|
||||
var parent_id = ids.get(channel.parent_id);
|
||||
let parent_id = ids.get(channel.parent_id);
|
||||
|
||||
await Channel.createChannel({ ...channel, guild_id, id, parent_id }, body.owner_id, {
|
||||
keepId: true,
|
||||
|
||||
@@ -18,7 +18,7 @@ export function enableAutoUpdate(opts: {
|
||||
downloadType?: "zip";
|
||||
}) {
|
||||
if (!opts.checkInterval) return;
|
||||
var interval = 1000 * 60 * 60 * 24;
|
||||
let interval = 1000 * 60 * 60 * 24;
|
||||
if (typeof opts.checkInterval === "number") opts.checkInterval = 1000 * interval;
|
||||
|
||||
const i = setInterval(async () => {
|
||||
|
||||
@@ -6,8 +6,8 @@ import fs from "fs";
|
||||
// TODO: yaml instead of json
|
||||
// const overridePath = path.join(process.cwd(), "config.json");
|
||||
|
||||
var config: ConfigValue;
|
||||
var pairs: ConfigEntity[];
|
||||
let config: ConfigValue;
|
||||
let pairs: ConfigEntity[];
|
||||
|
||||
// TODO: use events to inform about config updates
|
||||
// Config keys are separated with _
|
||||
@@ -57,7 +57,7 @@ function applyConfig(val: ConfigValue) {
|
||||
}
|
||||
|
||||
function pairsToConfig(pairs: ConfigEntity[]) {
|
||||
var value: any = {};
|
||||
let value: any = {};
|
||||
|
||||
pairs.forEach((p) => {
|
||||
const keys = p.key.split("_");
|
||||
|
||||
@@ -8,8 +8,8 @@ import { yellow, green, red } from "picocolors";
|
||||
// UUID extension option is only supported with postgres
|
||||
// We want to generate all id's with Snowflakes that's why we have our own BaseEntity class
|
||||
|
||||
var promise: Promise<any>;
|
||||
var dbConnection: Connection | undefined;
|
||||
let promise: Promise<any>;
|
||||
let dbConnection: Connection | undefined;
|
||||
let dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db");
|
||||
|
||||
export function initDatabase(): Promise<Connection> {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { BitField } from "./BitField";
|
||||
import "missing-native-js-functions";
|
||||
import { BitFieldResolvable, BitFlag } from "./BitField";
|
||||
|
||||
var HTTPError: any;
|
||||
let HTTPError: any;
|
||||
|
||||
try {
|
||||
HTTPError = require("lambert-server").HTTPError;
|
||||
@@ -207,9 +207,9 @@ export async function getPermission(
|
||||
} = {}
|
||||
) {
|
||||
if (!user_id) throw new HTTPError("User not found");
|
||||
var channel: Channel | undefined;
|
||||
var member: Member | undefined;
|
||||
var guild: Guild | undefined;
|
||||
let channel: Channel | undefined;
|
||||
let member: Member | undefined;
|
||||
let guild: Guild | undefined;
|
||||
|
||||
if (channel_id) {
|
||||
channel = await Channel.findOneOrFail({
|
||||
@@ -257,7 +257,7 @@ export async function getPermission(
|
||||
if (!recipient_ids?.length) recipient_ids = null;
|
||||
|
||||
// TODO: remove guild.roles and convert recipient_ids to recipients
|
||||
var permission = Permissions.finalPermission({
|
||||
let permission = Permissions.finalPermission({
|
||||
user: {
|
||||
id: user_id,
|
||||
roles: member?.roles.map((x) => x.id) || [],
|
||||
|
||||
@@ -3,7 +3,7 @@ import "missing-native-js-functions";
|
||||
import { BitFieldResolvable, BitFlag } from "./BitField";
|
||||
import { User } from "../entities";
|
||||
|
||||
var HTTPError: any;
|
||||
let HTTPError: any;
|
||||
|
||||
try {
|
||||
HTTPError = require("lambert-server").HTTPError;
|
||||
|
||||
@@ -84,10 +84,10 @@ export class Snowflake {
|
||||
}
|
||||
|
||||
static generateWorkerProcess() { // worker process - returns a number
|
||||
var time = BigInt(Date.now() - Snowflake.EPOCH) << BigInt(22);
|
||||
var worker = Snowflake.workerId << 17n;
|
||||
var process = Snowflake.processId << 12n;
|
||||
var increment = Snowflake.INCREMENT++;
|
||||
let time = BigInt(Date.now() - Snowflake.EPOCH) << BigInt(22);
|
||||
let worker = Snowflake.workerId << 17n;
|
||||
let process = Snowflake.processId << 12n;
|
||||
let increment = Snowflake.INCREMENT++;
|
||||
return BigInt(time | worker | process | increment);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ const path = require("path");
|
||||
global.expect.extend({
|
||||
toBeFasterThan: async (func, target) => {
|
||||
const start = performance.now();
|
||||
var error;
|
||||
let error;
|
||||
try {
|
||||
await func();
|
||||
} catch (e) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Server as WebSocketServer } from "ws";
|
||||
import { Config, db } from "@fosscord/util";
|
||||
import mediasoup from "mediasoup";
|
||||
|
||||
var port = Number(process.env.PORT);
|
||||
let port = Number(process.env.PORT);
|
||||
if (isNaN(port)) port = 3004;
|
||||
|
||||
export class Server {
|
||||
|
||||
Reference in New Issue
Block a user