95 lines
2.8 KiB
TypeScript
95 lines
2.8 KiB
TypeScript
import express from 'express';
|
|
import { engine } from 'express-handlebars';
|
|
import * as log from '../lib/log';
|
|
import { CustomItem, Session, db } from '../lib/db';
|
|
import { defaultItems } from '../lib/rpg/items';
|
|
import { Client, CDN } from 'discord.js';
|
|
import { getToken, getSessionString, getSession, setSession, updateCookie } from './oauth2';
|
|
import { getUser, getGuilds } from './user';
|
|
|
|
export async function startServer(bot: Client, port: number) {
|
|
const app = express();
|
|
const cdn = new CDN();
|
|
|
|
app.engine('handlebars', engine());
|
|
app.set('view engine', 'handlebars');
|
|
app.set('views', './views');
|
|
|
|
app.get('/api/items', async (req, res) => {
|
|
const guildID = req.query.guild;
|
|
|
|
let customItems : Partial<CustomItem>[];
|
|
if (guildID) {
|
|
customItems = await db<CustomItem>('customItems')
|
|
.select('emoji', 'name', 'id', 'description')
|
|
.where('guild', guildID)
|
|
.limit(25);
|
|
} else {
|
|
customItems = [];
|
|
}
|
|
|
|
res.json([...defaultItems, ...customItems]);
|
|
});
|
|
|
|
app.get('/api/status', async (_, res) => {
|
|
res.json({
|
|
guilds: bot.guilds.cache.size,
|
|
uptime: bot.uptime
|
|
});
|
|
});
|
|
|
|
app.get('/', async (req, res) => {
|
|
const code = req.query.code as string;
|
|
|
|
if (code) {
|
|
try {
|
|
const resp = await getToken(bot, code);
|
|
if (!resp) return res.status(400).send('Invalid code provided');
|
|
|
|
const sessionId = await getSessionString(decodeURIComponent(req.headers.cookie || ''));
|
|
|
|
setSession(sessionId, {
|
|
tokenType: resp.token_type,
|
|
accessToken: resp.access_token,
|
|
refreshToken: resp.refresh_token,
|
|
expiresAt: Date.now() + resp.expires_in * 1000,
|
|
});
|
|
|
|
updateCookie(res, sessionId);
|
|
|
|
return res.redirect('/profile');
|
|
} catch (err) {
|
|
log.error(err);
|
|
return res.status(500);
|
|
}
|
|
}
|
|
|
|
const session = await getSession(bot, req.headers);
|
|
const user = await getUser(session);
|
|
|
|
res.render('home', {
|
|
signedIn: session !== undefined,
|
|
username: user?.global_name,
|
|
avatar: user?.avatar ? cdn.avatar(user.id, user.avatar, { size: 128 }) : null,
|
|
layout: false,
|
|
});
|
|
});
|
|
|
|
app.get('/profile', async (req, res) => {
|
|
const session = await getSession(bot, req.headers);
|
|
if (!session) return res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${bot.config.clientId}&redirect_uri=${encodeURIComponent(bot.config.siteURL)}&response_type=code&scope=identify%20guilds`);
|
|
|
|
const user = await getUser(session);
|
|
const guilds = await getGuilds(session);
|
|
|
|
//res.sendFile('profile/index.html', { root: 'static/' });
|
|
res.json({
|
|
user,
|
|
guilds
|
|
});
|
|
});
|
|
|
|
app.use(express.static('static/'));
|
|
|
|
app.listen(port, () => log.info(`web interface listening on ${port}`));
|
|
} |