All files / lib/crowi index.ts

67.95% Statements 106/156
51.67% Branches 31/60
80% Functions 32/40
67.74% Lines 105/155

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435                                                      16x                   16x                                             17x   17x         17x   17x   17x         17x   17x   17x   17x       17x           17x                           17x     17x   17x 17x 17x 17x 17x 17x 17x 17x 17x   17x   17x 17x 17x 17x 17x 17x   17x         16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x       1x                           2x       71x       11x 11x                         1x       17x         17x           895x 241x     654x         217x 102x     115x         16x     16x           16x 16x         16x 16x           16x 16x           16x             16x 16x                     16x               16x       16x 16x 240x         17x 102x         16x       30x       18x               16x       16x   16x       16x   16x 16x                           16x         16x       16x 16x   16x 16x                         16x           16x       1x     17x                                             16x 16x   16x 16x   16x 16x   16x           16x               16x 16x                        
import Debug from 'debug'
import path, { sep } from 'path'
import mongoose from 'mongoose'
import Tokens from 'csrf'
import redis from 'redis'
import url from 'url'
import http from 'http'
import socketIO from 'socket.io'
import socketIORedis from 'socket.io-redis'
import connectRedis from 'connect-redis'
import express from 'express'
import session from 'express-session'
import errorHandler from 'errorhandler'
import morgan from 'morgan'
import dnscache from 'dnscache'
import models from 'server/models'
import events from 'server/events'
import middlewares from 'server/middlewares'
import controllers from 'server/controllers'
import routes from '../routes'
import LRU from '../service/lru'
import Config from '../service/config'
import mailer from '../util/mailer'
import slack from '../util/slack'
import expressInit from './express-init'
import Searcher from 'server/util/search'
 
const pkg = require('../../package.json')
 
type Models = { [K in keyof typeof models]: ReturnType<typeof models[K]> }
 
type Events = { [K in keyof typeof events]: InstanceType<typeof events[K]> }
 
type Middlewares = { [K in keyof ReturnType<typeof middlewares>]: ReturnType<typeof middlewares>[K] }
 
type Controllers = { [K in keyof ReturnType<typeof controllers>]: ReturnType<typeof controllers>[K] }
 
const debug = Debug('crowi:crowi')
 
class Crowi {
  version: string
 
  rootDir: string
 
  pluginDir: string
 
  publicDir: string
 
  localeDir: string
 
  resourceDir: string
 
  viewsDir: string
 
  mailDir: string
 
  tmpDir: string
 
  cacheDir: string
 
  app: any = null
 
  mongoose: any = null
 
  // FIXME after service/config typed
  config: any
 
  searcher: any = null
 
  mailer: any = {}
 
  lru: any = {}
 
  tokens: Tokens
 
  // FIXME: {} をアサインしないで済む方法を捜す
  models: Models = ({} as any) as Models
 
  events: Events = ({} as any) as Events
 
  middlewares: Middlewares = ({} as any) as Middlewares
 
  controllers: Controllers = ({} as any) as Controllers
 
  env: typeof process.env
 
  baseUrl: string | null = null
 
  node_env: string
 
  port: number
 
  redis: redis.RedisClient | null = null
 
  redisUrl: string | null
 
  redisOpts: any
 
  // TODO: @types モジュール入れたらやる
  sessionConfig: any
 
  io?: socketIO.Server
 
  // FIXME: util/slack に型付けたらやる
  slack: any
 
  initialized = false
 
  constructor(rootdir: string, env: typeof process.env) {
    this.version = pkg.version
 
    this.rootDir = rootdir
    this.pluginDir = path.join(this.rootDir, 'node_modules') + sep
    this.publicDir = path.join(this.rootDir, 'public') + sep
    this.localeDir = path.join(this.rootDir, 'locales') + sep
    this.resourceDir = path.join(this.rootDir, 'resource') + sep
    this.viewsDir = path.join(this.rootDir, 'views') + sep
    this.mailDir = path.join(this.viewsDir, 'mail') + sep
    this.tmpDir = path.join(this.rootDir, 'tmp') + sep
    this.cacheDir = path.join(this.tmpDir, 'cache')
 
    this.setupEvents()
 
    this.env = env
    this.baseUrl = this.env.BASE_URL || null
    this.node_env = this.env.NODE_ENV || 'development'
    this.port = this.env.PORT ? Number.parseInt(this.env.PORT) : 3000
    this.redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URL || null
    this.redisOpts = this.buildRedisOpts(this.redisUrl)
 
    this.tokens = new Tokens()
  }
 
  async init() {
    // setup database server and load all modesl
    await this.setupDatabase()
    await this.setupModels()
    await this.setupRedisClient()
    await this.setupSessionConfig()
    await this.setupConfig()
    await this.setupSearcher()
    await this.setupMailer()
    await this.setupSlack()
    await this.setupDNSCache()
    await this.setupLRU()
    await this.buildServer()
 
    this.initialized = true
  }
 
  isInitialized() {
    return this.initialized
  }
 
  isPageId(pageId) {
    if (!pageId) {
      return false
    }
 
    if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
      return true
    }
  }
 
  setConfig(config) {
    this.config.update(config)
  }
 
  getConfig() {
    return this.config.get()
  }
 
  getBaseUrl() {
    Eif (this.baseUrl) {
      return this.baseUrl
    }
    const config = this.getConfig()
    if (config && config.crowi && config.crowi['app:url']) {
      return config.crowi['app:url']
    }
 
    // This might be happend when env BASE_URL is not set and this is not an express request.
    // While initialize express, config.crowi['app:url'] could be set be detecting accessing URL.
    return null
  }
 
  getEnv() {
    return this.env
  }
 
  buildRedisOpts(redisUrl: string | null) {
    Iif (redisUrl) {
      const { hostname: host, port, auth } = url.parse(redisUrl)
      const password = auth ? { password: auth.split(':')[1] } : {}
      return { host, port, ...password }
    }
    return null
  }
 
  // getter/setter of model instance
  //
  model<T extends keyof Models>(name: T, model?: Models[T]): Models[T] {
    if (model) {
      return (this.models[name] = model)
    }
 
    return this.models[name]
  }
 
  // getter/setter of event instance
  event<T extends keyof Events>(name: T, event?: Events[T]): Events[T] {
    if (event) {
      return (this.events[name] = event)
    }
 
    return this.events[name]
  }
 
  setupDatabase() {
    // mongoUri = mongodb://user:password@host/dbname
    mongoose.Promise = global.Promise
 
    var mongoUri =
      this.env.MONGOLAB_URI || // for B.C.
      this.env.MONGODB_URI || // MONGOLAB changes their env name
      this.env.MONGOHQ_URL ||
      this.env.MONGO_URI ||
      'mongodb://localhost/crowi'
 
    return new Promise((resolve, reject) => {
      const mongooseOptions = {
        useNewUrlParser: true,
        useFindAndModify: false,
        useCreateIndex: true,
      }
      mongoose.connect(mongoUri, mongooseOptions, e => {
        Iif (e) {
          debug('DB Connect Error: ', e)
          debug('DB Connect Error: ', mongoUri)
          return reject(new Error("Cann't connect to Database Server."))
        }
 
        this.mongoose = mongoose
        return resolve(mongoose)
      })
    })
  }
 
  async setupRedisClient() {
    Iif (this.redisOpts) {
      const redisClient = redis.createClient(this.redisOpts)
      this.redis = redisClient
    }
  }
 
  setupSessionConfig() {
    const sessionAge = 1000 * 3600 * 24 * 30
    const sessionConfig = {
      rolling: true,
      secret: this.env.SECRET_TOKEN || 'this is default session secret',
      resave: false,
      saveUninitialized: true,
      cookie: {
        maxAge: sessionAge,
      },
      store: undefined,
    }
 
    Iif (this.redis) {
      const RedisStore = connectRedis(session)
      sessionConfig.store = new RedisStore({
        prefix: 'crowi:sess:',
        client: this.redis,
      })
    }
 
    this.sessionConfig = sessionConfig
  }
 
  async setupModels() {
    const keys = Object.keys(models) as (keyof typeof models)[]
    keys.forEach(key => {
      this.model(key, models[key](this))
    })
  }
 
  setupEvents() {
    return Object.entries(events).forEach(([key, Event]: any[]) => {
      this.event(key, new Event(this))
    })
  }
 
  getApp() {
    return this.app
  }
 
  getMongo() {
    return this.mongoose
  }
 
  getIo(): any {
    return this.io
  }
 
  getSearcher() {
    return this.searcher
  }
 
  getMailer() {
    return this.mailer
  }
 
  async setupConfig() {
    this.config = new Config(this)
 
    return this.config.load()
  }
 
  setupSearcher() {
    const searcherUri = this.env.ELASTICSEARCH_URI || this.env.BONSAI_URL || null
 
    return new Promise((resolve, reject) => {
      Iif (searcherUri) {
        try {
          this.searcher = new Searcher(this, searcherUri)
 
          // workaround
          setTimeout(() => {
            this.searcher.checkESVersion()
            this.searcher.ensureAlias()
          }, 5000)
        } catch (e) {
          debug('Error on setup searcher', e)
          this.searcher = null
        }
      }
      resolve()
    })
  }
 
  setupMailer() {
    this.mailer = mailer(this)
  }
 
  setupSlack() {
    const config = this.getConfig()
    const Config = this.model('Config')
 
    Eif (!Config.hasSlackConfig(config)) {
      this.slack = {}
    } else {
      this.slack = slack(this)
    }
  }
 
  async setupDNSCache() {
    /**
     * Enable dnscache
     * To prevent slow dns resolution in vm on linux.
     * In December 2018, linux kernel may have race in conntrack.
     * See: https://www.weave.works/blog/racy-conntrack-and-dns-lookup-timeouts
     */
    Eif (this.env.ENABLE_DNSCACHE !== 'true') return
 
    dnscache({ enable: true })
  }
 
  setupLRU() {
    this.lru = new LRU(this)
  }
 
  getTokens() {
    return this.tokens
  }
 
  start = () => {
    if (this.app === null) {
      throw new Error('Must call init() before start().')
    }
 
    const server = http.createServer(this.app).listen(this.port, () => {
      console.log('[' + this.node_env + '] Express server listening on port ' + this.port)
    })
    const io = socketIO(server, { transports: ['websocket'] })
    if (this.redisOpts) {
      io.adapter(socketIORedis(this.redisOpts))
      debug('Using socket.io-redis')
    }
    io.sockets.on('connection', socket => {
      debug('Websocket CONNECTED, socket.id:', socket.id)
    })
 
    this.io = io
 
    return this.app
  }
 
  buildServer() {
    const app = express()
    const env = this.node_env
 
    this.middlewares = middlewares(this, app)
    this.controllers = controllers(this, app)
 
    expressInit(this, app)
    routes(this, app)
 
    Iif (env == 'development') {
      // swig.setDefaults({ cache: false });
      app.use(errorHandler({ dumpExceptions: true, showStack: true }))
      app.use(morgan('dev'))
    }
 
    Iif (env == 'production') {
      app.use(morgan('combined'))
      app.use(function(err, req, res, next) {
        res.status(500)
        res.render('500', { error: err })
      })
    }
 
    this.app = app
    return app
  }
 
  exitOnError(err) {
    debug('Critical error occured.')
    console.error(err)
    console.error(err.stack)
    process.exit(1)
  }
}
 
export default Crowi