diff --git a/api/src/Server.ts b/api/src/Server.ts
index 12c1d6b4..a6887fd4 100644
--- a/api/src/Server.ts
+++ b/api/src/Server.ts
@@ -1,19 +1,17 @@
-import { OptionsJson } from "body-parser";
import "missing-native-js-functions";
-import { Connection } from "mongoose";
import { Server, ServerOptions } from "lambert-server";
import { Authentication, CORS } from "./middlewares/";
import { Config, initDatabase, initEvent } from "@fosscord/util";
import { ErrorHandler } from "./middlewares/ErrorHandler";
import { BodyParser } from "./middlewares/BodyParser";
import { Router, Request, Response, NextFunction } from "express";
-import mongoose from "mongoose";
import path from "path";
import { initRateLimits } from "./middlewares/RateLimit";
import TestClient from "./middlewares/TestClient";
import { initTranslation } from "./middlewares/Translation";
import morgan from "morgan";
import { initInstance } from "./util/Instance";
+import { registerRoutes } from "@fosscord/util";
export interface FosscordServerOptions extends ServerOptions {}
@@ -75,12 +73,12 @@ export class FosscordServer extends Server {
await initRateLimits(api);
await initTranslation(api);
- this.routes = await this.registerRoutes(path.join(__dirname, "routes", "/"));
+ this.routes = await registerRoutes(this, path.join(__dirname, "routes", "/"));
api.use("*", (error: any, req: Request, res: Response, next: NextFunction) => {
if (error) return next(error);
res.status(404).json({
- message: "404: Not Found",
+ message: "404 endpoint not found",
code: 0
});
next();
diff --git a/api/src/middlewares/Authentication.ts b/api/src/middlewares/Authentication.ts
index 5a082751..59a181e6 100644
--- a/api/src/middlewares/Authentication.ts
+++ b/api/src/middlewares/Authentication.ts
@@ -9,6 +9,8 @@ export const NO_AUTHORIZATION_ROUTES = [
"/ping",
"/gateway",
"/experiments",
+ "/-/readyz",
+ "/-/healthz",
/\/guilds\/\d+\/widget\.(json|png)/
];
diff --git a/api/src/routes/-/healthz.ts b/api/src/routes/-/healthz.ts
new file mode 100644
index 00000000..a42575f8
--- /dev/null
+++ b/api/src/routes/-/healthz.ts
@@ -0,0 +1,17 @@
+import { Router, Response, Request } from "express";
+import { route } from "@fosscord/api";
+import { getConnection } from "typeorm";
+
+const router = Router();
+
+router.get("/", route({}), (req: Request, res: Response) => {
+ try {
+ // test that the database is alive & responding
+ getConnection();
+ return res.sendStatus(200);
+ } catch(e) {
+ res.sendStatus(503);
+ }
+});
+
+export default router;
diff --git a/api/src/routes/-/readyz.ts b/api/src/routes/-/readyz.ts
new file mode 100644
index 00000000..a42575f8
--- /dev/null
+++ b/api/src/routes/-/readyz.ts
@@ -0,0 +1,17 @@
+import { Router, Response, Request } from "express";
+import { route } from "@fosscord/api";
+import { getConnection } from "typeorm";
+
+const router = Router();
+
+router.get("/", route({}), (req: Request, res: Response) => {
+ try {
+ // test that the database is alive & responding
+ getConnection();
+ return res.sendStatus(200);
+ } catch(e) {
+ res.sendStatus(503);
+ }
+});
+
+export default router;
diff --git a/api/src/routes/channels/#channel_id/invites.ts b/api/src/routes/channels/#channel_id/invites.ts
index 22420983..6d2c625d 100644
--- a/api/src/routes/channels/#channel_id/invites.ts
+++ b/api/src/routes/channels/#channel_id/invites.ts
@@ -2,7 +2,7 @@ import { Router, Request, Response } from "express";
import { HTTPError } from "lambert-server";
import { route } from "@fosscord/api";
import { random } from "@fosscord/api";
-import { getPermission, Channel, Invite, InviteCreateEvent, emitEvent, User, Guild, PublicInviteRelation } from "@fosscord/util";
+import { Channel, Invite, InviteCreateEvent, emitEvent, User, Guild, PublicInviteRelation } from "@fosscord/util";
import { isTextChannel } from "./messages";
const router: Router = Router();
diff --git a/api/src/routes/channels/#channel_id/messages/index.ts b/api/src/routes/channels/#channel_id/messages/index.ts
index 4ec31417..296bec9a 100644
--- a/api/src/routes/channels/#channel_id/messages/index.ts
+++ b/api/src/routes/channels/#channel_id/messages/index.ts
@@ -10,7 +10,8 @@ import {
getPermission,
Message,
MessageCreateEvent,
- uploadFile
+ uploadFile,
+ Member
} from "@fosscord/util";
import { HTTPError } from "lambert-server";
import { handleMessage, postHandleMessage, route } from "@fosscord/api";
@@ -22,7 +23,7 @@ const router: Router = Router();
export default router;
-function isTextChannel(type: ChannelType): boolean {
+export function isTextChannel(type: ChannelType): boolean {
switch (type) {
case ChannelType.GUILD_STORE:
case ChannelType.GUILD_VOICE:
@@ -39,7 +40,6 @@ function isTextChannel(type: ChannelType): boolean {
return true;
}
}
-module.exports.isTextChannel = isTextChannel;
export interface MessageCreateSchema {
content?: string;
@@ -64,6 +64,7 @@ export interface MessageCreateSchema {
payload_json?: string;
file?: any;
attachments?: any[]; //TODO we should create an interface for attachments
+ sticker_ids?: string[];
}
// https://discord.com/developers/docs/resources/channel#create-message
@@ -187,33 +188,34 @@ router.post(
message = await message.save();
- await channel.assign({ last_message_id: message.id }).save();
-
if (channel.isDm()) {
const channel_dto = await DmChannelDTO.from(channel);
- for (let recipient of channel.recipients!) {
- if (recipient.closed) {
- await emitEvent({
- event: "CHANNEL_CREATE",
- data: channel_dto.excludedRecipients([recipient.user_id]),
- user_id: recipient.user_id
- });
- }
- }
-
//Only one recipients should be closed here, since in group DMs the recipient is deleted not closed
+
await Promise.all(
- channel
- .recipients!.filter((r) => r.closed)
- .map(async (r) => {
- r.closed = false;
- return await r.save();
- })
+ channel.recipients!.map((recipient) => {
+ if (recipient.closed) {
+ recipient.closed = false;
+ return Promise.all([
+ recipient.save(),
+ emitEvent({
+ event: "CHANNEL_CREATE",
+ data: channel_dto.excludedRecipients([recipient.user_id]),
+ user_id: recipient.user_id
+ })
+ ]);
+ }
+ })
);
}
- await emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent);
+ await Promise.all([
+ channel.assign({ last_message_id: message.id }).save(),
+ message.guild_id ? Member.update({ id: req.user_id, guild_id: message.guild_id }, { last_message_id: message.id }) : null,
+ emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent)
+ ]);
+
postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error
return res.json(message);
diff --git a/api/src/routes/channels/#channel_id/permissions.ts b/api/src/routes/channels/#channel_id/permissions.ts
index 6ebf721a..2eded853 100644
--- a/api/src/routes/channels/#channel_id/permissions.ts
+++ b/api/src/routes/channels/#channel_id/permissions.ts
@@ -44,8 +44,8 @@ router.put(
};
channel.permission_overwrites!.push(overwrite);
}
- overwrite.allow = String(req.permission!.bitfield & (BigInt(body.allow) || 0n));
- overwrite.deny = String(req.permission!.bitfield & (BigInt(body.deny) || 0n));
+ overwrite.allow = String(req.permission!.bitfield & (BigInt(body.allow) || BigInt("0")));
+ overwrite.deny = String(req.permission!.bitfield & (BigInt(body.deny) || BigInt("0")));
await Promise.all([
channel.save(),
diff --git a/api/src/routes/channels/#channel_id/typing.ts b/api/src/routes/channels/#channel_id/typing.ts
index 45ed76db..56652368 100644
--- a/api/src/routes/channels/#channel_id/typing.ts
+++ b/api/src/routes/channels/#channel_id/typing.ts
@@ -9,14 +9,13 @@ router.post("/", route({ permission: "SEND_MESSAGES" }), async (req: Request, re
const user_id = req.user_id;
const timestamp = Date.now();
const channel = await Channel.findOneOrFail({ id: channel_id });
- const member = await Member.findOneOrFail({ where: { id: user_id }, relations: ["roles", "user"] });
+ const member = await Member.findOne({ where: { id: user_id, guild_id: channel.guild_id }, relations: ["roles", "user"] });
await emitEvent({
event: "TYPING_START",
channel_id: channel_id,
data: {
- // this is the paylod
- member: { ...member, roles: member.roles?.map((x) => x.id) },
+ ...(member ? { member: { ...member, roles: member?.roles?.map((x) => x.id) } } : null),
channel_id,
timestamp,
user_id,
diff --git a/api/src/routes/gateway.ts b/api/src/routes/gateway/bot.ts
index 4b3a0ea6..72313700 100644
--- a/api/src/routes/gateway.ts
+++ b/api/src/routes/gateway/bot.ts
@@ -1,15 +1,29 @@
import { Config } from "@fosscord/util";
import { Router, Response, Request } from "express";
-import { route } from "@fosscord/api";
+import { route, RouteOptions } from "@fosscord/api";
const router = Router();
-router.get("/", route({}), (req: Request, res: Response) => {
- const { endpointPublic } = Config.get().gateway;
- res.json({ url: endpointPublic || process.env.GATEWAY || "ws://localhost:3002" });
-});
+export interface GatewayBotResponse {
+ url: string;
+ shards: number;
+ session_start_limit: {
+ total: number;
+ remaining: number;
+ reset_after: number;
+ max_concurrency: number;
+ }
+}
+
+const options: RouteOptions = {
+ test: {
+ response: {
+ body: "GatewayBotResponse"
+ }
+ }
+};
-router.get("/bot", route({}), (req: Request, res: Response) => {
+router.get("/", route(options), (req: Request, res: Response) => {
const { endpointPublic } = Config.get().gateway;
res.json({
url: endpointPublic || process.env.GATEWAY || "ws://localhost:3002",
diff --git a/api/src/routes/gateway/index.ts b/api/src/routes/gateway/index.ts
new file mode 100644
index 00000000..9bad7478
--- /dev/null
+++ b/api/src/routes/gateway/index.ts
@@ -0,0 +1,24 @@
+import { Config } from "@fosscord/util";
+import { Router, Response, Request } from "express";
+import { route, RouteOptions } from "@fosscord/api";
+
+const router = Router();
+
+export interface GatewayResponse {
+ url: string;
+}
+
+const options: RouteOptions = {
+ test: {
+ response: {
+ body: "GatewayResponse"
+ }
+ }
+};
+
+router.get("/", route(options), (req: Request, res: Response) => {
+ const { endpointPublic } = Config.get().gateway;
+ res.json({ url: endpointPublic || process.env.GATEWAY || "ws://localhost:3002" });
+});
+
+export default router;
diff --git a/api/src/routes/gifs/search.ts b/api/src/routes/gifs/search.ts
index 3cbff64f..45b3ddca 100644
--- a/api/src/routes/gifs/search.ts
+++ b/api/src/routes/gifs/search.ts
@@ -1,37 +1,24 @@
import { Router, Response, Request } from "express";
import fetch from "node-fetch";
import { route } from "@fosscord/api";
+import { getGifApiKey, parseGifResult } from "./trending";
const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
- // TODO: Custom providers and code quality
- const { q, media_format, locale, provider } = req.query;
+ // TODO: Custom providers
+ const { q, media_format, locale } = req.query;
- const parseResult = (result: any) => {
- return {
- id: result.id,
- title: result.title,
- url: result.itemurl,
- src: result.media[0].mp4.url,
- gif_src: result.media[0].gif.url,
- width: result.media[0].mp4.dims[0],
- height: result.media[0].mp4.dims[1],
- preview: result.media[0].mp4.preview
- };
- };
+ const apiKey = getGifApiKey();
- const response = await fetch(`https://g.tenor.com/v1/search?q=${q}&media_format=${media_format}&locale=${locale}&key=LIVDSRZULELA`, {
+ const response = await fetch(`https://g.tenor.com/v1/search?q=${q}&media_format=${media_format}&locale=${locale}&key=${apiKey}`, {
method: "get",
headers: { "Content-Type": "application/json" }
});
const { results } = await response.json();
- let cache = new Array() as any[];
- results.forEach((result: any) => {
- cache.push(parseResult(result));
- });
- res.json(cache).status(200);
+
+ res.json(results.map(parseGifResult)).status(200);
});
export default router;
diff --git a/api/src/routes/gifs/trending-gifs.ts b/api/src/routes/gifs/trending-gifs.ts
index 76e791fa..b5f87222 100644
--- a/api/src/routes/gifs/trending-gifs.ts
+++ b/api/src/routes/gifs/trending-gifs.ts
@@ -1,37 +1,24 @@
import { Router, Response, Request } from "express";
import fetch from "node-fetch";
import { route } from "@fosscord/api";
+import { getGifApiKey, parseGifResult } from "./trending";
const router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
- // TODO: Custom providers and code quality
- const { media_format, locale, provider } = req.query;
+ // TODO: Custom providers
+ const { media_format, locale } = req.query;
- const parseResult = (result: any) => {
- return {
- id: result.id,
- title: result.title,
- url: result.itemurl,
- src: result.media[0].mp4.url,
- gif_src: result.media[0].gif.url,
- width: result.media[0].mp4.dims[0],
- height: result.media[0].mp4.dims[1],
- preview: result.media[0].mp4.preview
- };
- };
+ const apiKey = getGifApiKey();
- const response = await fetch(`https://g.tenor.com/v1/trending?media_format=${media_format}&locale=${locale}&key=LIVDSRZULELA`, {
+ const response = await fetch(`https://g.tenor.com/v1/trending?media_format=${media_format}&locale=${locale}&key=${apiKey}`, {
method: "get",
headers: { "Content-Type": "application/json" }
});
const { results } = await response.json();
- let cache = new Array() as any[];
- results.forEach((result: any) => {
- cache.push(parseResult(result));
- });
- res.json(cache).status(200);
+
+ res.json(results.map(parseGifResult)).status(200);
});
export default router;
diff --git a/api/src/routes/gifs/trending.ts b/api/src/routes/gifs/trending.ts
index 3b91eb12..7ee9337e 100644
--- a/api/src/routes/gifs/trending.ts
+++ b/api/src/routes/gifs/trending.ts
@@ -1,48 +1,57 @@
import { Router, Response, Request } from "express";
import fetch from "node-fetch";
import { route } from "@fosscord/api";
+import { Config } from "@fosscord/util";
+import { HTTPError } from "lambert-server";
const router = Router();
-router.get("/", route({}), async (req: Request, res: Response) => {
- // TODO: Custom providers and code quality
- const { media_format, locale, provider } = req.query;
-
- const parseResult = (result: any) => {
- return {
- id: result.id,
- title: result.title,
- url: result.itemurl,
- src: result.media[0].mp4.url,
- gif_src: result.media[0].gif.url,
- width: result.media[0].mp4.dims[0],
- height: result.media[0].mp4.dims[1],
- preview: result.media[0].mp4.preview
- };
+export function parseGifResult(result: any) {
+ return {
+ id: result.id,
+ title: result.title,
+ url: result.itemurl,
+ src: result.media[0].mp4.url,
+ gif_src: result.media[0].gif.url,
+ width: result.media[0].mp4.dims[0],
+ height: result.media[0].mp4.dims[1],
+ preview: result.media[0].mp4.preview
};
+}
+
+export function getGifApiKey() {
+ const { enabled, provider, apiKey } = Config.get().gif;
+ if (!enabled) throw new HTTPError(`Gifs are disabled`);
+ if (provider !== "tenor" || !apiKey) throw new HTTPError(`${provider} gif provider not supported`);
- const responseSource = await fetch(`https://g.tenor.com/v1/categories?media_format=${media_format}&locale=${locale}&key=LIVDSRZULELA`, {
- method: "get",
- headers: { "Content-Type": "application/json" }
- });
+ return apiKey;
+}
- const trendGifSource = await fetch(`https://g.tenor.com/v1/trending?media_format=${media_format}&locale=${locale}&key=LIVDSRZULELA`, {
- method: "get",
- headers: { "Content-Type": "application/json" }
- });
+router.get("/", route({}), async (req: Request, res: Response) => {
+ // TODO: Custom providers
+ // TODO: return gifs as mp4
+ const { media_format, locale } = req.query;
+
+ const apiKey = getGifApiKey();
+
+ const [responseSource, trendGifSource] = await Promise.all([
+ fetch(`https://g.tenor.com/v1/categories?locale=${locale}&key=${apiKey}`, {
+ method: "get",
+ headers: { "Content-Type": "application/json" }
+ }),
+ fetch(`https://g.tenor.com/v1/trending?locale=${locale}&key=${apiKey}`, {
+ method: "get",
+ headers: { "Content-Type": "application/json" }
+ })
+ ]);
const { tags } = await responseSource.json();
const { results } = await trendGifSource.json();
- let cache = new Array() as any[];
-
- tags.forEach((result: any) => {
- cache.push({
- name: result.searchterm,
- src: result.image
- });
- });
- res.json({ categories: [cache], gifs: [parseResult(results[0])] }).status(200);
+ res.json({
+ categories: tags.map((x: any) => ({ name: x.searchterm, src: x.image })),
+ gifs: [parseGifResult(results[0])]
+ }).status(200);
});
export default router;
diff --git a/api/src/routes/guilds/#guild_id/channels.ts b/api/src/routes/guilds/#guild_id/channels.ts
index a36e5448..a921fa21 100644
--- a/api/src/routes/guilds/#guild_id/channels.ts
+++ b/api/src/routes/guilds/#guild_id/channels.ts
@@ -31,10 +31,10 @@ router.patch("/", route({ body: "ChannelReorderSchema", permission: "MANAGE_CHAN
await Promise.all([
body.map(async (x) => {
- if (!x.position && !x.parent_id) throw new HTTPError(`You need to at least specify position or parent_id`, 400);
+ if (x.position == null && !x.parent_id) throw new HTTPError(`You need to at least specify position or parent_id`, 400);
const opts: any = {};
- if (x.position) opts.position = x.position;
+ if (x.position != null) opts.position = x.position;
if (x.parent_id) {
opts.parent_id = x.parent_id;
diff --git a/api/src/routes/guilds/#guild_id/emojis.ts b/api/src/routes/guilds/#guild_id/emojis.ts
new file mode 100644
index 00000000..85d7ac05
--- /dev/null
+++ b/api/src/routes/guilds/#guild_id/emojis.ts
@@ -0,0 +1,118 @@
+import { Router, Request, Response } from "express";
+import { Config, DiscordApiErrors, emitEvent, Emoji, GuildEmojisUpdateEvent, handleFile, Member, Snowflake, User } from "@fosscord/util";
+import { route } from "@fosscord/api";
+
+const router = Router();
+
+export interface EmojiCreateSchema {
+ name?: string;
+ image: string;
+ require_colons?: boolean | null;
+ roles?: string[];
+}
+
+export interface EmojiModifySchema {
+ name?: string;
+ roles?: string[];
+}
+
+router.get("/", route({}), async (req: Request, res: Response) => {
+ const { guild_id } = req.params;
+
+ await Member.IsInGuildOrFail(req.user_id, guild_id);
+
+ const emojis = await Emoji.find({ where: { guild_id: guild_id }, relations: ["user"] });
+
+ return res.json(emojis);
+});
+
+router.get("/:emoji_id", route({}), async (req: Request, res: Response) => {
+ const { guild_id, emoji_id } = req.params;
+
+ await Member.IsInGuildOrFail(req.user_id, guild_id);
+
+ const emoji = await Emoji.findOneOrFail({ where: { guild_id: guild_id, id: emoji_id }, relations: ["user"] });
+
+ return res.json(emoji);
+});
+
+router.post("/", route({ body: "EmojiCreateSchema", permission: "MANAGE_EMOJIS_AND_STICKERS" }), async (req: Request, res: Response) => {
+ const { guild_id } = req.params;
+ const body = req.body as EmojiCreateSchema;
+
+ const id = Snowflake.generate();
+ const emoji_count = await Emoji.count({ guild_id: guild_id });
+ const { maxEmojis } = Config.get().limits.guild;
+
+ if (emoji_count >= maxEmojis) throw DiscordApiErrors.MAXIMUM_NUMBER_OF_EMOJIS_REACHED.withParams(maxEmojis);
+ if (body.require_colons == null) body.require_colons = true;
+
+ const user = await User.findOneOrFail({ id: req.user_id });
+ body.image = (await handleFile(`/emojis/${id}`, body.image)) as string;
+
+ const emoji = await new Emoji({
+ id: id,
+ guild_id: guild_id,
+ ...body,
+ user: user,
+ managed: false,
+ animated: false, // TODO: Add support animated emojis
+ available: true,
+ roles: []
+ }).save();
+
+ await emitEvent({
+ event: "GUILD_EMOJIS_UPDATE",
+ guild_id: guild_id,
+ data: {
+ guild_id: guild_id,
+ emojis: await Emoji.find({ guild_id: guild_id })
+ }
+ } as GuildEmojisUpdateEvent);
+
+ return res.status(201).json(emoji);
+});
+
+router.patch(
+ "/:emoji_id",
+ route({ body: "EmojiModifySchema", permission: "MANAGE_EMOJIS_AND_STICKERS" }),
+ async (req: Request, res: Response) => {
+ const { emoji_id, guild_id } = req.params;
+ const body = req.body as EmojiModifySchema;
+
+ const emoji = await new Emoji({ ...body, id: emoji_id, guild_id: guild_id }).save();
+
+ await emitEvent({
+ event: "GUILD_EMOJIS_UPDATE",
+ guild_id: guild_id,
+ data: {
+ guild_id: guild_id,
+ emojis: await Emoji.find({ guild_id: guild_id })
+ }
+ } as GuildEmojisUpdateEvent);
+
+ return res.json(emoji);
+ }
+);
+
+router.delete("/:emoji_id", route({ permission: "MANAGE_EMOJIS_AND_STICKERS" }), async (req: Request, res: Response) => {
+ const { emoji_id, guild_id } = req.params;
+
+ await Emoji.delete({
+ id: emoji_id,
+ guild_id: guild_id
+ });
+
+ await emitEvent({
+ event: "GUILD_EMOJIS_UPDATE",
+ guild_id: guild_id,
+ data: {
+ guild_id: guild_id,
+ emojis: await Emoji.find({ guild_id: guild_id })
+ }
+ } as GuildEmojisUpdateEvent);
+
+ res.sendStatus(204);
+});
+
+export default router;
diff --git a/api/src/routes/guilds/#guild_id/premium.ts b/api/src/routes/guilds/#guild_id/premium.ts
new file mode 100644
index 00000000..75361ac6
--- /dev/null
+++ b/api/src/routes/guilds/#guild_id/premium.ts
@@ -0,0 +1,10 @@
+import { Router, Request, Response } from "express";
+import { route } from "@fosscord/api";
+const router = Router();
+
+router.get("/subscriptions", route({}), async (req: Request, res: Response) => {
+ // TODO:
+ res.json([]);
+});
+
+export default router;
diff --git a/api/src/routes/guilds/#guild_id/prune.ts b/api/src/routes/guilds/#guild_id/prune.ts
new file mode 100644
index 00000000..92809985
--- /dev/null
+++ b/api/src/routes/guilds/#guild_id/prune.ts
@@ -0,0 +1,82 @@
+import { Router, Request, Response } from "express";
+import { Guild, Member, Snowflake } from "@fosscord/util";
+import { LessThan, IsNull } from "typeorm";
+import { route } from "@fosscord/api";
+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();
+ date.setDate(date.getDate() - days);
+ //Snowflake should have `generateFromTime` method? Or similar?
+ var minId = BigInt(date.valueOf() - Snowflake.EPOCH) << BigInt(22);
+
+ var members = await Member.find({
+ where: [
+ {
+ guild_id,
+ last_message_id: LessThan(minId.toString())
+ },
+ {
+ last_message_id: IsNull()
+ }
+ ],
+ relations: ["roles"]
+ });
+ console.log(members);
+ if (!members.length) return [];
+
+ //I'm sure I can do this in the above db query ( and it would probably be better to do so ), but oh well.
+ if (roles.length && members.length) members = members.filter((user) => user.roles?.some((role) => roles.includes(role.id)));
+
+ const me = await Member.findOneOrFail({ id: user_id, guild_id }, { relations: ["roles"] });
+ const myHighestRole = Math.max(...(me.roles?.map((x) => x.position) || []));
+
+ const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
+
+ members = members.filter(
+ (member) =>
+ member.id !== guild.owner_id && //can't kick owner
+ member.roles?.some(
+ (role) =>
+ role.position < myHighestRole || //roles higher than me can't be kicked
+ me.id === guild.owner_id //owner can kick anyone
+ )
+ );
+
+ return members;
+};
+
+router.get("/", route({ permission: "KICK_MEMBERS" }), async (req: Request, res: Response) => {
+ const days = parseInt(req.query.days as string);
+
+ var 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[]);
+
+ res.send({ pruned: members.length });
+});
+
+export interface PruneSchema {
+ /**
+ * @min 0
+ */
+ days: number;
+}
+
+router.post("/", route({ permission: "KICK_MEMBERS" }), async (req: Request, res: Response) => {
+ const days = parseInt(req.body.days);
+
+ var roles = req.query.include_roles;
+ if (typeof roles === "string") roles = [roles];
+
+ const { guild_id } = req.params;
+ const members = await inactiveMembers(guild_id, req.user_id, days, roles as string[]);
+
+ await Promise.all(members.map((x) => Member.removeFromGuild(x.id, guild_id)));
+
+ res.send({ purged: members.length });
+});
+
+export default router;
diff --git a/api/src/routes/guilds/#guild_id/roles.ts b/api/src/routes/guilds/#guild_id/roles.ts
index d1d60906..b1875598 100644
--- a/api/src/routes/guilds/#guild_id/roles.ts
+++ b/api/src/routes/guilds/#guild_id/roles.ts
@@ -17,7 +17,7 @@ const router: Router = Router();
export interface RoleModifySchema {
name?: string;
- permissions?: bigint;
+ permissions?: string;
color?: number;
hoist?: boolean; // whether the role should be displayed separately in the sidebar
mentionable?: boolean; // whether the role should be mentionable
@@ -57,7 +57,7 @@ router.post("/", route({ body: "RoleModifySchema", permission: "MANAGE_ROLES" })
...body,
guild_id: guild_id,
managed: false,
- permissions: String(req.permission!.bitfield & (body.permissions || 0n)),
+ permissions: String(req.permission!.bitfield & BigInt(body.permissions || "0")),
tags: undefined
});
@@ -105,7 +105,12 @@ router.patch("/:role_id", route({ body: "RoleModifySchema", permission: "MANAGE_
const { role_id, guild_id } = req.params;
const body = req.body as RoleModifySchema;
- const role = new Role({ ...body, id: role_id, guild_id, permissions: String(req.permission!.bitfield & (body.permissions || 0n)) });
+ const role = new Role({
+ ...body,
+ id: role_id,
+ guild_id,
+ permissions: String(req.permission!.bitfield & BigInt(body.permissions || "0"))
+ });
await Promise.all([
role.save(),
diff --git a/api/src/routes/guilds/#guild_id/stickers.ts b/api/src/routes/guilds/#guild_id/stickers.ts
new file mode 100644
index 00000000..4ea1dce1
--- /dev/null
+++ b/api/src/routes/guilds/#guild_id/stickers.ts
@@ -0,0 +1,135 @@
+import {
+ emitEvent,
+ GuildStickersUpdateEvent,
+ handleFile,
+ Member,
+ Snowflake,
+ Sticker,
+ StickerFormatType,
+ StickerType,
+ uploadFile
+} from "@fosscord/util";
+import { Router, Request, Response } from "express";
+import { route } from "@fosscord/api";
+import multer from "multer";
+import { HTTPError } from "lambert-server";
+const router = Router();
+
+router.get("/", route({}), async (req: Request, res: Response) => {
+ const { guild_id } = req.params;
+ await Member.IsInGuildOrFail(req.user_id, guild_id);
+
+ res.json(await Sticker.find({ guild_id }));
+});
+
+const bodyParser = multer({
+ limits: {
+ fileSize: 1024 * 1024 * 100,
+ fields: 10,
+ files: 1
+ },
+ storage: multer.memoryStorage()
+}).single("file");
+
+router.post(
+ "/",
+ bodyParser,
+ route({ permission: "MANAGE_EMOJIS_AND_STICKERS", body: "ModifyGuildStickerSchema" }),
+ async (req: Request, res: Response) => {
+ if (!req.file) throw new HTTPError("missing file");
+
+ const { guild_id } = req.params;
+ const body = req.body as ModifyGuildStickerSchema;
+ const id = Snowflake.generate();
+
+ const [sticker] = await Promise.all([
+ new Sticker({
+ ...body,
+ guild_id,
+ id,
+ type: StickerType.GUILD,
+ format_type: getStickerFormat(req.file.mimetype),
+ available: true
+ }).save(),
+ uploadFile(`/stickers/${id}`, req.file)
+ ]);
+
+ await sendStickerUpdateEvent(guild_id);
+
+ res.json(sticker);
+ }
+);
+
+export function getStickerFormat(mime_type: string) {
+ switch (mime_type) {
+ case "image/apng":
+ return StickerFormatType.APNG;
+ case "application/json":
+ return StickerFormatType.LOTTIE;
+ case "image/png":
+ return StickerFormatType.PNG;
+ case "image/gif":
+ return StickerFormatType.GIF;
+ default:
+ throw new HTTPError("invalid sticker format: must be png, apng or lottie");
+ }
+}
+
+router.get("/:sticker_id", route({}), async (req: Request, res: Response) => {
+ const { guild_id, sticker_id } = req.params;
+ await Member.IsInGuildOrFail(req.user_id, guild_id);
+
+ res.json(await Sticker.findOneOrFail({ guild_id, id: sticker_id }));
+});
+
+export interface ModifyGuildStickerSchema {
+ /**
+ * @minLength 2
+ * @maxLength 30
+ */
+ name: string;
+ /**
+ * @maxLength 100
+ */
+ description?: string;
+ /**
+ * @maxLength 200
+ */
+ tags: string;
+}
+
+router.patch(
+ "/:sticker_id",
+ route({ body: "ModifyGuildStickerSchema", permission: "MANAGE_EMOJIS_AND_STICKERS" }),
+ async (req: Request, res: Response) => {
+ const { guild_id, sticker_id } = req.params;
+ const body = req.body as ModifyGuildStickerSchema;
+
+ const sticker = await new Sticker({ ...body, guild_id, id: sticker_id }).save();
+ await sendStickerUpdateEvent(guild_id);
+
+ return res.json(sticker);
+ }
+);
+
+async function sendStickerUpdateEvent(guild_id: string) {
+ return emitEvent({
+ event: "GUILD_STICKERS_UPDATE",
+ guild_id: guild_id,
+ data: {
+ guild_id: guild_id,
+ stickers: await Sticker.find({ guild_id: guild_id })
+ }
+ } as GuildStickersUpdateEvent);
+}
+
+router.delete("/:sticker_id", route({ permission: "MANAGE_EMOJIS_AND_STICKERS" }), async (req: Request, res: Response) => {
+ const { guild_id, sticker_id } = req.params;
+
+ await Sticker.delete({ guild_id, id: sticker_id });
+ await sendStickerUpdateEvent(guild_id);
+
+ return res.sendStatus(204);
+});
+
+export default router;
diff --git a/api/src/routes/guilds/#guild_id/vanity-url.ts b/api/src/routes/guilds/#guild_id/vanity-url.ts
index 7f2cea9e..63173345 100644
--- a/api/src/routes/guilds/#guild_id/vanity-url.ts
+++ b/api/src/routes/guilds/#guild_id/vanity-url.ts
@@ -10,10 +10,10 @@ const InviteRegex = /\W/g;
router.get("/", route({ permission: "MANAGE_GUILD" }), async (req: Request, res: Response) => {
const { guild_id } = req.params;
- const guild = await Guild.findOneOrFail({ where: { id: guild_id }, relations: ["vanity_url"] });
- if (!guild.vanity_url) return res.json({ code: null });
+ const invite = await Invite.findOne({ where: { guild_id: guild_id, vanity_url: true } });
+ if (!invite) return res.json({ code: null });
- return res.json({ code: guild.vanity_url_code, uses: guild.vanity_url.uses });
+ return res.json({ code: invite.code, uses: invite.uses });
});
export interface VanityUrlSchema {
@@ -33,20 +33,9 @@ router.patch("/", route({ body: "VanityUrlSchema", permission: "MANAGE_GUILD" })
const invite = await Invite.findOne({ code });
if (invite) throw new HTTPError("Invite already exists");
- const guild = await Guild.findOneOrFail({ id: guild_id });
const { id } = await Channel.findOneOrFail({ guild_id, type: ChannelType.GUILD_TEXT });
- Promise.all([
- Guild.update({ id: guild_id }, { vanity_url_code: code }),
- Invite.delete({ code: guild.vanity_url_code }),
- new Invite({
- code: code,
- uses: 0,
- created_at: new Date(),
- guild_id,
- channel_id: id
- }).save()
- ]);
+ await Invite.update({ vanity_url: true, guild_id }, { code: code, channel_id: id });
return res.json({ code: code });
});
diff --git a/api/src/routes/guilds/templates/index.ts b/api/src/routes/guilds/templates/index.ts
index b5e243e9..86316d23 100644
--- a/api/src/routes/guilds/templates/index.ts
+++ b/api/src/routes/guilds/templates/index.ts
@@ -47,7 +47,7 @@ router.post("/:code", route({ body: "GuildTemplateCreateSchema" }), async (req:
managed: true,
mentionable: true,
name: "@everyone",
- permissions: 2251804225n,
+ permissions: BigInt("2251804225"),
position: 0,
tags: null
}).save()
diff --git a/api/src/routes/invites/index.ts b/api/src/routes/invites/index.ts
index 0fcf7c86..185311bc 100644
--- a/api/src/routes/invites/index.ts
+++ b/api/src/routes/invites/index.ts
@@ -33,7 +33,6 @@ router.delete("/:code", route({}), async (req: Request, res: Response) => {
await Promise.all([
Invite.delete({ code }),
- Guild.update({ vanity_url_code: code }, { vanity_url_code: undefined }),
emitEvent({
event: "INVITE_DELETE",
guild_id: guild_id,
diff --git a/api/src/routes/sticker-packs/#id/index.ts b/api/src/routes/sticker-packs/#id/index.ts
deleted file mode 100644
index 7f723e97..00000000
--- a/api/src/routes/sticker-packs/#id/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { Request, Response, Router } from "express";
-import { route } from "@fosscord/api";
-
-const router: Router = Router();
-
-router.get("/", route({}), async (req: Request, res: Response) => {
- //TODO
- res.json({
- id: "",
- stickers: [],
- name: "",
- sku_id: "",
- cover_sticker_id: "",
- description: "",
- banner_asset_id: ""
- }).status(200);
-});
-
-export default router;
diff --git a/api/src/routes/sticker-packs/index.ts b/api/src/routes/sticker-packs/index.ts
index d671c161..e6560d12 100644
--- a/api/src/routes/sticker-packs/index.ts
+++ b/api/src/routes/sticker-packs/index.ts
@@ -1,11 +1,13 @@
import { Request, Response, Router } from "express";
import { route } from "@fosscord/api";
+import { StickerPack } from "@fosscord/util";
const router: Router = Router();
router.get("/", route({}), async (req: Request, res: Response) => {
- //TODO
- res.json({ sticker_packs: [] }).status(200);
+ const sticker_packs = await StickerPack.find({ relations: ["stickers"] });
+
+ res.json({ sticker_packs });
});
export default router;
diff --git a/api/src/routes/stickers/#sticker_id/index.ts b/api/src/routes/stickers/#sticker_id/index.ts
new file mode 100644
index 00000000..293ca089
--- /dev/null
+++ b/api/src/routes/stickers/#sticker_id/index.ts
@@ -0,0 +1,12 @@
+import { Sticker } from "@fosscord/util";
+import { Router, Request, Response } from "express";
+import { route } from "@fosscord/api";
+const router = Router();
+
+router.get("/", route({}), async (req: Request, res: Response) => {
+ const { sticker_id } = req.params;
+
+ res.json(await Sticker.find({ id: sticker_id }));
+});
+
+export default router;
diff --git a/api/src/routes/template.ts.disabled b/api/src/routes/template.ts.disabled
index ad785f10..fcc59ef4 100644
--- a/api/src/routes/template.ts.disabled
+++ b/api/src/routes/template.ts.disabled
@@ -1,10 +1,11 @@
//TODO: this is a template for a generic route
import { Router, Request, Response } from "express";
+import { route } from "@fosscord/api";
const router = Router();
-router.get("/", async (req: Request, res: Response) => {
- res.send({});
+router.get("/",route({}), async (req: Request, res: Response) => {
+ res.json({});
});
export default router;
diff --git a/api/src/routes/users/@me/settings.ts b/api/src/routes/users/@me/settings.ts
index 4e014126..b22b72fb 100644
--- a/api/src/routes/users/@me/settings.ts
+++ b/api/src/routes/users/@me/settings.ts
@@ -10,8 +10,9 @@ router.patch("/", route({ body: "UserSettingsSchema" }), async (req: Request, re
const body = req.body as UserSettings;
if (body.locale === "en") body.locale = "en-US"; // fix discord client crash on unkown locale
- // only users can update user settings
- await User.update({ id: req.user_id, bot: false }, { settings: body });
+ const user = await User.findOneOrFail({ id: req.user_id, bot: false });
+ user.settings = { ...user.settings, ...body };
+ await user.save();
res.sendStatus(204);
});
diff --git a/api/src/test/jwt.ts b/api/src/test/jwt.ts
deleted file mode 100644
index bdad513b..00000000
--- a/api/src/test/jwt.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-const jwa = require("jwa");
-
-var STR64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split("");
-
-function base64url(string: string, encoding: string) {
- // @ts-ignore
- return Buffer.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
-}
-
-function to64String(input: number, current = ""): string {
- if (input < 0 && current.length == 0) {
- input = input * -1;
- }
- var modify = input % 64;
- var remain = Math.floor(input / 64);
- var result = STR64[modify] + current;
- return remain <= 0 ? result : to64String(remain, result);
-}
-
-function to64Parse(input: string) {
- var result = 0;
- var toProc = input.split("");
- var e;
- for (e in toProc) {
- result = result * 64 + STR64.indexOf(toProc[e]);
- }
- return result;
-}
-
-// @ts-ignore
-const start = `${base64url("311129357362135041")}.${to64String(Date.now())}`;
-const signature = jwa("HS256").sign(start, `test`);
-const token = `${start}.${signature}`;
-console.log(token);
-
-// MzExMTI5MzU3MzYyMTM1MDQx.XdQb_rA.907VgF60kocnOTl32MSUWGSSzbAytQ0jbt36KjLaxuY
-// MzExMTI5MzU3MzYyMTM1MDQx.XdQbaPy.4vGx4L7IuFJGsRe6IL3BeybLIvbx4Vauvx12pwNsy2U
diff --git a/api/src/test/jwt2.ts b/api/src/test/jwt2.ts
deleted file mode 100644
index e231233d..00000000
--- a/api/src/test/jwt2.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import jwt from "jsonwebtoken";
-
-const algorithm = "HS256";
-const iat = Math.floor(Date.now() / 1000);
-
-// @ts-ignore
-const token = jwt.sign({ id: "311129357362135041" }, "secret", {
- algorithm,
-});
-console.log(token);
-
-const decoded = jwt.verify(token, "secret", { algorithms: [algorithm] });
-console.log(decoded);
diff --git a/api/src/test/password_test.ts b/api/src/test/password_test.ts
deleted file mode 100644
index 983b18ae..00000000
--- a/api/src/test/password_test.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { checkPassword } from "@fosscord/api";
-
-console.log(checkPassword("123456789012345"));
-// -> 0.25
-console.log(checkPassword("ABCDEFGHIJKLMOPQ"));
-// -> 0.25
-console.log(checkPassword("ABC123___...123"));
-// ->
-console.log(checkPassword(""));
-// ->
-// console.log(checkPassword(""));
-// // ->
diff --git a/api/src/util/Instance.ts b/api/src/util/Instance.ts
index a7b3205a..6bddfa98 100644
--- a/api/src/util/Instance.ts
+++ b/api/src/util/Instance.ts
@@ -1,4 +1,4 @@
-import { Config, Guild } from "@fosscord/util";
+import { Config, Guild, Session } from "@fosscord/util";
export async function initInstance() {
// TODO: clean up database and delete tombstone data
@@ -8,11 +8,14 @@ export async function initInstance() {
// TODO: check if any current user is not part of autoJoinGuilds
const { autoJoin } = Config.get().guild;
- if (autoJoin.enabled && autoJoin.guilds?.length) {
+ if (autoJoin.enabled && !autoJoin.guilds?.length) {
let guild = await Guild.findOne({});
- if (!guild) guild = await Guild.createGuild({});
-
- // @ts-ignore
- await Config.set({ guild: { autoJoin: { guilds: [guild.id] } } });
+ if (guild) {
+ // @ts-ignore
+ await Config.set({ guild: { autoJoin: { guilds: [guild.id] } } });
+ }
}
+
+ // TODO: do no clear sessions for instance cluster
+ await Session.delete({});
}
diff --git a/api/src/util/Message.ts b/api/src/util/Message.ts
index f8230124..d14d3aa2 100644
--- a/api/src/util/Message.ts
+++ b/api/src/util/Message.ts
@@ -24,7 +24,8 @@ import fetch from "node-fetch";
import cheerio from "cheerio";
import { MessageCreateSchema } from "../routes/channels/#channel_id/messages";
-// TODO: check webhook, application, system author
+// TODO: check webhook, application, system author, stickers
+// TODO: embed gifs/videos/images
const LINK_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
@@ -45,6 +46,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
const message = new Message({
...opts,
+ sticker_items: opts.sticker_ids?.map((x) => ({ id: x })),
guild_id: channel.guild_id,
channel_id: opts.channel_id,
attachments: opts.attachments || [],
@@ -81,7 +83,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
}
// TODO: stickers/activity
- if (!opts.content && !opts.embeds?.length && !opts.attachments?.length) {
+ if (!opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length) {
throw new HTTPError("Empty messages are not allowed", 50006);
}
|