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