1 import { isTestInstance } from './server/helpers/core-utils'
3 if (isTestInstance()) {
4 require('source-map-support').install()
7 // ----------- Node modules -----------
8 import * as bodyParser from 'body-parser'
9 import * as express from 'express'
10 // FIXME: cannot import express-validator
11 const expressValidator = require('express-validator')
12 import * as http from 'http'
13 import * as morgan from 'morgan'
14 import * as path from 'path'
15 import * as bittorrentTracker from 'bittorrent-tracker'
16 import * as cors from 'cors'
17 import { Server as WebSocketServer } from 'ws'
19 const TrackerServer = bittorrentTracker.Server
21 process.title = 'peertube'
23 // Create our main app
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
29 const missed = checkMissedConfig()
30 if (missed.length !== 0) {
31 throw new Error('Your configuration files miss keys: ' + missed)
34 import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
37 const errorMessage = checkConfig()
38 if (errorMessage !== null) {
39 throw new Error(errorMessage)
42 // ----------- Database -----------
43 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
44 import { logger } from './server/helpers/logger'
45 // Initialize database and models
46 import { database as db } from './server/initializers/database'
47 db.init(false).then(() => onDatabaseInitDone())
49 // ----------- PeerTube modules -----------
50 import { migrate, installApplication } from './server/initializers'
51 import { JobScheduler, activateSchedulers, VideosPreviewCache } from './server/lib'
52 import * as customValidators from './server/helpers/custom-validators'
53 import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
55 // ----------- Command line -----------
57 // ----------- App -----------
59 // Enable CORS for develop
60 if (isTestInstance()) {
61 app.use((req, res, next) => {
62 // These routes have already cors
64 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
65 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
68 origin: 'http://localhost:3000',
78 app.use(morgan('combined', {
79 stream: { write: logger.info }
82 app.use(bodyParser.json({ limit: '500kb' }))
83 app.use(bodyParser.urlencoded({ extended: false }))
84 // Validate some params for the API
85 app.use(expressValidator({
86 customValidators: customValidators
89 // ----------- Views, routes and static files -----------
92 const apiRoute = '/api/' + API_VERSION
93 app.use(apiRoute, apiRouter)
96 app.use('/', clientsRouter)
99 app.use('/', staticRouter)
101 // Always serve index client page (the client is a single page application, let it handle routing)
102 app.use('/*', function (req, res, next) {
103 res.sendFile(path.join(__dirname, '../client/dist/index.html'))
106 // ----------- Tracker -----------
108 const trackerServer = new TrackerServer({
115 trackerServer.on('error', function (err) {
119 trackerServer.on('warning', function (err) {
123 const server = http.createServer(app)
124 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
125 wss.on('connection', function (ws) {
126 trackerServer.onWebSocketConnection(ws)
129 // ----------- Errors -----------
131 // Catch 404 and forward to error handler
132 app.use(function (req, res, next) {
133 const err = new Error('Not Found')
138 app.use(function (err, req, res, next) {
140 res.sendStatus(err.status || 500)
143 // ----------- Run -----------
145 function onDatabaseInitDone () {
146 const port = CONFIG.LISTEN.PORT
147 // Run the migration scripts if needed
150 return installApplication()
153 // ----------- Make the server listening -----------
154 server.listen(port, function () {
155 // Activate the communication with friends
158 // Activate job scheduler
159 JobScheduler.Instance.activate()
161 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
163 logger.info('Server listening on port %d', port)
164 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)