make deployable

This commit is contained in:
41666 2017-12-29 10:12:54 -06:00
parent eaa1167f16
commit 309aee427e
15 changed files with 317 additions and 886 deletions

1
Server/.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules
.data
.env
public

View file

@ -1,12 +1,14 @@
const log = new (require('../logger'))('api/index')
const glob = require('glob')
const PROD = process.env.NODE_ENV === 'production'
module.exports = async (router, ctx) => {
const apis = glob.sync('./api/**/!(index).js')
const apis = glob.sync(`./api/**/!(index).js`)
log.debug('found apis', apis)
for (let a of apis) {
if (a.endsWith('_test.js') !== null && process.env.NODE_ENV !== 'development') {
if (a.endsWith('_test.js') && PROD) {
log.debug(`skipping ${a}`)
continue
}

View file

@ -5,6 +5,7 @@ const http = require('http')
const Koa = require('koa')
const app = new Koa()
const _io = require('socket.io')
const path = require('path')
const router = require('koa-better-router')().loadMethods()
const Roleypoly = require('./Roleypoly')
@ -34,6 +35,28 @@ async function start () {
const bodyParser = require('koa-bodyparser')
app.use(bodyParser({ types: ['json'] }))
// Compress
const compress = require('koa-compress')
app.use(compress())
// SPA + Static
if (process.env.NODE_ENV === 'production') {
const pub = path.join(__dirname, 'public')
const staticFiles = require('koa-static')
app.use(staticFiles(pub, { defer: true }))
const send = require('koa-send')
app.use(async (ctx, next) => {
if (ctx.path.startsWith('/api')) {
return next()
}
await next()
send(ctx, 'index.html', { root: pub })
})
}
// Request logger
app.use(async (ctx, next) => {
let timeStart = new Date()
@ -60,15 +83,18 @@ async function start () {
app.use(session({
key: 'roleypoly:sess',
maxAge: 'session',
siteOnly: true,
store: M.ctx.sessions
}, app))
await M.mountRoutes()
// SPA server
log.info(`starting HTTP server on ${process.env.APP_PORT || 6769}`)
server.listen(process.env.APP_PORT || 6769)
}
start().catch(e => {
console.error(e)
log.fatal('app failed to start', e)
})

View file

@ -15,6 +15,8 @@ class Logger {
if (typeof data[data.length - 1] === 'number') {
process.exit(data[data.length - 1])
} else {
process.exit(1)
}
throw text

View file

@ -10,34 +10,29 @@
},
"dependencies": {
"chalk": "^2.3.0",
"commander": "^2.12.2",
"discord.js": "^11.2.1",
"dotenv": "^4.0.0",
"erlpack": "github:discordapp/erlpack",
"eslint": "^4.12.1",
"eslint-config-standard": "^10.2.1",
"eventemitter3": "^3.0.0",
"eslint": "^4.14.0",
"eslint-config-standard": "^11.0.0-beta.0",
"glob": "^7.1.2",
"immutable": "^3.8.2",
"inquirer": "^4.0.1",
"koa": "^2.4.1",
"koa-better-router": "^2.1.1",
"koa-bodyparser": "^4.2.0",
"koa-passport": "^4.0.1",
"koa-send": "^4.1.2",
"koa-session": "^5.5.1",
"koa-compress": "^2.0.0",
"koa-static": "^4.0.2",
"ksuid": "^0.4.0",
"lru-cache": "^4.1.1",
"passport-discord": "^0.1.3",
"passport-oauth2-refresh": "^1.0.0",
"pg": "^7.4.0",
"pg-hstore": "^2.3.2",
"pm2": "^2.8.0",
"sequelize": "^4.26.0",
"pm2": "^2.9.1",
"sequelize": "^4.28.6",
"socket.io": "^2.0.4",
"standard": "^10.0.3",
"superagent": "^3.8.1",
"superagent": "^3.8.2",
"uuid": "^3.1.0",
"uws": "^9.14.0",
"yargs": "^10.0.3"
"uws": "^9.14.0"
}
}

View file

@ -12,8 +12,13 @@ class DiscordService extends Service {
this.oauthCallback = process.env.OAUTH_AUTH_CALLBACK
this.botCallback = `${ctx.config.appUrl}/api/oauth/bot/callback`
this.appUrl = process.env.APP_URL
this.isBot = process.env.IS_BOT === 'true' || false
this.rootUsers = new Set((process.env.ROOT_USERS||'').split(','))
this.client = new discord.Client()
this.client.options.disableEveryone = true
this.cmds = this._cmds()
this.startBot()
}
@ -25,7 +30,11 @@ class DiscordService extends Service {
async startBot () {
await this.client.login(this.botToken)
this.client.on('message', this.handleMessage.bind(this))
// not all roleypolys are bots.
if (this.isBot) {
this.log.info('this roleypoly is a bot')
this.client.on('message', this.handleMessage.bind(this))
}
for (let server of this.client.guilds.array()) {
await this.ctx.server.ensure(server)
@ -135,15 +144,77 @@ class DiscordService extends Service {
message.channel.send(`🔰 Assign your roles here! <${this.appUrl}/s/${message.guild.id}>`, { disableEveryone: true })
}
_cmds () {
const cmds = [
{
regex: /say (.*)/,
handler (message, matches, r) {
r(matches[0])
}
},
{
regex: /set username (.*)/,
async handler (message, matches) {
const { username } = this.client.user
await this.client.user.setUsername(matches[0])
message.channel.send(`Username changed from ${username} to ${matches[0]}`)
}
},
{
regex: /stats/,
async handler (message, matches) {
const t = [
`**Stats** 📈`,
'',
`👩‍❤️‍👩 **Users Served:** ${this.client.guilds.reduce((acc, g) => acc + g.memberCount, 0)}`,
`🔰 **Servers:** ${this.client.guilds.array().length}`
]
message.channel.send(t.join('\n'))
}
}
]
// prefix regex with ^ for ease of code
.map(({regex, ...rest}) => ({ regex: new RegExp(`^${regex.source}`, regex.flags), ...rest }))
return cmds
}
async handleCommand (message) {
const cmd = message.content.replace(`<@${this.client.user.id}> `, '')
this.log.debug(`got command from ${message.author.username}`, cmd)
for (let { regex, handler } of this.cmds) {
const match = regex.exec(cmd)
if (match !== null) {
this.log.debug('command accepted', { cmd, match })
try {
await handler.call(this, message, match.slice(1))
return
} catch (e) {
this.log.error('command errored', { e, cmd, message })
message.channel.send(`❌ **An error occured.** ${e}`)
return
}
}
}
// nothing matched?
this.mentionResponse(message)
}
handleMessage (message) {
if (message.author.bot && message.channel.type !== 'text') { // drop bot messages and dms
return
}
if (message.mentions.users.has(this.client.user.id)) {
this.mentionResponse(message)
if (this.rootUsers.has(message.author.id)) {
this.handleCommand.call(this, message)
} else {
this.mentionResponse.call(this, message)
}
}
}
}
module.exports = DiscordService

File diff suppressed because it is too large Load diff