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