a89cdd69aad1621bfff5fe36096df567bb2f52c9
[oweals/peertube.git] / server.ts
1 import { isTestInstance } from './server/helpers/core-utils'
2
3 if (isTestInstance()) {
4   require('source-map-support').install()
5 }
6
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'
16
17 const TrackerServer = bitTorrentTracker.Server
18
19 process.title = 'peertube'
20
21 // Create our main app
22 const app = express()
23
24 // ----------- Core checker -----------
25 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
26
27 const missed = checkMissedConfig()
28 if (missed.length !== 0) {
29   throw new Error('Your configuration files miss keys: ' + missed)
30 }
31
32 import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
33 checkFFmpeg(CONFIG)
34
35 const errorMessage = checkConfig()
36 if (errorMessage !== null) {
37   throw new Error(errorMessage)
38 }
39
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'
43
44 // Initialize database and models
45 import { initDatabaseModels } from './server/initializers/database'
46 import { migrate } from './server/initializers/migrator'
47 migrate()
48   .then(() => initDatabaseModels(false))
49   .then(() => onDatabaseInitDone())
50
51 // ----------- PeerTube modules -----------
52 import { installApplication } from './server/initializers'
53 import { activitypubHttpJobScheduler, transcodingJobScheduler, VideosPreviewCache } from './server/lib'
54 import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
55
56 // ----------- Command line -----------
57
58 // ----------- App -----------
59
60 // Enable CORS for develop
61 if (isTestInstance()) {
62   app.use((req, res, next) => {
63     // These routes have already cors
64     if (
65       req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
66       req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
67     ) {
68       return (cors({
69         origin: 'http://localhost:3000',
70         credentials: true
71       }))(req, res, next)
72     }
73
74     return next()
75   })
76 }
77
78 // For the logger
79 app.use(morgan('combined', {
80   stream: { write: logger.info }
81 }))
82 // For body requests
83 app.use(bodyParser.json({
84   type: [ 'application/json', 'application/*+json' ],
85   limit: '500kb'
86 }))
87 app.use(bodyParser.urlencoded({ extended: false }))
88
89 // ----------- Tracker -----------
90
91 const trackerServer = new TrackerServer({
92   http: false,
93   udp: false,
94   ws: false,
95   dht: false
96 })
97
98 trackerServer.on('error', function (err) {
99   logger.error(err)
100 })
101
102 trackerServer.on('warning', function (err) {
103   logger.error(err)
104 })
105
106 const server = http.createServer(app)
107 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
108 wss.on('connection', function (ws) {
109   trackerServer.onWebSocketConnection(ws)
110 })
111
112 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
113 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
114 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
115
116 // ----------- Views, routes and static files -----------
117
118 // API
119 const apiRoute = '/api/' + API_VERSION
120 app.use(apiRoute, apiRouter)
121
122 // Services (oembed...)
123 app.use('/services', servicesRouter)
124
125 app.use('/', webfingerRouter)
126 app.use('/', activityPubRouter)
127
128 // Client files
129 app.use('/', clientsRouter)
130
131 // Static files
132 app.use('/', staticRouter)
133
134 // Always serve index client page (the client is a single page application, let it handle routing)
135 app.use('/*', function (req, res) {
136   if (req.accepts(ACCEPT_HEADERS) === 'html') {
137     return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
138   }
139
140   return res.status(404).end()
141 })
142
143 // ----------- Errors -----------
144
145 // Catch 404 and forward to error handler
146 app.use(function (req, res, next) {
147   const err = new Error('Not Found')
148   err['status'] = 404
149   next(err)
150 })
151
152 app.use(function (err, req, res, next) {
153   logger.error(err)
154   res.sendStatus(err.status || 500)
155 })
156
157 // ----------- Run -----------
158
159 function onDatabaseInitDone () {
160   const port = CONFIG.LISTEN.PORT
161
162   installApplication()
163     .then(() => {
164       // ----------- Make the server listening -----------
165       server.listen(port, () => {
166         VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
167         activitypubHttpJobScheduler.activate()
168         transcodingJobScheduler.activate()
169
170         logger.info('Server listening on port %d', port)
171         logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
172       })
173     })
174 }