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 import * as http from 'http'
11 import * as morgan from 'morgan'
12 import * as path from 'path'
13 import * as bitTorrentTracker from 'bittorrent-tracker'
14 import * as cors from 'cors'
15 import { Server as WebSocketServer } from 'ws'
17 const TrackerServer = bitTorrentTracker.Server
19 process.title = 'peertube'
21 // Create our main app
24 // ----------- Core checker -----------
25 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
27 const missed = checkMissedConfig()
28 if (missed.length !== 0) {
29 throw new Error('Your configuration files miss keys: ' + missed)
32 import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
35 const errorMessage = checkConfig()
36 if (errorMessage !== null) {
37 throw new Error(errorMessage)
40 // ----------- Database -----------
41 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
42 import { logger } from './server/helpers/logger'
44 // Initialize database and models
45 import { initDatabaseModels } from './server/initializers/database'
46 import { migrate } from './server/initializers/migrator'
48 .then(() => initDatabaseModels(false))
49 .then(() => onDatabaseInitDone())
51 // ----------- PeerTube modules -----------
52 import { installApplication } from './server/initializers'
53 import { activitypubHttpJobScheduler, transcodingJobScheduler } from './server/lib/jobs'
54 import { VideosPreviewCache } from './server/lib/cache'
55 import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
57 // ----------- Command line -----------
59 // ----------- App -----------
61 // Enable CORS for develop
62 if (isTestInstance()) {
63 app.use((req, res, next) => {
64 // These routes have already cors
66 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
67 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
70 origin: 'http://localhost:3000',
80 app.use(morgan('combined', {
81 stream: { write: logger.info }
84 app.use(bodyParser.json({
85 type: [ 'application/json', 'application/*+json' ],
88 app.use(bodyParser.urlencoded({ extended: false }))
90 // ----------- Tracker -----------
92 const trackerServer = new TrackerServer({
99 trackerServer.on('error', function (err) {
103 trackerServer.on('warning', function (err) {
107 const server = http.createServer(app)
108 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
109 wss.on('connection', function (ws) {
110 trackerServer.onWebSocketConnection(ws)
113 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
114 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
115 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
117 // ----------- Views, routes and static files -----------
120 const apiRoute = '/api/' + API_VERSION
121 app.use(apiRoute, apiRouter)
123 // Services (oembed...)
124 app.use('/services', servicesRouter)
126 app.use('/', webfingerRouter)
127 app.use('/', activityPubRouter)
130 app.use('/', clientsRouter)
133 app.use('/', staticRouter)
135 // Always serve index client page (the client is a single page application, let it handle routing)
136 app.use('/*', function (req, res) {
137 if (req.accepts(ACCEPT_HEADERS) === 'html') {
138 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
141 return res.status(404).end()
144 // ----------- Errors -----------
146 // Catch 404 and forward to error handler
147 app.use(function (req, res, next) {
148 const err = new Error('Not Found')
153 app.use(function (err, req, res, next) {
155 res.sendStatus(err.status || 500)
158 // ----------- Run -----------
160 function onDatabaseInitDone () {
161 const port = CONFIG.LISTEN.PORT
165 // ----------- Make the server listening -----------
166 server.listen(port, () => {
167 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
168 activitypubHttpJobScheduler.activate()
169 transcodingJobScheduler.activate()
171 logger.info('Server listening on port %d', port)
172 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)