could listen to unix socket, better conf

This commit is contained in:
lesion
2019-06-10 00:40:37 +02:00
parent d1a56e5135
commit b01f4ef04d
15 changed files with 107 additions and 76 deletions

View File

@@ -25,8 +25,8 @@ export default {
page: { month, year}, page: { month, year},
} }
}, },
watch: { watch: {
// month selected
page () { page () {
this.updateEvents(this.page) this.updateEvents(this.page)
} }

View File

@@ -1,18 +1,19 @@
/** const path = require('path')
* GANCIO CONFIGURATION
*/
const env = process.env.NODE_ENV || 'development'
/** /**
* Database configuration * -[ GANCIO CONFIGURATION ]-
*
* -[ Database configuration ]-
* `development` configuration is enabled running `yarn dev` * `development` configuration is enabled running `yarn dev`
* while `production` with `yarn start` * while `production` with `yarn start`
* ref: http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor * ref: http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor
*
*/ */
const DB_CONF = { const DB_CONF = {
development: { development: {
storage: __dirname + '/db.sqlite', storage: path.join(__dirname, 'db.sqlite'),
dialect: 'sqlite', dialect: 'sqlite'
}, },
production: { production: {
username: '', username: '',
@@ -21,16 +22,32 @@ const DB_CONF = {
host: 'localhost', host: 'localhost',
dialect: 'postgres', dialect: 'postgres',
logging: false logging: false
}, }
} }
const SECRET_CONF = { const env = process.env.NODE_ENV || 'development'
/**
* -[ Main configuration ]-
*
*/
const config = {
server: {
port: '3000',
host: '0',
// uncomment to use unix socket to serve gancio
// path: '/tmp/gancio_socket',
},
locale: 'it',
title: 'GANCIO',
description: 'A shared agenda for radical communities',
baseurl: '' || 'http://localhost:3000',
// where events/users confirmation email are sent // where events/users confirmation email are sent
admin: 'gancio@example.com', admin: '',
db: DB_CONF[env], // jwt salt secret, generate it randomly with
// < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32};echo;
// jwt salt secret (generate it randomly)
secret: '', secret: '',
// smtp account to send email // smtp account to send email
@@ -42,17 +59,7 @@ const SECRET_CONF = {
pass: process.env.SMTP_PASS || '' pass: process.env.SMTP_PASS || ''
} }
}, },
db: DB_CONF[env]
} }
/** module.exports = config
* Main Gancio configuration
*/
const SHARED_CONF = {
locale: 'it',
title: 'GANCIO',
description: 'A calendar for radical communities',
baseurl: '' || 'http://localhost:3000',
env
}
module.exports = { SHARED_CONF, SECRET_CONF, ...SECRET_CONF.db }

View File

@@ -2,7 +2,7 @@ const argv = require('yargs').argv
const path = require('path') const path = require('path')
const config_path = path.resolve(argv.config || './config.js') const config_path = path.resolve(argv.config || './config.js')
const config = require(config_path).SHARED_CONF const config = require(config_path)
module.exports = { module.exports = {
mode: 'universal', mode: 'universal',
@@ -36,7 +36,9 @@ module.exports = {
'element-ui/lib/theme-chalk/index.css' 'element-ui/lib/theme-chalk/index.css'
], ],
env: { env: {
config baseurl: config.baseurl,
title: config.title,
description: config.description
}, },
/* /*
** Plugins to load before mounting the App ** Plugins to load before mounting the App
@@ -83,9 +85,22 @@ module.exports = {
** Build configuration ** Build configuration
*/ */
build: { build: {
optimization: {
splitChunks: {
cacheGroups: {
element: {
test: /[\\/]node_modules[\\/](element-ui)[\\/]/,
name: 'element-ui',
chunks: 'all'
}
}
}
},
transpile: [/^element-ui/, /^vue-awesome/], transpile: [/^element-ui/, /^vue-awesome/],
splitChunks: { splitChunks: {
layouts: true layouts: true
} },
cache: true,
parallel: true
} }
} }

View File

@@ -107,7 +107,7 @@ export default {
params.push(`places=${this.filters.places}`) params.push(`places=${this.filters.places}`)
} }
return `<iframe src="/embed/list?${params.join('&')}"></iframe>` return `<iframe src="${process.env.baseurl}/embed/list?${params.join('&')}"></iframe>`
}, },
link () { link () {
const tags = this.filters.tags.join(',') const tags = this.filters.tags.join(',')
@@ -123,7 +123,7 @@ export default {
} }
} }
return `/api/export/${this.type}${query}` return `${process.env.baseurl}/api/export/${this.type}${query}`
}, },
showLink () { showLink () {
return (['feed', 'ics'].indexOf(this.type)>-1) return (['feed', 'ics'].indexOf(this.type)>-1)

View File

@@ -42,7 +42,7 @@ const exportController = {
feed(res, events) { feed(res, events) {
res.type('application/rss+xml; charset=UTF-8') res.type('application/rss+xml; charset=UTF-8')
res.render('feed/rss.pug', { events, config: process.env.config, moment }) res.render('feed/rss.pug', { events, config: process.env, moment })
}, },
ics(res, events) { ics(res, events) {

View File

@@ -1,8 +1,6 @@
const Mastodon = require('mastodon-api') const Mastodon = require('mastodon-api')
const { setting: Setting } = require('../models') const { setting: Setting } = require('../models')
const baseurl = process.env.baseurl
const settingsController = { const settingsController = {
async setAdminSetting(key, value) { async setAdminSetting(key, value) {
@@ -20,7 +18,7 @@ const settingsController = {
async getAuthURL(req, res) { async getAuthURL(req, res) {
const instance = req.body.instance const instance = req.body.instance
const callback = `${baseurl}/api/settings/oauth` const callback = `${process.env.baseurl}/api/settings/oauth`
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`, const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`,
'gancio', 'read write', callback) 'gancio', 'read write', callback)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret, const url = await Mastodon.getAuthorizationUrl(client_id, client_secret,
@@ -33,7 +31,7 @@ const settingsController = {
async code(req, res) { async code(req, res) {
const code = req.query.code const code = req.query.code
let client_id, client_secret, instance let client_id, client_secret, instance
const callback = `${baseurl}/api/settings/oauth` const callback = `${process.env.baseurl}/api/settings/oauth`
const settings = await settingsController.settings() const settings = await settingsController.settings()

View File

@@ -30,7 +30,7 @@ const userController = {
email: user.email, email: user.email,
scope: [user.is_admin ? 'admin' : 'user'] scope: [user.is_admin ? 'admin' : 'user']
}, },
config.SECRET_CONF.secret config.secret
) )
res.json({ token: accessToken }) res.json({ token: accessToken })
@@ -164,7 +164,7 @@ const userController = {
if (!user) return res.sendStatus(200) if (!user) return res.sendStatus(200)
user.recover_code = crypto.randomBytes(16).toString('hex') user.recover_code = crypto.randomBytes(16).toString('hex')
mail.send(user.email, 'recover', { user, config: config.SHARED_CONF }) mail.send(user.email, 'recover', { user, config })
await user.save() await user.save()
res.sendStatus(200) res.sendStatus(200)
@@ -208,7 +208,7 @@ const userController = {
const user = await User.findByPk(req.body.id) const user = await User.findByPk(req.body.id)
if (user) { if (user) {
if (!user.is_active && req.body.is_active) { if (!user.is_active && req.body.is_active) {
await mail.send(user.email, 'confirm', { user, config: config.SHARED_CONF }) await mail.send(user.email, 'confirm', { user, config })
} }
await user.update(req.body) await user.update(req.body)
res.json(user) res.json(user)
@@ -229,7 +229,7 @@ const userController = {
const user = await User.create(req.body) const user = await User.create(req.body)
try { try {
mail.send([user.email, config.SECRET_CONF.admin], 'register', { user, config: config.SHARED_CONF }) mail.send([user.email, config.admin], 'register', { user, config })
} catch (e) { } catch (e) {
return res.status(400).json(e) return res.status(400).json(e)
} }
@@ -238,7 +238,7 @@ const userController = {
email: user.email, email: user.email,
scope: [user.is_admin ? 'admin' : 'user'] scope: [user.is_admin ? 'admin' : 'user']
} }
const token = jwt.sign(payload, config.SECRET_CONF.secret) const token = jwt.sign(payload, config.secret)
res.json({ token, user }) res.json({ token, user })
} catch (e) { } catch (e) {
res.status(404).json(e) res.status(404).json(e)

View File

@@ -22,7 +22,7 @@ api.use(bodyParser.urlencoded({ extended: false }))
api.use(bodyParser.json()) api.use(bodyParser.json())
const jwt = expressJwt({ const jwt = expressJwt({
secret: config.SECRET_CONF.secret, secret: config.secret,
credentialsRequired: false credentialsRequired: false
}) })

View File

@@ -3,7 +3,7 @@ const path = require('path')
const moment = require('moment') const moment = require('moment')
const config = require('../config') const config = require('../config')
moment.locale(config.SHARED_CONF.locale) moment.locale(config.locale)
const mail = { const mail = {
send(addresses, template, locals) { send(addresses, template, locals) {
const email = new Email({ const email = new Email({
@@ -17,25 +17,25 @@ const mail = {
} }
}, },
message: { message: {
from: `${config.SHARED_CONF.title} <${config.SECRET_CONF.smtp.auth.user}>` from: `${config.title} <${config.smtp.auth.user}>`
}, },
send: true, send: true,
i18n: { i18n: {
directory: path.join(__dirname, '..', '..', 'locales', 'email'), directory: path.join(__dirname, '..', '..', 'locales', 'email'),
defaultLocale: config.SHARED_CONF.locale defaultLocale: config.locale
}, },
transport: config.SECRET_CONF.smtp transport: config.smtp
}) })
const msg = { const msg = {
template, template,
message: { message: {
to: addresses, to: addresses,
bcc: config.SECRET_CONF.admin bcc: config.admin
}, },
locals: { locals: {
...locals, ...locals,
locale: config.SHARED_CONF.locale, locale: config.locale,
config: config.SHARED_CONF, config: { title: config.title, baseurl: config.baseurl, description: config.description },
datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm') datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm')
} }
} }

View File

@@ -4,10 +4,10 @@ const path = require('path')
const Sequelize = require('sequelize') const Sequelize = require('sequelize')
const config_path = path.resolve(argv.config || './config.js') const config_path = path.resolve(argv.config || './config.js')
const basename = path.basename(__filename) const basename = path.basename(__filename)
const config = require(config_path).SECRET_CONF.db const config = require(config_path)
const db = {} const db = {}
const sequelize = new Sequelize(config) const sequelize = new Sequelize(config.db)
fs fs
.readdirSync(__dirname) .readdirSync(__dirname)

View File

@@ -3,5 +3,3 @@ const path = require('path')
const config_path = path.resolve(argv.config || './config.js') const config_path = path.resolve(argv.config || './config.js')
module.exports = require(config_path) module.exports = require(config_path)

View File

@@ -10,8 +10,8 @@ if (!fs.existsSync(config_path)) {
process.exit(1) process.exit(1)
} }
const { SECRET_CONF, SHARED_CONF } = require(config_path) const config = require(config_path)
if (!SECRET_CONF.secret) { if (!config.secret) {
console.error(`Please specify a random 'secret' in '${config_path}'!`) console.error(`Please specify a random 'secret' in '${config_path}'!`)
process.exit(1) process.exit(1)
} }
@@ -19,9 +19,9 @@ if (!SECRET_CONF.secret) {
const Sequelize = require('sequelize') const Sequelize = require('sequelize')
let db let db
try { try {
db = new Sequelize(SECRET_CONF.db) db = new Sequelize(config.db)
} catch (e) { } catch (e) {
console.error(`DB Error: check '${SHARED_CONF.env}' configuration.\n (sequelize error -> ${e})`) console.error(`DB Error: check '${config.env}' configuration.\n (sequelize error -> ${e})`)
process.exit(1) process.exit(1)
} }
@@ -29,13 +29,13 @@ try {
module.exports = db.authenticate() module.exports = db.authenticate()
.then(() => { .then(() => {
require('./api/models') require('./api/models')
if (SHARED_CONF.env === 'development') { if (config.env === 'development') {
console.error('DB Force sync') console.error('DB Force sync')
return db.sync({ force: true }) return db.sync({ force: true })
} }
}) })
.catch(e => { .catch(e => {
console.error(e) console.error(e)
console.error(`DB Error: check '${SHARED_CONF.env}' configuration\n (sequelize error -> ${e})`) console.error(`DB Error: check '${config.env}' configuration\n (sequelize error -> ${e})`)
process.exit(1) process.exit(1)
}) })

View File

@@ -6,17 +6,18 @@ const morgan = require('morgan')
const { Nuxt, Builder } = require('nuxt') const { Nuxt, Builder } = require('nuxt')
const firstRun = require('./firstrun') const firstRun = require('./firstrun')
// Import and Set Nuxt.js options // Import and Set Nuxt.js options
const config = require('../nuxt.config.js') const nuxt_config = require('../nuxt.config.js')
const config = require('./config')
const app = express() const app = express()
async function start() { async function start() {
// Init Nuxt.js // Init Nuxt.js
const nuxt = new Nuxt(config) const nuxt = new Nuxt(nuxt_config)
const { host, port } = nuxt.options.server // const { host, port } = nuxt.options.server
// Build only in dev mode // Build only in dev mode
if (config.dev) { if (nuxt_config.dev) {
const builder = new Builder(nuxt) const builder = new Builder(nuxt)
await builder.build() await builder.build()
} else { } else {
@@ -29,10 +30,26 @@ async function start() {
app.use(nuxt.render) app.use(nuxt.render)
// Listen the server // Listen the server
app.listen(port, host) const server = app.listen(config.server)
consola.ready({
message: `Server listening on http://${host}:${port}`, // close connections/port/unix socket
badge: true function shutdown() {
consola.info(`Closing connections..`)
server.close()
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
server.on('error', e => {
consola.error(e)
})
server.on('listening', () => {
const address = server.address()
consola.ready({
message: `Server listening on ${(typeof address) === 'object' ? `${address.address}:${address.port}` : address}`,
badge: true
})
}) })
} }

View File

@@ -1,7 +1,7 @@
// const mail = require('./mail') const mail = require('./mail')
const bot = require('./api/controller/bot') const bot = require('./api/controller/bot')
const settingsController = require('./api/controller/settings') const settingsController = require('./api/controller/settings')
// const config = require('./config.js') const config = require('./config.js')
const { Event, Notification, EventNotification, const { Event, Notification, EventNotification,
User, Place, Tag } = require('./api/models') User, Place, Tag } = require('./api/models')
@@ -12,10 +12,10 @@ async function sendNotification(notification, event, eventNotification) {
switch (notification.type) { switch (notification.type) {
// case 'mail': // case 'mail':
// return mail.send(notification.email, 'event', { event, config, notification }) // return mail.send(notification.email, 'event', { event, config, notification })
// case 'admin_email': case 'admin_email':
// const admins = await User.findAll({ where: { is_admin: true } }) // const admins = await User.findAll({ where: { is_admin: true } })
// const admin_emails = admins.map(admin => admin.email) // const admin_emails = admins.map(admin => admin.email)
// return mail.send(admin_emails, 'event', { event, to_confirm: true, notification }) return mail.send(admin_emails, 'event', { event, to_confirm: true, notification })
case 'mastodon': case 'mastodon':
// instance publish // instance publish
if (settings.mastodon_auth.instance && settings.mastodon_auth.access_token) { if (settings.mastodon_auth.instance && settings.mastodon_auth.access_token) {
@@ -58,8 +58,4 @@ function startLoop(seconds) {
interval = setInterval(notify, seconds * 1000) interval = setInterval(notify, seconds * 1000)
} }
function stopLoop() { startLoop(26000)
stopInterval(interval)
}
module.exports = { startLoop, stopLoop }