mirror of
https://github.com/roleypoly/roleypoly-v1.git
synced 2025-04-25 12:19:10 +00:00
chore: remove semi
This commit is contained in:
parent
4b75eaa0ab
commit
8fcc0dcbf9
64 changed files with 1073 additions and 1073 deletions
|
@ -1,3 +1,3 @@
|
||||||
module.exports = {
|
module.exports = {
|
||||||
extends: 'standard',
|
extends: 'standard',
|
||||||
};
|
}
|
||||||
|
|
|
@ -5,5 +5,5 @@ module.exports = {
|
||||||
singleQuote: true,
|
singleQuote: true,
|
||||||
trailingComma: 'es5',
|
trailingComma: 'es5',
|
||||||
bracketSpacing: true,
|
bracketSpacing: true,
|
||||||
semi: true,
|
semi: false,
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,38 +1,38 @@
|
||||||
const log = new (require('./logger'))('Roleypoly');
|
const log = new (require('./logger'))('Roleypoly')
|
||||||
const Sequelize = require('sequelize');
|
const Sequelize = require('sequelize')
|
||||||
const fetchModels = require('./models');
|
const fetchModels = require('./models')
|
||||||
const fetchApis = require('./api');
|
const fetchApis = require('./api')
|
||||||
|
|
||||||
class Roleypoly {
|
class Roleypoly {
|
||||||
constructor(router, io, app) {
|
constructor(router, io, app) {
|
||||||
this.router = router;
|
this.router = router
|
||||||
this.io = io;
|
this.io = io
|
||||||
this.ctx = {};
|
this.ctx = {}
|
||||||
|
|
||||||
this.ctx.config = {
|
this.ctx.config = {
|
||||||
appUrl: process.env.APP_URL,
|
appUrl: process.env.APP_URL,
|
||||||
};
|
}
|
||||||
|
|
||||||
this.ctx.io = io;
|
this.ctx.io = io
|
||||||
this.__app = app;
|
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() {
|
async awaitServices() {
|
||||||
await this.__initialized;
|
await this.__initialized
|
||||||
}
|
}
|
||||||
|
|
||||||
async _mountServices() {
|
async _mountServices() {
|
||||||
const sequelize = new Sequelize(process.env.DB_URL, {
|
const sequelize = new Sequelize(process.env.DB_URL, {
|
||||||
logging: log.sql.bind(log, log),
|
logging: log.sql.bind(log, log),
|
||||||
});
|
})
|
||||||
this.ctx.sql = sequelize;
|
this.ctx.sql = sequelize
|
||||||
this.M = fetchModels(sequelize);
|
this.M = fetchModels(sequelize)
|
||||||
this.ctx.M = this.M;
|
this.ctx.M = this.M
|
||||||
await sequelize.sync();
|
await sequelize.sync()
|
||||||
|
|
||||||
// this.ctx.redis = new (require('ioredis'))({
|
// this.ctx.redis = new (require('ioredis'))({
|
||||||
// port: process.env.REDIS_PORT || '6379',
|
// port: process.env.REDIS_PORT || '6379',
|
||||||
|
@ -42,16 +42,16 @@ class Roleypoly {
|
||||||
// enableReadyCheck: true,
|
// enableReadyCheck: true,
|
||||||
// enableOfflineQueue: true
|
// enableOfflineQueue: true
|
||||||
// })
|
// })
|
||||||
this.ctx.server = new (require('./services/server'))(this.ctx);
|
this.ctx.server = new (require('./services/server'))(this.ctx)
|
||||||
this.ctx.discord = new (require('./services/discord'))(this.ctx);
|
this.ctx.discord = new (require('./services/discord'))(this.ctx)
|
||||||
this.ctx.sessions = new (require('./services/sessions'))(this.ctx);
|
this.ctx.sessions = new (require('./services/sessions'))(this.ctx)
|
||||||
this.ctx.P = new (require('./services/presentation'))(this.ctx);
|
this.ctx.P = new (require('./services/presentation'))(this.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
async mountRoutes() {
|
async mountRoutes() {
|
||||||
fetchApis(this.router, this.ctx);
|
fetchApis(this.router, this.ctx)
|
||||||
this.__app.use(this.router.middleware());
|
this.__app.use(this.router.middleware())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Roleypoly;
|
module.exports = Roleypoly
|
||||||
|
|
|
@ -1,76 +1,76 @@
|
||||||
module.exports = (R, $) => {
|
module.exports = (R, $) => {
|
||||||
R.post('/api/auth/token', async ctx => {
|
R.post('/api/auth/token', async ctx => {
|
||||||
const { token } = ctx.request.body;
|
const { token } = ctx.request.body
|
||||||
|
|
||||||
if (token == null || token === '') {
|
if (token == null || token === '') {
|
||||||
ctx.body = { err: 'token_missing' };
|
ctx.body = { err: 'token_missing' }
|
||||||
ctx.status = 400;
|
ctx.status = 400
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctx.session.accessToken === undefined || ctx.session.expiresAt < Date.now()) {
|
if (ctx.session.accessToken === undefined || ctx.session.expiresAt < Date.now()) {
|
||||||
const data = await $.discord.getAuthToken(token);
|
const data = await $.discord.getAuthToken(token)
|
||||||
ctx.session.accessToken = data.access_token;
|
ctx.session.accessToken = data.access_token
|
||||||
ctx.session.refreshToken = data.refresh_token;
|
ctx.session.refreshToken = data.refresh_token
|
||||||
ctx.session.expiresAt = Date.now() + (ctx.expires_in || 1000 * 60 * 60 * 24);
|
ctx.session.expiresAt = Date.now() + (ctx.expires_in || 1000 * 60 * 60 * 24)
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await $.discord.getUser(ctx.session.accessToken);
|
const user = await $.discord.getUser(ctx.session.accessToken)
|
||||||
ctx.session.userId = user.id;
|
ctx.session.userId = user.id
|
||||||
ctx.session.avatarHash = user.avatar;
|
ctx.session.avatarHash = user.avatar
|
||||||
|
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
avatar: user.avatar,
|
avatar: user.avatar,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
discriminator: user.discriminator,
|
discriminator: user.discriminator,
|
||||||
};
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/auth/user', async ctx => {
|
R.get('/api/auth/user', async ctx => {
|
||||||
if (ctx.session.accessToken === undefined) {
|
if (ctx.session.accessToken === undefined) {
|
||||||
ctx.body = { err: 'not_logged_in' };
|
ctx.body = { err: 'not_logged_in' }
|
||||||
ctx.status = 401;
|
ctx.status = 401
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await $.discord.getUser(ctx.session.accessToken);
|
const user = await $.discord.getUser(ctx.session.accessToken)
|
||||||
ctx.session.userId = user.id;
|
ctx.session.userId = user.id
|
||||||
ctx.session.avatarHash = user.avatar;
|
ctx.session.avatarHash = user.avatar
|
||||||
|
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
avatar: user.avatar,
|
avatar: user.avatar,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
discriminator: user.discriminator,
|
discriminator: user.discriminator,
|
||||||
};
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/auth/redirect', ctx => {
|
R.get('/api/auth/redirect', ctx => {
|
||||||
const url = $.discord.getAuthUrl();
|
const url = $.discord.getAuthUrl()
|
||||||
if (ctx.query.url === '✔️') {
|
if (ctx.query.url === '✔️') {
|
||||||
ctx.body = { url };
|
ctx.body = { url }
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.redirect(url);
|
ctx.redirect(url)
|
||||||
});
|
})
|
||||||
|
|
||||||
R.post('/api/auth/logout', ctx => {
|
R.post('/api/auth/logout', ctx => {
|
||||||
ctx.session = null;
|
ctx.session = null
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/oauth/bot', ctx => {
|
R.get('/api/oauth/bot', ctx => {
|
||||||
const url = $.discord.getBotJoinUrl();
|
const url = $.discord.getBotJoinUrl()
|
||||||
if (ctx.query.url === '✔️') {
|
if (ctx.query.url === '✔️') {
|
||||||
ctx.body = { url };
|
ctx.body = { url }
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.redirect(url);
|
ctx.redirect(url)
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/oauth/bot/callback', ctx => {
|
R.get('/api/oauth/bot/callback', ctx => {
|
||||||
console.log(ctx.request);
|
console.log(ctx.request)
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,22 +1,22 @@
|
||||||
const log = new (require('../logger'))('api/index');
|
const log = new (require('../logger'))('api/index')
|
||||||
const glob = require('glob');
|
const glob = require('glob')
|
||||||
|
|
||||||
const PROD = process.env.NODE_ENV === 'production';
|
const PROD = process.env.NODE_ENV === 'production'
|
||||||
|
|
||||||
module.exports = async (router, ctx) => {
|
module.exports = async (router, ctx) => {
|
||||||
const apis = glob.sync(`./api/**/!(index).js`);
|
const apis = glob.sync(`./api/**/!(index).js`)
|
||||||
log.debug('found apis', apis);
|
log.debug('found apis', apis)
|
||||||
|
|
||||||
for (let a of apis) {
|
for (let a of apis) {
|
||||||
if (a.endsWith('_test.js') && PROD) {
|
if (a.endsWith('_test.js') && PROD) {
|
||||||
log.debug(`skipping ${a}`);
|
log.debug(`skipping ${a}`)
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
log.debug(`mounting ${a}`);
|
log.debug(`mounting ${a}`)
|
||||||
try {
|
try {
|
||||||
require(a.replace('api/', ''))(router, ctx);
|
require(a.replace('api/', ''))(router, ctx)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.error(`couldn't mount ${a}`, e);
|
log.error(`couldn't mount ${a}`, e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,91 +1,91 @@
|
||||||
module.exports = (R, $) => {
|
module.exports = (R, $) => {
|
||||||
R.get('/api/servers', async ctx => {
|
R.get('/api/servers', async ctx => {
|
||||||
try {
|
try {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
const srv = $.discord.getRelevantServers(userId);
|
const srv = $.discord.getRelevantServers(userId)
|
||||||
const presentable = await $.P.presentableServers(srv, userId);
|
const presentable = await $.P.presentableServers(srv, userId)
|
||||||
|
|
||||||
ctx.body = presentable;
|
ctx.body = presentable
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e.trace || e.stack);
|
console.error(e.trace || e.stack)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/server/:id', async ctx => {
|
R.get('/api/server/:id', async ctx => {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
const { id } = ctx.params;
|
const { id } = ctx.params
|
||||||
|
|
||||||
const srv = $.discord.client.guilds.get(id);
|
const srv = $.discord.client.guilds.get(id)
|
||||||
|
|
||||||
if (srv == null) {
|
if (srv == null) {
|
||||||
ctx.body = { err: 'not found' };
|
ctx.body = { err: 'not found' }
|
||||||
ctx.status = 404;
|
ctx.status = 404
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let gm;
|
let gm
|
||||||
if (srv.members.has(userId)) {
|
if (srv.members.has(userId)) {
|
||||||
gm = $.discord.gm(id, userId);
|
gm = $.discord.gm(id, userId)
|
||||||
} else if ($.discord.isRoot(userId)) {
|
} else if ($.discord.isRoot(userId)) {
|
||||||
gm = $.discord.fakeGm({ id: userId });
|
gm = $.discord.fakeGm({ id: userId })
|
||||||
} else {
|
} else {
|
||||||
ctx.body = { err: 'not_a_member' };
|
ctx.body = { err: 'not_a_member' }
|
||||||
ctx.status = 400;
|
ctx.status = 400
|
||||||
return;
|
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 => {
|
R.get('/api/server/:id/slug', async ctx => {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
const { id } = ctx.params;
|
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) {
|
if (srv == null) {
|
||||||
ctx.body = { err: 'not found' };
|
ctx.body = { err: 'not found' }
|
||||||
ctx.status = 404;
|
ctx.status = 404
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.body = await $.P.serverSlug(srv);
|
ctx.body = await $.P.serverSlug(srv)
|
||||||
});
|
})
|
||||||
|
|
||||||
R.patch('/api/server/:id', async ctx => {
|
R.patch('/api/server/:id', async ctx => {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
const { id } = ctx.params;
|
const { id } = ctx.params
|
||||||
|
|
||||||
let gm = $.discord.gm(id, userId);
|
let gm = $.discord.gm(id, userId)
|
||||||
if (gm == null && $.discord.isRoot(userId)) {
|
if (gm == null && $.discord.isRoot(userId)) {
|
||||||
gm = $.discord.fakeGm({ id: userId });
|
gm = $.discord.fakeGm({ id: userId })
|
||||||
}
|
}
|
||||||
|
|
||||||
// check perms
|
// check perms
|
||||||
if (!$.discord.getPermissions(gm).canManageRoles) {
|
if (!$.discord.getPermissions(gm).canManageRoles) {
|
||||||
ctx.status = 403;
|
ctx.status = 403
|
||||||
ctx.body = { err: 'cannot_manage_roles' };
|
ctx.body = { err: 'cannot_manage_roles' }
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const { message = null, categories = null } = ctx.request.body;
|
const { message = null, categories = null } = ctx.request.body
|
||||||
|
|
||||||
// todo make less nasty
|
// todo make less nasty
|
||||||
await $.server.update(id, {
|
await $.server.update(id, {
|
||||||
...(message != null ? { message } : {}),
|
...(message != null ? { message } : {}),
|
||||||
...(categories != null ? { categories } : {}),
|
...(categories != null ? { categories } : {}),
|
||||||
});
|
})
|
||||||
|
|
||||||
ctx.body = { ok: true };
|
ctx.body = { ok: true }
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/admin/servers', async ctx => {
|
R.get('/api/admin/servers', async ctx => {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
if (!$.discord.isRoot(userId)) {
|
if (!$.discord.isRoot(userId)) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.body = $.discord.client.guilds.map(g => ({
|
ctx.body = $.discord.client.guilds.map(g => ({
|
||||||
|
@ -93,16 +93,16 @@ module.exports = (R, $) => {
|
||||||
name: g.name,
|
name: g.name,
|
||||||
members: g.members.array().length,
|
members: g.members.array().length,
|
||||||
roles: g.roles.array().length,
|
roles: g.roles.array().length,
|
||||||
}));
|
}))
|
||||||
});
|
})
|
||||||
|
|
||||||
R.patch('/api/servers/:server/roles', async ctx => {
|
R.patch('/api/servers/:server/roles', async ctx => {
|
||||||
const { userId } = ctx.session;
|
const { userId } = ctx.session
|
||||||
const { server } = ctx.params;
|
const { server } = ctx.params
|
||||||
|
|
||||||
let gm = $.discord.gm(server, userId);
|
let gm = $.discord.gm(server, userId)
|
||||||
if (gm == null && $.discord.isRoot(userId)) {
|
if (gm == null && $.discord.isRoot(userId)) {
|
||||||
gm = $.discord.fakeGm({ id: userId });
|
gm = $.discord.fakeGm({ id: userId })
|
||||||
}
|
}
|
||||||
|
|
||||||
// check perms
|
// check perms
|
||||||
|
@ -112,24 +112,24 @@ module.exports = (R, $) => {
|
||||||
// return
|
// 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) {
|
if (added.length > 0) {
|
||||||
gm = await gm.addRoles(added.filter(pred));
|
gm = await gm.addRoles(added.filter(pred))
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (removed.length > 0) {
|
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) })
|
// console.log('role patch', { added, removed, allowedRoles, addedFiltered: added.filterNot(pred), removedFiltered: removed.filterNot(pred) })
|
||||||
|
|
||||||
ctx.body = { ok: true };
|
ctx.body = { ok: true }
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,26 +1,26 @@
|
||||||
module.exports = (R, $) => {
|
module.exports = (R, $) => {
|
||||||
R.get('/api/~/relevant-servers/:user', (ctx, next) => {
|
R.get('/api/~/relevant-servers/:user', (ctx, next) => {
|
||||||
// ctx.body = 'ok'
|
// ctx.body = 'ok'
|
||||||
const srv = $.discord.getRelevantServers(ctx.params.user);
|
const srv = $.discord.getRelevantServers(ctx.params.user)
|
||||||
ctx.body = $.discord.presentableServers(srv, ctx.params.user);
|
ctx.body = $.discord.presentableServers(srv, ctx.params.user)
|
||||||
return;
|
return
|
||||||
});
|
})
|
||||||
|
|
||||||
R.get('/api/~/roles/:id/:userId', (ctx, next) => {
|
R.get('/api/~/roles/:id/:userId', (ctx, next) => {
|
||||||
// ctx.body = 'ok'
|
// 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) {
|
if (srv === undefined) {
|
||||||
ctx.body = { err: 'not found' };
|
ctx.body = { err: 'not found' }
|
||||||
ctx.status = 404;
|
ctx.status = 404
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const gm = srv.members.get(userId);
|
const gm = srv.members.get(userId)
|
||||||
const roles = $.discord.presentableRoles(id, gm);
|
const roles = $.discord.presentableRoles(id, gm)
|
||||||
|
|
||||||
ctx.boy = roles;
|
ctx.boy = roles
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
136
Server/index.js
136
Server/index.js
|
@ -1,96 +1,96 @@
|
||||||
require('dotenv').config({ silent: true });
|
require('dotenv').config({ silent: true })
|
||||||
const log = new (require('./logger'))('index');
|
const log = new (require('./logger'))('index')
|
||||||
|
|
||||||
const http = require('http');
|
const http = require('http')
|
||||||
const Koa = require('koa');
|
const Koa = require('koa')
|
||||||
const app = new Koa();
|
const app = new Koa()
|
||||||
const _io = require('socket.io');
|
const _io = require('socket.io')
|
||||||
const fs = require('fs');
|
const fs = require('fs')
|
||||||
const path = require('path');
|
const path = require('path')
|
||||||
const router = require('koa-better-router')().loadMethods();
|
const router = require('koa-better-router')().loadMethods()
|
||||||
const Roleypoly = require('./Roleypoly');
|
const Roleypoly = require('./Roleypoly')
|
||||||
const ksuid = require('ksuid');
|
const ksuid = require('ksuid')
|
||||||
|
|
||||||
// monkey patch async-reduce because F U T U R E
|
// monkey patch async-reduce because F U T U R E
|
||||||
Array.prototype.areduce = async function(predicate, acc = []) {
|
Array.prototype.areduce = async function(predicate, acc = []) {
|
||||||
// eslint-disable-line
|
// eslint-disable-line
|
||||||
for (let i of this) {
|
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 =
|
||||||
Array.prototype.filterNot ||
|
Array.prototype.filterNot ||
|
||||||
function(predicate) {
|
function(predicate) {
|
||||||
return this.filter(v => !predicate(v));
|
return this.filter(v => !predicate(v))
|
||||||
};
|
}
|
||||||
|
|
||||||
// Create the server and socket.io server
|
// Create the server and socket.io server
|
||||||
const server = http.createServer(app.callback());
|
const server = http.createServer(app.callback())
|
||||||
const io = _io(server, { transports: ['websocket'], path: '/api/socket.io' });
|
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() {
|
async function start() {
|
||||||
await M.awaitServices();
|
await M.awaitServices()
|
||||||
|
|
||||||
// body parser
|
// body parser
|
||||||
const bodyParser = require('koa-bodyparser');
|
const bodyParser = require('koa-bodyparser')
|
||||||
app.use(bodyParser({ types: ['json'] }));
|
app.use(bodyParser({ types: ['json'] }))
|
||||||
|
|
||||||
// Compress
|
// Compress
|
||||||
const compress = require('koa-compress');
|
const compress = require('koa-compress')
|
||||||
app.use(compress());
|
app.use(compress())
|
||||||
|
|
||||||
// SPA + Static
|
// SPA + Static
|
||||||
if (process.env.NODE_ENV === 'production') {
|
if (process.env.NODE_ENV === 'production') {
|
||||||
const pub = path.resolve(path.join(__dirname, 'public'));
|
const pub = path.resolve(path.join(__dirname, 'public'))
|
||||||
log.info('public path', pub);
|
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 }))
|
// 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) => {
|
app.use(async (ctx, next) => {
|
||||||
if (ctx.path.startsWith('/api')) {
|
if (ctx.path.startsWith('/api')) {
|
||||||
log.info('api breakout');
|
log.info('api breakout')
|
||||||
return next();
|
return next()
|
||||||
}
|
}
|
||||||
|
|
||||||
const chkPath = path.resolve(path.join(pub, ctx.path));
|
const chkPath = path.resolve(path.join(pub, ctx.path))
|
||||||
log.info('chkPath', chkPath);
|
log.info('chkPath', chkPath)
|
||||||
if (!chkPath.startsWith(pub)) {
|
if (!chkPath.startsWith(pub)) {
|
||||||
return next();
|
return next()
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
fs.statSync(chkPath);
|
fs.statSync(chkPath)
|
||||||
log.info('sync pass');
|
log.info('sync pass')
|
||||||
ctx.body = fs.readFileSync(chkPath);
|
ctx.body = fs.readFileSync(chkPath)
|
||||||
ctx.type = path.extname(ctx.path);
|
ctx.type = path.extname(ctx.path)
|
||||||
log.info('body sent');
|
log.info('body sent')
|
||||||
ctx.status = 200;
|
ctx.status = 200
|
||||||
return next();
|
return next()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.warn('failed');
|
log.warn('failed')
|
||||||
if (ctx.path.startsWith('/static/')) {
|
if (ctx.path.startsWith('/static/')) {
|
||||||
return next();
|
return next()
|
||||||
}
|
}
|
||||||
try {
|
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) {
|
} catch (e) {
|
||||||
ctx.body = e.stack || e.trace;
|
ctx.body = e.stack || e.trace
|
||||||
ctx.status = 500;
|
ctx.status = 500
|
||||||
}
|
}
|
||||||
log.info('index sent');
|
log.info('index sent')
|
||||||
ctx.status = 200;
|
ctx.status = 200
|
||||||
return next();
|
return next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// try {
|
// try {
|
||||||
|
@ -98,7 +98,7 @@ async function start() {
|
||||||
// } catch (e) {
|
// } catch (e) {
|
||||||
// send(ctx, 'index.html', { root: pub })
|
// send(ctx, 'index.html', { root: pub })
|
||||||
// }
|
// }
|
||||||
});
|
})
|
||||||
// const sendOpts = {root: pub, index: 'index.html'}
|
// const sendOpts = {root: pub, index: 'index.html'}
|
||||||
// // const sendOpts = {}
|
// // const sendOpts = {}
|
||||||
// app.use(async (ctx, next) => {
|
// app.use(async (ctx, next) => {
|
||||||
|
@ -123,29 +123,29 @@ async function start() {
|
||||||
|
|
||||||
// Request logger
|
// Request logger
|
||||||
app.use(async (ctx, next) => {
|
app.use(async (ctx, next) => {
|
||||||
let timeStart = new Date();
|
let timeStart = new Date()
|
||||||
try {
|
try {
|
||||||
await next();
|
await next()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.error(e);
|
log.error(e)
|
||||||
ctx.status = ctx.status || 500;
|
ctx.status = ctx.status || 500
|
||||||
if (DEVEL) {
|
if (DEVEL) {
|
||||||
ctx.body = ctx.body || e.stack;
|
ctx.body = ctx.body || e.stack
|
||||||
} else {
|
} else {
|
||||||
ctx.body = {
|
ctx.body = {
|
||||||
err: 'something terrible happened.',
|
err: 'something terrible happened.',
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let timeElapsed = new Date() - timeStart;
|
}
|
||||||
|
let timeElapsed = new Date() - timeStart
|
||||||
|
|
||||||
log.request(
|
log.request(
|
||||||
`${ctx.status} ${ctx.method} ${ctx.url} - ${ctx.ip} - took ${timeElapsed}ms`
|
`${ctx.status} ${ctx.method} ${ctx.url} - ${ctx.ip} - took ${timeElapsed}ms`
|
||||||
);
|
)
|
||||||
// return null
|
// return null
|
||||||
});
|
})
|
||||||
|
|
||||||
const session = require('koa-session');
|
const session = require('koa-session')
|
||||||
app.use(
|
app.use(
|
||||||
session(
|
session(
|
||||||
{
|
{
|
||||||
|
@ -154,21 +154,21 @@ async function start() {
|
||||||
siteOnly: true,
|
siteOnly: true,
|
||||||
store: M.ctx.sessions,
|
store: M.ctx.sessions,
|
||||||
genid: () => {
|
genid: () => {
|
||||||
return ksuid.randomSync().string;
|
return ksuid.randomSync().string
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
app
|
app
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
|
|
||||||
await M.mountRoutes();
|
await M.mountRoutes()
|
||||||
|
|
||||||
// SPA server
|
// SPA server
|
||||||
|
|
||||||
log.info(`starting HTTP server on ${process.env.APP_PORT || 6769}`);
|
log.info(`starting HTTP server on ${process.env.APP_PORT || 6769}`)
|
||||||
server.listen(process.env.APP_PORT || 6769);
|
server.listen(process.env.APP_PORT || 6769)
|
||||||
}
|
}
|
||||||
|
|
||||||
start().catch(e => {
|
start().catch(e => {
|
||||||
log.fatal('app failed to start', e);
|
log.fatal('app failed to start', e)
|
||||||
});
|
})
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
const chalk = require('chalk');
|
const chalk = require('chalk')
|
||||||
// const { debug } = require('yargs').argv
|
// const { debug } = require('yargs').argv
|
||||||
// process.env.DEBUG = process.env.DEBUG || debug
|
// process.env.DEBUG = process.env.DEBUG || debug
|
||||||
// logger template//
|
// logger template//
|
||||||
|
@ -6,54 +6,54 @@ const chalk = require('chalk');
|
||||||
|
|
||||||
class Logger {
|
class Logger {
|
||||||
constructor(name, debugOverride = false) {
|
constructor(name, debugOverride = false) {
|
||||||
this.name = name;
|
this.name = name
|
||||||
this.debugOn =
|
this.debugOn =
|
||||||
process.env.DEBUG === 'true' || process.env.DEBUG === '*' || debugOverride;
|
process.env.DEBUG === 'true' || process.env.DEBUG === '*' || debugOverride
|
||||||
}
|
}
|
||||||
|
|
||||||
fatal(text, ...data) {
|
fatal(text, ...data) {
|
||||||
this.error(text, data);
|
this.error(text, data)
|
||||||
|
|
||||||
if (typeof data[data.length - 1] === 'number') {
|
if (typeof data[data.length - 1] === 'number') {
|
||||||
process.exit(data[data.length - 1]);
|
process.exit(data[data.length - 1])
|
||||||
} else {
|
} else {
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
throw text;
|
throw text
|
||||||
}
|
}
|
||||||
|
|
||||||
error(text, ...data) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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) {
|
debug(text, ...data) {
|
||||||
if (this.debugOn) {
|
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) {
|
sql(logger, ...data) {
|
||||||
if (logger.debugOn) {
|
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
|
||||||
|
|
|
@ -11,5 +11,5 @@ module.exports = (sql, DataTypes) => {
|
||||||
message: {
|
message: {
|
||||||
type: DataTypes.TEXT,
|
type: DataTypes.TEXT,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
|
@ -3,5 +3,5 @@ module.exports = (sequelize, DataTypes) => {
|
||||||
id: { type: DataTypes.TEXT, primaryKey: true },
|
id: { type: DataTypes.TEXT, primaryKey: true },
|
||||||
maxAge: DataTypes.BIGINT,
|
maxAge: DataTypes.BIGINT,
|
||||||
data: DataTypes.JSONB,
|
data: DataTypes.JSONB,
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,37 +1,37 @@
|
||||||
const log = new (require('../logger'))('models/index');
|
const log = new (require('../logger'))('models/index')
|
||||||
const glob = require('glob');
|
const glob = require('glob')
|
||||||
const path = require('path');
|
const path = require('path')
|
||||||
const util = require('../util/model-methods');
|
const util = require('../util/model-methods')
|
||||||
|
|
||||||
module.exports = sql => {
|
module.exports = sql => {
|
||||||
const models = {};
|
const models = {}
|
||||||
const modelFiles = glob.sync('./models/**/!(index).js');
|
const modelFiles = glob.sync('./models/**/!(index).js')
|
||||||
log.debug('found models', modelFiles);
|
log.debug('found models', modelFiles)
|
||||||
|
|
||||||
modelFiles.forEach(v => {
|
modelFiles.forEach(v => {
|
||||||
let name = path.basename(v).replace('.js', '');
|
let name = path.basename(v).replace('.js', '')
|
||||||
if (v === './models/index.js') {
|
if (v === './models/index.js') {
|
||||||
log.debug('index.js hit, skipped');
|
log.debug('index.js hit, skipped')
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
log.debug('importing..', v.replace('models/', ''));
|
log.debug('importing..', v.replace('models/', ''))
|
||||||
let model = sql.import(v.replace('models/', ''));
|
let model = sql.import(v.replace('models/', ''))
|
||||||
models[name] = model;
|
models[name] = model
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.fatal('error importing model ' + v, err);
|
log.fatal('error importing model ' + v, err)
|
||||||
process.exit(-1);
|
process.exit(-1)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
Object.keys(models).forEach(v => {
|
Object.keys(models).forEach(v => {
|
||||||
if (models[v].hasOwnProperty('__associations')) {
|
if (models[v].hasOwnProperty('__associations')) {
|
||||||
models[v].__associations(models);
|
models[v].__associations(models)
|
||||||
}
|
}
|
||||||
if (models[v].hasOwnProperty('__instanceMethods')) {
|
if (models[v].hasOwnProperty('__instanceMethods')) {
|
||||||
models[v].__instanceMethods(models[v]);
|
models[v].__instanceMethods(models[v])
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
return models;
|
return models
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
const Logger = require('../logger');
|
const Logger = require('../logger')
|
||||||
|
|
||||||
class Service {
|
class Service {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
this.ctx = ctx;
|
this.ctx = ctx
|
||||||
this.log = new Logger(this.constructor.name);
|
this.log = new Logger(this.constructor.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Service;
|
module.exports = Service
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
const Service = require('./Service');
|
const Service = require('./Service')
|
||||||
const DiscordRPC = require('@roleypoly/rpc/discord');
|
const DiscordRPC = require('@roleypoly/rpc/discord')
|
||||||
|
|
||||||
class DiscordRPCService extends Service {}
|
class DiscordRPCService extends Service {}
|
||||||
|
|
|
@ -1,30 +1,30 @@
|
||||||
const Service = require('./Service');
|
const Service = require('./Service')
|
||||||
const discord = require('discord.js');
|
const discord = require('discord.js')
|
||||||
const superagent = require('superagent');
|
const superagent = require('superagent')
|
||||||
|
|
||||||
class DiscordService extends Service {
|
class DiscordService extends Service {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx)
|
||||||
|
|
||||||
this.botToken = process.env.DISCORD_BOT_TOKEN;
|
this.botToken = process.env.DISCORD_BOT_TOKEN
|
||||||
this.clientId = process.env.DISCORD_CLIENT_ID;
|
this.clientId = process.env.DISCORD_CLIENT_ID
|
||||||
this.clientSecret = process.env.DISCORD_CLIENT_SECRET;
|
this.clientSecret = process.env.DISCORD_CLIENT_SECRET
|
||||||
this.oauthCallback = process.env.OAUTH_AUTH_CALLBACK;
|
this.oauthCallback = process.env.OAUTH_AUTH_CALLBACK
|
||||||
this.botCallback = `${ctx.config.appUrl}/api/oauth/bot/callback`;
|
this.botCallback = `${ctx.config.appUrl}/api/oauth/bot/callback`
|
||||||
this.appUrl = process.env.APP_URL;
|
this.appUrl = process.env.APP_URL
|
||||||
this.isBot = process.env.IS_BOT === 'true' || false;
|
this.isBot = process.env.IS_BOT === 'true' || false
|
||||||
this.rootUsers = new Set((process.env.ROOT_USERS || '').split(','));
|
this.rootUsers = new Set((process.env.ROOT_USERS || '').split(','))
|
||||||
|
|
||||||
this.client = new discord.Client();
|
this.client = new discord.Client()
|
||||||
this.client.options.disableEveryone = true;
|
this.client.options.disableEveryone = true
|
||||||
|
|
||||||
this.cmds = this._cmds();
|
this.cmds = this._cmds()
|
||||||
|
|
||||||
this.startBot();
|
this.startBot()
|
||||||
}
|
}
|
||||||
|
|
||||||
ownGm(server) {
|
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' }) {
|
fakeGm({ id = 0, nickname = '[none]', displayHexColor = '#ffffff' }) {
|
||||||
|
@ -35,41 +35,41 @@ class DiscordService extends Service {
|
||||||
__faked: true,
|
__faked: true,
|
||||||
roles: {
|
roles: {
|
||||||
has() {
|
has() {
|
||||||
return false;
|
return false
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isRoot(id) {
|
isRoot(id) {
|
||||||
return this.rootUsers.has(id);
|
return this.rootUsers.has(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
async startBot() {
|
async startBot() {
|
||||||
await this.client.login(this.botToken);
|
await this.client.login(this.botToken)
|
||||||
|
|
||||||
// not all roleypolys are bots.
|
// not all roleypolys are bots.
|
||||||
if (this.isBot) {
|
if (this.isBot) {
|
||||||
this.log.info('this roleypoly is a bot');
|
this.log.info('this roleypoly is a bot')
|
||||||
this.client.on('message', this.handleMessage.bind(this));
|
this.client.on('message', this.handleMessage.bind(this))
|
||||||
this.client.on('guildCreate', this.handleJoin.bind(this));
|
this.client.on('guildCreate', this.handleJoin.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let server of this.client.guilds.array()) {
|
for (let server of this.client.guilds.array()) {
|
||||||
await this.ctx.server.ensure(server);
|
await this.ctx.server.ensure(server)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getRelevantServers(userId) {
|
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) {
|
gm(serverId, userId) {
|
||||||
return this.client.guilds.get(serverId).members.get(userId);
|
return this.client.guilds.get(serverId).members.get(userId)
|
||||||
}
|
}
|
||||||
|
|
||||||
getRoles(server) {
|
getRoles(server) {
|
||||||
return this.client.guilds.get(server).roles;
|
return this.client.guilds.get(server).roles
|
||||||
}
|
}
|
||||||
|
|
||||||
getPermissions(gm) {
|
getPermissions(gm) {
|
||||||
|
@ -77,23 +77,23 @@ class DiscordService extends Service {
|
||||||
return {
|
return {
|
||||||
isAdmin: true,
|
isAdmin: true,
|
||||||
canManageRoles: true,
|
canManageRoles: true,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isAdmin: gm.permissions.hasPermission('ADMINISTRATOR'),
|
isAdmin: gm.permissions.hasPermission('ADMINISTRATOR'),
|
||||||
canManageRoles: gm.permissions.hasPermission('MANAGE_ROLES', false, true),
|
canManageRoles: gm.permissions.hasPermission('MANAGE_ROLES', false, true),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
safeRole(server, role) {
|
safeRole(server, role) {
|
||||||
const r = this.getRoles(server).get(role);
|
const r = this.getRoles(server).get(role)
|
||||||
return r.editable && !r.hasPermission('MANAGE_ROLES', false, true);
|
return r.editable && !r.hasPermission('MANAGE_ROLES', false, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// oauth step 2 flow, grab the auth token via code
|
// oauth step 2 flow, grab the auth token via code
|
||||||
async getAuthToken(code) {
|
async getAuthToken(code) {
|
||||||
const url = 'https://discordapp.com/api/oauth2/token';
|
const url = 'https://discordapp.com/api/oauth2/token'
|
||||||
try {
|
try {
|
||||||
const rsp = await superagent
|
const rsp = await superagent
|
||||||
.post(url)
|
.post(url)
|
||||||
|
@ -104,27 +104,27 @@ class DiscordService extends Service {
|
||||||
grant_type: 'authorization_code',
|
grant_type: 'authorization_code',
|
||||||
code: code,
|
code: code,
|
||||||
redirect_uri: this.oauthCallback,
|
redirect_uri: this.oauthCallback,
|
||||||
});
|
})
|
||||||
|
|
||||||
return rsp.body;
|
return rsp.body
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.log.error('getAuthToken failed', e);
|
this.log.error('getAuthToken failed', e)
|
||||||
throw e;
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUser(authToken) {
|
async getUser(authToken) {
|
||||||
const url = 'https://discordapp.com/api/v6/users/@me';
|
const url = 'https://discordapp.com/api/v6/users/@me'
|
||||||
try {
|
try {
|
||||||
if (authToken == null || authToken === '') {
|
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}`);
|
const rsp = await superagent.get(url).set('Authorization', `Bearer ${authToken}`)
|
||||||
return rsp.body;
|
return rsp.body
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.log.error('getUser error', e);
|
this.log.error('getUser error', e)
|
||||||
throw e;
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -153,20 +153,20 @@ class DiscordService extends Service {
|
||||||
// returns oauth authorize url with IDENTIFY permission
|
// returns oauth authorize url with IDENTIFY permission
|
||||||
// we only need IDENTIFY because we only use it for matching IDs from the bot
|
// we only need IDENTIFY because we only use it for matching IDs from the bot
|
||||||
getAuthUrl(state) {
|
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
|
// returns the bot join url with MANAGE_ROLES permission
|
||||||
// MANAGE_ROLES is the only permission we really need.
|
// MANAGE_ROLES is the only permission we really need.
|
||||||
getBotJoinUrl() {
|
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) {
|
mentionResponse(message) {
|
||||||
message.channel.send(
|
message.channel.send(
|
||||||
`🔰 Assign your roles here! <${this.appUrl}/s/${message.guild.id}>`,
|
`🔰 Assign your roles here! <${this.appUrl}/s/${message.guild.id}>`,
|
||||||
{ disableEveryone: true }
|
{ disableEveryone: true }
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
_cmds() {
|
_cmds() {
|
||||||
|
@ -174,15 +174,15 @@ class DiscordService extends Service {
|
||||||
{
|
{
|
||||||
regex: /say (.*)/,
|
regex: /say (.*)/,
|
||||||
handler(message, matches, r) {
|
handler(message, matches, r) {
|
||||||
r(matches[0]);
|
r(matches[0])
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
regex: /set username (.*)/,
|
regex: /set username (.*)/,
|
||||||
async handler(message, matches) {
|
async handler(message, matches) {
|
||||||
const { username } = this.client.user;
|
const { username } = this.client.user
|
||||||
await this.client.user.setUsername(matches[0]);
|
await this.client.user.setUsername(matches[0])
|
||||||
message.channel.send(`Username changed from ${username} to ${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,
|
(acc, g) => acc + g.roles.size,
|
||||||
0
|
0
|
||||||
)}`,
|
)}`,
|
||||||
];
|
]
|
||||||
message.channel.send(t.join('\n'));
|
message.channel.send(t.join('\n'))
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
@ -209,51 +209,51 @@ class DiscordService extends Service {
|
||||||
.map(({ regex, ...rest }) => ({
|
.map(({ regex, ...rest }) => ({
|
||||||
regex: new RegExp(`^${regex.source}`, regex.flags),
|
regex: new RegExp(`^${regex.source}`, regex.flags),
|
||||||
...rest,
|
...rest,
|
||||||
}));
|
}))
|
||||||
|
|
||||||
return cmds;
|
return cmds
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleCommand(message) {
|
async handleCommand(message) {
|
||||||
const cmd = message.content.replace(`<@${this.client.user.id}> `, '');
|
const cmd = message.content.replace(`<@${this.client.user.id}> `, '')
|
||||||
this.log.debug(`got command from ${message.author.username}`, cmd);
|
this.log.debug(`got command from ${message.author.username}`, cmd)
|
||||||
for (let { regex, handler } of this.cmds) {
|
for (let { regex, handler } of this.cmds) {
|
||||||
const match = regex.exec(cmd);
|
const match = regex.exec(cmd)
|
||||||
if (match !== null) {
|
if (match !== null) {
|
||||||
this.log.debug('command accepted', { cmd, match });
|
this.log.debug('command accepted', { cmd, match })
|
||||||
try {
|
try {
|
||||||
await handler.call(this, message, match.slice(1));
|
await handler.call(this, message, match.slice(1))
|
||||||
return;
|
return
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.log.error('command errored', { e, cmd, message });
|
this.log.error('command errored', { e, cmd, message })
|
||||||
message.channel.send(`❌ **An error occured.** ${e}`);
|
message.channel.send(`❌ **An error occured.** ${e}`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// nothing matched?
|
// nothing matched?
|
||||||
this.mentionResponse(message);
|
this.mentionResponse(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMessage(message) {
|
handleMessage(message) {
|
||||||
if (message.author.bot && message.channel.type !== 'text') {
|
if (message.author.bot && message.channel.type !== 'text') {
|
||||||
// drop bot messages and dms
|
// drop bot messages and dms
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.mentions.users.has(this.client.user.id)) {
|
if (message.mentions.users.has(this.client.user.id)) {
|
||||||
if (this.rootUsers.has(message.author.id)) {
|
if (this.rootUsers.has(message.author.id)) {
|
||||||
this.handleCommand(message);
|
this.handleCommand(message)
|
||||||
} else {
|
} else {
|
||||||
this.mentionResponse(message);
|
this.mentionResponse(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleJoin(guild) {
|
async handleJoin(guild) {
|
||||||
await this.ctx.server.ensure(guild);
|
await this.ctx.server.ensure(guild)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = DiscordService;
|
module.exports = DiscordService
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
const Service = require('./Service');
|
const Service = require('./Service')
|
||||||
const LRU = require('lru-cache');
|
const LRU = require('lru-cache')
|
||||||
|
|
||||||
class PresentationService extends Service {
|
class PresentationService extends Service {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx)
|
||||||
this.M = ctx.M;
|
this.M = ctx.M
|
||||||
this.discord = ctx.discord;
|
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) {
|
serverSlug(server) {
|
||||||
|
@ -16,31 +16,31 @@ class PresentationService extends Service {
|
||||||
name: server.name,
|
name: server.name,
|
||||||
ownerID: server.ownerID,
|
ownerID: server.ownerID,
|
||||||
icon: server.icon,
|
icon: server.icon,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async oldPresentableServers(collection, userId) {
|
async oldPresentableServers(collection, userId) {
|
||||||
let servers = [];
|
let servers = []
|
||||||
|
|
||||||
for (let server of collection.array()) {
|
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) {
|
async presentableServers(collection, userId) {
|
||||||
return collection.array().areduce(async (acc, server) => {
|
return collection.array().areduce(async (acc, server) => {
|
||||||
const gm = server.members.get(userId);
|
const gm = server.members.get(userId)
|
||||||
acc.push(await this.presentableServer(server, gm, { incRoles: false }));
|
acc.push(await this.presentableServer(server, gm, { incRoles: false }))
|
||||||
return acc;
|
return acc
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async presentableServer(server, gm, { incRoles = true } = {}) {
|
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 {
|
return {
|
||||||
id: server.id,
|
id: server.id,
|
||||||
|
@ -58,7 +58,7 @@ class PresentationService extends Service {
|
||||||
message: sd.message,
|
message: sd.message,
|
||||||
categories: sd.categories,
|
categories: sd.categories,
|
||||||
perms: this.discord.getPermissions(gm),
|
perms: this.discord.getPermissions(gm),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async rolesByServer(server) {
|
async rolesByServer(server) {
|
||||||
|
@ -70,8 +70,8 @@ class PresentationService extends Service {
|
||||||
name: r.name,
|
name: r.name,
|
||||||
position: r.position,
|
position: r.position,
|
||||||
safe: this.discord.safeRole(server.id, r.id),
|
safe: this.discord.safeRole(server.id, r.id),
|
||||||
}));
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = PresentationService;
|
module.exports = PresentationService
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
const Service = require('./Service');
|
const Service = require('./Service')
|
||||||
|
|
||||||
class ServerService extends Service {
|
class ServerService extends Service {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx)
|
||||||
this.Server = ctx.M.Server;
|
this.Server = ctx.M.Server
|
||||||
this.P = ctx.P;
|
this.P = ctx.P
|
||||||
}
|
}
|
||||||
|
|
||||||
async ensure(server) {
|
async ensure(server) {
|
||||||
let srv;
|
let srv
|
||||||
try {
|
try {
|
||||||
srv = await this.get(server.id);
|
srv = await this.get(server.id)
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
|
||||||
if (srv == null) {
|
if (srv == null) {
|
||||||
|
@ -18,20 +18,20 @@ class ServerService extends Service {
|
||||||
id: server.id,
|
id: server.id,
|
||||||
message: '',
|
message: '',
|
||||||
categories: {},
|
categories: {},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
create({ 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) {
|
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) {
|
async get(id, plain = true) {
|
||||||
|
@ -39,26 +39,26 @@ class ServerService extends Service {
|
||||||
where: {
|
where: {
|
||||||
id,
|
id,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
if (!plain) {
|
if (!plain) {
|
||||||
return s;
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.get({ plain: true });
|
return s.get({ plain: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAllowedRoles(id) {
|
async getAllowedRoles(id) {
|
||||||
const server = await this.get(id);
|
const server = await this.get(id)
|
||||||
|
|
||||||
return Object.values(server.categories).reduce((acc, c) => {
|
return Object.values(server.categories).reduce((acc, c) => {
|
||||||
if (c.hidden !== true) {
|
if (c.hidden !== true) {
|
||||||
return acc.concat(c.roles);
|
return acc.concat(c.roles)
|
||||||
}
|
}
|
||||||
|
|
||||||
return acc;
|
return acc
|
||||||
}, []);
|
}, [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ServerService;
|
module.exports = ServerService
|
||||||
|
|
|
@ -1,40 +1,40 @@
|
||||||
const Service = require('./Service');
|
const Service = require('./Service')
|
||||||
|
|
||||||
class SessionsService extends Service {
|
class SessionsService extends Service {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx)
|
||||||
this.Session = ctx.M.Session;
|
this.Session = ctx.M.Session
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(id, { rolling }) {
|
async get(id, { rolling }) {
|
||||||
const user = await this.Session.findOne({ where: { id } });
|
const user = await this.Session.findOne({ where: { id } })
|
||||||
|
|
||||||
if (user === null) {
|
if (user === null) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return user.data;
|
return user.data
|
||||||
}
|
}
|
||||||
|
|
||||||
async set(id, data, { maxAge, rolling, changed }) {
|
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) {
|
if (session === null) {
|
||||||
session = this.Session.build({ id });
|
session = this.Session.build({ id })
|
||||||
}
|
}
|
||||||
|
|
||||||
session.data = data;
|
session.data = data
|
||||||
session.maxAge = maxAge;
|
session.maxAge = maxAge
|
||||||
|
|
||||||
return session.save();
|
return session.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
async destroy(id) {
|
async destroy(id) {
|
||||||
const sess = await this.Session.findOne({ where: { id } });
|
const sess = await this.Session.findOne({ where: { id } })
|
||||||
|
|
||||||
if (sess != null) {
|
if (sess != null) {
|
||||||
return sess.destroy();
|
return sess.destroy()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = SessionsService;
|
module.exports = SessionsService
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
const ksuid = require('ksuid');
|
const ksuid = require('ksuid')
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
ksuid(field = 'id') {
|
ksuid(field = 'id') {
|
||||||
return async function() {
|
return async function() {
|
||||||
this.id = await ksuid.random();
|
this.id = await ksuid.random()
|
||||||
return this;
|
return this
|
||||||
};
|
}
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
|
|
|
@ -5,5 +5,5 @@ module.exports = {
|
||||||
singleQuote: true,
|
singleQuote: true,
|
||||||
trailingComma: 'es5',
|
trailingComma: 'es5',
|
||||||
bracketSpacing: true,
|
bracketSpacing: true,
|
||||||
semi: true,
|
semi: false,
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,26 +1,26 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Provider } from 'react-redux';
|
import { Provider } from 'react-redux'
|
||||||
import { ConnectedRouter } from 'react-router-redux';
|
import { ConnectedRouter } from 'react-router-redux'
|
||||||
import { DragDropContext } from 'react-dnd';
|
import { DragDropContext } from 'react-dnd'
|
||||||
import HTML5Backend from 'react-dnd-html5-backend';
|
import HTML5Backend from 'react-dnd-html5-backend'
|
||||||
import createHistory from 'history/createBrowserHistory';
|
import createHistory from 'history/createBrowserHistory'
|
||||||
import configureStore from './store/configureStore';
|
import configureStore from './store/configureStore'
|
||||||
import './App.css';
|
import './App.css'
|
||||||
import './generic.sass';
|
import './generic.sass'
|
||||||
|
|
||||||
import Wrapper from './components/wrapper';
|
import Wrapper from './components/wrapper'
|
||||||
import AppRouter from './router';
|
import AppRouter from './router'
|
||||||
import { userInit } from './actions';
|
import { userInit } from './actions'
|
||||||
|
|
||||||
const history = createHistory();
|
const history = createHistory()
|
||||||
const store = configureStore(undefined, history);
|
const store = configureStore(undefined, history)
|
||||||
|
|
||||||
window.__APP_STORE__ = store;
|
window.__APP_STORE__ = store
|
||||||
|
|
||||||
@DragDropContext(HTML5Backend)
|
@DragDropContext(HTML5Backend)
|
||||||
class App extends Component {
|
class App extends Component {
|
||||||
componentWillMount() {
|
componentWillMount() {
|
||||||
store.dispatch(userInit);
|
store.dispatch(userInit)
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
|
@ -32,8 +32,8 @@ class App extends Component {
|
||||||
</Wrapper>
|
</Wrapper>
|
||||||
</ConnectedRouter>
|
</ConnectedRouter>
|
||||||
</Provider>
|
</Provider>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default App;
|
export default App
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import ReactDOM from 'react-dom';
|
import ReactDOM from 'react-dom'
|
||||||
import App from './App';
|
import App from './App'
|
||||||
|
|
||||||
it('renders without crashing', () => {
|
it('renders without crashing', () => {
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div')
|
||||||
ReactDOM.render(<App />, div);
|
ReactDOM.render(<App />, div)
|
||||||
});
|
})
|
||||||
|
|
|
@ -1,88 +1,88 @@
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import { push } from 'react-router-redux';
|
import { push } from 'react-router-redux'
|
||||||
|
|
||||||
export const fetchServers = async dispatch => {
|
export const fetchServers = async dispatch => {
|
||||||
const rsp = await superagent.get('/api/servers');
|
const rsp = await superagent.get('/api/servers')
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('update servers'),
|
type: Symbol.for('update servers'),
|
||||||
data: rsp.body,
|
data: rsp.body,
|
||||||
});
|
})
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('app ready'),
|
type: Symbol.for('app ready'),
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const userInit = async dispatch => {
|
export const userInit = async dispatch => {
|
||||||
if (!window.location.pathname.startsWith('/oauth')) {
|
if (!window.location.pathname.startsWith('/oauth')) {
|
||||||
try {
|
try {
|
||||||
const rsp = await superagent.get('/api/auth/user');
|
const rsp = await superagent.get('/api/auth/user')
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('set user'),
|
type: Symbol.for('set user'),
|
||||||
data: rsp.body,
|
data: rsp.body,
|
||||||
});
|
})
|
||||||
|
|
||||||
dispatch(fetchServers);
|
dispatch(fetchServers)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('app ready'),
|
type: Symbol.for('app ready'),
|
||||||
});
|
})
|
||||||
// window.location.href = '/oauth/flow'
|
// window.location.href = '/oauth/flow'
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('app ready'),
|
type: Symbol.for('app ready'),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const userLogout = async dispatch => {
|
export const userLogout = async dispatch => {
|
||||||
try {
|
try {
|
||||||
await superagent.post('/api/auth/logout');
|
await superagent.post('/api/auth/logout')
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('reset user'),
|
type: Symbol.for('reset user'),
|
||||||
});
|
})
|
||||||
|
|
||||||
window.location.href = '/';
|
window.location.href = '/'
|
||||||
};
|
}
|
||||||
|
|
||||||
export const startServerPolling = dispatch => {
|
export const startServerPolling = dispatch => {
|
||||||
return poll(window.__APP_STORE__.dispatch, window.__APP_STORE__.getState); // let's not cheat... :c
|
return poll(window.__APP_STORE__.dispatch, window.__APP_STORE__.getState) // let's not cheat... :c
|
||||||
};
|
}
|
||||||
|
|
||||||
const poll = (dispatch, getState) => {
|
const poll = (dispatch, getState) => {
|
||||||
const { servers } = getState();
|
const { servers } = getState()
|
||||||
let stop = false;
|
let stop = false
|
||||||
const stopPolling = () => {
|
const stopPolling = () => {
|
||||||
stop = true;
|
stop = true
|
||||||
};
|
}
|
||||||
const pollFunc = async () => {
|
const pollFunc = async () => {
|
||||||
if (stop) {
|
if (stop) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await fetchServers(dispatch);
|
await fetchServers(dispatch)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e)
|
||||||
setTimeout(pollFunc, 5000);
|
setTimeout(pollFunc, 5000)
|
||||||
}
|
}
|
||||||
|
|
||||||
const newServers = getState().servers;
|
const newServers = getState().servers
|
||||||
if (servers.size >= newServers.size) {
|
if (servers.size >= newServers.size) {
|
||||||
setTimeout(pollFunc, 5000);
|
setTimeout(pollFunc, 5000)
|
||||||
} else {
|
} else {
|
||||||
const old = servers.keySeq().toSet();
|
const old = servers.keySeq().toSet()
|
||||||
const upd = newServers.keySeq().toSet();
|
const upd = newServers.keySeq().toSet()
|
||||||
const newSrv = upd.subtract(old);
|
const newSrv = upd.subtract(old)
|
||||||
stopPolling();
|
stopPolling()
|
||||||
dispatch(push(`/s/${newSrv.toJS()[0]}/edit`));
|
dispatch(push(`/s/${newSrv.toJS()[0]}/edit`))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
pollFunc();
|
pollFunc()
|
||||||
return stopPolling;
|
return stopPolling
|
||||||
};
|
}
|
||||||
|
|
|
@ -2,12 +2,12 @@ export const fadeOut = cb => dispatch => {
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('app fade'),
|
type: Symbol.for('app fade'),
|
||||||
data: true,
|
data: true,
|
||||||
});
|
})
|
||||||
|
|
||||||
setTimeout(cb, 300);
|
setTimeout(cb, 300)
|
||||||
};
|
}
|
||||||
|
|
||||||
export const fadeIn = {
|
export const fadeIn = {
|
||||||
type: Symbol.for('app fade'),
|
type: Symbol.for('app fade'),
|
||||||
data: false,
|
data: false,
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,23 +1,23 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom'
|
||||||
import TypingDemo from '../demos/typing';
|
import TypingDemo from '../demos/typing'
|
||||||
import RoleypolyDemo from '../demos/roleypoly';
|
import RoleypolyDemo from '../demos/roleypoly'
|
||||||
import * as Actions from '../../actions';
|
import * as Actions from '../../actions'
|
||||||
import './styles.sass';
|
import './styles.sass'
|
||||||
import discordLogo from '../../pages/images/discord-logo.svg';
|
import discordLogo from '../../pages/images/discord-logo.svg'
|
||||||
|
|
||||||
export default class AddServer extends Component {
|
export default class AddServer extends Component {
|
||||||
polling = null;
|
polling = null
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
if (this.props.match.params.server !== undefined) {
|
if (this.props.match.params.server !== undefined) {
|
||||||
this.pollingStop = Actions.startServerPolling(this.props.dispatch);
|
this.pollingStop = Actions.startServerPolling(this.props.dispatch)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillUnmount() {
|
componentWillUnmount() {
|
||||||
if (this.pollingStop != null) {
|
if (this.pollingStop != null) {
|
||||||
this.pollingStop();
|
this.pollingStop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,6 +59,6 @@ export default class AddServer extends Component {
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import RoleDemo from '../role/demo';
|
import RoleDemo from '../role/demo'
|
||||||
|
|
||||||
const RoleypolyDemo = () => (
|
const RoleypolyDemo = () => (
|
||||||
<div className="demo__roleypoly">
|
<div className="demo__roleypoly">
|
||||||
|
@ -9,6 +9,6 @@ const RoleypolyDemo = () => (
|
||||||
<RoleDemo name="a proud role ♡" color="#5C8B88" />
|
<RoleDemo name="a proud role ♡" color="#5C8B88" />
|
||||||
<RoleDemo name="a wonderful role ♡" color="#D6B3C7" />
|
<RoleDemo name="a wonderful role ♡" color="#D6B3C7" />
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
|
|
||||||
export default RoleypolyDemo;
|
export default RoleypolyDemo
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import moment from 'moment';
|
import moment from 'moment'
|
||||||
import Typist from 'react-typist';
|
import Typist from 'react-typist'
|
||||||
import './typing.sass';
|
import './typing.sass'
|
||||||
|
|
||||||
const Typing = () => (
|
const Typing = () => (
|
||||||
<div className="demo__discord rp-discord">
|
<div className="demo__discord rp-discord">
|
||||||
|
@ -26,6 +26,6 @@ const Typing = () => (
|
||||||
</Typist>
|
</Typist>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
|
|
||||||
export default Typing;
|
export default Typing
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import { createDevTools } from 'redux-devtools';
|
import { createDevTools } from 'redux-devtools'
|
||||||
import LogMonitor from 'redux-devtools-log-monitor';
|
import LogMonitor from 'redux-devtools-log-monitor'
|
||||||
import DockMonitor from 'redux-devtools-dock-monitor';
|
import DockMonitor from 'redux-devtools-dock-monitor'
|
||||||
|
|
||||||
export default createDevTools(
|
export default createDevTools(
|
||||||
<DockMonitor toggleVisibilityKey="`" changePositionKey="ctrl-w">
|
<DockMonitor toggleVisibilityKey="`" changePositionKey="ctrl-w">
|
||||||
<LogMonitor />
|
<LogMonitor />
|
||||||
</DockMonitor>
|
</DockMonitor>
|
||||||
);
|
)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
|
|
||||||
const Logotype = ({
|
const Logotype = ({
|
||||||
fill = 'var(--c-7)',
|
fill = 'var(--c-7)',
|
||||||
|
@ -39,6 +39,6 @@ const Logotype = ({
|
||||||
></use>
|
></use>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
);
|
)
|
||||||
|
|
||||||
export default Logotype;
|
export default Logotype
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Redirect } from 'react-router-dom';
|
import { Redirect } from 'react-router-dom'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { push } from 'react-router-redux';
|
import { push } from 'react-router-redux'
|
||||||
import { fetchServers } from '../../actions';
|
import { fetchServers } from '../../actions'
|
||||||
|
|
||||||
@connect()
|
@connect()
|
||||||
class OauthCallback extends Component {
|
class OauthCallback extends Component {
|
||||||
|
@ -11,14 +11,14 @@ class OauthCallback extends Component {
|
||||||
notReady: true,
|
notReady: true,
|
||||||
message: 'chotto matte kudasai...',
|
message: 'chotto matte kudasai...',
|
||||||
url: null,
|
url: null,
|
||||||
};
|
}
|
||||||
|
|
||||||
async componentDidMount() {
|
async componentDidMount() {
|
||||||
const {
|
const {
|
||||||
body: { url },
|
body: { url },
|
||||||
} = await superagent.get('/api/oauth/bot?url=✔️');
|
} = await superagent.get('/api/oauth/bot?url=✔️')
|
||||||
this.setState({ url, notReady: false });
|
this.setState({ url, notReady: false })
|
||||||
window.location.href = url;
|
window.location.href = url
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
|
@ -28,8 +28,8 @@ class OauthCallback extends Component {
|
||||||
<a style={{ zIndex: 10000 }} href={this.state.url}>
|
<a style={{ zIndex: 10000 }} href={this.state.url}>
|
||||||
Something oopsed, click me to get to where you meant.
|
Something oopsed, click me to get to where you meant.
|
||||||
</a>
|
</a>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default OauthCallback;
|
export default OauthCallback
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Redirect } from 'react-router-dom';
|
import { Redirect } from 'react-router-dom'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { fetchServers } from '../../actions';
|
import { fetchServers } from '../../actions'
|
||||||
|
|
||||||
@connect()
|
@connect()
|
||||||
class OauthCallback extends Component {
|
class OauthCallback extends Component {
|
||||||
|
@ -10,66 +10,66 @@ class OauthCallback extends Component {
|
||||||
notReady: true,
|
notReady: true,
|
||||||
message: 'chotto matte kudasai...',
|
message: 'chotto matte kudasai...',
|
||||||
redirect: '/s',
|
redirect: '/s',
|
||||||
};
|
}
|
||||||
|
|
||||||
stopped = false;
|
stopped = false
|
||||||
|
|
||||||
componentDidUnmount() {
|
componentDidUnmount() {
|
||||||
this.stopped = true;
|
this.stopped = true
|
||||||
}
|
}
|
||||||
|
|
||||||
async componentDidMount() {
|
async componentDidMount() {
|
||||||
// handle stuff in the url
|
// handle stuff in the url
|
||||||
const sp = new URLSearchParams(this.props.location.search);
|
const sp = new URLSearchParams(this.props.location.search)
|
||||||
const token = sp.get('code');
|
const token = sp.get('code')
|
||||||
|
|
||||||
if (token === '' || token == null) {
|
if (token === '' || token == null) {
|
||||||
this.setState({ message: 'token missing, what are you trying to do?!' });
|
this.setState({ message: 'token missing, what are you trying to do?!' })
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const stateToken = sp.get('state');
|
const stateToken = sp.get('state')
|
||||||
const state = JSON.parse(window.sessionStorage.getItem('state') || 'null');
|
const state = JSON.parse(window.sessionStorage.getItem('state') || 'null')
|
||||||
|
|
||||||
if (state !== null && state.state === stateToken && state.redirect != null) {
|
if (state !== null && state.state === stateToken && state.redirect != null) {
|
||||||
this.setState({ redirect: state.redirect });
|
this.setState({ redirect: state.redirect })
|
||||||
}
|
}
|
||||||
|
|
||||||
this.props.history.replace(this.props.location.pathname);
|
this.props.history.replace(this.props.location.pathname)
|
||||||
|
|
||||||
let counter = 0;
|
let counter = 0
|
||||||
const retry = async () => {
|
const retry = async () => {
|
||||||
if (this.stopped) return;
|
if (this.stopped) return
|
||||||
try {
|
try {
|
||||||
const rsp = await superagent.get('/api/auth/user');
|
const rsp = await superagent.get('/api/auth/user')
|
||||||
this.props.dispatch({
|
this.props.dispatch({
|
||||||
type: Symbol.for('set user'),
|
type: Symbol.for('set user'),
|
||||||
data: rsp.body,
|
data: rsp.body,
|
||||||
});
|
})
|
||||||
this.props.dispatch(fetchServers);
|
this.props.dispatch(fetchServers)
|
||||||
this.setState({ notReady: false });
|
this.setState({ notReady: false })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
counter++;
|
counter++
|
||||||
if (counter > 10) {
|
if (counter > 10) {
|
||||||
this.setState({ message: "i couldn't log you in. :c" });
|
this.setState({ message: "i couldn't log you in. :c" })
|
||||||
} else {
|
} else {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
retry();
|
retry()
|
||||||
}, 250);
|
}, 250)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
// pass token to backend, await it to finish it's business.
|
// pass token to backend, await it to finish it's business.
|
||||||
try {
|
try {
|
||||||
await superagent.post('/api/auth/token').send({ token });
|
await superagent.post('/api/auth/token').send({ token })
|
||||||
// this.props.onLogin(rsp.body)
|
// this.props.onLogin(rsp.body)
|
||||||
|
|
||||||
retry();
|
retry()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('token pass error', e);
|
console.error('token pass error', e)
|
||||||
this.setState({ message: 'g-gomen nasai... i broke it...' });
|
this.setState({ message: 'g-gomen nasai... i broke it...' })
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// update user stuff here
|
// update user stuff here
|
||||||
|
@ -80,8 +80,8 @@ class OauthCallback extends Component {
|
||||||
this.state.message
|
this.state.message
|
||||||
) : (
|
) : (
|
||||||
<Redirect to={this.state.redirect} />
|
<Redirect to={this.state.redirect} />
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default OauthCallback;
|
export default OauthCallback
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Redirect } from 'react-router-dom';
|
import { Redirect } from 'react-router-dom'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import uuidv4 from 'uuid/v4';
|
import uuidv4 from 'uuid/v4'
|
||||||
import { fetchServers } from '../../actions';
|
import { fetchServers } from '../../actions'
|
||||||
|
|
||||||
@connect()
|
@connect()
|
||||||
class OauthCallback extends Component {
|
class OauthCallback extends Component {
|
||||||
|
@ -12,60 +12,60 @@ class OauthCallback extends Component {
|
||||||
message: 'chotto matte kudasai...',
|
message: 'chotto matte kudasai...',
|
||||||
redirect: '/s',
|
redirect: '/s',
|
||||||
url: null,
|
url: null,
|
||||||
};
|
}
|
||||||
|
|
||||||
async fetchUser() {
|
async fetchUser() {
|
||||||
const rsp = await superagent.get('/api/auth/user');
|
const rsp = await superagent.get('/api/auth/user')
|
||||||
sessionStorage.setItem('user', JSON.stringify(rsp.body));
|
sessionStorage.setItem('user', JSON.stringify(rsp.body))
|
||||||
sessionStorage.setItem('user.update', JSON.stringify(Date.now()));
|
sessionStorage.setItem('user.update', JSON.stringify(Date.now()))
|
||||||
this.props.dispatch({
|
this.props.dispatch({
|
||||||
type: Symbol.for('set user'),
|
type: Symbol.for('set user'),
|
||||||
data: rsp.body,
|
data: rsp.body,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
setupUser() {
|
setupUser() {
|
||||||
const userUpdateTime = sessionStorage.getItem('user.update') || 0;
|
const userUpdateTime = sessionStorage.getItem('user.update') || 0
|
||||||
if (+userUpdateTime + 1000 * 60 * 10 > Date.now()) {
|
if (+userUpdateTime + 1000 * 60 * 10 > Date.now()) {
|
||||||
const user = sessionStorage.getItem('user');
|
const user = sessionStorage.getItem('user')
|
||||||
if (user != null && user !== '') {
|
if (user != null && user !== '') {
|
||||||
this.props.dispatch({
|
this.props.dispatch({
|
||||||
type: Symbol.for('set user'),
|
type: Symbol.for('set user'),
|
||||||
data: JSON.parse(user),
|
data: JSON.parse(user),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.fetchUser();
|
return this.fetchUser()
|
||||||
}
|
}
|
||||||
|
|
||||||
async componentDidMount() {
|
async componentDidMount() {
|
||||||
const state = uuidv4();
|
const state = uuidv4()
|
||||||
|
|
||||||
const oUrl = new URL(window.location.href);
|
const oUrl = new URL(window.location.href)
|
||||||
if (oUrl.searchParams.has('r')) {
|
if (oUrl.searchParams.has('r')) {
|
||||||
this.setState({ redirect: oUrl.searchParams.get('r') });
|
this.setState({ redirect: oUrl.searchParams.get('r') })
|
||||||
}
|
}
|
||||||
|
|
||||||
window.sessionStorage.setItem(
|
window.sessionStorage.setItem(
|
||||||
'state',
|
'state',
|
||||||
JSON.stringify({ state, redirect: oUrl.searchParams.get('r') })
|
JSON.stringify({ state, redirect: oUrl.searchParams.get('r') })
|
||||||
);
|
)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.setupUser();
|
await this.setupUser()
|
||||||
|
|
||||||
this.props.dispatch(fetchServers);
|
this.props.dispatch(fetchServers)
|
||||||
this.setState({ notReady: false });
|
this.setState({ notReady: false })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const {
|
const {
|
||||||
body: { url },
|
body: { url },
|
||||||
} = await superagent.get('/api/auth/redirect?url=✔️');
|
} = await superagent.get('/api/auth/redirect?url=✔️')
|
||||||
const nUrl = new URL(url);
|
const nUrl = new URL(url)
|
||||||
|
|
||||||
nUrl.searchParams.set('state', state);
|
nUrl.searchParams.set('state', state)
|
||||||
this.setState({ url: nUrl.toString() });
|
this.setState({ url: nUrl.toString() })
|
||||||
window.location.href = nUrl.toString();
|
window.location.href = nUrl.toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -79,8 +79,8 @@ class OauthCallback extends Component {
|
||||||
Something oopsed, click me to get to where you meant.
|
Something oopsed, click me to get to where you meant.
|
||||||
</a>
|
</a>
|
||||||
</>
|
</>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default OauthCallback;
|
export default OauthCallback
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { DropTarget } from 'react-dnd';
|
import { DropTarget } from 'react-dnd'
|
||||||
|
|
||||||
import Role from '../role/draggable';
|
import Role from '../role/draggable'
|
||||||
import CategoryEditor from './CategoryEditor';
|
import CategoryEditor from './CategoryEditor'
|
||||||
|
|
||||||
@DropTarget(
|
@DropTarget(
|
||||||
Symbol.for('dnd: role'),
|
Symbol.for('dnd: role'),
|
||||||
{
|
{
|
||||||
drop(props, monitor, element) {
|
drop(props, monitor, element) {
|
||||||
props.onDrop(monitor.getItem());
|
props.onDrop(monitor.getItem())
|
||||||
},
|
},
|
||||||
canDrop(props, monitor) {
|
canDrop(props, monitor) {
|
||||||
return (
|
return (
|
||||||
props.mode !== Symbol.for('edit') && monitor.getItem().category !== props.name
|
props.mode !== Symbol.for('edit') && monitor.getItem().category !== props.name
|
||||||
);
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
(connect, monitor) => ({
|
(connect, monitor) => ({
|
||||||
|
@ -35,10 +35,10 @@ class Category extends Component {
|
||||||
mode,
|
mode,
|
||||||
onEditOpen,
|
onEditOpen,
|
||||||
...rest
|
...rest
|
||||||
} = this.props;
|
} = this.props
|
||||||
|
|
||||||
if (mode === Symbol.for('edit')) {
|
if (mode === Symbol.for('edit')) {
|
||||||
return <CategoryEditor category={category} name={name} {...rest} />;
|
return <CategoryEditor category={category} name={name} {...rest} />
|
||||||
}
|
}
|
||||||
|
|
||||||
return connectDropTarget(
|
return connectDropTarget(
|
||||||
|
@ -63,7 +63,7 @@ class Category extends Component {
|
||||||
.map((r, k) => <Role key={k} role={r} categoryId={name} />)
|
.map((r, k) => <Role key={k} role={r} categoryId={name} />)
|
||||||
.toArray()}
|
.toArray()}
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export default Category;
|
export default Category
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
|
|
||||||
export default class CategoryEditor extends Component {
|
export default class CategoryEditor extends Component {
|
||||||
onKeyPress = e => {
|
onKeyPress = e => {
|
||||||
const { onSave } = this.props;
|
const { onSave } = this.props
|
||||||
|
|
||||||
switch (e.key) {
|
switch (e.key) {
|
||||||
case 'Enter':
|
case 'Enter':
|
||||||
case 'Escape':
|
case 'Escape':
|
||||||
return onSave();
|
return onSave()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { category } = this.props;
|
const { category } = this.props
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="role-editor__category editor" onKeyDown={this.onKeyPress}>
|
<div className="role-editor__category editor" onKeyDown={this.onKeyPress}>
|
||||||
|
@ -104,6 +104,6 @@ export default class CategoryEditor extends Component {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
import { Set } from 'immutable';
|
import { Set } from 'immutable'
|
||||||
import * as UIActions from '../../actions/ui';
|
import * as UIActions from '../../actions/ui'
|
||||||
import { getViewMap, setup } from '../role-picker/actions';
|
import { getViewMap, setup } from '../role-picker/actions'
|
||||||
import uuidv4 from 'uuid/v4';
|
import uuidv4 from 'uuid/v4'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
|
|
||||||
export const constructView = id => async (dispatch, getState) => {
|
export const constructView = id => async (dispatch, getState) => {
|
||||||
await setup(id)(dispatch);
|
await setup(id)(dispatch)
|
||||||
const server = getState().servers.get(id);
|
const server = getState().servers.get(id)
|
||||||
|
|
||||||
let { viewMap, hasSafeRoles } = getViewMap(server);
|
let { viewMap, hasSafeRoles } = getViewMap(server)
|
||||||
viewMap = viewMap.map((c, idx) => c.set('mode', Symbol.for('drop')));
|
viewMap = viewMap.map((c, idx) => c.set('mode', Symbol.for('drop')))
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('re: setup'),
|
type: Symbol.for('re: setup'),
|
||||||
|
@ -18,10 +18,10 @@ export const constructView = id => async (dispatch, getState) => {
|
||||||
viewMap,
|
viewMap,
|
||||||
originalSnapshot: viewMap,
|
originalSnapshot: viewMap,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
dispatch(UIActions.fadeIn);
|
dispatch(UIActions.fadeIn)
|
||||||
};
|
}
|
||||||
|
|
||||||
export const addRoleToCategory = (id, oldId, role, flip = true) => dispatch => {
|
export const addRoleToCategory = (id, oldId, role, flip = true) => dispatch => {
|
||||||
dispatch({
|
dispatch({
|
||||||
|
@ -30,12 +30,12 @@ export const addRoleToCategory = (id, oldId, role, flip = true) => dispatch => {
|
||||||
id,
|
id,
|
||||||
role,
|
role,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
if (flip) {
|
if (flip) {
|
||||||
dispatch(removeRoleFromCategory(oldId, id, role, false));
|
dispatch(removeRoleFromCategory(oldId, id, role, false))
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const removeRoleFromCategory = (id, oldId, role, flip = true) => dispatch => {
|
export const removeRoleFromCategory = (id, oldId, role, flip = true) => dispatch => {
|
||||||
dispatch({
|
dispatch({
|
||||||
|
@ -44,12 +44,12 @@ export const removeRoleFromCategory = (id, oldId, role, flip = true) => dispatch
|
||||||
id,
|
id,
|
||||||
role,
|
role,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
if (flip) {
|
if (flip) {
|
||||||
dispatch(addRoleToCategory(oldId, id, role, false));
|
dispatch(addRoleToCategory(oldId, id, role, false))
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const editCategory = ({ id, key, value }) => dispatch => {
|
export const editCategory = ({ id, key, value }) => dispatch => {
|
||||||
dispatch({
|
dispatch({
|
||||||
|
@ -59,12 +59,12 @@ export const editCategory = ({ id, key, value }) => dispatch => {
|
||||||
key,
|
key,
|
||||||
value,
|
value,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const saveCategory = (id, category) => dispatch => {
|
export const saveCategory = (id, category) => dispatch => {
|
||||||
if (category.get('name') === '') {
|
if (category.get('name') === '') {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
|
@ -73,8 +73,8 @@ export const saveCategory = (id, category) => dispatch => {
|
||||||
id,
|
id,
|
||||||
mode: Symbol.for('drop'),
|
mode: Symbol.for('drop'),
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const openEditor = id => ({
|
export const openEditor = id => ({
|
||||||
type: Symbol.for('re: switch category mode'),
|
type: Symbol.for('re: switch category mode'),
|
||||||
|
@ -82,13 +82,13 @@ export const openEditor = id => ({
|
||||||
id,
|
id,
|
||||||
mode: Symbol.for('edit'),
|
mode: Symbol.for('edit'),
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
export const deleteCategory = (id, category) => (dispatch, getState) => {
|
export const deleteCategory = (id, category) => (dispatch, getState) => {
|
||||||
const roles = category.get('roles');
|
const roles = category.get('roles')
|
||||||
const rolesMap = category.get('roles_map');
|
const rolesMap = category.get('roles_map')
|
||||||
|
|
||||||
let uncategorized = getState().roleEditor.getIn(['viewMap', 'Uncategorized']);
|
let uncategorized = getState().roleEditor.getIn(['viewMap', 'Uncategorized'])
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('re: set category'),
|
type: Symbol.for('re: set category'),
|
||||||
|
@ -101,27 +101,27 @@ export const deleteCategory = (id, category) => (dispatch, getState) => {
|
||||||
type: 'multi',
|
type: 'multi',
|
||||||
mode: null,
|
mode: null,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('re: delete category'),
|
type: Symbol.for('re: delete category'),
|
||||||
data: id,
|
data: id,
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const createCategory = (dispatch, getState) => {
|
export const createCategory = (dispatch, getState) => {
|
||||||
const { roleEditor } = getState();
|
const { roleEditor } = getState()
|
||||||
const vm = roleEditor.get('viewMap');
|
const vm = roleEditor.get('viewMap')
|
||||||
|
|
||||||
let name = 'New Category';
|
let name = 'New Category'
|
||||||
let idx = 1;
|
let idx = 1
|
||||||
const pred = c => c.get('name') === name;
|
const pred = c => c.get('name') === name
|
||||||
while (vm.find(pred) !== undefined) {
|
while (vm.find(pred) !== undefined) {
|
||||||
idx++;
|
idx++
|
||||||
name = `New Category ${idx}`;
|
name = `New Category ${idx}`
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = uuidv4();
|
const id = uuidv4()
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('re: set category'),
|
type: Symbol.for('re: set category'),
|
||||||
|
@ -135,17 +135,17 @@ export const createCategory = (dispatch, getState) => {
|
||||||
position: idx,
|
position: idx,
|
||||||
mode: Symbol.for('edit'),
|
mode: Symbol.for('edit'),
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const bumpCategory = (category, name) => move => async (dispatch, getState) => {
|
export const bumpCategory = (category, name) => move => async (dispatch, getState) => {
|
||||||
const { roleEditor } = getState();
|
const { roleEditor } = getState()
|
||||||
const vm = roleEditor.get('viewMap');
|
const vm = roleEditor.get('viewMap')
|
||||||
|
|
||||||
const position = category.get('position');
|
const position = category.get('position')
|
||||||
const nextPos = position + move;
|
const nextPos = position + move
|
||||||
|
|
||||||
const replaceThisOne = vm.findKey(category => category.get('position') === nextPos);
|
const replaceThisOne = vm.findKey(category => category.get('position') === nextPos)
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('re: edit category'),
|
type: Symbol.for('re: edit category'),
|
||||||
|
@ -154,7 +154,7 @@ export const bumpCategory = (category, name) => move => async (dispatch, getStat
|
||||||
key: 'position',
|
key: 'position',
|
||||||
value: nextPos,
|
value: nextPos,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
if (!!replaceThisOne) {
|
if (!!replaceThisOne) {
|
||||||
dispatch({
|
dispatch({
|
||||||
|
@ -164,9 +164,9 @@ export const bumpCategory = (category, name) => move => async (dispatch, getStat
|
||||||
key: 'position',
|
key: 'position',
|
||||||
value: position,
|
value: position,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const saveServer = id => async (dispatch, getState) => {
|
export const saveServer = id => async (dispatch, getState) => {
|
||||||
const viewMap = getState()
|
const viewMap = getState()
|
||||||
|
@ -177,21 +177,21 @@ export const saveServer = id => async (dispatch, getState) => {
|
||||||
.delete('roles_map')
|
.delete('roles_map')
|
||||||
.delete('mode')
|
.delete('mode')
|
||||||
.delete('id')
|
.delete('id')
|
||||||
);
|
)
|
||||||
|
|
||||||
viewMap.map((v, idx) => {
|
viewMap.map((v, idx) => {
|
||||||
if (v.has('position')) {
|
if (v.has('position')) {
|
||||||
return v;
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
console.warn('category position wasnt set, so fake ones are being made', {
|
console.warn('category position wasnt set, so fake ones are being made', {
|
||||||
cat: v.toJS(),
|
cat: v.toJS(),
|
||||||
idx,
|
idx,
|
||||||
position: viewMap.count() + idx,
|
position: viewMap.count() + idx,
|
||||||
});
|
})
|
||||||
return v.set('position', viewMap.count() + idx);
|
return v.set('position', viewMap.count() + idx)
|
||||||
});
|
})
|
||||||
|
|
||||||
await superagent.patch(`/api/server/${id}`).send({ categories: viewMap.toJS() });
|
await superagent.patch(`/api/server/${id}`).send({ categories: viewMap.toJS() })
|
||||||
dispatch({ type: Symbol.for('re: swap original state') });
|
dispatch({ type: Symbol.for('re: swap original state') })
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,33 +1,33 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Set } from 'immutable';
|
import { Set } from 'immutable'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { DropTarget } from 'react-dnd';
|
import { DropTarget } from 'react-dnd'
|
||||||
import { Link, Prompt, Redirect } from 'react-router-dom';
|
import { Link, Prompt, Redirect } from 'react-router-dom'
|
||||||
import { Scrollbars } from 'react-custom-scrollbars';
|
import { Scrollbars } from 'react-custom-scrollbars'
|
||||||
import * as Actions from './actions';
|
import * as Actions from './actions'
|
||||||
import * as PickerActions from '../role-picker/actions';
|
import * as PickerActions from '../role-picker/actions'
|
||||||
import * as UIActions from '../../actions/ui';
|
import * as UIActions from '../../actions/ui'
|
||||||
import './RoleEditor.sass';
|
import './RoleEditor.sass'
|
||||||
|
|
||||||
import Category from './Category';
|
import Category from './Category'
|
||||||
import CategoryEditor from './CategoryEditor';
|
import CategoryEditor from './CategoryEditor'
|
||||||
import Role from '../role/draggable';
|
import Role from '../role/draggable'
|
||||||
|
|
||||||
const mapState = ({ rolePicker, roleEditor, servers }, ownProps) => ({
|
const mapState = ({ rolePicker, roleEditor, servers }, ownProps) => ({
|
||||||
rp: rolePicker,
|
rp: rolePicker,
|
||||||
editor: roleEditor,
|
editor: roleEditor,
|
||||||
server: servers.get(ownProps.match.params.server),
|
server: servers.get(ownProps.match.params.server),
|
||||||
});
|
})
|
||||||
|
|
||||||
@connect(mapState)
|
@connect(mapState)
|
||||||
@DropTarget(
|
@DropTarget(
|
||||||
Symbol.for('dnd: role'),
|
Symbol.for('dnd: role'),
|
||||||
{
|
{
|
||||||
drop(props, monitor, element) {
|
drop(props, monitor, element) {
|
||||||
element.dropRole({}, 'Uncategorized')(monitor.getItem());
|
element.dropRole({}, 'Uncategorized')(monitor.getItem())
|
||||||
},
|
},
|
||||||
canDrop(props, monitor) {
|
canDrop(props, monitor) {
|
||||||
return monitor.getItem().category !== 'Uncategorized';
|
return monitor.getItem().category !== 'Uncategorized'
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
(connect, monitor) => ({
|
(connect, monitor) => ({
|
||||||
|
@ -45,75 +45,75 @@ class RoleEditor extends Component {
|
||||||
match: {
|
match: {
|
||||||
params: { server },
|
params: { server },
|
||||||
},
|
},
|
||||||
} = this.props;
|
} = this.props
|
||||||
dispatch(Actions.constructView(server));
|
dispatch(Actions.constructView(server))
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillReceiveProps(nextProps) {
|
componentWillReceiveProps(nextProps) {
|
||||||
if (this.props.match.params.server !== nextProps.match.params.server) {
|
if (this.props.match.params.server !== nextProps.match.params.server) {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(
|
dispatch(
|
||||||
UIActions.fadeOut(() =>
|
UIActions.fadeOut(() =>
|
||||||
dispatch(Actions.constructView(nextProps.match.params.server))
|
dispatch(Actions.constructView(nextProps.match.params.server))
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dropRole = (category, name) => ({ role, category }) => {
|
dropRole = (category, name) => ({ role, category }) => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
console.log(role);
|
console.log(role)
|
||||||
dispatch(Actions.addRoleToCategory(name, category, role));
|
dispatch(Actions.addRoleToCategory(name, category, role))
|
||||||
};
|
}
|
||||||
|
|
||||||
createCategory = () => {
|
createCategory = () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.createCategory);
|
dispatch(Actions.createCategory)
|
||||||
};
|
}
|
||||||
|
|
||||||
saveCategory = (category, name) => () => {
|
saveCategory = (category, name) => () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.saveCategory(name, category));
|
dispatch(Actions.saveCategory(name, category))
|
||||||
};
|
}
|
||||||
|
|
||||||
deleteCategory = (category, id) => () => {
|
deleteCategory = (category, id) => () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.deleteCategory(id, category));
|
dispatch(Actions.deleteCategory(id, category))
|
||||||
};
|
}
|
||||||
|
|
||||||
openEditor = (category, name) => () => {
|
openEditor = (category, name) => () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.openEditor(name));
|
dispatch(Actions.openEditor(name))
|
||||||
};
|
}
|
||||||
|
|
||||||
editCategory = (category, id) => (key, type) => event => {
|
editCategory = (category, id) => (key, type) => event => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
let value;
|
let value
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Symbol.for('edit: text'):
|
case Symbol.for('edit: text'):
|
||||||
value = event.target.value;
|
value = event.target.value
|
||||||
break;
|
break
|
||||||
|
|
||||||
case Symbol.for('edit: bool'):
|
case Symbol.for('edit: bool'):
|
||||||
value = event.target.checked;
|
value = event.target.checked
|
||||||
break;
|
break
|
||||||
|
|
||||||
case Symbol.for('edit: select'):
|
case Symbol.for('edit: select'):
|
||||||
value = event.target.value;
|
value = event.target.value
|
||||||
break;
|
break
|
||||||
|
|
||||||
default:
|
default:
|
||||||
value = null;
|
value = null
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch(Actions.editCategory({ category, id, key, type, value }));
|
dispatch(Actions.editCategory({ category, id, key, type, value }))
|
||||||
};
|
}
|
||||||
|
|
||||||
resetServer = () => {
|
resetServer = () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch({ type: Symbol.for('re: reset') });
|
dispatch({ type: Symbol.for('re: reset') })
|
||||||
};
|
}
|
||||||
|
|
||||||
saveServer = () => {
|
saveServer = () => {
|
||||||
const {
|
const {
|
||||||
|
@ -121,32 +121,32 @@ class RoleEditor extends Component {
|
||||||
match: {
|
match: {
|
||||||
params: { server },
|
params: { server },
|
||||||
},
|
},
|
||||||
} = this.props;
|
} = this.props
|
||||||
dispatch(Actions.saveServer(server));
|
dispatch(Actions.saveServer(server))
|
||||||
};
|
}
|
||||||
|
|
||||||
onBump = (category, name) => move => () =>
|
onBump = (category, name) => move => () =>
|
||||||
this.props.dispatch(Actions.bumpCategory(category, name)(move));
|
this.props.dispatch(Actions.bumpCategory(category, name)(move))
|
||||||
|
|
||||||
get hasChanged() {
|
get hasChanged() {
|
||||||
return (
|
return (
|
||||||
this.props.editor.get('originalSnapshot').hashCode() !==
|
this.props.editor.get('originalSnapshot').hashCode() !==
|
||||||
this.props.editor.get('viewMap').hashCode()
|
this.props.editor.get('viewMap').hashCode()
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { server } = this.props;
|
const { server } = this.props
|
||||||
|
|
||||||
if (server == null) {
|
if (server == null) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
if (server.getIn(['perms', 'canManageRoles']) !== true) {
|
if (server.getIn(['perms', 'canManageRoles']) !== true) {
|
||||||
return <Redirect to={`/s/${server.get('id')}`} />;
|
return <Redirect to={`/s/${server.get('id')}`} />
|
||||||
}
|
}
|
||||||
|
|
||||||
const vm = this.props.editor.get('viewMap');
|
const vm = this.props.editor.get('viewMap')
|
||||||
return (
|
return (
|
||||||
<div className="inner role-editor">
|
<div className="inner role-editor">
|
||||||
<Prompt
|
<Prompt
|
||||||
|
@ -231,8 +231,8 @@ class RoleEditor extends Component {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default RoleEditor;
|
export default RoleEditor
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Map } from 'immutable';
|
import { Map } from 'immutable'
|
||||||
|
|
||||||
import Role from '../role';
|
import Role from '../role'
|
||||||
|
|
||||||
class Category extends Component {
|
class Category extends Component {
|
||||||
toggleRoleMulti(id, next) {
|
toggleRoleMulti(id, next) {
|
||||||
this.props.onChange(Map({ [id]: next }));
|
this.props.onChange(Map({ [id]: next }))
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleRoleSingle(id, next) {
|
toggleRoleSingle(id, next) {
|
||||||
|
@ -14,31 +14,31 @@ class Category extends Component {
|
||||||
.get('roles')
|
.get('roles')
|
||||||
.reduce((acc, i) => acc.set(i, false), Map())
|
.reduce((acc, i) => acc.set(i, false), Map())
|
||||||
.set(id, next)
|
.set(id, next)
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
onRoleToggle = id => (next, old) => {
|
onRoleToggle = id => (next, old) => {
|
||||||
const type = this.props.category.get('type');
|
const type = this.props.category.get('type')
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'single':
|
case 'single':
|
||||||
return this.toggleRoleSingle(id, next);
|
return this.toggleRoleSingle(id, next)
|
||||||
case 'multi':
|
case 'multi':
|
||||||
return this.toggleRoleMulti(id, next);
|
return this.toggleRoleMulti(id, next)
|
||||||
default:
|
default:
|
||||||
console.warn('DEFAULTING TO MULTI', id, next, old);
|
console.warn('DEFAULTING TO MULTI', id, next, old)
|
||||||
return this.toggleRoleMulti(id, next);
|
return this.toggleRoleMulti(id, next)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { category, name, isSelected } = this.props;
|
const { category, name, isSelected } = this.props
|
||||||
if (category.get('hidden')) {
|
if (category.get('hidden')) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
if (category.get('roles').count() === 0) {
|
if (category.get('roles').count() === 0) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -49,7 +49,7 @@ class Category extends Component {
|
||||||
.sortBy(r => r.get('position'))
|
.sortBy(r => r.get('position'))
|
||||||
.reverse()
|
.reverse()
|
||||||
.map((r, k) => {
|
.map((r, k) => {
|
||||||
const id = r.get('id');
|
const id = r.get('id')
|
||||||
return (
|
return (
|
||||||
<Role
|
<Role
|
||||||
key={k}
|
key={k}
|
||||||
|
@ -58,11 +58,11 @@ class Category extends Component {
|
||||||
selected={isSelected(id)}
|
selected={isSelected(id)}
|
||||||
onToggle={this.onRoleToggle(id)}
|
onToggle={this.onRoleToggle(id)}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
})
|
})
|
||||||
.toArray()}
|
.toArray()}
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export default Category;
|
export default Category
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import { Map, Set, fromJS } from 'immutable';
|
import { Map, Set, fromJS } from 'immutable'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import * as UIActions from '../../actions/ui';
|
import * as UIActions from '../../actions/ui'
|
||||||
|
|
||||||
export const setup = id => async dispatch => {
|
export const setup = id => async dispatch => {
|
||||||
const rsp = await superagent.get(`/api/server/${id}`);
|
const rsp = await superagent.get(`/api/server/${id}`)
|
||||||
const data = rsp.body;
|
const data = rsp.body
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('server: set'),
|
type: Symbol.for('server: set'),
|
||||||
|
@ -12,25 +12,25 @@ export const setup = id => async dispatch => {
|
||||||
id,
|
id,
|
||||||
...data,
|
...data,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
dispatch(constructView(id));
|
dispatch(constructView(id))
|
||||||
};
|
}
|
||||||
|
|
||||||
export const getViewMap = server => {
|
export const getViewMap = server => {
|
||||||
const roles = server.get('roles');
|
const roles = server.get('roles')
|
||||||
const categories = server.get('categories');
|
const categories = server.get('categories')
|
||||||
const categoriesIds = server.get('categories').keySeq();
|
const categoriesIds = server.get('categories').keySeq()
|
||||||
|
|
||||||
const allRoles = server
|
const allRoles = server
|
||||||
.get('roles')
|
.get('roles')
|
||||||
.filter(v => v.get('safe'))
|
.filter(v => v.get('safe'))
|
||||||
.map(r => r.get('id'))
|
.map(r => r.get('id'))
|
||||||
.toSet();
|
.toSet()
|
||||||
const accountedRoles = categories
|
const accountedRoles = categories
|
||||||
.map(c => c.get('roles'))
|
.map(c => c.get('roles'))
|
||||||
.toSet()
|
.toSet()
|
||||||
.flatten();
|
.flatten()
|
||||||
const unaccountedRoles = allRoles.subtract(accountedRoles);
|
const unaccountedRoles = allRoles.subtract(accountedRoles)
|
||||||
|
|
||||||
// console.log('roles', allRoles.toJS(), accountedRoles.toJS(), unaccountedRoles.toJS())
|
// console.log('roles', allRoles.toJS(), accountedRoles.toJS(), unaccountedRoles.toJS())
|
||||||
|
|
||||||
|
@ -61,29 +61,29 @@ export const getViewMap = server => {
|
||||||
.map(r => server.get('roles').find(sr => sr.get('id') === r))
|
.map(r => server.get('roles').find(sr => sr.get('id') === r))
|
||||||
.filter(r => r != null)
|
.filter(r => r != null)
|
||||||
// sort by server position, backwards.
|
// sort by server position, backwards.
|
||||||
.sort((a, b) => a.position > b.position);
|
.sort((a, b) => a.position > b.position)
|
||||||
// force data to sets
|
// force data to sets
|
||||||
return c.set('roles_map', Set(roles)).set('roles', Set(c.get('roles')));
|
return c.set('roles_map', Set(roles)).set('roles', Set(c.get('roles')))
|
||||||
});
|
})
|
||||||
|
|
||||||
const selected = roles.reduce(
|
const selected = roles.reduce(
|
||||||
(acc, r) => acc.set(r.get('id'), r.get('selected')),
|
(acc, r) => acc.set(r.get('id'), r.get('selected')),
|
||||||
Map()
|
Map()
|
||||||
);
|
)
|
||||||
|
|
||||||
const hasSafeRoles = allRoles.size > 0;
|
const hasSafeRoles = allRoles.size > 0
|
||||||
|
|
||||||
return {
|
return {
|
||||||
viewMap,
|
viewMap,
|
||||||
selected,
|
selected,
|
||||||
hasSafeRoles,
|
hasSafeRoles,
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const constructView = id => (dispatch, getState) => {
|
export const constructView = id => (dispatch, getState) => {
|
||||||
const server = getState().servers.get(id);
|
const server = getState().servers.get(id)
|
||||||
|
|
||||||
const { viewMap, selected } = getViewMap(server);
|
const { viewMap, selected } = getViewMap(server)
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('rp: setup role picker'),
|
type: Symbol.for('rp: setup role picker'),
|
||||||
|
@ -95,77 +95,77 @@ export const constructView = id => (dispatch, getState) => {
|
||||||
isEditingMessage: false,
|
isEditingMessage: false,
|
||||||
messageBuffer: '',
|
messageBuffer: '',
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
dispatch(UIActions.fadeIn);
|
dispatch(UIActions.fadeIn)
|
||||||
};
|
}
|
||||||
|
|
||||||
export const resetSelected = dispatch => {
|
export const resetSelected = dispatch => {
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('rp: reset selected'),
|
type: Symbol.for('rp: reset selected'),
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const submitSelected = serverId => async (dispatch, getState) => {
|
export const submitSelected = serverId => async (dispatch, getState) => {
|
||||||
const { rolePicker } = getState();
|
const { rolePicker } = getState()
|
||||||
const original = rolePicker.get('originalRolesSelected');
|
const original = rolePicker.get('originalRolesSelected')
|
||||||
const current = rolePicker.get('rolesSelected');
|
const current = rolePicker.get('rolesSelected')
|
||||||
|
|
||||||
const diff = original.reduce((acc, v, k) => {
|
const diff = original.reduce((acc, v, k) => {
|
||||||
if (current.get(k) !== v) {
|
if (current.get(k) !== v) {
|
||||||
// if original value is false, then we know we're adding, otherwise removing.
|
// if original value is false, then we know we're adding, otherwise removing.
|
||||||
if (v !== true) {
|
if (v !== true) {
|
||||||
return acc.set('added', acc.get('added').add(k));
|
return acc.set('added', acc.get('added').add(k))
|
||||||
} else {
|
} else {
|
||||||
return acc.set('removed', acc.get('removed').add(k));
|
return acc.set('removed', acc.get('removed').add(k))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return acc;
|
return acc
|
||||||
}, Map({ added: Set(), removed: Set() }));
|
}, Map({ added: Set(), removed: Set() }))
|
||||||
|
|
||||||
await superagent.patch(`/api/servers/${serverId}/roles`).send(diff.toJS());
|
await superagent.patch(`/api/servers/${serverId}/roles`).send(diff.toJS())
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('rp: sync selected roles'),
|
type: Symbol.for('rp: sync selected roles'),
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const updateRoles = roles => ({
|
export const updateRoles = roles => ({
|
||||||
type: Symbol.for('rp: update selected roles'),
|
type: Symbol.for('rp: update selected roles'),
|
||||||
data: roles,
|
data: roles,
|
||||||
});
|
})
|
||||||
|
|
||||||
export const openMessageEditor = id => (dispatch, getState) => {
|
export const openMessageEditor = id => (dispatch, getState) => {
|
||||||
const message = getState().servers.getIn([id, 'message']);
|
const message = getState().servers.getIn([id, 'message'])
|
||||||
dispatch(editServerMessage(id, message));
|
dispatch(editServerMessage(id, message))
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('rp: set message editor state'),
|
type: Symbol.for('rp: set message editor state'),
|
||||||
data: true,
|
data: true,
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const saveServerMessage = id => async (dispatch, getState) => {
|
export const saveServerMessage = id => async (dispatch, getState) => {
|
||||||
const message = getState().rolePicker.get('messageBuffer');
|
const message = getState().rolePicker.get('messageBuffer')
|
||||||
|
|
||||||
await superagent.patch(`/api/server/${id}`).send({ message });
|
await superagent.patch(`/api/server/${id}`).send({ message })
|
||||||
|
|
||||||
dispatch(closeMessageEditor);
|
dispatch(closeMessageEditor)
|
||||||
dispatch({
|
dispatch({
|
||||||
type: Symbol.for('server: edit message'),
|
type: Symbol.for('server: edit message'),
|
||||||
data: {
|
data: {
|
||||||
id,
|
id,
|
||||||
message,
|
message,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
export const editServerMessage = (id, message) => ({
|
export const editServerMessage = (id, message) => ({
|
||||||
type: Symbol.for('rp: edit message buffer'),
|
type: Symbol.for('rp: edit message buffer'),
|
||||||
data: message,
|
data: message,
|
||||||
});
|
})
|
||||||
|
|
||||||
export const closeMessageEditor = {
|
export const closeMessageEditor = {
|
||||||
type: Symbol.for('rp: set message editor state'),
|
type: Symbol.for('rp: set message editor state'),
|
||||||
data: false,
|
data: false,
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,22 +1,22 @@
|
||||||
import React, { Component, Fragment } from 'react';
|
import React, { Component, Fragment } from 'react'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { Prompt } from 'react-router-dom';
|
import { Prompt } from 'react-router-dom'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import * as Actions from './actions';
|
import * as Actions from './actions'
|
||||||
import * as UIActions from '../../actions/ui';
|
import * as UIActions from '../../actions/ui'
|
||||||
import { msgToReal } from '../../utils';
|
import { msgToReal } from '../../utils'
|
||||||
import './RolePicker.sass';
|
import './RolePicker.sass'
|
||||||
|
|
||||||
import Category from './Category';
|
import Category from './Category'
|
||||||
import { Scrollbars } from 'react-custom-scrollbars';
|
import { Scrollbars } from 'react-custom-scrollbars'
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom'
|
||||||
|
|
||||||
const mapState = ({ rolePicker, servers }, ownProps) => {
|
const mapState = ({ rolePicker, servers }, ownProps) => {
|
||||||
return {
|
return {
|
||||||
data: rolePicker,
|
data: rolePicker,
|
||||||
server: servers.get(ownProps.match.params.server),
|
server: servers.get(ownProps.match.params.server),
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
@connect(mapState)
|
@connect(mapState)
|
||||||
class RolePicker extends Component {
|
class RolePicker extends Component {
|
||||||
|
@ -26,59 +26,59 @@ class RolePicker extends Component {
|
||||||
match: {
|
match: {
|
||||||
params: { server },
|
params: { server },
|
||||||
},
|
},
|
||||||
} = this.props;
|
} = this.props
|
||||||
dispatch(Actions.setup(server));
|
dispatch(Actions.setup(server))
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillReceiveProps(nextProps) {
|
componentWillReceiveProps(nextProps) {
|
||||||
if (this.props.match.params.server !== nextProps.match.params.server) {
|
if (this.props.match.params.server !== nextProps.match.params.server) {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(
|
dispatch(
|
||||||
UIActions.fadeOut(() => dispatch(Actions.setup(nextProps.match.params.server)))
|
UIActions.fadeOut(() => dispatch(Actions.setup(nextProps.match.params.server)))
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get serverId() {
|
get serverId() {
|
||||||
return this.props.server.get('id');
|
return this.props.server.get('id')
|
||||||
}
|
}
|
||||||
|
|
||||||
isSelected = id => {
|
isSelected = id => {
|
||||||
return this.props.data.getIn(['rolesSelected', id]);
|
return this.props.data.getIn(['rolesSelected', id])
|
||||||
};
|
}
|
||||||
|
|
||||||
get rolesHaveChanged() {
|
get rolesHaveChanged() {
|
||||||
const { data } = this.props;
|
const { data } = this.props
|
||||||
return !data.get('rolesSelected').equals(data.get('originalRolesSelected'));
|
return !data.get('rolesSelected').equals(data.get('originalRolesSelected'))
|
||||||
}
|
}
|
||||||
|
|
||||||
editServerMessage = e => {
|
editServerMessage = e => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.editServerMessage(this.serverId, e.target.value));
|
dispatch(Actions.editServerMessage(this.serverId, e.target.value))
|
||||||
};
|
}
|
||||||
|
|
||||||
saveServerMessage = e => {
|
saveServerMessage = e => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.saveServerMessage(this.serverId));
|
dispatch(Actions.saveServerMessage(this.serverId))
|
||||||
};
|
}
|
||||||
|
|
||||||
openMessageEditor = () => {
|
openMessageEditor = () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.openMessageEditor(this.serverId));
|
dispatch(Actions.openMessageEditor(this.serverId))
|
||||||
};
|
}
|
||||||
|
|
||||||
closeMessageEditor = () => {
|
closeMessageEditor = () => {
|
||||||
const { dispatch } = this.props;
|
const { dispatch } = this.props
|
||||||
dispatch(Actions.closeMessageEditor);
|
dispatch(Actions.closeMessageEditor)
|
||||||
};
|
}
|
||||||
|
|
||||||
renderServerMessage(server) {
|
renderServerMessage(server) {
|
||||||
const isEditing = this.props.data.get('isEditingMessage');
|
const isEditing = this.props.data.get('isEditingMessage')
|
||||||
const roleManager = server.getIn(['perms', 'canManageRoles']);
|
const roleManager = server.getIn(['perms', 'canManageRoles'])
|
||||||
const msg = server.get('message');
|
const msg = server.get('message')
|
||||||
const msgBuffer = this.props.data.get('messageBuffer');
|
const msgBuffer = this.props.data.get('messageBuffer')
|
||||||
|
|
||||||
console.log(msg, roleManager, isEditing, this.props.data.toJS());
|
console.log(msg, roleManager, isEditing, this.props.data.toJS())
|
||||||
|
|
||||||
if (!roleManager && msg !== '') {
|
if (!roleManager && msg !== '') {
|
||||||
return (
|
return (
|
||||||
|
@ -86,7 +86,7 @@ class RolePicker extends Component {
|
||||||
<h3>Server Message</h3>
|
<h3>Server Message</h3>
|
||||||
<p dangerouslySetInnerHTML={{ __html: msgToReal(msg) }}></p>
|
<p dangerouslySetInnerHTML={{ __html: msgToReal(msg) }}></p>
|
||||||
</section>
|
</section>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (roleManager && !isEditing) {
|
if (roleManager && !isEditing) {
|
||||||
|
@ -107,7 +107,7 @@ class RolePicker extends Component {
|
||||||
}}
|
}}
|
||||||
></p>
|
></p>
|
||||||
</section>
|
</section>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (roleManager && isEditing) {
|
if (roleManager && isEditing) {
|
||||||
|
@ -137,18 +137,18 @@ class RolePicker extends Component {
|
||||||
value={msgBuffer}
|
value={msgBuffer}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { data, server, dispatch } = this.props;
|
const { data, server, dispatch } = this.props
|
||||||
const vm = data.get('viewMap');
|
const vm = data.get('viewMap')
|
||||||
|
|
||||||
if (server === undefined) {
|
if (server === undefined) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -207,8 +207,8 @@ class RolePicker extends Component {
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default RolePicker;
|
export default RolePicker
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Map } from 'immutable';
|
import { Map } from 'immutable'
|
||||||
|
|
||||||
import Role from './index';
|
import Role from './index'
|
||||||
|
|
||||||
export default class DemoRole extends Component {
|
export default class DemoRole extends Component {
|
||||||
state = {
|
state = {
|
||||||
isSelected: false,
|
isSelected: false,
|
||||||
};
|
}
|
||||||
|
|
||||||
handleToggle = () => {
|
handleToggle = () => {
|
||||||
this.setState({ isSelected: !this.state.isSelected });
|
this.setState({ isSelected: !this.state.isSelected })
|
||||||
};
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
return (
|
return (
|
||||||
|
@ -20,6 +20,6 @@ export default class DemoRole extends Component {
|
||||||
onToggle={this.handleToggle}
|
onToggle={this.handleToggle}
|
||||||
type="button"
|
type="button"
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { DragSource } from 'react-dnd';
|
import { DragSource } from 'react-dnd'
|
||||||
|
|
||||||
import Role from './index';
|
import Role from './index'
|
||||||
|
|
||||||
// @DragSource(Symbol.for('dnd: role'), {
|
// @DragSource(Symbol.for('dnd: role'), {
|
||||||
// beginDrag ({ role, categoryId }) {
|
// beginDrag ({ role, categoryId }) {
|
||||||
|
@ -17,7 +17,7 @@ export default
|
||||||
Symbol.for('dnd: role'),
|
Symbol.for('dnd: role'),
|
||||||
{
|
{
|
||||||
beginDrag({ role, categoryId }) {
|
beginDrag({ role, categoryId }) {
|
||||||
return { role, category: categoryId };
|
return { role, category: categoryId }
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
(connect, monitor) => ({
|
(connect, monitor) => ({
|
||||||
|
@ -27,6 +27,6 @@ export default
|
||||||
)
|
)
|
||||||
class DraggableRole extends Component {
|
class DraggableRole extends Component {
|
||||||
render() {
|
render() {
|
||||||
return <Role {...this.props} type="drag" />;
|
return <Role {...this.props} type="drag" />
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import PropTypes from 'prop-types';
|
import PropTypes from 'prop-types'
|
||||||
import Color from 'color';
|
import Color from 'color'
|
||||||
import './Role.sass';
|
import './Role.sass'
|
||||||
|
|
||||||
const whiteColor = Color('#efefef');
|
const whiteColor = Color('#efefef')
|
||||||
|
|
||||||
class Role extends Component {
|
class Role extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
|
@ -12,28 +12,28 @@ class Role extends Component {
|
||||||
type: PropTypes.string,
|
type: PropTypes.string,
|
||||||
selected: PropTypes.bool,
|
selected: PropTypes.bool,
|
||||||
disabled: PropTypes.bool,
|
disabled: PropTypes.bool,
|
||||||
};
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
let { role, selected, disabled, type, isDragging } = this.props;
|
let { role, selected, disabled, type, isDragging } = this.props
|
||||||
type = type || 'button';
|
type = type || 'button'
|
||||||
|
|
||||||
// console.log(this.props)
|
// console.log(this.props)
|
||||||
|
|
||||||
let color = Color(role.get('color'));
|
let color = Color(role.get('color'))
|
||||||
|
|
||||||
if (color.rgbNumber() === 0) {
|
if (color.rgbNumber() === 0) {
|
||||||
color = whiteColor;
|
color = whiteColor
|
||||||
}
|
}
|
||||||
|
|
||||||
const c = color;
|
const c = color
|
||||||
let hc = color.lighten(0.1);
|
let hc = color.lighten(0.1)
|
||||||
|
|
||||||
const out = (
|
const out = (
|
||||||
<div
|
<div
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!disabled && this.props.onToggle != null) {
|
if (!disabled && this.props.onToggle != null) {
|
||||||
this.props.onToggle(!selected, selected);
|
this.props.onToggle(!selected, selected)
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
{...(disabled
|
{...(disabled
|
||||||
|
@ -52,14 +52,14 @@ class Role extends Component {
|
||||||
<div className={`role__option ${selected ? 'selected' : ''}`} />
|
<div className={`role__option ${selected ? 'selected' : ''}`} />
|
||||||
<div className="role__name">{role.get('name')}</div>
|
<div className="role__name">{role.get('name')}</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
|
|
||||||
if (type === 'drag' && this.props.connectDragSource != null) {
|
if (type === 'drag' && this.props.connectDragSource != null) {
|
||||||
return this.props.connectDragSource(out);
|
return this.props.connectDragSource(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
return out;
|
return out
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Role;
|
export default Role
|
||||||
|
|
|
@ -1,17 +1,17 @@
|
||||||
import React, { Component, Fragment } from 'react';
|
import React, { Component, Fragment } from 'react'
|
||||||
import ImmutablePropTypes from 'react-immutable-proptypes';
|
import ImmutablePropTypes from 'react-immutable-proptypes'
|
||||||
import PropTypes from 'prop-types';
|
import PropTypes from 'prop-types'
|
||||||
import ServerCard from './ServerCard';
|
import ServerCard from './ServerCard'
|
||||||
import UserCard from './UserCard';
|
import UserCard from './UserCard'
|
||||||
import { Scrollbars } from 'react-custom-scrollbars';
|
import { Scrollbars } from 'react-custom-scrollbars'
|
||||||
import { NavLink } from 'react-router-dom';
|
import { NavLink } from 'react-router-dom'
|
||||||
|
|
||||||
class ServersNavigation extends Component {
|
class ServersNavigation extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
user: ImmutablePropTypes.map.isRequired,
|
user: ImmutablePropTypes.map.isRequired,
|
||||||
servers: ImmutablePropTypes.orderedMapOf(ImmutablePropTypes.map).isRequired,
|
servers: ImmutablePropTypes.orderedMapOf(ImmutablePropTypes.map).isRequired,
|
||||||
className: PropTypes.string,
|
className: PropTypes.string,
|
||||||
};
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
// console.log(this.props.servers)
|
// console.log(this.props.servers)
|
||||||
|
@ -21,8 +21,8 @@ class ServersNavigation extends Component {
|
||||||
<div className={this.props.className}>
|
<div className={this.props.className}>
|
||||||
<Scrollbars autoHeight autoHeightMax="calc(100vh - 180px)">
|
<Scrollbars autoHeight autoHeightMax="calc(100vh - 180px)">
|
||||||
{this.props.servers.reduce((acc, s, i) => {
|
{this.props.servers.reduce((acc, s, i) => {
|
||||||
acc.push(<ServerCard server={s} user={this.props.user} key={i} />);
|
acc.push(<ServerCard server={s} user={this.props.user} key={i} />)
|
||||||
return acc;
|
return acc
|
||||||
}, [])}
|
}, [])}
|
||||||
<NavLink
|
<NavLink
|
||||||
className="server-list__item add-new"
|
className="server-list__item add-new"
|
||||||
|
@ -36,8 +36,8 @@ class ServersNavigation extends Component {
|
||||||
</Scrollbars>
|
</Scrollbars>
|
||||||
</div>
|
</div>
|
||||||
</Fragment>
|
</Fragment>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default ServersNavigation;
|
export default ServersNavigation
|
||||||
|
|
|
@ -1,26 +1,26 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import ImmutablePropTypes from 'react-immutable-proptypes';
|
import ImmutablePropTypes from 'react-immutable-proptypes'
|
||||||
import { NavLink } from 'react-router-dom';
|
import { NavLink } from 'react-router-dom'
|
||||||
import './ServerCard.sass';
|
import './ServerCard.sass'
|
||||||
import { withRouter } from 'react-router';
|
import { withRouter } from 'react-router'
|
||||||
|
|
||||||
class ServerCard extends Component {
|
class ServerCard extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
user: ImmutablePropTypes.map.isRequired,
|
user: ImmutablePropTypes.map.isRequired,
|
||||||
server: ImmutablePropTypes.map.isRequired,
|
server: ImmutablePropTypes.map.isRequired,
|
||||||
};
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { server, user } = this.props;
|
const { server, user } = this.props
|
||||||
|
|
||||||
let icon = '';
|
let icon = ''
|
||||||
|
|
||||||
console.log(__filename, server);
|
console.log(__filename, server)
|
||||||
|
|
||||||
const s = server.get('server');
|
const s = server.get('server')
|
||||||
const gm = server.get('gm');
|
const gm = server.get('gm')
|
||||||
const perms = server.get('perms');
|
const perms = server.get('perms')
|
||||||
|
|
||||||
if (perms.get('canManageRoles')) {
|
if (perms.get('canManageRoles')) {
|
||||||
icon = (
|
icon = (
|
||||||
|
@ -32,7 +32,7 @@ class ServerCard extends Component {
|
||||||
className="server-list__item__tag"
|
className="server-list__item__tag"
|
||||||
uk-icon="icon: bolt; ratio: 0.7"
|
uk-icon="icon: bolt; ratio: 0.7"
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (perms.get('isAdmin')) {
|
if (perms.get('isAdmin')) {
|
||||||
|
@ -45,7 +45,7 @@ class ServerCard extends Component {
|
||||||
className="server-list__item__tag"
|
className="server-list__item__tag"
|
||||||
uk-icon="icon: star; ratio: 0.7"
|
uk-icon="icon: star; ratio: 0.7"
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -69,8 +69,8 @@ class ServerCard extends Component {
|
||||||
{icon}
|
{icon}
|
||||||
</div>
|
</div>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default ServerCard;
|
export default ServerCard
|
||||||
|
|
|
@ -1,35 +1,35 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Link, Redirect } from 'react-router-dom';
|
import { Link, Redirect } from 'react-router-dom'
|
||||||
import superagent from 'superagent';
|
import superagent from 'superagent'
|
||||||
import discordLogo from '../../pages/images/discord-logo.svg';
|
import discordLogo from '../../pages/images/discord-logo.svg'
|
||||||
|
|
||||||
export default class ServerLanding extends Component {
|
export default class ServerLanding extends Component {
|
||||||
state = {
|
state = {
|
||||||
server: null,
|
server: null,
|
||||||
exit: false,
|
exit: false,
|
||||||
};
|
}
|
||||||
|
|
||||||
async componentWillMount() {
|
async componentWillMount() {
|
||||||
console.log(this.props);
|
console.log(this.props)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const rsp = await superagent.get(
|
const rsp = await superagent.get(
|
||||||
`/api/server/${this.props.match.params.server}/slug`
|
`/api/server/${this.props.match.params.server}/slug`
|
||||||
);
|
)
|
||||||
this.setState({ server: rsp.body });
|
this.setState({ server: rsp.body })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.setState({ exit: true });
|
this.setState({ exit: true })
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
if (this.state.exit === true) {
|
if (this.state.exit === true) {
|
||||||
return <Redirect to="/" />;
|
return <Redirect to="/" />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.state.server === null) {
|
if (this.state.server === null) {
|
||||||
return null; //SPINNER
|
return null //SPINNER
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -54,6 +54,6 @@ export default class ServerLanding extends Component {
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,30 +1,30 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import ImmutablePropTypes from 'react-immutable-proptypes';
|
import ImmutablePropTypes from 'react-immutable-proptypes'
|
||||||
import { NavLink } from 'react-router-dom';
|
import { NavLink } from 'react-router-dom'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import * as Actions from '../../actions';
|
import * as Actions from '../../actions'
|
||||||
import './UserCard.sass';
|
import './UserCard.sass'
|
||||||
|
|
||||||
@connect()
|
@connect()
|
||||||
class UserCard extends Component {
|
class UserCard extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
user: ImmutablePropTypes.map,
|
user: ImmutablePropTypes.map,
|
||||||
};
|
}
|
||||||
|
|
||||||
get avatar() {
|
get avatar() {
|
||||||
const { user } = this.props;
|
const { user } = this.props
|
||||||
const avatar = user.get('avatar');
|
const avatar = user.get('avatar')
|
||||||
|
|
||||||
if (avatar === '' || avatar == null) {
|
if (avatar === '' || avatar == null) {
|
||||||
return `https://cdn.discordapp.com/embed/avatars/${Math.ceil(Math.random() * 9999) %
|
return `https://cdn.discordapp.com/embed/avatars/${Math.ceil(Math.random() * 9999) %
|
||||||
5}.png`;
|
5}.png`
|
||||||
}
|
}
|
||||||
|
|
||||||
return `https://cdn.discordapp.com/avatars/${user.get('id')}/${avatar}.png`;
|
return `https://cdn.discordapp.com/avatars/${user.get('id')}/${avatar}.png`
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { user } = this.props;
|
const { user } = this.props
|
||||||
|
|
||||||
// console.log(this.props)
|
// console.log(this.props)
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ class UserCard extends Component {
|
||||||
title="Sign out"
|
title="Sign out"
|
||||||
uk-icon="icon: sign-out"
|
uk-icon="icon: sign-out"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
this.props.dispatch(Actions.userLogout);
|
this.props.dispatch(Actions.userLogout)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</li>
|
</li>
|
||||||
|
@ -63,8 +63,8 @@ class UserCard extends Component {
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default UserCard;
|
export default UserCard
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Route, Switch } from 'react-router-dom';
|
import { Route, Switch } from 'react-router-dom'
|
||||||
import { Scrollbars } from 'react-custom-scrollbars';
|
import { Scrollbars } from 'react-custom-scrollbars'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { withRouter, Redirect } from 'react-router';
|
import { withRouter, Redirect } from 'react-router'
|
||||||
import './index.sass';
|
import './index.sass'
|
||||||
|
|
||||||
import Navigation from './Navigation';
|
import Navigation from './Navigation'
|
||||||
import RolePicker from '../role-picker';
|
import RolePicker from '../role-picker'
|
||||||
import RoleEditor from '../role-editor';
|
import RoleEditor from '../role-editor'
|
||||||
import AddServer from '../add-server';
|
import AddServer from '../add-server'
|
||||||
import Error404 from '../../pages/Error404';
|
import Error404 from '../../pages/Error404'
|
||||||
|
|
||||||
// import mockData from './mockData'
|
// import mockData from './mockData'
|
||||||
|
|
||||||
|
@ -18,20 +18,20 @@ const mapState = ({ servers, user, appState }) => {
|
||||||
servers,
|
servers,
|
||||||
user,
|
user,
|
||||||
fade: appState.fade,
|
fade: appState.fade,
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
@connect(mapState)
|
@connect(mapState)
|
||||||
class Servers extends Component {
|
class Servers extends Component {
|
||||||
get defaultPath() {
|
get defaultPath() {
|
||||||
console.log(this.props.servers.toJS());
|
console.log(this.props.servers.toJS())
|
||||||
|
|
||||||
const first = this.props.servers.first();
|
const first = this.props.servers.first()
|
||||||
if (first != null) {
|
if (first != null) {
|
||||||
return first.get('id');
|
return first.get('id')
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'add';
|
return 'add'
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
|
@ -62,8 +62,8 @@ class Servers extends Component {
|
||||||
</Scrollbars>
|
</Scrollbars>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Servers;
|
export default Servers
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react'
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom'
|
||||||
import Scrollbars from 'react-custom-scrollbars';
|
import Scrollbars from 'react-custom-scrollbars'
|
||||||
import Logotype from '../logotype';
|
import Logotype from '../logotype'
|
||||||
import './wrapper.sass';
|
import './wrapper.sass'
|
||||||
import discordLogo from '../../pages/images/discord-logo.svg';
|
import discordLogo from '../../pages/images/discord-logo.svg'
|
||||||
|
|
||||||
class Wrapper extends Component {
|
class Wrapper extends Component {
|
||||||
render() {
|
render() {
|
||||||
|
@ -45,8 +45,8 @@ class Wrapper extends Component {
|
||||||
</div>
|
</div>
|
||||||
</Scrollbars>
|
</Scrollbars>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Wrapper;
|
export default Wrapper
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import ReactDOM from 'react-dom';
|
import ReactDOM from 'react-dom'
|
||||||
import './index.css';
|
import './index.css'
|
||||||
import App from './App';
|
import App from './App'
|
||||||
import { unregister } from './registerServiceWorker';
|
import { unregister } from './registerServiceWorker'
|
||||||
|
|
||||||
ReactDOM.render(<App />, document.getElementById('root'));
|
ReactDOM.render(<App />, document.getElementById('root'))
|
||||||
unregister();
|
unregister()
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import './landing.sass';
|
import './landing.sass'
|
||||||
|
|
||||||
const Error404 = ({ root = false }) => (
|
const Error404 = ({ root = false }) => (
|
||||||
<div className="landing uk-width-1-1 uk-text-center">
|
<div className="landing uk-width-1-1 uk-text-center">
|
||||||
|
@ -14,6 +14,6 @@ const Error404 = ({ root = false }) => (
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
|
|
||||||
export default Error404;
|
export default Error404
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import React, { Component, Fragment } from 'react';
|
import React, { Component, Fragment } from 'react'
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom'
|
||||||
import Scrollbars from 'react-custom-scrollbars';
|
import Scrollbars from 'react-custom-scrollbars'
|
||||||
import Typist from 'react-typist';
|
import Typist from 'react-typist'
|
||||||
import moment from 'moment';
|
import moment from 'moment'
|
||||||
import './landing.sass';
|
import './landing.sass'
|
||||||
import discordLogo from './images/discord-logo.svg';
|
import discordLogo from './images/discord-logo.svg'
|
||||||
import RoleypolyDemo from '../components/demos/roleypoly';
|
import RoleypolyDemo from '../components/demos/roleypoly'
|
||||||
import TypingDemo from '../components/demos/typing';
|
import TypingDemo from '../components/demos/typing'
|
||||||
|
|
||||||
const Landing = ({ root = false }) => (
|
const Landing = ({ root = false }) => (
|
||||||
<div className="landing uk-width-1-1 uk-text-center">
|
<div className="landing uk-width-1-1 uk-text-center">
|
||||||
|
@ -34,5 +34,5 @@ const Landing = ({ root = false }) => (
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
export default Landing;
|
export default Landing
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import React, { Fragment } from 'react';
|
import React, { Fragment } from 'react'
|
||||||
|
|
||||||
import goodImg from './images/whynoroles-good.png';
|
import goodImg from './images/whynoroles-good.png'
|
||||||
import badImg from './images/whynoroles-bad.png';
|
import badImg from './images/whynoroles-bad.png'
|
||||||
|
|
||||||
const WhyNoRoles = props => {
|
const WhyNoRoles = props => {
|
||||||
return (
|
return (
|
||||||
|
@ -27,7 +27,7 @@ const WhyNoRoles = props => {
|
||||||
In this example, Roleypoly is above other roles, and will be able to assign them.
|
In this example, Roleypoly is above other roles, and will be able to assign them.
|
||||||
</p>
|
</p>
|
||||||
</Fragment>
|
</Fragment>
|
||||||
);
|
)
|
||||||
};
|
}
|
||||||
|
|
||||||
export default WhyNoRoles;
|
export default WhyNoRoles
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import React from 'react';
|
import React from 'react'
|
||||||
import { Route, Switch } from 'react-router-dom';
|
import { Route, Switch } from 'react-router-dom'
|
||||||
import Scrollbars from 'react-custom-scrollbars';
|
import Scrollbars from 'react-custom-scrollbars'
|
||||||
import './pages.sass';
|
import './pages.sass'
|
||||||
|
|
||||||
import WhyNoRoles from './WhyNoRoles';
|
import WhyNoRoles from './WhyNoRoles'
|
||||||
import Error404 from './Error404';
|
import Error404 from './Error404'
|
||||||
export { default as Landing } from './Landing';
|
export { default as Landing } from './Landing'
|
||||||
export { default as Error404 } from './Error404';
|
export { default as Error404 } from './Error404'
|
||||||
|
|
||||||
const Pages = props => {
|
const Pages = props => {
|
||||||
return (
|
return (
|
||||||
|
@ -21,7 +21,7 @@ const Pages = props => {
|
||||||
</div>
|
</div>
|
||||||
</Scrollbars>
|
</Scrollbars>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
};
|
}
|
||||||
|
|
||||||
export default Pages;
|
export default Pages
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
import { combineReducers } from 'redux';
|
import { combineReducers } from 'redux'
|
||||||
|
|
||||||
import servers from './servers';
|
import servers from './servers'
|
||||||
import user from './user';
|
import user from './user'
|
||||||
import rolePicker from './role-picker';
|
import rolePicker from './role-picker'
|
||||||
import roleEditor from './role-editor';
|
import roleEditor from './role-editor'
|
||||||
import { routerMiddleware } from 'react-router-redux';
|
import { routerMiddleware } from 'react-router-redux'
|
||||||
// import roles from './roles'
|
// import roles from './roles'
|
||||||
|
|
||||||
const initialState = {
|
const initialState = {
|
||||||
ready: false,
|
ready: false,
|
||||||
fade: true,
|
fade: true,
|
||||||
};
|
}
|
||||||
|
|
||||||
const appState = (state = initialState, { type, data }) => {
|
const appState = (state = initialState, { type, data }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
|
@ -19,18 +19,18 @@ const appState = (state = initialState, { type, data }) => {
|
||||||
...state,
|
...state,
|
||||||
ready: true,
|
ready: true,
|
||||||
fade: false,
|
fade: false,
|
||||||
};
|
}
|
||||||
|
|
||||||
case Symbol.for('app fade'):
|
case Symbol.for('app fade'):
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
fade: data,
|
fade: data,
|
||||||
};
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
const rootReducer = combineReducers({
|
const rootReducer = combineReducers({
|
||||||
appState,
|
appState,
|
||||||
|
@ -40,6 +40,6 @@ const rootReducer = combineReducers({
|
||||||
// roles,
|
// roles,
|
||||||
rolePicker,
|
rolePicker,
|
||||||
roleEditor,
|
roleEditor,
|
||||||
});
|
})
|
||||||
|
|
||||||
export default rootReducer;
|
export default rootReducer
|
||||||
|
|
|
@ -1,44 +1,44 @@
|
||||||
import { Map, OrderedMap, fromJS } from 'immutable';
|
import { Map, OrderedMap, fromJS } from 'immutable'
|
||||||
|
|
||||||
const initialState = Map({
|
const initialState = Map({
|
||||||
viewMap: OrderedMap({}),
|
viewMap: OrderedMap({}),
|
||||||
originalSnapshot: OrderedMap({}),
|
originalSnapshot: OrderedMap({}),
|
||||||
hasAvailableRoles: true,
|
hasAvailableRoles: true,
|
||||||
});
|
})
|
||||||
|
|
||||||
const reducer = (state = initialState, { type, data }) => {
|
const reducer = (state = initialState, { type, data }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Symbol.for('re: setup'):
|
case Symbol.for('re: setup'):
|
||||||
const { viewMap, originalSnapshot, ...rest } = data;
|
const { viewMap, originalSnapshot, ...rest } = data
|
||||||
return state.merge({
|
return state.merge({
|
||||||
viewMap: OrderedMap(viewMap),
|
viewMap: OrderedMap(viewMap),
|
||||||
originalSnapshot: OrderedMap(originalSnapshot),
|
originalSnapshot: OrderedMap(originalSnapshot),
|
||||||
...rest,
|
...rest,
|
||||||
});
|
})
|
||||||
|
|
||||||
case Symbol.for('re: set category'):
|
case Symbol.for('re: set category'):
|
||||||
return state.setIn(['viewMap', data.id], Map(data));
|
return state.setIn(['viewMap', data.id], Map(data))
|
||||||
|
|
||||||
case Symbol.for('re: edit category'):
|
case Symbol.for('re: edit category'):
|
||||||
return state.setIn(['viewMap', data.id, data.key], data.value);
|
return state.setIn(['viewMap', data.id, data.key], data.value)
|
||||||
|
|
||||||
case Symbol.for('re: delete category'):
|
case Symbol.for('re: delete category'):
|
||||||
return state.deleteIn(['viewMap', data]);
|
return state.deleteIn(['viewMap', data])
|
||||||
|
|
||||||
case Symbol.for('re: switch category mode'):
|
case Symbol.for('re: switch category mode'):
|
||||||
return state.setIn(['viewMap', data.id, 'mode'], data.mode);
|
return state.setIn(['viewMap', data.id, 'mode'], data.mode)
|
||||||
|
|
||||||
case Symbol.for('re: add role to category'):
|
case Symbol.for('re: add role to category'):
|
||||||
const category = state.getIn(['viewMap', data.id]);
|
const category = state.getIn(['viewMap', data.id])
|
||||||
return state.setIn(
|
return state.setIn(
|
||||||
['viewMap', data.id],
|
['viewMap', data.id],
|
||||||
category
|
category
|
||||||
.set('roles', category.get('roles').add(data.role.get('id')))
|
.set('roles', category.get('roles').add(data.role.get('id')))
|
||||||
.set('roles_map', category.get('roles_map').add(data.role))
|
.set('roles_map', category.get('roles_map').add(data.role))
|
||||||
);
|
)
|
||||||
|
|
||||||
case Symbol.for('re: remove role from category'):
|
case Symbol.for('re: remove role from category'):
|
||||||
const rmCat = state.getIn(['viewMap', data.id]);
|
const rmCat = state.getIn(['viewMap', data.id])
|
||||||
return state.setIn(
|
return state.setIn(
|
||||||
['viewMap', data.id],
|
['viewMap', data.id],
|
||||||
rmCat
|
rmCat
|
||||||
|
@ -50,17 +50,17 @@ const reducer = (state = initialState, { type, data }) => {
|
||||||
'roles_map',
|
'roles_map',
|
||||||
rmCat.get('roles_map').filterNot(r => r.get('id') === data.role.get('id'))
|
rmCat.get('roles_map').filterNot(r => r.get('id') === data.role.get('id'))
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
|
|
||||||
case Symbol.for('re: reset'):
|
case Symbol.for('re: reset'):
|
||||||
return state.set('viewMap', state.get('originalSnapshot'));
|
return state.set('viewMap', state.get('originalSnapshot'))
|
||||||
|
|
||||||
case Symbol.for('re: swap original state'):
|
case Symbol.for('re: swap original state'):
|
||||||
return state.set('originalSnapshot', state.get('viewMap'));
|
return state.set('originalSnapshot', state.get('viewMap'))
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export default reducer;
|
export default reducer
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { Map, OrderedMap } from 'immutable';
|
import { Map, OrderedMap } from 'immutable'
|
||||||
|
|
||||||
const initialState = Map({
|
const initialState = Map({
|
||||||
hidden: true, // should the view be hidden?
|
hidden: true, // should the view be hidden?
|
||||||
|
@ -8,37 +8,37 @@ const initialState = Map({
|
||||||
viewMap: OrderedMap({}), // roles in categories
|
viewMap: OrderedMap({}), // roles in categories
|
||||||
originalRolesSelected: Map({}), // Map<role id, bool> -- original roles for diffing against selected
|
originalRolesSelected: Map({}), // Map<role id, bool> -- original roles for diffing against selected
|
||||||
rolesSelected: Map({}), // Map<role id, bool> -- new roles for diffing
|
rolesSelected: Map({}), // Map<role id, bool> -- new roles for diffing
|
||||||
});
|
})
|
||||||
|
|
||||||
export default (state = initialState, { type, data }) => {
|
export default (state = initialState, { type, data }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Symbol.for('rp: setup role picker'):
|
case Symbol.for('rp: setup role picker'):
|
||||||
return Map(data);
|
return Map(data)
|
||||||
|
|
||||||
case Symbol.for('rp: hide role picker ui'):
|
case Symbol.for('rp: hide role picker ui'):
|
||||||
return state.set('hidden', data);
|
return state.set('hidden', data)
|
||||||
|
|
||||||
case Symbol.for('rp: reset role picker ui'):
|
case Symbol.for('rp: reset role picker ui'):
|
||||||
return state.set('emptyRoles', data);
|
return state.set('emptyRoles', data)
|
||||||
|
|
||||||
case Symbol.for('rp: update selected roles'):
|
case Symbol.for('rp: update selected roles'):
|
||||||
return state.mergeIn(['rolesSelected'], data);
|
return state.mergeIn(['rolesSelected'], data)
|
||||||
|
|
||||||
case Symbol.for('rp: sync selected roles'):
|
case Symbol.for('rp: sync selected roles'):
|
||||||
return state.set('originalRolesSelected', state.get('rolesSelected'));
|
return state.set('originalRolesSelected', state.get('rolesSelected'))
|
||||||
|
|
||||||
case Symbol.for('rp: reset selected'):
|
case Symbol.for('rp: reset selected'):
|
||||||
return state.set('rolesSelected', state.get('originalRolesSelected'));
|
return state.set('rolesSelected', state.get('originalRolesSelected'))
|
||||||
|
|
||||||
case Symbol.for('rp: set message editor state'):
|
case Symbol.for('rp: set message editor state'):
|
||||||
return state.set('isEditingMessage', data);
|
return state.set('isEditingMessage', data)
|
||||||
|
|
||||||
case Symbol.for('rp: edit message buffer'):
|
case Symbol.for('rp: edit message buffer'):
|
||||||
return state.set('messageBuffer', data);
|
return state.set('messageBuffer', data)
|
||||||
// case Symbol.for('rp: zero role picker'):
|
// case Symbol.for('rp: zero role picker'):
|
||||||
// return initialState
|
// return initialState
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { Set, OrderedMap, Map, fromJS } from 'immutable';
|
import { Set, OrderedMap, Map, fromJS } from 'immutable'
|
||||||
|
|
||||||
const blankServer = Map({
|
const blankServer = Map({
|
||||||
id: '386659935687147521',
|
id: '386659935687147521',
|
||||||
|
@ -19,14 +19,14 @@ const blankServer = Map({
|
||||||
isAdmin: true,
|
isAdmin: true,
|
||||||
canManageRoles: true,
|
canManageRoles: true,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
const initialState = OrderedMap({});
|
const initialState = OrderedMap({})
|
||||||
|
|
||||||
export default (state = initialState, { type, data }) => {
|
export default (state = initialState, { type, data }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Symbol.for('update servers'):
|
case Symbol.for('update servers'):
|
||||||
return data.reduce((acc, s) => acc.set(s.id, fromJS(s)), OrderedMap());
|
return data.reduce((acc, s) => acc.set(s.id, fromJS(s)), OrderedMap())
|
||||||
|
|
||||||
// case Symbol.for('update server roles'):
|
// case Symbol.for('update server roles'):
|
||||||
// return state.set(data.id,
|
// return state.set(data.id,
|
||||||
|
@ -34,15 +34,15 @@ export default (state = initialState, { type, data }) => {
|
||||||
// )
|
// )
|
||||||
|
|
||||||
case Symbol.for('server: set'):
|
case Symbol.for('server: set'):
|
||||||
return state.set(data.id, fromJS(data));
|
return state.set(data.id, fromJS(data))
|
||||||
|
|
||||||
case Symbol.for('server: edit message'):
|
case Symbol.for('server: edit message'):
|
||||||
return state.setIn([data.id, 'message'], data.message);
|
return state.setIn([data.id, 'message'], data.message)
|
||||||
|
|
||||||
case Symbol.for('add debug server'):
|
case Symbol.for('add debug server'):
|
||||||
return state.set('0', blankServer);
|
return state.set('0', blankServer)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { Map } from 'immutable';
|
import { Map } from 'immutable'
|
||||||
|
|
||||||
const initialState = Map({
|
const initialState = Map({
|
||||||
isLoggedIn: false,
|
isLoggedIn: false,
|
||||||
|
@ -6,17 +6,17 @@ const initialState = Map({
|
||||||
discriminator: '0001',
|
discriminator: '0001',
|
||||||
id: '',
|
id: '',
|
||||||
avatar: null,
|
avatar: null,
|
||||||
});
|
})
|
||||||
|
|
||||||
export default (state = initialState, { type, data }) => {
|
export default (state = initialState, { type, data }) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case Symbol.for('set user'):
|
case Symbol.for('set user'):
|
||||||
return Map({ ...data, isLoggedIn: true });
|
return Map({ ...data, isLoggedIn: true })
|
||||||
|
|
||||||
case Symbol.for('reset user'):
|
case Symbol.for('reset user'):
|
||||||
return initialState;
|
return initialState
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return state;
|
return state
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
|
@ -16,30 +16,30 @@ const isLocalhost = Boolean(
|
||||||
window.location.hostname.match(
|
window.location.hostname.match(
|
||||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
|
|
||||||
export default function register() {
|
export default function register() {
|
||||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||||
// The URL constructor is available in all browsers that support SW.
|
// The URL constructor is available in all browsers that support SW.
|
||||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
|
const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
|
||||||
if (publicUrl.origin !== window.location.origin) {
|
if (publicUrl.origin !== window.location.origin) {
|
||||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||||
// from what our page is served on. This might happen if a CDN is used to
|
// from what our page is served on. This might happen if a CDN is used to
|
||||||
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
|
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('load', () => {
|
window.addEventListener('load', () => {
|
||||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
|
||||||
|
|
||||||
if (isLocalhost) {
|
if (isLocalhost) {
|
||||||
// This is running on localhost. Lets check if a service worker still exists or not.
|
// This is running on localhost. Lets check if a service worker still exists or not.
|
||||||
checkValidServiceWorker(swUrl);
|
checkValidServiceWorker(swUrl)
|
||||||
} else {
|
} else {
|
||||||
// Is not local host. Just register service worker
|
// Is not local host. Just register service worker
|
||||||
registerValidSW(swUrl);
|
registerValidSW(swUrl)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,7 +48,7 @@ function registerValidSW(swUrl) {
|
||||||
.register(swUrl)
|
.register(swUrl)
|
||||||
.then(registration => {
|
.then(registration => {
|
||||||
registration.onupdatefound = () => {
|
registration.onupdatefound = () => {
|
||||||
const installingWorker = registration.installing;
|
const installingWorker = registration.installing
|
||||||
installingWorker.onstatechange = () => {
|
installingWorker.onstatechange = () => {
|
||||||
if (installingWorker.state === 'installed') {
|
if (installingWorker.state === 'installed') {
|
||||||
if (navigator.serviceWorker.controller) {
|
if (navigator.serviceWorker.controller) {
|
||||||
|
@ -56,20 +56,20 @@ function registerValidSW(swUrl) {
|
||||||
// the fresh content will have been added to the cache.
|
// the fresh content will have been added to the cache.
|
||||||
// It's the perfect time to display a "New content is
|
// It's the perfect time to display a "New content is
|
||||||
// available; please refresh." message in your web app.
|
// available; please refresh." message in your web app.
|
||||||
console.log('New content is available; please refresh.');
|
console.log('New content is available; please refresh.')
|
||||||
} else {
|
} else {
|
||||||
// At this point, everything has been precached.
|
// At this point, everything has been precached.
|
||||||
// It's the perfect time to display a
|
// It's the perfect time to display a
|
||||||
// "Content is cached for offline use." message.
|
// "Content is cached for offline use." message.
|
||||||
console.log('Content is cached for offline use.');
|
console.log('Content is cached for offline use.')
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
};
|
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
console.error('Error during service worker registration:', error);
|
console.error('Error during service worker registration:', error)
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkValidServiceWorker(swUrl) {
|
function checkValidServiceWorker(swUrl) {
|
||||||
|
@ -84,23 +84,23 @@ function checkValidServiceWorker(swUrl) {
|
||||||
// No service worker found. Probably a different app. Reload the page.
|
// No service worker found. Probably a different app. Reload the page.
|
||||||
navigator.serviceWorker.ready.then(registration => {
|
navigator.serviceWorker.ready.then(registration => {
|
||||||
registration.unregister().then(() => {
|
registration.unregister().then(() => {
|
||||||
window.location.reload();
|
window.location.reload()
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
} else {
|
} else {
|
||||||
// Service worker found. Proceed as normal.
|
// Service worker found. Proceed as normal.
|
||||||
registerValidSW(swUrl);
|
registerValidSW(swUrl)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
console.log('No internet connection found. App is running in offline mode.');
|
console.log('No internet connection found. App is running in offline mode.')
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function unregister() {
|
export function unregister() {
|
||||||
if ('serviceWorker' in navigator) {
|
if ('serviceWorker' in navigator) {
|
||||||
navigator.serviceWorker.ready.then(registration => {
|
navigator.serviceWorker.ready.then(registration => {
|
||||||
registration.unregister();
|
registration.unregister()
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,26 +1,26 @@
|
||||||
import React, { Component, Fragment } from 'react';
|
import React, { Component, Fragment } from 'react'
|
||||||
import { Route, Switch, Redirect } from 'react-router-dom';
|
import { Route, Switch, Redirect } from 'react-router-dom'
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux'
|
||||||
import { withRouter } from 'react-router';
|
import { withRouter } from 'react-router'
|
||||||
|
|
||||||
import Servers from '../components/servers';
|
import Servers from '../components/servers'
|
||||||
import OauthCallback from '../components/oauth-callback';
|
import OauthCallback from '../components/oauth-callback'
|
||||||
import OauthFlow from '../components/oauth-flow';
|
import OauthFlow from '../components/oauth-flow'
|
||||||
import OauthBotFlow from '../components/oauth-bot-flow';
|
import OauthBotFlow from '../components/oauth-bot-flow'
|
||||||
import Pages, { Landing, Error404 } from '../pages';
|
import Pages, { Landing, Error404 } from '../pages'
|
||||||
import ServerLanding from '../components/servers/ServerLanding';
|
import ServerLanding from '../components/servers/ServerLanding'
|
||||||
|
|
||||||
const aaa = props => <div>{JSON.stringify(props)}</div>;
|
const aaa = props => <div>{JSON.stringify(props)}</div>
|
||||||
|
|
||||||
export default
|
export default
|
||||||
@withRouter
|
@withRouter
|
||||||
@connect(({ appState, user }) => ({ ready: appState.ready, user }))
|
@connect(({ appState, user }) => ({ ready: appState.ready, user }))
|
||||||
class AppRouter extends Component {
|
class AppRouter extends Component {
|
||||||
render() {
|
render() {
|
||||||
const isLoggedIn = this.props.user.get('isLoggedIn');
|
const isLoggedIn = this.props.user.get('isLoggedIn')
|
||||||
|
|
||||||
if (!this.props.ready) {
|
if (!this.props.ready) {
|
||||||
return null;
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -52,6 +52,6 @@ class AppRouter extends Component {
|
||||||
|
|
||||||
<Route component={Error404} />
|
<Route component={Error404} />
|
||||||
</Switch>
|
</Switch>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
import { createStore, applyMiddleware, compose } from 'redux';
|
import { createStore, applyMiddleware, compose } from 'redux'
|
||||||
import thunk from 'redux-thunk';
|
import thunk from 'redux-thunk'
|
||||||
import { createLogger } from 'redux-logger';
|
import { createLogger } from 'redux-logger'
|
||||||
// import api from '../middleware/api'
|
// import api from '../middleware/api'
|
||||||
import rootReducer from '../reducers';
|
import rootReducer from '../reducers'
|
||||||
import DevTools from '../components/dev-tools';
|
import DevTools from '../components/dev-tools'
|
||||||
import { routerMiddleware } from 'react-router-redux';
|
import { routerMiddleware } from 'react-router-redux'
|
||||||
|
|
||||||
const configureStore = (preloadedState, history) => {
|
const configureStore = (preloadedState, history) => {
|
||||||
const store = createStore(
|
const store = createStore(
|
||||||
|
@ -14,16 +14,16 @@ const configureStore = (preloadedState, history) => {
|
||||||
applyMiddleware(thunk, routerMiddleware(history), createLogger())
|
applyMiddleware(thunk, routerMiddleware(history), createLogger())
|
||||||
// DevTools.instrument()
|
// DevTools.instrument()
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
|
|
||||||
if (module.hot) {
|
if (module.hot) {
|
||||||
// Enable Webpack hot module replacement for reducers
|
// Enable Webpack hot module replacement for reducers
|
||||||
module.hot.accept('../reducers', () => {
|
module.hot.accept('../reducers', () => {
|
||||||
store.replaceReducer(rootReducer);
|
store.replaceReducer(rootReducer)
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return store;
|
return store
|
||||||
};
|
}
|
||||||
|
|
||||||
export default configureStore;
|
export default configureStore
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
if (process.env.NODE_ENV === 'production') {
|
if (process.env.NODE_ENV === 'production') {
|
||||||
module.exports = require('./configureStore.prod');
|
module.exports = require('./configureStore.prod')
|
||||||
} else {
|
} else {
|
||||||
module.exports = require('./configureStore.dev');
|
module.exports = require('./configureStore.dev')
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
import { createStore, applyMiddleware } from 'redux';
|
import { createStore, applyMiddleware } from 'redux'
|
||||||
import { routerMiddleware } from 'react-router-redux';
|
import { routerMiddleware } from 'react-router-redux'
|
||||||
|
|
||||||
import thunk from 'redux-thunk';
|
import thunk from 'redux-thunk'
|
||||||
// import api from '../middleware/api'
|
// import api from '../middleware/api'
|
||||||
import rootReducer from '../reducers';
|
import rootReducer from '../reducers'
|
||||||
|
|
||||||
const configureStore = (preloadedState, history) =>
|
const configureStore = (preloadedState, history) =>
|
||||||
createStore(
|
createStore(
|
||||||
rootReducer,
|
rootReducer,
|
||||||
preloadedState,
|
preloadedState,
|
||||||
applyMiddleware(thunk, routerMiddleware(history))
|
applyMiddleware(thunk, routerMiddleware(history))
|
||||||
);
|
)
|
||||||
|
|
||||||
export default configureStore;
|
export default configureStore
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
export const msgToReal = msg => msg.replace(/</g, '<').replace(/\n/g, '<br />');
|
export const msgToReal = msg => msg.replace(/</g, '<').replace(/\n/g, '<br />')
|
||||||
|
|
Loading…
Add table
Reference in a new issue