Don't send view on private video
[oweals/peertube.git] / server.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { ScheduleVideoUpdateModel } from './server/models/video/schedule-video-update'
3
4 require('tls').DEFAULT_ECDH_CURVE = 'auto'
5
6 import { isTestInstance } from './server/helpers/core-utils'
7
8 if (isTestInstance()) {
9   require('source-map-support').install()
10 }
11
12 // ----------- Node modules -----------
13 import * as bodyParser from 'body-parser'
14 import * as express from 'express'
15 import * as http from 'http'
16 import * as morgan from 'morgan'
17 import * as bitTorrentTracker from 'bittorrent-tracker'
18 import * as cors from 'cors'
19 import { Server as WebSocketServer } from 'ws'
20
21 const TrackerServer = bitTorrentTracker.Server
22
23 process.title = 'peertube'
24
25 // Create our main app
26 const app = express()
27
28 // ----------- Core checker -----------
29 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
30
31 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
32 import { logger } from './server/helpers/logger'
33 import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
34
35 const missed = checkMissedConfig()
36 if (missed.length !== 0) {
37   logger.error('Your configuration files miss keys: ' + missed)
38   process.exit(-1)
39 }
40
41 checkFFmpeg(CONFIG)
42   .catch(err => {
43     logger.error('Error in ffmpeg check.', { err })
44     process.exit(-1)
45   })
46
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49   throw new Error(errorMessage)
50 }
51
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
54
55 // ----------- Database -----------
56
57 // Initialize database and models
58 import { initDatabaseModels } from './server/initializers/database'
59 import { migrate } from './server/initializers/migrator'
60 migrate()
61   .then(() => initDatabaseModels(false))
62   .then(() => startApplication())
63   .catch(err => {
64     logger.error('Cannot start application.', { err })
65     process.exit(-1)
66   })
67
68 // ----------- PeerTube modules -----------
69 import { installApplication } from './server/initializers'
70 import { Emailer } from './server/lib/emailer'
71 import { JobQueue } from './server/lib/job-queue'
72 import { VideosPreviewCache } from './server/lib/cache'
73 import {
74   activityPubRouter,
75   apiRouter,
76   clientsRouter,
77   feedsRouter,
78   staticRouter,
79   servicesRouter,
80   webfingerRouter
81 } from './server/controllers'
82 import { Redis } from './server/lib/redis'
83 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
84 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
85 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
86
87 // ----------- Command line -----------
88
89 // ----------- App -----------
90
91 // Enable CORS for develop
92 if (isTestInstance()) {
93   app.use((req, res, next) => {
94     // These routes have already cors
95     if (
96       req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
97       req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
98     ) {
99       return (cors({
100         origin: '*',
101         exposedHeaders: 'Retry-After',
102         credentials: true
103       }))(req, res, next)
104     }
105
106     return next()
107   })
108 }
109
110 // For the logger
111 app.use(morgan('combined', {
112   stream: { write: logger.info.bind(logger) }
113 }))
114 // For body requests
115 app.use(bodyParser.urlencoded({ extended: false }))
116 app.use(bodyParser.json({
117   type: [ 'application/json', 'application/*+json' ],
118   limit: '500kb'
119 }))
120
121 // ----------- Tracker -----------
122
123 const trackerServer = new TrackerServer({
124   http: false,
125   udp: false,
126   ws: false,
127   dht: false
128 })
129
130 trackerServer.on('error', function (err) {
131   logger.error('Error in websocket tracker.', err)
132 })
133
134 trackerServer.on('warning', function (err) {
135   logger.error('Warning in websocket tracker.', err)
136 })
137
138 const server = http.createServer(app)
139 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
140 wss.on('connection', function (ws) {
141   trackerServer.onWebSocketConnection(ws)
142 })
143
144 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
145 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
146 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
147
148 // ----------- Views, routes and static files -----------
149
150 // API
151 const apiRoute = '/api/' + API_VERSION
152 app.use(apiRoute, apiRouter)
153
154 // Services (oembed...)
155 app.use('/services', servicesRouter)
156
157 app.use('/', activityPubRouter)
158 app.use('/', feedsRouter)
159 app.use('/', webfingerRouter)
160
161 // Static files
162 app.use('/', staticRouter)
163
164 // Client files, last valid routes!
165 app.use('/', clientsRouter)
166
167 // ----------- Errors -----------
168
169 // Catch 404 and forward to error handler
170 app.use(function (req, res, next) {
171   const err = new Error('Not Found')
172   err['status'] = 404
173   next(err)
174 })
175
176 app.use(function (err, req, res, next) {
177   let error = 'Unknown error.'
178   if (err) {
179     error = err.stack || err.message || err
180   }
181
182   logger.error('Error in controller.', { error })
183   return res.status(err.status || 500).end()
184 })
185
186 // ----------- Run -----------
187
188 async function startApplication () {
189   const port = CONFIG.LISTEN.PORT
190   const hostname = CONFIG.LISTEN.HOSTNAME
191
192   await installApplication()
193
194   // Email initialization
195   Emailer.Instance.init()
196   await Emailer.Instance.checkConnectionOrDie()
197
198   await JobQueue.Instance.init()
199
200   // Caches initializations
201   VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
202
203   // Enable Schedulers
204   BadActorFollowScheduler.Instance.enable()
205   RemoveOldJobsScheduler.Instance.enable()
206   UpdateVideosScheduler.Instance.enable()
207
208   // Redis initialization
209   Redis.Instance.init()
210
211   // Make server listening
212   server.listen(port, hostname, () => {
213     logger.info('Server listening on %s:%d', hostname, port)
214     logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
215   })
216 }