Add ability to configure log level
[oweals/peertube.git] / server / initializers / constants.ts
1 import { IConfig } from 'config'
2 import { dirname, join } from 'path'
3 import { JobCategory, JobState, VideoRateType } from '../../shared/models'
4 import { ActivityPubActorType } from '../../shared/models/activitypub'
5 import { FollowState } from '../../shared/models/actors'
6 import { VideoPrivacy } from '../../shared/models/videos'
7 // Do not use barrels, remain constants as independent as possible
8 import { buildPath, isTestInstance, root, sanitizeHost, sanitizeUrl } from '../helpers/core-utils'
9
10 // Use a variable to reload the configuration if we need
11 let config: IConfig = require('config')
12
13 // ---------------------------------------------------------------------------
14
15 const LAST_MIGRATION_VERSION = 175
16
17 // ---------------------------------------------------------------------------
18
19 // API version
20 const API_VERSION = 'v1'
21
22 // Number of results by default for the pagination
23 const PAGINATION_COUNT_DEFAULT = 15
24
25 // Sortable columns per schema
26 const SORTABLE_COLUMNS = {
27   USERS: [ 'id', 'username', 'createdAt' ],
28   ACCOUNTS: [ 'createdAt' ],
29   JOBS: [ 'id', 'createdAt' ],
30   VIDEO_ABUSES: [ 'id', 'createdAt' ],
31   VIDEO_CHANNELS: [ 'id', 'name', 'updatedAt', 'createdAt' ],
32   VIDEOS: [ 'name', 'duration', 'createdAt', 'views', 'likes' ],
33   VIDEO_COMMENT_THREADS: [ 'createdAt' ],
34   BLACKLISTS: [ 'id', 'name', 'duration', 'views', 'likes', 'dislikes', 'uuid', 'createdAt' ],
35   FOLLOWERS: [ 'createdAt' ],
36   FOLLOWING: [ 'createdAt' ]
37 }
38
39 const OAUTH_LIFETIME = {
40   ACCESS_TOKEN: 3600 * 4, // 4 hours
41   REFRESH_TOKEN: 1209600 // 2 weeks
42 }
43
44 // ---------------------------------------------------------------------------
45
46 // Number of points we add/remove after a successful/bad request
47 const ACTOR_FOLLOW_SCORE = {
48   PENALTY: -10,
49   BONUS: 10,
50   BASE: 1000,
51   MAX: 10000
52 }
53
54 const FOLLOW_STATES: { [ id: string ]: FollowState } = {
55   PENDING: 'pending',
56   ACCEPTED: 'accepted'
57 }
58
59 const REMOTE_SCHEME = {
60   HTTP: 'https',
61   WS: 'wss'
62 }
63
64 const JOB_STATES: { [ id: string ]: JobState } = {
65   PENDING: 'pending',
66   PROCESSING: 'processing',
67   ERROR: 'error',
68   SUCCESS: 'success'
69 }
70 const JOB_CATEGORIES: { [ id: string ]: JobCategory } = {
71   TRANSCODING: 'transcoding',
72   ACTIVITYPUB_HTTP: 'activitypub-http'
73 }
74 // How many maximum jobs we fetch from the database per cycle
75 const JOBS_FETCH_LIMIT_PER_CYCLE = {
76   transcoding: 10,
77   httpRequest: 20
78 }
79 // 1 minutes
80 let JOBS_FETCHING_INTERVAL = 60000
81
82 // 1 hour
83 let SCHEDULER_INTERVAL = 60000 * 60
84
85 // ---------------------------------------------------------------------------
86
87 const CONFIG = {
88   CUSTOM_FILE: getLocalConfigFilePath(),
89   LISTEN: {
90     PORT: config.get<number>('listen.port')
91   },
92   DATABASE: {
93     DBNAME: 'peertube' + config.get<string>('database.suffix'),
94     HOSTNAME: config.get<string>('database.hostname'),
95     PORT: config.get<number>('database.port'),
96     USERNAME: config.get<string>('database.username'),
97     PASSWORD: config.get<string>('database.password')
98   },
99   STORAGE: {
100     AVATARS_DIR: buildPath(config.get<string>('storage.avatars')),
101     LOG_DIR: buildPath(config.get<string>('storage.logs')),
102     VIDEOS_DIR: buildPath(config.get<string>('storage.videos')),
103     THUMBNAILS_DIR: buildPath(config.get<string>('storage.thumbnails')),
104     PREVIEWS_DIR: buildPath(config.get<string>('storage.previews')),
105     TORRENTS_DIR: buildPath(config.get<string>('storage.torrents')),
106     CACHE_DIR: buildPath(config.get<string>('storage.cache'))
107   },
108   WEBSERVER: {
109     SCHEME: config.get<boolean>('webserver.https') === true ? 'https' : 'http',
110     WS: config.get<boolean>('webserver.https') === true ? 'wss' : 'ws',
111     HOSTNAME: config.get<string>('webserver.hostname'),
112     PORT: config.get<number>('webserver.port'),
113     URL: '',
114     HOST: ''
115   },
116   LOG: {
117     LEVEL: config.get<string>('log.level')
118   },
119   ADMIN: {
120     get EMAIL () { return config.get<string>('admin.email') }
121   },
122   SIGNUP: {
123     get ENABLED () { return config.get<boolean>('signup.enabled') },
124     get LIMIT () { return config.get<number>('signup.limit') }
125   },
126   USER: {
127     get VIDEO_QUOTA () { return config.get<number>('user.video_quota') }
128   },
129   TRANSCODING: {
130     get ENABLED () { return config.get<boolean>('transcoding.enabled') },
131     get THREADS () { return config.get<number>('transcoding.threads') },
132     RESOLUTIONS: {
133       get '240p' () { return config.get<boolean>('transcoding.resolutions.240p') },
134       get '360p' () { return config.get<boolean>('transcoding.resolutions.360p') },
135       get '480p' () { return config.get<boolean>('transcoding.resolutions.480p') },
136       get '720p' () { return config.get<boolean>('transcoding.resolutions.720p') },
137       get '1080p' () { return config.get<boolean>('transcoding.resolutions.1080p') }
138     }
139   },
140   CACHE: {
141     PREVIEWS: {
142       get SIZE () { return config.get<number>('cache.previews.size') }
143     }
144   }
145 }
146
147 // ---------------------------------------------------------------------------
148
149 const CONSTRAINTS_FIELDS = {
150   USERS: {
151     USERNAME: { min: 3, max: 20 }, // Length
152     PASSWORD: { min: 6, max: 255 }, // Length
153     VIDEO_QUOTA: { min: -1 }
154   },
155   VIDEO_ABUSES: {
156     REASON: { min: 2, max: 300 } // Length
157   },
158   VIDEO_CHANNELS: {
159     NAME: { min: 3, max: 120 }, // Length
160     DESCRIPTION: { min: 3, max: 250 }, // Length
161     URL: { min: 3, max: 2000 } // Length
162   },
163   VIDEOS: {
164     NAME: { min: 3, max: 120 }, // Length
165     TRUNCATED_DESCRIPTION: { min: 3, max: 250 }, // Length
166     DESCRIPTION: { min: 3, max: 3000 }, // Length
167     EXTNAME: [ '.mp4', '.ogv', '.webm' ],
168     INFO_HASH: { min: 40, max: 40 }, // Length, info hash is 20 bytes length but we represent it in hexadecimal so 20 * 2
169     DURATION: { min: 1 }, // Number
170     TAGS: { min: 0, max: 5 }, // Number of total tags
171     TAG: { min: 2, max: 30 }, // Length
172     THUMBNAIL: { min: 2, max: 30 },
173     THUMBNAIL_DATA: { min: 0, max: 20000 }, // Bytes
174     VIEWS: { min: 0 },
175     LIKES: { min: 0 },
176     DISLIKES: { min: 0 },
177     FILE_SIZE: { min: 10 },
178     URL: { min: 3, max: 2000 } // Length
179   },
180   ACTORS: {
181     PUBLIC_KEY: { min: 10, max: 5000 }, // Length
182     PRIVATE_KEY: { min: 10, max: 5000 }, // Length
183     URL: { min: 3, max: 2000 }, // Length
184     AVATAR: {
185       EXTNAME: [ '.png', '.jpeg', '.jpg' ],
186       FILE_SIZE: {
187         max: 2 * 1024 * 1024 // 2MB
188       }
189     }
190   },
191   VIDEO_EVENTS: {
192     COUNT: { min: 0 }
193   },
194   VIDEO_COMMENTS: {
195     TEXT: { min: 2, max: 3000 }, // Length
196     URL: { min: 3, max: 2000 } // Length
197   }
198 }
199
200 const VIDEO_RATE_TYPES: { [ id: string ]: VideoRateType } = {
201   LIKE: 'like',
202   DISLIKE: 'dislike'
203 }
204
205 const VIDEO_CATEGORIES = {
206   1: 'Music',
207   2: 'Films',
208   3: 'Vehicles',
209   4: 'Art',
210   5: 'Sports',
211   6: 'Travels',
212   7: 'Gaming',
213   8: 'People',
214   9: 'Comedy',
215   10: 'Entertainment',
216   11: 'News',
217   12: 'How To',
218   13: 'Education',
219   14: 'Activism',
220   15: 'Science & Technology',
221   16: 'Animals',
222   17: 'Kids',
223   18: 'Food'
224 }
225
226 // See https://creativecommons.org/licenses/?lang=en
227 const VIDEO_LICENCES = {
228   1: 'Attribution',
229   2: 'Attribution - Share Alike',
230   3: 'Attribution - No Derivatives',
231   4: 'Attribution - Non Commercial',
232   5: 'Attribution - Non Commercial - Share Alike',
233   6: 'Attribution - Non Commercial - No Derivatives',
234   7: 'Public Domain Dedication'
235 }
236
237 // See https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers#Nationalencyklopedin
238 const VIDEO_LANGUAGES = {
239   1: 'English',
240   2: 'Spanish',
241   3: 'Mandarin',
242   4: 'Hindi',
243   5: 'Arabic',
244   6: 'Portuguese',
245   7: 'Bengali',
246   8: 'Russian',
247   9: 'Japanese',
248   10: 'Punjabi',
249   11: 'German',
250   12: 'Korean',
251   13: 'French',
252   14: 'Italian'
253 }
254
255 const VIDEO_PRIVACIES = {
256   [VideoPrivacy.PUBLIC]: 'Public',
257   [VideoPrivacy.UNLISTED]: 'Unlisted',
258   [VideoPrivacy.PRIVATE]: 'Private'
259 }
260
261 const VIDEO_MIMETYPE_EXT = {
262   'video/webm': '.webm',
263   'video/ogg': '.ogv',
264   'video/mp4': '.mp4'
265 }
266
267 const AVATAR_MIMETYPE_EXT = {
268   'image/png': '.png',
269   'image/jpg': '.jpg',
270   'image/jpeg': '.jpg'
271 }
272
273 // ---------------------------------------------------------------------------
274
275 const SERVER_ACTOR_NAME = 'peertube'
276
277 const ACTIVITY_PUB = {
278   POTENTIAL_ACCEPT_HEADERS: [
279     'application/activity+json',
280     'application/ld+json',
281     'application/ld+json; profile="https://www.w3.org/ns/activitystreams"'
282   ],
283   ACCEPT_HEADER: 'application/activity+json, application/ld+json',
284   PUBLIC: 'https://www.w3.org/ns/activitystreams#Public',
285   COLLECTION_ITEMS_PER_PAGE: 10,
286   FETCH_PAGE_LIMIT: 100,
287   MAX_HTTP_ATTEMPT: 5,
288   URL_MIME_TYPES: {
289     VIDEO: Object.keys(VIDEO_MIMETYPE_EXT),
290     TORRENT: [ 'application/x-bittorrent' ],
291     MAGNET: [ 'application/x-bittorrent;x-scheme-handler/magnet' ]
292   },
293   MAX_RECURSION_COMMENTS: 100,
294   ACTOR_REFRESH_INTERVAL: 3600 * 24 * 1000 // 1 day
295 }
296
297 const ACTIVITY_PUB_ACTOR_TYPES: { [ id: string ]: ActivityPubActorType } = {
298   GROUP: 'Group',
299   PERSON: 'Person',
300   APPLICATION: 'Application'
301 }
302
303 // ---------------------------------------------------------------------------
304
305 const PRIVATE_RSA_KEY_SIZE = 2048
306
307 // Password encryption
308 const BCRYPT_SALT_SIZE = 10
309
310 // ---------------------------------------------------------------------------
311
312 // Express static paths (router)
313 const STATIC_PATHS = {
314   PREVIEWS: '/static/previews/',
315   THUMBNAILS: '/static/thumbnails/',
316   TORRENTS: '/static/torrents/',
317   WEBSEED: '/static/webseed/',
318   AVATARS: '/static/avatars/'
319 }
320
321 // Cache control
322 let STATIC_MAX_AGE = '30d'
323
324 // Videos thumbnail size
325 const THUMBNAILS_SIZE = {
326   width: 200,
327   height: 110
328 }
329 const PREVIEWS_SIZE = {
330   width: 560,
331   height: 315
332 }
333 const AVATARS_SIZE = {
334   width: 120,
335   height: 120
336 }
337
338 const EMBED_SIZE = {
339   width: 560,
340   height: 315
341 }
342
343 // Sub folders of cache directory
344 const CACHE = {
345   DIRECTORIES: {
346     PREVIEWS: join(CONFIG.STORAGE.CACHE_DIR, 'previews')
347   }
348 }
349
350 const ACCEPT_HEADERS = [ 'html', 'application/json' ].concat(ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS)
351
352 // ---------------------------------------------------------------------------
353
354 const OPENGRAPH_AND_OEMBED_COMMENT = '<!-- open graph and oembed tags -->'
355
356 // ---------------------------------------------------------------------------
357
358 // Special constants for a test instance
359 if (isTestInstance() === true) {
360   ACTOR_FOLLOW_SCORE.BASE = 20
361   JOBS_FETCHING_INTERVAL = 1000
362   REMOTE_SCHEME.HTTP = 'http'
363   REMOTE_SCHEME.WS = 'ws'
364   STATIC_MAX_AGE = '0'
365   ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE = 2
366   ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL = 10 * 1000 // 10 seconds
367   CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max = 100 * 1024 // 100KB
368   SCHEDULER_INTERVAL = 10000
369 }
370
371 updateWebserverConfig()
372
373 // ---------------------------------------------------------------------------
374
375 export {
376   API_VERSION,
377   AVATARS_SIZE,
378   ACCEPT_HEADERS,
379   BCRYPT_SALT_SIZE,
380   CACHE,
381   CONFIG,
382   CONSTRAINTS_FIELDS,
383   EMBED_SIZE,
384   JOB_STATES,
385   JOBS_FETCH_LIMIT_PER_CYCLE,
386   JOBS_FETCHING_INTERVAL,
387   JOB_CATEGORIES,
388   LAST_MIGRATION_VERSION,
389   OAUTH_LIFETIME,
390   OPENGRAPH_AND_OEMBED_COMMENT,
391   PAGINATION_COUNT_DEFAULT,
392   ACTOR_FOLLOW_SCORE,
393   PREVIEWS_SIZE,
394   REMOTE_SCHEME,
395   FOLLOW_STATES,
396   SERVER_ACTOR_NAME,
397   PRIVATE_RSA_KEY_SIZE,
398   SORTABLE_COLUMNS,
399   STATIC_MAX_AGE,
400   STATIC_PATHS,
401   ACTIVITY_PUB,
402   ACTIVITY_PUB_ACTOR_TYPES,
403   THUMBNAILS_SIZE,
404   VIDEO_CATEGORIES,
405   VIDEO_LANGUAGES,
406   VIDEO_PRIVACIES,
407   VIDEO_LICENCES,
408   VIDEO_RATE_TYPES,
409   VIDEO_MIMETYPE_EXT,
410   AVATAR_MIMETYPE_EXT,
411   SCHEDULER_INTERVAL
412 }
413
414 // ---------------------------------------------------------------------------
415
416 function getLocalConfigFilePath () {
417   const configSources = config.util.getConfigSources()
418   if (configSources.length === 0) throw new Error('Invalid config source.')
419
420   let filename = 'local'
421   if (process.env.NODE_ENV) filename += `-${process.env.NODE_ENV}`
422   if (process.env.NODE_APP_INSTANCE) filename += `-${process.env.NODE_APP_INSTANCE}`
423
424   return join(dirname(configSources[ 0 ].name), filename + '.json')
425 }
426
427 function updateWebserverConfig () {
428   CONFIG.WEBSERVER.URL = sanitizeUrl(CONFIG.WEBSERVER.SCHEME + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT)
429   CONFIG.WEBSERVER.HOST = sanitizeHost(CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT, REMOTE_SCHEME.HTTP)
430 }
431
432 export function reloadConfig () {
433
434   function directory () {
435     if (process.env.NODE_CONFIG_DIR) {
436       return process.env.NODE_CONFIG_DIR
437     }
438
439     return join(root(), 'config')
440   }
441
442   function purge () {
443     for (const fileName in require.cache) {
444       if (-1 === fileName.indexOf(directory())) {
445         continue
446       }
447
448       delete require.cache[fileName]
449     }
450
451     delete require.cache[require.resolve('config')]
452   }
453
454   purge()
455
456   config = require('config')
457
458   updateWebserverConfig()
459 }