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