refactor: moved server content to /server

This commit is contained in:
NGPixel 2017-04-28 17:58:38 -04:00
parent 86eb7a427d
commit d4b73be1e7
97 changed files with 7452 additions and 73 deletions

5
.build/_preinit.js Normal file
View File

@ -0,0 +1,5 @@
window.MathJax = {
root: '/js/mathjax',
delayStartupUntil: 'configured'
}
;

View File

@ -27,6 +27,7 @@
"ws": true, "ws": true,
"Mongoose": true, "Mongoose": true,
"ROOTPATH": true, "ROOTPATH": true,
"SERVERPATH": true,
"IS_DEBUG": true, "IS_DEBUG": true,
"PROCNAME": true "PROCNAME": true
} }

8
.gitignore vendored
View File

@ -1,7 +1,6 @@
# Logs # Logs
logs logs
*.log *.log
npm-debug.log*
/logs /logs
# Deployment builds # Deployment builds
@ -11,11 +10,11 @@ dist
node_modules node_modules
npm/node_modules npm/node_modules
# Optional npm cache directory # NPM / Yarn
.npm .npm
.yarn.lock
# Optional REPL history
.node_repl_history .node_repl_history
npm-debug.log*
# NewRelic APM # NewRelic APM
newrelic.js newrelic.js
@ -25,7 +24,6 @@ newrelic.js
# Fusebox # Fusebox
.fusebox .fusebox
.build
# Config Files # Config Files
config.yml config.yml

View File

@ -20,7 +20,7 @@ before_script:
- npm install -g snyk - npm install -g snyk
- snyk auth $SNYK_TOKEN - snyk auth $SNYK_TOKEN
before_deploy: before_deploy:
- tar -czf wiki-js.tar.gz * -X .deployexclude - tar -czf wiki-js.tar.gz * -X .build/.deployexclude
- snyk monitor - snyk monitor
deploy: deploy:
provider: releases provider: releases

14
fuse.js
View File

@ -213,15 +213,7 @@ globalTasks.then(() => {
exec: (args.i) ? 'node --inspect server' : 'node server', exec: (args.i) ? 'node --inspect server' : 'node server',
ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'], ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
ext: 'js json', ext: 'js json',
watch: [ watch: ['server'],
'controllers',
'libs',
'locales',
'middlewares',
'models',
'agent.js',
'server.js'
],
env: { 'NODE_ENV': 'development' } env: { 'NODE_ENV': 'development' }
}) })
}, 1000) }, 1000)
@ -258,9 +250,7 @@ globalTasks.then(() => {
exec: 'node wiki configure', exec: 'node wiki configure',
ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'], ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
ext: 'js json', ext: 'js json',
watch: [ watch: ['server/configure.js'],
'configure.js'
],
env: { 'NODE_ENV': 'development' } env: { 'NODE_ENV': 'development' }
}) })
}, 1000) }, 1000)

View File

@ -60,7 +60,7 @@
"file-type": "^4.2.0", "file-type": "^4.2.0",
"filesize.js": "^1.0.2", "filesize.js": "^1.0.2",
"follow-redirects": "^1.2.3", "follow-redirects": "^1.2.3",
"fs-extra": "^2.1.2", "fs-extra": "^3.0.0",
"git-wrapper2-promise": "^0.2.9", "git-wrapper2-promise": "^0.2.9",
"highlight.js": "^9.11.0", "highlight.js": "^9.11.0",
"i18next": "^8.0.0", "i18next": "^8.0.0",
@ -145,7 +145,7 @@
"nodemon": "latest", "nodemon": "latest",
"pug-lint": "latest", "pug-lint": "latest",
"snyk": "latest", "snyk": "latest",
"standard": "^10.0.2", "standard": "latest",
"sticky-js": "^1.2.0", "sticky-js": "^1.2.0",
"twemoji-awesome": "^1.0.6", "twemoji-awesome": "^1.0.6",
"uglify-js": "latest", "uglify-js": "latest",

View File

@ -4,8 +4,13 @@
// Licensed under AGPLv3 // Licensed under AGPLv3
// =========================================== // ===========================================
const path = require('path')
const ROOTPATH = process.cwd()
const SERVERPATH = path.join(ROOTPATH, 'server')
global.PROCNAME = 'AGENT' global.PROCNAME = 'AGENT'
global.ROOTPATH = __dirname global.ROOTPATH = ROOTPATH
global.SERVERPATH = SERVERPATH
global.IS_DEBUG = process.env.NODE_ENV === 'development' global.IS_DEBUG = process.env.NODE_ENV === 'development'
let appconf = require('./libs/config')() let appconf = require('./libs/config')()
@ -34,20 +39,19 @@ global.mark = require('./libs/markdown')
// Load modules // Load modules
// ---------------------------------------- // ----------------------------------------
var moment = require('moment') const moment = require('moment')
var Promise = require('bluebird') const Promise = require('bluebird')
var fs = Promise.promisifyAll(require('fs-extra')) const fs = Promise.promisifyAll(require('fs-extra'))
var klaw = require('klaw') const klaw = require('klaw')
var path = require('path') const Cron = require('cron').CronJob
var Cron = require('cron').CronJob
// ---------------------------------------- // ----------------------------------------
// Start Cron // Start Cron
// ---------------------------------------- // ----------------------------------------
var job let job
var jobIsBusy = false let jobIsBusy = false
var jobUplWatchStarted = false let jobUplWatchStarted = false
db.onReady.then(() => { db.onReady.then(() => {
return db.Entry.remove({}) return db.Entry.remove({})

View File

@ -1,7 +1,10 @@
'use strict' 'use strict'
module.exports = (port, spinner) => { module.exports = (port, spinner) => {
const ROOTPATH = __dirname const path = require('path')
const ROOTPATH = process.cwd()
const SERVERPATH = path.join(ROOTPATH, 'server')
const IS_DEBUG = process.env.NODE_ENV === 'development' const IS_DEBUG = process.env.NODE_ENV === 'development'
// ---------------------------------------- // ----------------------------------------
@ -13,7 +16,6 @@ module.exports = (port, spinner) => {
const express = require('express') const express = require('express')
const favicon = require('serve-favicon') const favicon = require('serve-favicon')
const http = require('http') const http = require('http')
const path = require('path')
const Promise = require('bluebird') const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs-extra')) const fs = Promise.promisifyAll(require('fs-extra'))
const yaml = require('js-yaml') const yaml = require('js-yaml')
@ -39,7 +41,7 @@ module.exports = (port, spinner) => {
// View Engine Setup // View Engine Setup
// ---------------------------------------- // ----------------------------------------
app.set('views', path.join(ROOTPATH, 'views')) app.set('views', path.join(SERVERPATH, 'views'))
app.set('view engine', 'pug') app.set('view engine', 'pug')
app.use(bodyParser.json()) app.use(bodyParser.json())
@ -55,8 +57,8 @@ module.exports = (port, spinner) => {
let langs = [] let langs = []
let conf = {} let conf = {}
try { try {
langs = yaml.safeLoad(fs.readFileSync('./app/data.yml', 'utf8')).langs langs = yaml.safeLoad(fs.readFileSync(path.join(SERVERPATH, 'app/data.yml'), 'utf8')).langs
conf = yaml.safeLoad(fs.readFileSync('./config.yml', 'utf8')) conf = yaml.safeLoad(fs.readFileSync(path.join(ROOTPATH, 'config.yml'), 'utf8'))
} catch (err) { } catch (err) {
console.error(err) console.error(err)
} }
@ -304,7 +306,7 @@ module.exports = (port, spinner) => {
} }
}) })
}), }),
fs.readFileAsync('./config.yml', 'utf8').then(confRaw => { fs.readFileAsync(path.join(ROOTPATH, 'config.yml'), 'utf8').then(confRaw => {
let conf = yaml.safeLoad(confRaw) let conf = yaml.safeLoad(confRaw)
conf.title = req.body.title conf.title = req.body.title
conf.host = req.body.host conf.host = req.body.host
@ -347,12 +349,12 @@ module.exports = (port, spinner) => {
return crypto.randomBytesAsync(32).then(buf => { return crypto.randomBytesAsync(32).then(buf => {
conf.sessionSecret = buf.toString('hex') conf.sessionSecret = buf.toString('hex')
confRaw = yaml.safeDump(conf) confRaw = yaml.safeDump(conf)
return fs.writeFileAsync('./config.yml', confRaw) return fs.writeFileAsync(path.join(ROOTPATH, 'config.yml'), confRaw)
}) })
}) })
).then(() => { ).then(() => {
if (process.env.IS_HEROKU) { if (process.env.IS_HEROKU) {
return fs.outputJsonAsync('./app/heroku.json', { configured: true }) return fs.outputJsonAsync(path.join(SERVERPATH, 'app/heroku.json'), { configured: true })
} else { } else {
return true return true
} }

View File

@ -50,7 +50,7 @@ router.put('/edit/*', (req, res, next) => {
let safePath = entries.parsePath(_.replace(req.path, '/edit', '')) let safePath = entries.parsePath(_.replace(req.path, '/edit', ''))
entries.update(safePath, req.body.markdown).then(() => { entries.update(safePath, req.body.markdown, req.user).then(() => {
return res.json({ return res.json({
ok: true ok: true
}) || true }) || true
@ -118,7 +118,7 @@ router.put('/create/*', (req, res, next) => {
let safePath = entries.parsePath(_.replace(req.path, '/create', '')) let safePath = entries.parsePath(_.replace(req.path, '/create', ''))
entries.create(safePath, req.body.markdown).then(() => { entries.create(safePath, req.body.markdown, req.user).then(() => {
return res.json({ return res.json({
ok: true ok: true
}) || true }) || true
@ -232,7 +232,7 @@ router.put('/*', (req, res, next) => {
let safeNewPath = entries.parsePath(req.body.move) let safeNewPath = entries.parsePath(req.body.move)
entries.move(safePath, safeNewPath).then(() => { entries.move(safePath, safeNewPath, req.user).then(() => {
res.json({ res.json({
ok: true ok: true
}) })

View File

@ -6,13 +6,14 @@
// Licensed under AGPLv3 // Licensed under AGPLv3
// =========================================== // ===========================================
global.PROCNAME = 'SERVER' const path = require('path')
global.ROOTPATH = __dirname const ROOTPATH = process.cwd()
global.IS_DEBUG = process.env.NODE_ENV === 'development' const SERVERPATH = path.join(ROOTPATH, 'server')
if (IS_DEBUG) { global.PROCNAME = 'SERVER'
try { require('newrelic') } catch (err) {} global.ROOTPATH = ROOTPATH
} global.SERVERPATH = SERVERPATH
global.IS_DEBUG = process.env.NODE_ENV === 'development'
process.env.VIPS_WARNING = false process.env.VIPS_WARNING = false
@ -57,13 +58,12 @@ const i18nextBackend = require('i18next-node-fs-backend')
const i18nextMw = require('i18next-express-middleware') const i18nextMw = require('i18next-express-middleware')
const passport = require('passport') const passport = require('passport')
const passportSocketIo = require('passport.socketio') const passportSocketIo = require('passport.socketio')
const path = require('path')
const session = require('express-session') const session = require('express-session')
const SessionMongoStore = require('connect-mongo')(session) const SessionMongoStore = require('connect-mongo')(session)
const socketio = require('socket.io') const socketio = require('socket.io')
var mw = autoload(path.join(ROOTPATH, '/middlewares')) var mw = autoload(path.join(SERVERPATH, '/middlewares'))
var ctrl = autoload(path.join(ROOTPATH, '/controllers')) var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
// ---------------------------------------- // ----------------------------------------
// Define Express App // Define Express App
@ -141,7 +141,7 @@ lang
// ---------------------------------------- // ----------------------------------------
app.use(i18nextMw.handle(lang)) app.use(i18nextMw.handle(lang))
app.set('views', path.join(ROOTPATH, 'views')) app.set('views', path.join(SERVERPATH, 'views'))
app.set('view engine', 'pug') app.set('view engine', 'pug')
app.use(bodyParser.json()) app.use(bodyParser.json())
@ -241,7 +241,7 @@ io.on('connection', ctrl.ws)
// Start child processes // Start child processes
// ---------------------------------------- // ----------------------------------------
let bgAgent = fork('agent.js') let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
bgAgent.on('message', m => { bgAgent.on('message', m => {
if (!m.action) { if (!m.action) {

View File

@ -6,6 +6,8 @@ const pm2 = Promise.promisifyAll(require('pm2'))
const ora = require('ora') const ora = require('ora')
const path = require('path') const path = require('path')
const ROOTPATH = process.cwd()
module.exports = { module.exports = {
/** /**
* Detect the most appropriate start mode * Detect the most appropriate start mode
@ -22,14 +24,14 @@ module.exports = {
*/ */
startInBackgroundMode: function () { startInBackgroundMode: function () {
let spinner = ora('Initializing...').start() let spinner = ora('Initializing...').start()
return fs.emptyDirAsync(path.join(__dirname, './logs')).then(() => { return fs.emptyDirAsync(path.join(ROOTPATH, './logs')).then(() => {
return pm2.connectAsync().then(() => { return pm2.connectAsync().then(() => {
return pm2.startAsync({ return pm2.startAsync({
name: 'wiki', name: 'wiki',
script: 'server.js', script: 'server',
cwd: __dirname, cwd: ROOTPATH,
output: path.join(__dirname, './logs/wiki-output.log'), output: path.join(ROOTPATH, './logs/wiki-output.log'),
error: path.join(__dirname, './logs/wiki-error.log'), error: path.join(ROOTPATH, './logs/wiki-error.log'),
minUptime: 5000, minUptime: 5000,
maxRestarts: 5 maxRestarts: 5
}).then(() => { }).then(() => {

View File

@ -3,6 +3,7 @@
const fs = require('fs') const fs = require('fs')
const yaml = require('js-yaml') const yaml = require('js-yaml')
const _ = require('lodash') const _ = require('lodash')
const path = require('path')
/** /**
* Load Application Configuration * Load Application Configuration
@ -12,9 +13,9 @@ const _ = require('lodash')
*/ */
module.exports = (confPaths) => { module.exports = (confPaths) => {
confPaths = _.defaults(confPaths, { confPaths = _.defaults(confPaths, {
config: './config.yml', config: path.join(ROOTPATH, 'config.yml'),
data: './app/data.yml', data: path.join(SERVERPATH, 'app/data.yml'),
dataRegex: '../app/regex.js' dataRegex: path.join(SERVERPATH, 'app/regex.js')
}) })
let appconfig = {} let appconfig = {}

View File

@ -23,7 +23,7 @@ module.exports = {
let self = this let self = this
global.Mongoose = modb global.Mongoose = modb
let dbModelsPath = path.resolve(ROOTPATH, 'models') let dbModelsPath = path.join(SERVERPATH, 'models')
modb.Promise = require('bluebird') modb.Promise = require('bluebird')

View File

@ -249,15 +249,16 @@ module.exports = {
* *
* @param {String} entryPath The entry path * @param {String} entryPath The entry path
* @param {String} contents The markdown-formatted contents * @param {String} contents The markdown-formatted contents
* @param {Object} author The author user object
* @return {Promise<Boolean>} True on success, false on failure * @return {Promise<Boolean>} True on success, false on failure
*/ */
update (entryPath, contents) { update (entryPath, contents, author) {
let self = this let self = this
let fpath = self.getFullPath(entryPath) let fpath = self.getFullPath(entryPath)
return fs.statAsync(fpath).then((st) => { return fs.statAsync(fpath).then((st) => {
if (st.isFile()) { if (st.isFile()) {
return self.makePersistent(entryPath, contents).then(() => { return self.makePersistent(entryPath, contents, author).then(() => {
return self.updateCache(entryPath).then(entry => { return self.updateCache(entryPath).then(entry => {
return search.add(entry) return search.add(entry)
}) })
@ -353,14 +354,15 @@ module.exports = {
* *
* @param {String} entryPath The entry path * @param {String} entryPath The entry path
* @param {String} contents The markdown-formatted contents * @param {String} contents The markdown-formatted contents
* @param {Object} author The author user object
* @return {Promise<Boolean>} True on success, false on failure * @return {Promise<Boolean>} True on success, false on failure
*/ */
create (entryPath, contents) { create (entryPath, contents, author) {
let self = this let self = this
return self.exists(entryPath).then((docExists) => { return self.exists(entryPath).then((docExists) => {
if (!docExists) { if (!docExists) {
return self.makePersistent(entryPath, contents).then(() => { return self.makePersistent(entryPath, contents, author).then(() => {
return self.updateCache(entryPath).then(entry => { return self.updateCache(entryPath).then(entry => {
return search.add(entry) return search.add(entry)
}) })
@ -379,14 +381,15 @@ module.exports = {
* *
* @param {String} entryPath The entry path * @param {String} entryPath The entry path
* @param {String} contents The markdown-formatted contents * @param {String} contents The markdown-formatted contents
* @param {Object} author The author user object
* @return {Promise<Boolean>} True on success, false on failure * @return {Promise<Boolean>} True on success, false on failure
*/ */
makePersistent (entryPath, contents) { makePersistent (entryPath, contents, author) {
let self = this let self = this
let fpath = self.getFullPath(entryPath) let fpath = self.getFullPath(entryPath)
return fs.outputFileAsync(fpath, contents).then(() => { return fs.outputFileAsync(fpath, contents).then(() => {
return git.commitDocument(entryPath) return git.commitDocument(entryPath, author)
}) })
}, },
@ -395,9 +398,10 @@ module.exports = {
* *
* @param {String} entryPath The current entry path * @param {String} entryPath The current entry path
* @param {String} newEntryPath The new entry path * @param {String} newEntryPath The new entry path
* @param {Object} author The author user object
* @return {Promise} Promise of the operation * @return {Promise} Promise of the operation
*/ */
move (entryPath, newEntryPath) { move (entryPath, newEntryPath, author) {
let self = this let self = this
if (_.isEmpty(entryPath) || entryPath === 'home') { if (_.isEmpty(entryPath) || entryPath === 'home') {
@ -405,7 +409,7 @@ module.exports = {
} }
return git.moveDocument(entryPath, newEntryPath).then(() => { return git.moveDocument(entryPath, newEntryPath).then(() => {
return git.commitDocument(newEntryPath).then(() => { return git.commitDocument(newEntryPath, author).then(() => {
// Delete old cache version // Delete old cache version
let oldEntryCachePath = self.getCachePath(entryPath) let oldEntryCachePath = self.getCachePath(entryPath)

View File

@ -195,7 +195,7 @@ module.exports = {
* @param {String} entryPath The entry path * @param {String} entryPath The entry path
* @return {Promise} Resolve on commit success * @return {Promise} Resolve on commit success
*/ */
commitDocument (entryPath) { commitDocument (entryPath, author) {
let self = this let self = this
let gitFilePath = entryPath + '.md' let gitFilePath = entryPath + '.md'
let commitMsg = '' let commitMsg = ''
@ -207,7 +207,7 @@ module.exports = {
commitMsg = (isTracked) ? 'Updated ' + gitFilePath : 'Added ' + gitFilePath commitMsg = (isTracked) ? 'Updated ' + gitFilePath : 'Added ' + gitFilePath
return self._git.add(gitFilePath) return self._git.add(gitFilePath)
}).then(() => { }).then(() => {
return self._git.commit(commitMsg).catch((err) => { return self._git.exec('commit', ['-m', commitMsg, '--author="' + author.name + ' <' + author.email + '>"']).catch((err) => {
if (_.includes(err.stdout, 'nothing to commit')) { return true } if (_.includes(err.stdout, 'nothing to commit')) { return true }
}) })
}) })

View File

@ -51,6 +51,10 @@ module.exports = {
add (content) { add (content) {
let self = this let self = this
if (!content.isEntry) {
return Promise.resolve(true)
}
return self._isReady.then(() => { return self._isReady.then(() => {
return self.delete(content._id).then(() => { return self.delete(content._id).then(() => {
return self._si.concurrentAddAsync({ return self._si.concurrentAddAsync({

View File

@ -71,7 +71,7 @@ describe('Code Linting', () => {
const lint = new PugLint() const lint = new PugLint()
const pugConfig = fs.readJsonSync('.pug-lintrc.json') const pugConfig = fs.readJsonSync('.pug-lintrc.json')
lint.configure(pugConfig) lint.configure(pugConfig)
let report = lint.checkPath('./views') let report = lint.checkPath('./server/views')
expect(report).toPugLint() expect(report).toPugLint()
}) })
}) })

View File

@ -7,7 +7,7 @@
// Licensed under AGPLv3 // Licensed under AGPLv3
// =========================================== // ===========================================
const init = require('./init') const init = require('./server/init')
require('yargs') // eslint-disable-line no-unused-expressions require('yargs') // eslint-disable-line no-unused-expressions
.usage('Usage: node $0 <cmd> [args]') .usage('Usage: node $0 <cmd> [args]')

7368
yarn.lock Normal file

File diff suppressed because it is too large Load Diff