chore: remove semi

This commit is contained in:
Katie Thornhill 2019-11-19 23:06:33 -05:00
parent 4b75eaa0ab
commit 8fcc0dcbf9
No known key found for this signature in database
GPG key ID: F76EDC6541A99644
64 changed files with 1073 additions and 1073 deletions

View file

@ -1,3 +1,3 @@
module.exports = {
extends: 'standard',
};
}

View file

@ -5,5 +5,5 @@ module.exports = {
singleQuote: true,
trailingComma: 'es5',
bracketSpacing: true,
semi: true,
};
semi: false,
}

View file

@ -1,38 +1,38 @@
const log = new (require('./logger'))('Roleypoly');
const Sequelize = require('sequelize');
const fetchModels = require('./models');
const fetchApis = require('./api');
const log = new (require('./logger'))('Roleypoly')
const Sequelize = require('sequelize')
const fetchModels = require('./models')
const fetchApis = require('./api')
class Roleypoly {
constructor(router, io, app) {
this.router = router;
this.io = io;
this.ctx = {};
this.router = router
this.io = io
this.ctx = {}
this.ctx.config = {
appUrl: process.env.APP_URL,
};
}
this.ctx.io = io;
this.__app = app;
this.ctx.io = io
this.__app = app
if (log.debugOn) log.warn('debug mode is on');
if (log.debugOn) log.warn('debug mode is on')
this.__initialized = this._mountServices();
this.__initialized = this._mountServices()
}
async awaitServices() {
await this.__initialized;
await this.__initialized
}
async _mountServices() {
const sequelize = new Sequelize(process.env.DB_URL, {
logging: log.sql.bind(log, log),
});
this.ctx.sql = sequelize;
this.M = fetchModels(sequelize);
this.ctx.M = this.M;
await sequelize.sync();
})
this.ctx.sql = sequelize
this.M = fetchModels(sequelize)
this.ctx.M = this.M
await sequelize.sync()
// this.ctx.redis = new (require('ioredis'))({
// port: process.env.REDIS_PORT || '6379',
@ -42,16 +42,16 @@ class Roleypoly {
// enableReadyCheck: true,
// enableOfflineQueue: true
// })
this.ctx.server = new (require('./services/server'))(this.ctx);
this.ctx.discord = new (require('./services/discord'))(this.ctx);
this.ctx.sessions = new (require('./services/sessions'))(this.ctx);
this.ctx.P = new (require('./services/presentation'))(this.ctx);
this.ctx.server = new (require('./services/server'))(this.ctx)
this.ctx.discord = new (require('./services/discord'))(this.ctx)
this.ctx.sessions = new (require('./services/sessions'))(this.ctx)
this.ctx.P = new (require('./services/presentation'))(this.ctx)
}
async mountRoutes() {
fetchApis(this.router, this.ctx);
this.__app.use(this.router.middleware());
fetchApis(this.router, this.ctx)
this.__app.use(this.router.middleware())
}
}
module.exports = Roleypoly;
module.exports = Roleypoly

View file

@ -1,76 +1,76 @@
module.exports = (R, $) => {
R.post('/api/auth/token', async ctx => {
const { token } = ctx.request.body;
const { token } = ctx.request.body
if (token == null || token === '') {
ctx.body = { err: 'token_missing' };
ctx.status = 400;
return;
ctx.body = { err: 'token_missing' }
ctx.status = 400
return
}
if (ctx.session.accessToken === undefined || ctx.session.expiresAt < Date.now()) {
const data = await $.discord.getAuthToken(token);
ctx.session.accessToken = data.access_token;
ctx.session.refreshToken = data.refresh_token;
ctx.session.expiresAt = Date.now() + (ctx.expires_in || 1000 * 60 * 60 * 24);
const data = await $.discord.getAuthToken(token)
ctx.session.accessToken = data.access_token
ctx.session.refreshToken = data.refresh_token
ctx.session.expiresAt = Date.now() + (ctx.expires_in || 1000 * 60 * 60 * 24)
}
const user = await $.discord.getUser(ctx.session.accessToken);
ctx.session.userId = user.id;
ctx.session.avatarHash = user.avatar;
const user = await $.discord.getUser(ctx.session.accessToken)
ctx.session.userId = user.id
ctx.session.avatarHash = user.avatar
ctx.body = {
id: user.id,
avatar: user.avatar,
username: user.username,
discriminator: user.discriminator,
};
});
}
})
R.get('/api/auth/user', async ctx => {
if (ctx.session.accessToken === undefined) {
ctx.body = { err: 'not_logged_in' };
ctx.status = 401;
return;
ctx.body = { err: 'not_logged_in' }
ctx.status = 401
return
}
const user = await $.discord.getUser(ctx.session.accessToken);
ctx.session.userId = user.id;
ctx.session.avatarHash = user.avatar;
const user = await $.discord.getUser(ctx.session.accessToken)
ctx.session.userId = user.id
ctx.session.avatarHash = user.avatar
ctx.body = {
id: user.id,
avatar: user.avatar,
username: user.username,
discriminator: user.discriminator,
};
});
}
})
R.get('/api/auth/redirect', ctx => {
const url = $.discord.getAuthUrl();
const url = $.discord.getAuthUrl()
if (ctx.query.url === '✔️') {
ctx.body = { url };
return;
ctx.body = { url }
return
}
ctx.redirect(url);
});
ctx.redirect(url)
})
R.post('/api/auth/logout', ctx => {
ctx.session = null;
});
ctx.session = null
})
R.get('/api/oauth/bot', ctx => {
const url = $.discord.getBotJoinUrl();
const url = $.discord.getBotJoinUrl()
if (ctx.query.url === '✔️') {
ctx.body = { url };
return;
ctx.body = { url }
return
}
ctx.redirect(url);
});
ctx.redirect(url)
})
R.get('/api/oauth/bot/callback', ctx => {
console.log(ctx.request);
});
};
console.log(ctx.request)
})
}

View file

@ -1,22 +1,22 @@
const log = new (require('../logger'))('api/index');
const glob = require('glob');
const log = new (require('../logger'))('api/index')
const glob = require('glob')
const PROD = process.env.NODE_ENV === 'production';
const PROD = process.env.NODE_ENV === 'production'
module.exports = async (router, ctx) => {
const apis = glob.sync(`./api/**/!(index).js`);
log.debug('found apis', apis);
const apis = glob.sync(`./api/**/!(index).js`)
log.debug('found apis', apis)
for (let a of apis) {
if (a.endsWith('_test.js') && PROD) {
log.debug(`skipping ${a}`);
continue;
log.debug(`skipping ${a}`)
continue
}
log.debug(`mounting ${a}`);
log.debug(`mounting ${a}`)
try {
require(a.replace('api/', ''))(router, ctx);
require(a.replace('api/', ''))(router, ctx)
} catch (e) {
log.error(`couldn't mount ${a}`, e);
log.error(`couldn't mount ${a}`, e)
}
}
};
}

View file

@ -1,91 +1,91 @@
module.exports = (R, $) => {
R.get('/api/servers', async ctx => {
try {
const { userId } = ctx.session;
const srv = $.discord.getRelevantServers(userId);
const presentable = await $.P.presentableServers(srv, userId);
const { userId } = ctx.session
const srv = $.discord.getRelevantServers(userId)
const presentable = await $.P.presentableServers(srv, userId)
ctx.body = presentable;
ctx.body = presentable
} catch (e) {
console.error(e.trace || e.stack);
console.error(e.trace || e.stack)
}
});
})
R.get('/api/server/:id', async ctx => {
const { userId } = ctx.session;
const { id } = ctx.params;
const { userId } = ctx.session
const { id } = ctx.params
const srv = $.discord.client.guilds.get(id);
const srv = $.discord.client.guilds.get(id)
if (srv == null) {
ctx.body = { err: 'not found' };
ctx.status = 404;
return;
ctx.body = { err: 'not found' }
ctx.status = 404
return
}
let gm;
let gm
if (srv.members.has(userId)) {
gm = $.discord.gm(id, userId);
gm = $.discord.gm(id, userId)
} else if ($.discord.isRoot(userId)) {
gm = $.discord.fakeGm({ id: userId });
gm = $.discord.fakeGm({ id: userId })
} else {
ctx.body = { err: 'not_a_member' };
ctx.status = 400;
return;
ctx.body = { err: 'not_a_member' }
ctx.status = 400
return
}
const server = await $.P.presentableServer(srv, gm);
const server = await $.P.presentableServer(srv, gm)
ctx.body = server;
});
ctx.body = server
})
R.get('/api/server/:id/slug', async ctx => {
const { userId } = ctx.session;
const { id } = ctx.params;
const { userId } = ctx.session
const { id } = ctx.params
const srv = $.discord.client.guilds.get(id);
const srv = $.discord.client.guilds.get(id)
console.log(srv);
console.log(srv)
if (srv == null) {
ctx.body = { err: 'not found' };
ctx.status = 404;
return;
ctx.body = { err: 'not found' }
ctx.status = 404
return
}
ctx.body = await $.P.serverSlug(srv);
});
ctx.body = await $.P.serverSlug(srv)
})
R.patch('/api/server/:id', async ctx => {
const { userId } = ctx.session;
const { id } = ctx.params;
const { userId } = ctx.session
const { id } = ctx.params
let gm = $.discord.gm(id, userId);
let gm = $.discord.gm(id, userId)
if (gm == null && $.discord.isRoot(userId)) {
gm = $.discord.fakeGm({ id: userId });
gm = $.discord.fakeGm({ id: userId })
}
// check perms
if (!$.discord.getPermissions(gm).canManageRoles) {
ctx.status = 403;
ctx.body = { err: 'cannot_manage_roles' };
return;
ctx.status = 403
ctx.body = { err: 'cannot_manage_roles' }
return
}
const { message = null, categories = null } = ctx.request.body;
const { message = null, categories = null } = ctx.request.body
// todo make less nasty
await $.server.update(id, {
...(message != null ? { message } : {}),
...(categories != null ? { categories } : {}),
});
})
ctx.body = { ok: true };
});
ctx.body = { ok: true }
})
R.get('/api/admin/servers', async ctx => {
const { userId } = ctx.session;
const { userId } = ctx.session
if (!$.discord.isRoot(userId)) {
return;
return
}
ctx.body = $.discord.client.guilds.map(g => ({
@ -93,16 +93,16 @@ module.exports = (R, $) => {
name: g.name,
members: g.members.array().length,
roles: g.roles.array().length,
}));
});
}))
})
R.patch('/api/servers/:server/roles', async ctx => {
const { userId } = ctx.session;
const { server } = ctx.params;
const { userId } = ctx.session
const { server } = ctx.params
let gm = $.discord.gm(server, userId);
let gm = $.discord.gm(server, userId)
if (gm == null && $.discord.isRoot(userId)) {
gm = $.discord.fakeGm({ id: userId });
gm = $.discord.fakeGm({ id: userId })
}
// check perms
@ -112,24 +112,24 @@ module.exports = (R, $) => {
// return
// }
const { added, removed } = ctx.request.body;
const { added, removed } = ctx.request.body
const allowedRoles = await $.server.getAllowedRoles(server);
const allowedRoles = await $.server.getAllowedRoles(server)
const pred = r => $.discord.safeRole(server, r) && allowedRoles.indexOf(r) !== -1;
const pred = r => $.discord.safeRole(server, r) && allowedRoles.indexOf(r) !== -1
if (added.length > 0) {
gm = await gm.addRoles(added.filter(pred));
gm = await gm.addRoles(added.filter(pred))
}
setTimeout(() => {
if (removed.length > 0) {
gm.removeRoles(removed.filter(pred));
gm.removeRoles(removed.filter(pred))
}
}, 1000);
}, 1000)
// console.log('role patch', { added, removed, allowedRoles, addedFiltered: added.filterNot(pred), removedFiltered: removed.filterNot(pred) })
ctx.body = { ok: true };
});
};
ctx.body = { ok: true }
})
}

View file

@ -1,26 +1,26 @@
module.exports = (R, $) => {
R.get('/api/~/relevant-servers/:user', (ctx, next) => {
// ctx.body = 'ok'
const srv = $.discord.getRelevantServers(ctx.params.user);
ctx.body = $.discord.presentableServers(srv, ctx.params.user);
return;
});
const srv = $.discord.getRelevantServers(ctx.params.user)
ctx.body = $.discord.presentableServers(srv, ctx.params.user)
return
})
R.get('/api/~/roles/:id/:userId', (ctx, next) => {
// ctx.body = 'ok'
const { id, userId } = ctx.params;
const { id, userId } = ctx.params
const srv = $.discord.client.guilds.get(id);
const srv = $.discord.client.guilds.get(id)
if (srv === undefined) {
ctx.body = { err: 'not found' };
ctx.status = 404;
return;
ctx.body = { err: 'not found' }
ctx.status = 404
return
}
const gm = srv.members.get(userId);
const roles = $.discord.presentableRoles(id, gm);
const gm = srv.members.get(userId)
const roles = $.discord.presentableRoles(id, gm)
ctx.boy = roles;
});
};
ctx.boy = roles
})
}

View file

@ -1,96 +1,96 @@
require('dotenv').config({ silent: true });
const log = new (require('./logger'))('index');
require('dotenv').config({ silent: true })
const log = new (require('./logger'))('index')
const http = require('http');
const Koa = require('koa');
const app = new Koa();
const _io = require('socket.io');
const fs = require('fs');
const path = require('path');
const router = require('koa-better-router')().loadMethods();
const Roleypoly = require('./Roleypoly');
const ksuid = require('ksuid');
const http = require('http')
const Koa = require('koa')
const app = new Koa()
const _io = require('socket.io')
const fs = require('fs')
const path = require('path')
const router = require('koa-better-router')().loadMethods()
const Roleypoly = require('./Roleypoly')
const ksuid = require('ksuid')
// monkey patch async-reduce because F U T U R E
Array.prototype.areduce = async function(predicate, acc = []) {
// eslint-disable-line
for (let i of this) {
acc = await predicate(acc, i);
acc = await predicate(acc, i)
}
return acc;
};
return acc
}
Array.prototype.filterNot =
Array.prototype.filterNot ||
function(predicate) {
return this.filter(v => !predicate(v));
};
return this.filter(v => !predicate(v))
}
// Create the server and socket.io server
const server = http.createServer(app.callback());
const io = _io(server, { transports: ['websocket'], path: '/api/socket.io' });
const server = http.createServer(app.callback())
const io = _io(server, { transports: ['websocket'], path: '/api/socket.io' })
const M = new Roleypoly(router, io, app); // eslint-disable-line no-unused-vars
const M = new Roleypoly(router, io, app) // eslint-disable-line no-unused-vars
app.keys = [process.env.APP_KEY];
app.keys = [process.env.APP_KEY]
const DEVEL = process.env.NODE_ENV === 'development';
const DEVEL = process.env.NODE_ENV === 'development'
async function start() {
await M.awaitServices();
await M.awaitServices()
// body parser
const bodyParser = require('koa-bodyparser');
app.use(bodyParser({ types: ['json'] }));
const bodyParser = require('koa-bodyparser')
app.use(bodyParser({ types: ['json'] }))
// Compress
const compress = require('koa-compress');
app.use(compress());
const compress = require('koa-compress')
app.use(compress())
// SPA + Static
if (process.env.NODE_ENV === 'production') {
const pub = path.resolve(path.join(__dirname, 'public'));
log.info('public path', pub);
const pub = path.resolve(path.join(__dirname, 'public'))
log.info('public path', pub)
const staticFiles = require('koa-static');
const staticFiles = require('koa-static')
// app.use(staticFiles(pub, { defer: true, gzip: true, br: true }))
const send = require('koa-send');
const send = require('koa-send')
app.use(async (ctx, next) => {
if (ctx.path.startsWith('/api')) {
log.info('api breakout');
return next();
log.info('api breakout')
return next()
}
const chkPath = path.resolve(path.join(pub, ctx.path));
log.info('chkPath', chkPath);
const chkPath = path.resolve(path.join(pub, ctx.path))
log.info('chkPath', chkPath)
if (!chkPath.startsWith(pub)) {
return next();
return next()
}
try {
fs.statSync(chkPath);
log.info('sync pass');
ctx.body = fs.readFileSync(chkPath);
ctx.type = path.extname(ctx.path);
log.info('body sent');
ctx.status = 200;
return next();
fs.statSync(chkPath)
log.info('sync pass')
ctx.body = fs.readFileSync(chkPath)
ctx.type = path.extname(ctx.path)
log.info('body sent')
ctx.status = 200
return next()
} catch (e) {
log.warn('failed');
log.warn('failed')
if (ctx.path.startsWith('/static/')) {
return next();
return next()
}
try {
ctx.body = fs.readFileSync(path.join(pub, 'index.html'), { encoding: 'utf-8' });
ctx.body = fs.readFileSync(path.join(pub, 'index.html'), { encoding: 'utf-8' })
} catch (e) {
ctx.body = e.stack || e.trace;
ctx.status = 500;
ctx.body = e.stack || e.trace
ctx.status = 500
}
log.info('index sent');
ctx.status = 200;
return next();
log.info('index sent')
ctx.status = 200
return next()
}
// try {
@ -98,7 +98,7 @@ async function start() {
// } catch (e) {
// send(ctx, 'index.html', { root: pub })
// }
});
})
// const sendOpts = {root: pub, index: 'index.html'}
// // const sendOpts = {}
// app.use(async (ctx, next) => {
@ -123,29 +123,29 @@ async function start() {
// Request logger
app.use(async (ctx, next) => {
let timeStart = new Date();
let timeStart = new Date()
try {
await next();
await next()
} catch (e) {
log.error(e);
ctx.status = ctx.status || 500;
log.error(e)
ctx.status = ctx.status || 500
if (DEVEL) {
ctx.body = ctx.body || e.stack;
ctx.body = ctx.body || e.stack
} else {
ctx.body = {
err: 'something terrible happened.',
};
}
}
}
let timeElapsed = new Date() - timeStart;
let timeElapsed = new Date() - timeStart
log.request(
`${ctx.status} ${ctx.method} ${ctx.url} - ${ctx.ip} - took ${timeElapsed}ms`
);
)
// return null
});
})
const session = require('koa-session');
const session = require('koa-session')
app.use(
session(
{
@ -154,21 +154,21 @@ async function start() {
siteOnly: true,
store: M.ctx.sessions,
genid: () => {
return ksuid.randomSync().string;
return ksuid.randomSync().string
},
},
app
)
);
)
await M.mountRoutes();
await M.mountRoutes()
// SPA server
log.info(`starting HTTP server on ${process.env.APP_PORT || 6769}`);
server.listen(process.env.APP_PORT || 6769);
log.info(`starting HTTP server on ${process.env.APP_PORT || 6769}`)
server.listen(process.env.APP_PORT || 6769)
}
start().catch(e => {
log.fatal('app failed to start', e);
});
log.fatal('app failed to start', e)
})

View file

@ -1,4 +1,4 @@
const chalk = require('chalk');
const chalk = require('chalk')
// const { debug } = require('yargs').argv
// process.env.DEBUG = process.env.DEBUG || debug
// logger template//
@ -6,54 +6,54 @@ const chalk = require('chalk');
class Logger {
constructor(name, debugOverride = false) {
this.name = name;
this.name = name
this.debugOn =
process.env.DEBUG === 'true' || process.env.DEBUG === '*' || debugOverride;
process.env.DEBUG === 'true' || process.env.DEBUG === '*' || debugOverride
}
fatal(text, ...data) {
this.error(text, data);
this.error(text, data)
if (typeof data[data.length - 1] === 'number') {
process.exit(data[data.length - 1]);
process.exit(data[data.length - 1])
} else {
process.exit(1);
process.exit(1)
}
throw text;
throw text
}
error(text, ...data) {
console.error(chalk.red.bold(`ERR ${this.name}:`) + `\n ${text}`, data);
console.error(chalk.red.bold(`ERR ${this.name}:`) + `\n ${text}`, data)
}
warn(text, ...data) {
console.warn(chalk.yellow.bold(`WARN ${this.name}:`) + `\n ${text}`, data);
console.warn(chalk.yellow.bold(`WARN ${this.name}:`) + `\n ${text}`, data)
}
notice(text, ...data) {
console.log(chalk.cyan.bold(`NOTICE ${this.name}:`) + `\n ${text}`, data);
console.log(chalk.cyan.bold(`NOTICE ${this.name}:`) + `\n ${text}`, data)
}
info(text, ...data) {
console.info(chalk.blue.bold(`INFO ${this.name}:`) + `\n ${text}`, data);
console.info(chalk.blue.bold(`INFO ${this.name}:`) + `\n ${text}`, data)
}
request(text, ...data) {
console.info(chalk.green.bold(`HTTP ${this.name}:`) + `\n ${text}`);
console.info(chalk.green.bold(`HTTP ${this.name}:`) + `\n ${text}`)
}
debug(text, ...data) {
if (this.debugOn) {
console.log(chalk.gray.bold(`DEBUG ${this.name}:`) + `\n ${text}`, data);
console.log(chalk.gray.bold(`DEBUG ${this.name}:`) + `\n ${text}`, data)
}
}
sql(logger, ...data) {
if (logger.debugOn) {
console.log(chalk.bold('DEBUG SQL:\n '), data);
console.log(chalk.bold('DEBUG SQL:\n '), data)
}
}
}
module.exports = Logger;
module.exports = Logger

View file

@ -11,5 +11,5 @@ module.exports = (sql, DataTypes) => {
message: {
type: DataTypes.TEXT,
},
});
};
})
}

View file

@ -3,5 +3,5 @@ module.exports = (sequelize, DataTypes) => {
id: { type: DataTypes.TEXT, primaryKey: true },
maxAge: DataTypes.BIGINT,
data: DataTypes.JSONB,
});
};
})
}

View file

@ -1,37 +1,37 @@
const log = new (require('../logger'))('models/index');
const glob = require('glob');
const path = require('path');
const util = require('../util/model-methods');
const log = new (require('../logger'))('models/index')
const glob = require('glob')
const path = require('path')
const util = require('../util/model-methods')
module.exports = sql => {
const models = {};
const modelFiles = glob.sync('./models/**/!(index).js');
log.debug('found models', modelFiles);
const models = {}
const modelFiles = glob.sync('./models/**/!(index).js')
log.debug('found models', modelFiles)
modelFiles.forEach(v => {
let name = path.basename(v).replace('.js', '');
let name = path.basename(v).replace('.js', '')
if (v === './models/index.js') {
log.debug('index.js hit, skipped');
return;
log.debug('index.js hit, skipped')
return
}
try {
log.debug('importing..', v.replace('models/', ''));
let model = sql.import(v.replace('models/', ''));
models[name] = model;
log.debug('importing..', v.replace('models/', ''))
let model = sql.import(v.replace('models/', ''))
models[name] = model
} catch (err) {
log.fatal('error importing model ' + v, err);
process.exit(-1);
log.fatal('error importing model ' + v, err)
process.exit(-1)
}
});
})
Object.keys(models).forEach(v => {
if (models[v].hasOwnProperty('__associations')) {
models[v].__associations(models);
models[v].__associations(models)
}
if (models[v].hasOwnProperty('__instanceMethods')) {
models[v].__instanceMethods(models[v]);
models[v].__instanceMethods(models[v])
}
});
})
return models;
};
return models
}

View file

@ -1,10 +1,10 @@
const Logger = require('../logger');
const Logger = require('../logger')
class Service {
constructor(ctx) {
this.ctx = ctx;
this.log = new Logger(this.constructor.name);
this.ctx = ctx
this.log = new Logger(this.constructor.name)
}
}
module.exports = Service;
module.exports = Service

View file

@ -1,4 +1,4 @@
const Service = require('./Service');
const DiscordRPC = require('@roleypoly/rpc/discord');
const Service = require('./Service')
const DiscordRPC = require('@roleypoly/rpc/discord')
class DiscordRPCService extends Service {}

View file

@ -1,30 +1,30 @@
const Service = require('./Service');
const discord = require('discord.js');
const superagent = require('superagent');
const Service = require('./Service')
const discord = require('discord.js')
const superagent = require('superagent')
class DiscordService extends Service {
constructor(ctx) {
super(ctx);
super(ctx)
this.botToken = process.env.DISCORD_BOT_TOKEN;
this.clientId = process.env.DISCORD_CLIENT_ID;
this.clientSecret = process.env.DISCORD_CLIENT_SECRET;
this.oauthCallback = process.env.OAUTH_AUTH_CALLBACK;
this.botCallback = `${ctx.config.appUrl}/api/oauth/bot/callback`;
this.appUrl = process.env.APP_URL;
this.isBot = process.env.IS_BOT === 'true' || false;
this.rootUsers = new Set((process.env.ROOT_USERS || '').split(','));
this.botToken = process.env.DISCORD_BOT_TOKEN
this.clientId = process.env.DISCORD_CLIENT_ID
this.clientSecret = process.env.DISCORD_CLIENT_SECRET
this.oauthCallback = process.env.OAUTH_AUTH_CALLBACK
this.botCallback = `${ctx.config.appUrl}/api/oauth/bot/callback`
this.appUrl = process.env.APP_URL
this.isBot = process.env.IS_BOT === 'true' || false
this.rootUsers = new Set((process.env.ROOT_USERS || '').split(','))
this.client = new discord.Client();
this.client.options.disableEveryone = true;
this.client = new discord.Client()
this.client.options.disableEveryone = true
this.cmds = this._cmds();
this.cmds = this._cmds()
this.startBot();
this.startBot()
}
ownGm(server) {
return this.gm(server, this.client.user.id);
return this.gm(server, this.client.user.id)
}
fakeGm({ id = 0, nickname = '[none]', displayHexColor = '#ffffff' }) {
@ -35,41 +35,41 @@ class DiscordService extends Service {
__faked: true,
roles: {
has() {
return false;
return false
},
},
};
}
}
isRoot(id) {
return this.rootUsers.has(id);
return this.rootUsers.has(id)
}
async startBot() {
await this.client.login(this.botToken);
await this.client.login(this.botToken)
// not all roleypolys are bots.
if (this.isBot) {
this.log.info('this roleypoly is a bot');
this.client.on('message', this.handleMessage.bind(this));
this.client.on('guildCreate', this.handleJoin.bind(this));
this.log.info('this roleypoly is a bot')
this.client.on('message', this.handleMessage.bind(this))
this.client.on('guildCreate', this.handleJoin.bind(this))
}
for (let server of this.client.guilds.array()) {
await this.ctx.server.ensure(server);
await this.ctx.server.ensure(server)
}
}
getRelevantServers(userId) {
return this.client.guilds.filter(g => g.members.has(userId));
return this.client.guilds.filter(g => g.members.has(userId))
}
gm(serverId, userId) {
return this.client.guilds.get(serverId).members.get(userId);
return this.client.guilds.get(serverId).members.get(userId)
}
getRoles(server) {
return this.client.guilds.get(server).roles;
return this.client.guilds.get(server).roles
}
getPermissions(gm) {
@ -77,23 +77,23 @@ class DiscordService extends Service {
return {
isAdmin: true,
canManageRoles: true,
};
}
}
return {
isAdmin: gm.permissions.hasPermission('ADMINISTRATOR'),
canManageRoles: gm.permissions.hasPermission('MANAGE_ROLES', false, true),
};
}
}
safeRole(server, role) {
const r = this.getRoles(server).get(role);
return r.editable && !r.hasPermission('MANAGE_ROLES', false, true);
const r = this.getRoles(server).get(role)
return r.editable && !r.hasPermission('MANAGE_ROLES', false, true)
}
// oauth step 2 flow, grab the auth token via code
async getAuthToken(code) {
const url = 'https://discordapp.com/api/oauth2/token';
const url = 'https://discordapp.com/api/oauth2/token'
try {
const rsp = await superagent
.post(url)
@ -104,27 +104,27 @@ class DiscordService extends Service {
grant_type: 'authorization_code',
code: code,
redirect_uri: this.oauthCallback,
});
})
return rsp.body;
return rsp.body
} catch (e) {
this.log.error('getAuthToken failed', e);
throw e;
this.log.error('getAuthToken failed', e)
throw e
}
}
async getUser(authToken) {
const url = 'https://discordapp.com/api/v6/users/@me';
const url = 'https://discordapp.com/api/v6/users/@me'
try {
if (authToken == null || authToken === '') {
throw new Error('not logged in');
throw new Error('not logged in')
}
const rsp = await superagent.get(url).set('Authorization', `Bearer ${authToken}`);
return rsp.body;
const rsp = await superagent.get(url).set('Authorization', `Bearer ${authToken}`)
return rsp.body
} catch (e) {
this.log.error('getUser error', e);
throw e;
this.log.error('getUser error', e)
throw e
}
}
@ -153,20 +153,20 @@ class DiscordService extends Service {
// returns oauth authorize url with IDENTIFY permission
// we only need IDENTIFY because we only use it for matching IDs from the bot
getAuthUrl(state) {
return `https://discordapp.com/oauth2/authorize?client_id=${this.clientId}&redirect_uri=${this.oauthCallback}&response_type=code&scope=identify&state=${state}`;
return `https://discordapp.com/oauth2/authorize?client_id=${this.clientId}&redirect_uri=${this.oauthCallback}&response_type=code&scope=identify&state=${state}`
}
// returns the bot join url with MANAGE_ROLES permission
// MANAGE_ROLES is the only permission we really need.
getBotJoinUrl() {
return `https://discordapp.com/oauth2/authorize?client_id=${this.clientId}&scope=bot&permissions=268435456`;
return `https://discordapp.com/oauth2/authorize?client_id=${this.clientId}&scope=bot&permissions=268435456`
}
mentionResponse(message) {
message.channel.send(
`🔰 Assign your roles here! <${this.appUrl}/s/${message.guild.id}>`,
{ disableEveryone: true }
);
)
}
_cmds() {
@ -174,15 +174,15 @@ class DiscordService extends Service {
{
regex: /say (.*)/,
handler(message, matches, r) {
r(matches[0]);
r(matches[0])
},
},
{
regex: /set username (.*)/,
async handler(message, matches) {
const { username } = this.client.user;
await this.client.user.setUsername(matches[0]);
message.channel.send(`Username changed from ${username} to ${matches[0]}`);
const { username } = this.client.user
await this.client.user.setUsername(matches[0])
message.channel.send(`Username changed from ${username} to ${matches[0]}`)
},
},
{
@ -200,8 +200,8 @@ class DiscordService extends Service {
(acc, g) => acc + g.roles.size,
0
)}`,
];
message.channel.send(t.join('\n'));
]
message.channel.send(t.join('\n'))
},
},
]
@ -209,51 +209,51 @@ class DiscordService extends Service {
.map(({ regex, ...rest }) => ({
regex: new RegExp(`^${regex.source}`, regex.flags),
...rest,
}));
}))
return cmds;
return cmds
}
async handleCommand(message) {
const cmd = message.content.replace(`<@${this.client.user.id}> `, '');
this.log.debug(`got command from ${message.author.username}`, cmd);
const cmd = message.content.replace(`<@${this.client.user.id}> `, '')
this.log.debug(`got command from ${message.author.username}`, cmd)
for (let { regex, handler } of this.cmds) {
const match = regex.exec(cmd);
const match = regex.exec(cmd)
if (match !== null) {
this.log.debug('command accepted', { cmd, match });
this.log.debug('command accepted', { cmd, match })
try {
await handler.call(this, message, match.slice(1));
return;
await handler.call(this, message, match.slice(1))
return
} catch (e) {
this.log.error('command errored', { e, cmd, message });
message.channel.send(`❌ **An error occured.** ${e}`);
return;
this.log.error('command errored', { e, cmd, message })
message.channel.send(`❌ **An error occured.** ${e}`)
return
}
}
}
// nothing matched?
this.mentionResponse(message);
this.mentionResponse(message)
}
handleMessage(message) {
if (message.author.bot && message.channel.type !== 'text') {
// drop bot messages and dms
return;
return
}
if (message.mentions.users.has(this.client.user.id)) {
if (this.rootUsers.has(message.author.id)) {
this.handleCommand(message);
this.handleCommand(message)
} else {
this.mentionResponse(message);
this.mentionResponse(message)
}
}
}
async handleJoin(guild) {
await this.ctx.server.ensure(guild);
await this.ctx.server.ensure(guild)
}
}
module.exports = DiscordService;
module.exports = DiscordService

View file

@ -1,13 +1,13 @@
const Service = require('./Service');
const LRU = require('lru-cache');
const Service = require('./Service')
const LRU = require('lru-cache')
class PresentationService extends Service {
constructor(ctx) {
super(ctx);
this.M = ctx.M;
this.discord = ctx.discord;
super(ctx)
this.M = ctx.M
this.discord = ctx.discord
this.cache = new LRU({ max: 500, maxAge: 100 * 60 * 5 });
this.cache = new LRU({ max: 500, maxAge: 100 * 60 * 5 })
}
serverSlug(server) {
@ -16,31 +16,31 @@ class PresentationService extends Service {
name: server.name,
ownerID: server.ownerID,
icon: server.icon,
};
}
}
async oldPresentableServers(collection, userId) {
let servers = [];
let servers = []
for (let server of collection.array()) {
const gm = server.members.get(userId);
const gm = server.members.get(userId)
servers.push(await this.presentableServer(server, gm));
servers.push(await this.presentableServer(server, gm))
}
return servers;
return servers
}
async presentableServers(collection, userId) {
return collection.array().areduce(async (acc, server) => {
const gm = server.members.get(userId);
acc.push(await this.presentableServer(server, gm, { incRoles: false }));
return acc;
});
const gm = server.members.get(userId)
acc.push(await this.presentableServer(server, gm, { incRoles: false }))
return acc
})
}
async presentableServer(server, gm, { incRoles = true } = {}) {
const sd = await this.ctx.server.get(server.id);
const sd = await this.ctx.server.get(server.id)
return {
id: server.id,
@ -58,7 +58,7 @@ class PresentationService extends Service {
message: sd.message,
categories: sd.categories,
perms: this.discord.getPermissions(gm),
};
}
}
async rolesByServer(server) {
@ -70,8 +70,8 @@ class PresentationService extends Service {
name: r.name,
position: r.position,
safe: this.discord.safeRole(server.id, r.id),
}));
}))
}
}
module.exports = PresentationService;
module.exports = PresentationService

View file

@ -1,16 +1,16 @@
const Service = require('./Service');
const Service = require('./Service')
class ServerService extends Service {
constructor(ctx) {
super(ctx);
this.Server = ctx.M.Server;
this.P = ctx.P;
super(ctx)
this.Server = ctx.M.Server
this.P = ctx.P
}
async ensure(server) {
let srv;
let srv
try {
srv = await this.get(server.id);
srv = await this.get(server.id)
} catch (e) {}
if (srv == null) {
@ -18,20 +18,20 @@ class ServerService extends Service {
id: server.id,
message: '',
categories: {},
});
})
}
}
create({ id, message, categories }) {
const srv = this.Server.build({ id, message, categories });
const srv = this.Server.build({ id, message, categories })
return srv.save();
return srv.save()
}
async update(id, newData) {
const srv = await this.get(id, false);
const srv = await this.get(id, false)
return srv.update(newData);
return srv.update(newData)
}
async get(id, plain = true) {
@ -39,26 +39,26 @@ class ServerService extends Service {
where: {
id,
},
});
})
if (!plain) {
return s;
return s
}
return s.get({ plain: true });
return s.get({ plain: true })
}
async getAllowedRoles(id) {
const server = await this.get(id);
const server = await this.get(id)
return Object.values(server.categories).reduce((acc, c) => {
if (c.hidden !== true) {
return acc.concat(c.roles);
return acc.concat(c.roles)
}
return acc;
}, []);
return acc
}, [])
}
}
module.exports = ServerService;
module.exports = ServerService

View file

@ -1,40 +1,40 @@
const Service = require('./Service');
const Service = require('./Service')
class SessionsService extends Service {
constructor(ctx) {
super(ctx);
this.Session = ctx.M.Session;
super(ctx)
this.Session = ctx.M.Session
}
async get(id, { rolling }) {
const user = await this.Session.findOne({ where: { id } });
const user = await this.Session.findOne({ where: { id } })
if (user === null) {
return null;
return null
}
return user.data;
return user.data
}
async set(id, data, { maxAge, rolling, changed }) {
let session = await this.Session.findOne({ where: { id } });
let session = await this.Session.findOne({ where: { id } })
if (session === null) {
session = this.Session.build({ id });
session = this.Session.build({ id })
}
session.data = data;
session.maxAge = maxAge;
session.data = data
session.maxAge = maxAge
return session.save();
return session.save()
}
async destroy(id) {
const sess = await this.Session.findOne({ where: { id } });
const sess = await this.Session.findOne({ where: { id } })
if (sess != null) {
return sess.destroy();
return sess.destroy()
}
}
}
module.exports = SessionsService;
module.exports = SessionsService

View file

@ -1,10 +1,10 @@
const ksuid = require('ksuid');
const ksuid = require('ksuid')
module.exports = {
ksuid(field = 'id') {
return async function() {
this.id = await ksuid.random();
return this;
};
this.id = await ksuid.random()
return this
}
},
};
}