]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/plugins/plugin-manager.ts
Logging ip requesting unknown infoHash
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
CommitLineData
345da516
C
1import { PluginModel } from '../../models/server/plugin'
2import { logger } from '../../helpers/logger'
f023a19c 3import { basename, join } from 'path'
345da516
C
4import { CONFIG } from '../../initializers/config'
5import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
d75db01f
C
6import {
7 ClientScript,
8 PluginPackageJson,
9 PluginTranslationPaths as PackagePluginTranslations
10} from '../../../shared/models/plugins/plugin-package-json.model'
345da516 11import { createReadStream, createWriteStream } from 'fs'
bc0d801b 12import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
345da516 13import { PluginType } from '../../../shared/models/plugins/plugin.type'
f023a19c 14import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
09071200 15import { outputFile, readJSON } from 'fs-extra'
5e2b2e27 16import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model'
b4055e1c 17import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
9ae88819 18import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
32fe0013 19import { PluginLibrary } from '../../typings/plugins'
a8b666e9 20import { ClientHtml } from '../client-html'
d75db01f 21import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
5e2b2e27
C
22import { RegisterHelpersStore } from './register-helpers-store'
23import { RegisterServerHookOptions } from '@shared/models/plugins/register-server-hook.model'
9107d791
C
24import { MOAuthTokenUser, MUser } from '@server/typings/models'
25import { RegisterServerAuthPassOptions, RegisterServerAuthExternalOptions } from '@shared/models/plugins/register-server-auth.model'
345da516
C
26
27export interface RegisteredPlugin {
b5f919ac 28 npmName: string
345da516
C
29 name: string
30 version: string
31 description: string
32 peertubeEngine: string
33
34 type: PluginType
35
36 path: string
37
38 staticDirs: { [name: string]: string }
2c053942 39 clientScripts: { [name: string]: ClientScript }
345da516
C
40
41 css: string[]
42
43 // Only if this is a plugin
7fed6375 44 registerHelpersStore?: RegisterHelpersStore
345da516
C
45 unregister?: Function
46}
47
48export interface HookInformationValue {
b5f919ac 49 npmName: string
345da516
C
50 pluginName: string
51 handler: Function
52 priority: number
53}
54
d75db01f 55type PluginLocalesTranslations = {
a1587156 56 [locale: string]: PluginTranslation
d75db01f
C
57}
58
b4055e1c 59export class PluginManager implements ServerHook {
345da516
C
60
61 private static instance: PluginManager
62
a1587156 63 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
7fed6375 64
a1587156 65 private hooks: { [name: string]: HookInformationValue[] } = {}
d75db01f 66 private translations: PluginLocalesTranslations = {}
345da516
C
67
68 private constructor () {
69 }
70
ad91e700 71 // ###################### Getters ######################
345da516 72
6702a1b2
C
73 isRegistered (npmName: string) {
74 return !!this.getRegisteredPluginOrTheme(npmName)
75 }
76
b5f919ac
C
77 getRegisteredPluginOrTheme (npmName: string) {
78 return this.registeredPlugins[npmName]
7cd4d2ba
C
79 }
80
e1c55031 81 getRegisteredPluginByShortName (name: string) {
b5f919ac
C
82 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
83 const registered = this.getRegisteredPluginOrTheme(npmName)
7cd4d2ba
C
84
85 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
86
87 return registered
345da516
C
88 }
89
e1c55031 90 getRegisteredThemeByShortName (name: string) {
b5f919ac
C
91 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
92 const registered = this.getRegisteredPluginOrTheme(npmName)
345da516
C
93
94 if (!registered || registered.type !== PluginType.THEME) return undefined
95
96 return registered
97 }
98
18a6f04c 99 getRegisteredPlugins () {
7cd4d2ba
C
100 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
101 }
102
103 getRegisteredThemes () {
104 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
18a6f04c
C
105 }
106
7fed6375
C
107 getIdAndPassAuths () {
108 return this.getRegisteredPlugins()
ebefc902
C
109 .map(p => ({
110 npmName: p.npmName,
111 name: p.name,
112 version: p.version,
113 idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths()
114 }))
7fed6375
C
115 .filter(v => v.idAndPassAuths.length !== 0)
116 }
117
118 getExternalAuths () {
119 return this.getRegisteredPlugins()
ebefc902
C
120 .map(p => ({
121 npmName: p.npmName,
122 name: p.name,
123 version: p.version,
124 externalAuths: p.registerHelpersStore.getExternalAuths()
125 }))
126 .filter(v => v.externalAuths.length !== 0)
7fed6375
C
127 }
128
b5f919ac 129 getRegisteredSettings (npmName: string) {
7fed6375
C
130 const result = this.getRegisteredPluginOrTheme(npmName)
131 if (!result || result.type !== PluginType.PLUGIN) return []
5e2b2e27 132
7fed6375 133 return result.registerHelpersStore.getSettings()
5e2b2e27
C
134 }
135
136 getRouter (npmName: string) {
7fed6375
C
137 const result = this.getRegisteredPluginOrTheme(npmName)
138 if (!result || result.type !== PluginType.PLUGIN) return null
5e2b2e27 139
7fed6375 140 return result.registerHelpersStore.getRouter()
ad91e700
C
141 }
142
d75db01f
C
143 getTranslations (locale: string) {
144 return this.translations[locale] || {}
145 }
146
e307e4fc
C
147 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
148 const auth = this.getAuth(token.User.pluginAuth, token.authName)
149 if (!auth) return true
150
151 if (auth.hookTokenValidity) {
152 try {
153 const { valid } = await auth.hookTokenValidity({ token, type })
154
155 if (valid === false) {
156 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
157 }
158
159 return valid
160 } catch (err) {
161 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
162 return true
163 }
164 }
165
166 return true
167 }
168
a5896799
C
169 // ###################### External events ######################
170
171 onLogout (npmName: string, authName: string, user: MUser) {
172 const auth = this.getAuth(npmName, authName)
173
174 if (auth?.onLogout) {
175 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
176
177 try {
178 auth.onLogout(user)
179 } catch (err) {
180 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
181 }
182 }
183 }
184
185 onSettingsChanged (name: string, settings: any) {
186 const registered = this.getRegisteredPluginByShortName(name)
187 if (!registered) {
188 logger.error('Cannot find plugin %s to call on settings changed.', name)
189 }
190
191 for (const cb of registered.registerHelpersStore.getOnSettingsChangedCallbacks()) {
192 try {
193 cb(settings)
194 } catch (err) {
195 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
196 }
197 }
198 }
199
ad91e700
C
200 // ###################### Hooks ######################
201
a1587156 202 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
89cd1275 203 if (!this.hooks[hookName]) return Promise.resolve(result)
dba85a1e 204
b4055e1c 205 const hookType = getHookType(hookName)
18a6f04c
C
206
207 for (const hook of this.hooks[hookName]) {
89cd1275
C
208 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
209
210 result = await internalRunHook(hook.handler, hookType, result, params, err => {
18a6f04c 211 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
b4055e1c 212 })
18a6f04c
C
213 }
214
215 return result
216 }
217
ad91e700
C
218 // ###################### Registration ######################
219
220 async registerPluginsAndThemes () {
221 await this.resetCSSGlobalFile()
222
223 const plugins = await PluginModel.listEnabledPluginsAndThemes()
224
225 for (const plugin of plugins) {
226 try {
227 await this.registerPluginOrTheme(plugin)
228 } catch (err) {
587568e1
C
229 // Try to unregister the plugin
230 try {
231 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
232 } catch {
233 // we don't care if we cannot unregister it
234 }
235
ad91e700
C
236 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
237 }
238 }
239
240 this.sortHooksByPriority()
241 }
242
b5f919ac
C
243 // Don't need the plugin type since themes cannot register server code
244 async unregister (npmName: string) {
245 logger.info('Unregister plugin %s.', npmName)
246
247 const plugin = this.getRegisteredPluginOrTheme(npmName)
345da516
C
248
249 if (!plugin) {
b5f919ac 250 throw new Error(`Unknown plugin ${npmName} to unregister`)
345da516
C
251 }
252
60cfd4cb
C
253 delete this.registeredPlugins[plugin.npmName]
254
d75db01f
C
255 this.deleteTranslations(plugin.npmName)
256
b5f919ac
C
257 if (plugin.type === PluginType.PLUGIN) {
258 await plugin.unregister()
345da516 259
b5f919ac
C
260 // Remove hooks of this plugin
261 for (const key of Object.keys(this.hooks)) {
98da1a7b 262 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
b5f919ac 263 }
2c053942 264
7fed6375 265 const store = plugin.registerHelpersStore
5e2b2e27
C
266 store.reinitVideoConstants(plugin.npmName)
267
b5f919ac
C
268 logger.info('Regenerating registered plugin CSS to global file.')
269 await this.regeneratePluginGlobalCSS()
2c053942 270 }
345da516
C
271 }
272
ad91e700
C
273 // ###################### Installation ######################
274
275 async install (toInstall: string, version?: string, fromDisk = false) {
f023a19c 276 let plugin: PluginModel
b5f919ac 277 let npmName: string
f023a19c
C
278
279 logger.info('Installing plugin %s.', toInstall)
280
281 try {
282 fromDisk
283 ? await installNpmPluginFromDisk(toInstall)
284 : await installNpmPlugin(toInstall, version)
285
b5f919ac
C
286 npmName = fromDisk ? basename(toInstall) : toInstall
287 const pluginType = PluginModel.getTypeFromNpmName(npmName)
288 const pluginName = PluginModel.normalizePluginName(npmName)
f023a19c 289
09071200 290 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
9157d598
C
291
292 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
f023a19c
C
293
294 [ plugin ] = await PluginModel.upsert({
295 name: pluginName,
296 description: packageJSON.description,
dba85a1e 297 homepage: packageJSON.homepage,
f023a19c
C
298 type: pluginType,
299 version: packageJSON.version,
300 enabled: true,
301 uninstalled: false,
302 peertubeEngine: packageJSON.engine.peertube
303 }, { returning: true })
304 } catch (err) {
305 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
306
307 try {
b5f919ac 308 await removeNpmPlugin(npmName)
f023a19c
C
309 } catch (err) {
310 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
311 }
312
313 throw err
314 }
315
316 logger.info('Successful installation of plugin %s.', toInstall)
317
318 await this.registerPluginOrTheme(plugin)
b5f919ac
C
319
320 return plugin
321 }
322
323 async update (toUpdate: string, version?: string, fromDisk = false) {
324 const npmName = fromDisk ? basename(toUpdate) : toUpdate
325
326 logger.info('Updating plugin %s.', npmName)
327
328 // Unregister old hooks
329 await this.unregister(npmName)
330
331 return this.install(toUpdate, version, fromDisk)
f023a19c
C
332 }
333
dba85a1e
C
334 async uninstall (npmName: string) {
335 logger.info('Uninstalling plugin %s.', npmName)
2c053942 336
2c053942 337 try {
b5f919ac 338 await this.unregister(npmName)
2c053942 339 } catch (err) {
b5f919ac 340 logger.warn('Cannot unregister plugin %s.', npmName, { err })
2c053942
C
341 }
342
dba85a1e 343 const plugin = await PluginModel.loadByNpmName(npmName)
2c053942 344 if (!plugin || plugin.uninstalled === true) {
dba85a1e 345 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
2c053942
C
346 return
347 }
348
349 plugin.enabled = false
350 plugin.uninstalled = true
351
352 await plugin.save()
f023a19c 353
dba85a1e 354 await removeNpmPlugin(npmName)
2c053942 355
dba85a1e 356 logger.info('Plugin %s uninstalled.', npmName)
f023a19c
C
357 }
358
ad91e700
C
359 // ###################### Private register ######################
360
345da516 361 private async registerPluginOrTheme (plugin: PluginModel) {
b5f919ac
C
362 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
363
364 logger.info('Registering plugin or theme %s.', npmName)
345da516 365
09071200 366 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
f023a19c 367 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
345da516 368
9157d598 369 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
345da516
C
370
371 let library: PluginLibrary
7fed6375 372 let registerHelpersStore: RegisterHelpersStore
345da516 373 if (plugin.type === PluginType.PLUGIN) {
7fed6375
C
374 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
375 library = result.library
376 registerHelpersStore = result.registerStore
345da516
C
377 }
378
2c053942
C
379 const clientScripts: { [id: string]: ClientScript } = {}
380 for (const c of packageJSON.clientScripts) {
381 clientScripts[c.script] = c
382 }
383
a1587156 384 this.registeredPlugins[npmName] = {
b5f919ac 385 npmName,
345da516
C
386 name: plugin.name,
387 type: plugin.type,
388 version: plugin.version,
389 description: plugin.description,
390 peertubeEngine: plugin.peertubeEngine,
391 path: pluginPath,
392 staticDirs: packageJSON.staticDirs,
2c053942 393 clientScripts,
345da516 394 css: packageJSON.css,
7fed6375 395 registerHelpersStore: registerHelpersStore || undefined,
345da516
C
396 unregister: library ? library.unregister : undefined
397 }
d75db01f
C
398
399 await this.addTranslations(plugin, npmName, packageJSON.translations)
345da516
C
400 }
401
402 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
b5f919ac
C
403 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
404
09071200
C
405 // Delete cache if needed
406 const modulePath = join(pluginPath, packageJSON.library)
407 delete require.cache[modulePath]
408 const library: PluginLibrary = require(modulePath)
f023a19c 409
345da516
C
410 if (!isLibraryCodeValid(library)) {
411 throw new Error('Library code is not valid (miss register or unregister function)')
412 }
413
7fed6375
C
414 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
415 library.register(registerOptions)
32fe0013 416 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
345da516 417
b5f919ac 418 logger.info('Add plugin %s CSS to global file.', npmName)
345da516
C
419
420 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
421
7fed6375 422 return { library, registerStore }
345da516
C
423 }
424
d75db01f
C
425 // ###################### Translations ######################
426
427 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
428 for (const locale of Object.keys(translationPaths)) {
429 const path = translationPaths[locale]
430 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
431
432 if (!this.translations[locale]) this.translations[locale] = {}
433 this.translations[locale][npmName] = json
434
435 logger.info('Added locale %s of plugin %s.', locale, npmName)
436 }
437 }
438
439 private deleteTranslations (npmName: string) {
440 for (const locale of Object.keys(this.translations)) {
441 delete this.translations[locale][npmName]
442
443 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
444 }
445 }
446
ad91e700 447 // ###################### CSS ######################
345da516 448
2c053942 449 private resetCSSGlobalFile () {
3e753302
C
450 ClientHtml.invalidCache()
451
2c053942
C
452 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
453 }
454
345da516
C
455 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
456 for (const cssPath of cssRelativePaths) {
457 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
458 }
a8b666e9
C
459
460 ClientHtml.invalidCache()
345da516
C
461 }
462
463 private concatFiles (input: string, output: string) {
464 return new Promise<void>((res, rej) => {
2c053942
C
465 const inputStream = createReadStream(input)
466 const outputStream = createWriteStream(output, { flags: 'a' })
345da516
C
467
468 inputStream.pipe(outputStream)
469
470 inputStream.on('end', () => res())
471 inputStream.on('error', err => rej(err))
472 })
473 }
474
ad91e700
C
475 private async regeneratePluginGlobalCSS () {
476 await this.resetCSSGlobalFile()
477
1198edf4 478 for (const plugin of this.getRegisteredPlugins()) {
ad91e700
C
479 await this.addCSSToGlobalFile(plugin.path, plugin.css)
480 }
481 }
482
483 // ###################### Utils ######################
484
485 private sortHooksByPriority () {
486 for (const hookName of Object.keys(this.hooks)) {
487 this.hooks[hookName].sort((a, b) => {
488 return b.priority - a.priority
489 })
490 }
491 }
492
f023a19c
C
493 private getPackageJSON (pluginName: string, pluginType: PluginType) {
494 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
495
09071200 496 return readJSON(pluginPath) as Promise<PluginPackageJson>
f023a19c
C
497 }
498
499 private getPluginPath (pluginName: string, pluginType: PluginType) {
b5f919ac 500 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
f023a19c 501
b5f919ac 502 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
f023a19c
C
503 }
504
e307e4fc
C
505 private getAuth (npmName: string, authName: string) {
506 const plugin = this.getRegisteredPluginOrTheme(npmName)
507 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
508
9107d791
C
509 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpersStore.getIdAndPassAuths()
510 auths = auths.concat(plugin.registerHelpersStore.getExternalAuths())
511
512 return auths.find(a => a.authName === authName)
e307e4fc
C
513 }
514
ad91e700 515 // ###################### Private getters ######################
2c053942 516
7cd4d2ba
C
517 private getRegisteredPluginsOrThemes (type: PluginType) {
518 const plugins: RegisteredPlugin[] = []
519
b5f919ac 520 for (const npmName of Object.keys(this.registeredPlugins)) {
a1587156 521 const plugin = this.registeredPlugins[npmName]
7cd4d2ba
C
522 if (plugin.type !== type) continue
523
524 plugins.push(plugin)
525 }
526
527 return plugins
528 }
529
32fe0013
C
530 // ###################### Generate register helpers ######################
531
7fed6375
C
532 private getRegisterHelpers (
533 npmName: string,
534 plugin: PluginModel
535 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
5e2b2e27 536 const onHookAdded = (options: RegisterServerHookOptions) => {
32fe0013
C
537 if (!this.hooks[options.target]) this.hooks[options.target] = []
538
539 this.hooks[options.target].push({
5e2b2e27 540 npmName: npmName,
32fe0013
C
541 pluginName: plugin.name,
542 handler: options.handler,
543 priority: options.priority || 0
544 })
545 }
546
5e2b2e27 547 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
32fe0013 548
7fed6375
C
549 return {
550 registerStore: registerHelpersStore,
551 registerOptions: registerHelpersStore.buildRegisterHelpers()
552 }
ee286591
C
553 }
554
9157d598
C
555 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
556 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
557 if (!packageJSON.css) packageJSON.css = []
558 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
559 if (!packageJSON.translations) packageJSON.translations = {}
560
561 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
562 if (!packageJSONValid) {
563 const formattedFields = badFields.map(f => `"${f}"`)
a1587156 564 .join(', ')
9157d598
C
565
566 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
567 }
568 }
569
345da516
C
570 static get Instance () {
571 return this.instance || (this.instance = new this())
572 }
573}