You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
7.0 KiB

  1. 'use strict'
  2. // ===========================================
  3. // Wiki.js
  4. // 1.0.0
  5. // Licensed under AGPLv3
  6. // ===========================================
  7. const path = require('path')
  8. const ROOTPATH = process.cwd()
  9. const SERVERPATH = path.join(ROOTPATH, 'server')
  10. global.ROOTPATH = ROOTPATH
  11. global.SERVERPATH = SERVERPATH
  12. const IS_DEBUG = process.env.NODE_ENV === 'development'
  13. process.env.VIPS_WARNING = false
  14. // if (IS_DEBUG) {
  15. // require('@glimpse/glimpse').init()
  16. // }
  17. let appconf = require('./libs/config')()
  18. global.appconfig = appconf.config
  19. global.appdata = appconf.data
  20. // ----------------------------------------
  21. // Load Winston
  22. // ----------------------------------------
  23. global.winston = require('./libs/logger')(IS_DEBUG, 'SERVER')
  24. global.winston.info('Wiki.js is initializing...')
  25. // ----------------------------------------
  26. // Load global modules
  27. // ----------------------------------------
  28. global.lcdata = require('./libs/local').init()
  29. global.db = require('./libs/db').init()
  30. global.entries = require('./libs/entries').init()
  31. global.git = require('./libs/git').init(false)
  32. global.lang = require('i18next')
  33. global.mark = require('./libs/markdown')
  34. global.search = require('./libs/search').init()
  35. global.upl = require('./libs/uploads').init()
  36. // ----------------------------------------
  37. // Load modules
  38. // ----------------------------------------
  39. const autoload = require('auto-load')
  40. const bodyParser = require('body-parser')
  41. const compression = require('compression')
  42. const cookieParser = require('cookie-parser')
  43. const express = require('express')
  44. const favicon = require('serve-favicon')
  45. const flash = require('connect-flash')
  46. const fork = require('child_process').fork
  47. const http = require('http')
  48. const i18nBackend = require('i18next-node-fs-backend')
  49. const passport = require('passport')
  50. const passportSocketIo = require('passport.socketio')
  51. const session = require('express-session')
  52. const SessionMongoStore = require('connect-mongo')(session)
  53. const graceful = require('node-graceful')
  54. const socketio = require('socket.io')
  55. var mw = autoload(path.join(SERVERPATH, '/middlewares'))
  56. var ctrl = autoload(path.join(SERVERPATH, '/controllers'))
  57. // ----------------------------------------
  58. // Define Express App
  59. // ----------------------------------------
  60. const app = express()
  61. global.app = app
  62. app.use(compression())
  63. // ----------------------------------------
  64. // Security
  65. // ----------------------------------------
  66. app.use(mw.security)
  67. // ----------------------------------------
  68. // Public Assets
  69. // ----------------------------------------
  70. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')))
  71. app.use(express.static(path.join(ROOTPATH, 'assets'), {
  72. index: false,
  73. maxAge: '7d'
  74. }))
  75. // ----------------------------------------
  76. // Passport Authentication
  77. // ----------------------------------------
  78. require('./libs/auth')(passport)
  79. global.rights = require('./libs/rights')
  80. global.rights.init()
  81. let sessionStore = new SessionMongoStore({
  82. mongooseConnection: global.db.connection,
  83. touchAfter: 15
  84. })
  85. app.use(cookieParser())
  86. app.use(session({
  87. name: 'wikijs.sid',
  88. store: sessionStore,
  89. secret: appconfig.sessionSecret,
  90. resave: false,
  91. saveUninitialized: false
  92. }))
  93. app.use(flash())
  94. app.use(passport.initialize())
  95. app.use(passport.session())
  96. // ----------------------------------------
  97. // SEO
  98. // ----------------------------------------
  99. app.use(mw.seo)
  100. // ----------------------------------------
  101. // Localization Engine
  102. // ----------------------------------------
  103. global.lang
  104. .use(i18nBackend)
  105. .init({
  106. load: 'languageOnly',
  107. ns: ['common', 'admin', 'auth', 'errors', 'git'],
  108. defaultNS: 'common',
  109. saveMissing: false,
  110. preload: [appconfig.lang],
  111. lng: appconfig.lang,
  112. fallbackLng: 'en',
  113. backend: {
  114. loadPath: path.join(SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
  115. }
  116. })
  117. // ----------------------------------------
  118. // View Engine Setup
  119. // ----------------------------------------
  120. app.set('views', path.join(SERVERPATH, 'views'))
  121. app.set('view engine', 'pug')
  122. app.use(bodyParser.json({ limit: '1mb' }))
  123. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  124. // ----------------------------------------
  125. // View accessible data
  126. // ----------------------------------------
  127. app.locals._ = require('lodash')
  128. app.locals.t = global.lang.t.bind(global.lang)
  129. app.locals.moment = require('moment')
  130. app.locals.moment.locale(appconfig.lang)
  131. app.locals.appconfig = appconfig
  132. app.use(mw.flash)
  133. // ----------------------------------------
  134. // Controllers
  135. // ----------------------------------------
  136. app.use('/', ctrl.auth)
  137. app.use('/uploads', mw.auth, ctrl.uploads)
  138. app.use('/admin', mw.auth, ctrl.admin)
  139. app.use('/', mw.auth, ctrl.pages)
  140. // ----------------------------------------
  141. // Error handling
  142. // ----------------------------------------
  143. app.use(function (req, res, next) {
  144. var err = new Error('Not Found')
  145. err.status = 404
  146. next(err)
  147. })
  148. app.use(function (err, req, res, next) {
  149. res.status(err.status || 500)
  150. res.render('error', {
  151. message: err.message,
  152. error: IS_DEBUG ? err : {}
  153. })
  154. })
  155. // ----------------------------------------
  156. // Start HTTP server
  157. // ----------------------------------------
  158. global.winston.info('Starting HTTP/WS server on port ' + appconfig.port + '...')
  159. app.set('port', appconfig.port)
  160. var server = http.createServer(app)
  161. var io = socketio(server)
  162. server.listen(appconfig.port)
  163. server.on('error', (error) => {
  164. if (error.syscall !== 'listen') {
  165. throw error
  166. }
  167. // handle specific listen errors with friendly messages
  168. switch (error.code) {
  169. case 'EACCES':
  170. global.winston.error('Listening on port ' + appconfig.port + ' requires elevated privileges!')
  171. return process.exit(1)
  172. case 'EADDRINUSE':
  173. global.winston.error('Port ' + appconfig.port + ' is already in use!')
  174. return process.exit(1)
  175. default:
  176. throw error
  177. }
  178. })
  179. server.on('listening', () => {
  180. global.winston.info('HTTP/WS server started successfully! [RUNNING]')
  181. })
  182. // ----------------------------------------
  183. // WebSocket
  184. // ----------------------------------------
  185. io.use(passportSocketIo.authorize({
  186. key: 'wikijs.sid',
  187. store: sessionStore,
  188. secret: appconfig.sessionSecret,
  189. cookieParser,
  190. success: (data, accept) => {
  191. accept()
  192. },
  193. fail: (data, message, error, accept) => {
  194. accept()
  195. }
  196. }))
  197. io.on('connection', ctrl.ws)
  198. // ----------------------------------------
  199. // Start child processes
  200. // ----------------------------------------
  201. let bgAgent = fork(path.join(SERVERPATH, 'agent.js'))
  202. bgAgent.on('message', m => {
  203. if (!m.action) {
  204. return
  205. }
  206. switch (m.action) {
  207. case 'searchAdd':
  208. global.search.add(m.content)
  209. break
  210. }
  211. })
  212. // ----------------------------------------
  213. // Graceful shutdown
  214. // ----------------------------------------
  215. graceful.on('exit', () => {
  216. global.winston.info('- SHUTTING DOWN - Performing git sync...')
  217. return global.git.resync().then(() => {
  218. global.winston.info('- SHUTTING DOWN - Git sync successful. Now safe to exit.')
  219. process.kill(process.pid, 'SIGINT')
  220. })
  221. })