Bumped to version v0.0.9-alpha
[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 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
60
61 // ----------- Command line -----------
62
63 // ----------- App -----------
64
65 // Enable CORS for develop
66 if (isTestInstance()) {
67   app.use((req, res, next) => {
68     // These routes have already cors
69     if (
70       req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
71       req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
72     ) {
73       return (cors({
74         origin: 'http://localhost:3000',
75         credentials: true
76       }))(req, res, next)
77     }
78
79     return next()
80   })
81 }
82
83 // For the logger
84 app.use(morgan('combined', {
85   stream: { write: logger.info }
86 }))
87 // For body requests
88 app.use(bodyParser.json({
89   type: [ 'application/json', 'application/*+json' ],
90   limit: '500kb'
91 }))
92 app.use(bodyParser.urlencoded({ extended: false }))
93
94 // ----------- Tracker -----------
95
96 const trackerServer = new TrackerServer({
97   http: false,
98   udp: false,
99   ws: false,
100   dht: false
101 })
102
103 trackerServer.on('error', function (err) {
104   logger.error(err)
105 })
106
107 trackerServer.on('warning', function (err) {
108   logger.error(err)
109 })
110
111 const server = http.createServer(app)
112 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
113 wss.on('connection', function (ws) {
114   trackerServer.onWebSocketConnection(ws)
115 })
116
117 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
118 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
119 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
120
121 // ----------- Views, routes and static files -----------
122
123 // API
124 const apiRoute = '/api/' + API_VERSION
125 app.use(apiRoute, apiRouter)
126
127 // Services (oembed...)
128 app.use('/services', servicesRouter)
129
130 app.use('/', webfingerRouter)
131 app.use('/', activityPubRouter)
132
133 // Client files
134 app.use('/', clientsRouter)
135
136 // Static files
137 app.use('/', staticRouter)
138
139 // Always serve index client page (the client is a single page application, let it handle routing)
140 app.use('/*', function (req, res) {
141   if (req.accepts(ACCEPT_HEADERS) === 'html') {
142     return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
143   }
144
145   return res.status(404).end()
146 })
147
148 // ----------- Errors -----------
149
150 // Catch 404 and forward to error handler
151 app.use(function (req, res, next) {
152   const err = new Error('Not Found')
153   err['status'] = 404
154   next(err)
155 })
156
157 app.use(function (err, req, res, next) {
158   logger.error(err, err)
159   res.sendStatus(err.status || 500)
160 })
161
162 // ----------- Run -----------
163
164 function onDatabaseInitDone () {
165   const port = CONFIG.LISTEN.PORT
166
167   installApplication()
168     .then(() => {
169       // ----------- Make the server listening -----------
170       server.listen(port, () => {
171         VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
172         BadActorFollowScheduler.Instance.enable()
173
174         activitypubHttpJobScheduler.activate()
175         transcodingJobScheduler.activate()
176
177         logger.info('Server listening on port %d', port)
178         logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
179       })
180     })
181 }