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 // ----------- Database -----------
27 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
28 import { logger } from './server/helpers/logger'
29 import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
30 // Initialize database and models
31 import { database as db } from './server/initializers/database'
32 db.init(false).then(() => onDatabaseInitDone())
34 // ----------- Checker -----------
35 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
37 const missed = checkMissedConfig()
38 if (missed.length !== 0) {
39 throw new Error('Miss some configurations keys : ' + missed)
43 const errorMessage = checkConfig()
44 if (errorMessage !== null) {
45 throw new Error(errorMessage)
48 // ----------- PeerTube modules -----------
49 import { migrate, installApplication } from './server/initializers'
50 import { JobScheduler, activateSchedulers, VideosPreviewCache } from './server/lib'
51 import * as customValidators from './server/helpers/custom-validators'
52 import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
54 // ----------- Command line -----------
56 // ----------- App -----------
58 // Enable CORS for develop
59 if (isTestInstance()) {
60 app.use((req, res, next) => {
61 // These routes have already cors
63 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
64 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
67 origin: 'http://localhost:3000',
77 app.use(morgan('combined', {
78 stream: { write: logger.info }
81 app.use(bodyParser.json({ limit: '500kb' }))
82 app.use(bodyParser.urlencoded({ extended: false }))
83 // Validate some params for the API
84 app.use(expressValidator({
85 customValidators: customValidators
88 // ----------- Views, routes and static files -----------
91 const apiRoute = '/api/' + API_VERSION
92 app.use(apiRoute, apiRouter)
95 app.use('/', clientsRouter)
98 app.use('/', staticRouter)
100 // Always serve index client page (the client is a single page application, let it handle routing)
101 app.use('/*', function (req, res, next) {
102 res.sendFile(path.join(__dirname, '../client/dist/index.html'))
105 // ----------- Tracker -----------
107 const trackerServer = new TrackerServer({
114 trackerServer.on('error', function (err) {
118 trackerServer.on('warning', function (err) {
122 const server = http.createServer(app)
123 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
124 wss.on('connection', function (ws) {
125 trackerServer.onWebSocketConnection(ws)
128 // ----------- Errors -----------
130 // Catch 404 and forward to error handler
131 app.use(function (req, res, next) {
132 const err = new Error('Not Found')
137 app.use(function (err, req, res, next) {
139 res.sendStatus(err.status || 500)
142 // ----------- Run -----------
144 function onDatabaseInitDone () {
145 const port = CONFIG.LISTEN.PORT
146 // Run the migration scripts if needed
149 return installApplication()
152 // ----------- Make the server listening -----------
153 server.listen(port, function () {
154 // Activate the communication with friends
157 // Activate job scheduler
158 JobScheduler.Instance.activate()
160 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
162 logger.info('Server listening on port %d', port)
163 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)