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