]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Make it compile at least
[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 { 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 { httpRequestJobScheduler, transcodingJobScheduler, VideosPreviewCache } from './server/lib'
50import { apiRouter, clientsRouter, staticRouter, servicesRouter } 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({ limit: '500kb' }))
80app.use(bodyParser.urlencoded({ extended: false }))
81
82// ----------- Tracker -----------
83
84const trackerServer = new TrackerServer({
85 http: false,
86 udp: false,
87 ws: false,
88 dht: false
89})
90
91trackerServer.on('error', function (err) {
92 logger.error(err)
93})
94
95trackerServer.on('warning', function (err) {
96 logger.error(err)
97})
98
99const server = http.createServer(app)
100const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
101wss.on('connection', function (ws) {
102 trackerServer.onWebSocketConnection(ws)
103})
104
105const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
106app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
107app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
108
109// ----------- Views, routes and static files -----------
110
111// API
112const apiRoute = '/api/' + API_VERSION
113app.use(apiRoute, apiRouter)
114
115// Services (oembed...)
116app.use('/services', servicesRouter)
117
118// Client files
119app.use('/', clientsRouter)
120
121// Static files
122app.use('/', staticRouter)
123
124// Always serve index client page (the client is a single page application, let it handle routing)
125app.use('/*', function (req, res) {
126 res.sendFile(path.join(__dirname, '../client/dist/index.html'))
127})
128
129// ----------- Errors -----------
130
131// Catch 404 and forward to error handler
132app.use(function (req, res, next) {
133 const err = new Error('Not Found')
134 err['status'] = 404
135 next(err)
136})
137
138app.use(function (err, req, res, next) {
139 logger.error(err)
140 res.sendStatus(err.status || 500)
141})
142
143// ----------- Run -----------
144
145function onDatabaseInitDone () {
146 const port = CONFIG.LISTEN.PORT
147 // Run the migration scripts if needed
148 migrate()
149 .then(() => installApplication())
150 .then(() => {
151 // ----------- Make the server listening -----------
152 server.listen(port, () => {
153 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
154 httpRequestJobScheduler.activate()
155 transcodingJobScheduler.activate()
156
157 logger.info('Server listening on port %d', port)
158 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
159 })
160 })
161}