Add pod list endpoint with pagination, sort...
[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 { 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 // Initialize database and models
44 import { database as db } from './server/initializers/database'
45 db.init(false).then(() => onDatabaseInitDone())
46
47 // ----------- PeerTube modules -----------
48 import { migrate, installApplication } from './server/initializers'
49 import { JobScheduler, activateSchedulers, VideosPreviewCache } from './server/lib'
50 import { apiRouter, clientsRouter, staticRouter, servicesRouter } from './server/controllers'
51
52 // ----------- Command line -----------
53
54 // ----------- App -----------
55
56 // Enable CORS for develop
57 if (isTestInstance()) {
58   app.use((req, res, next) => {
59     // These routes have already cors
60     if (
61       req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
62       req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
63     ) {
64       return (cors({
65         origin: 'http://localhost:3000',
66         credentials: true
67       }))(req, res, next)
68     }
69
70     return next()
71   })
72 }
73
74 // For the logger
75 app.use(morgan('combined', {
76   stream: { write: logger.info }
77 }))
78 // For body requests
79 app.use(bodyParser.json({ limit: '500kb' }))
80 app.use(bodyParser.urlencoded({ extended: false }))
81
82 // ----------- Views, routes and static files -----------
83
84 // API
85 const apiRoute = '/api/' + API_VERSION
86 app.use(apiRoute, apiRouter)
87
88 // Services (oembed...)
89 app.use('/services', servicesRouter)
90
91 // Client files
92 app.use('/', clientsRouter)
93
94 // Static files
95 app.use('/', staticRouter)
96
97 // Always serve index client page (the client is a single page application, let it handle routing)
98 app.use('/*', function (req, res, next) {
99   res.sendFile(path.join(__dirname, '../client/dist/index.html'))
100 })
101
102 // ----------- Tracker -----------
103
104 const trackerServer = new TrackerServer({
105   http: false,
106   udp: false,
107   ws: false,
108   dht: false
109 })
110
111 trackerServer.on('error', function (err) {
112   logger.error(err)
113 })
114
115 trackerServer.on('warning', function (err) {
116   logger.error(err)
117 })
118
119 const server = http.createServer(app)
120 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
121 wss.on('connection', function (ws) {
122   trackerServer.onWebSocketConnection(ws)
123 })
124
125 // ----------- Errors -----------
126
127 // Catch 404 and forward to error handler
128 app.use(function (req, res, next) {
129   const err = new Error('Not Found')
130   err['status'] = 404
131   next(err)
132 })
133
134 app.use(function (err, req, res, next) {
135   logger.error(err)
136   res.sendStatus(err.status || 500)
137 })
138
139 // ----------- Run -----------
140
141 function onDatabaseInitDone () {
142   const port = CONFIG.LISTEN.PORT
143     // Run the migration scripts if needed
144   migrate()
145     .then(() => {
146       return installApplication()
147     })
148     .then(() => {
149       // ----------- Make the server listening -----------
150       server.listen(port, function () {
151         // Activate the communication with friends
152         activateSchedulers()
153
154         // Activate job scheduler
155         JobScheduler.Instance.activate()
156
157         VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
158
159         logger.info('Server listening on port %d', port)
160         logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
161       })
162     })
163 }