1 import decache from 'decache'
2 import * as express from 'express'
3 import { createReadStream, createWriteStream } from 'fs'
4 import { ensureDir, outputFile, readJSON } from 'fs-extra'
5 import { basename, join } from 'path'
6 import { MOAuthTokenUser, MUser } from '@server/types/models'
7 import { RegisterServerHookOptions } from '@shared/models/plugins/register-server-hook.model'
8 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
12 PluginTranslationPaths as PackagePluginTranslations
13 } from '../../../shared/models/plugins/plugin-package-json.model'
14 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
15 import { PluginType } from '../../../shared/models/plugins/plugin.type'
16 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model'
17 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
18 import { logger } from '../../helpers/logger'
19 import { CONFIG } from '../../initializers/config'
20 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
21 import { PluginModel } from '../../models/server/plugin'
22 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
23 import { ClientHtml } from '../client-html'
24 import { RegisterHelpers } from './register-helpers'
25 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
26 import { getCompleteLocale } from '@shared/core-utils'
28 export interface RegisteredPlugin {
33 peertubeEngine: string
39 staticDirs: { [name: string]: string }
40 clientScripts: { [name: string]: ClientScript }
44 // Only if this is a plugin
45 registerHelpers?: RegisterHelpers
49 export interface HookInformationValue {
56 type PluginLocalesTranslations = {
57 [locale: string]: PluginTranslation
60 export class PluginManager implements ServerHook {
62 private static instance: PluginManager
64 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
66 private hooks: { [name: string]: HookInformationValue[] } = {}
67 private translations: PluginLocalesTranslations = {}
69 private constructor () {
72 // ###################### Getters ######################
74 isRegistered (npmName: string) {
75 return !!this.getRegisteredPluginOrTheme(npmName)
78 getRegisteredPluginOrTheme (npmName: string) {
79 return this.registeredPlugins[npmName]
82 getRegisteredPluginByShortName (name: string) {
83 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
84 const registered = this.getRegisteredPluginOrTheme(npmName)
86 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
91 getRegisteredThemeByShortName (name: string) {
92 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
93 const registered = this.getRegisteredPluginOrTheme(npmName)
95 if (!registered || registered.type !== PluginType.THEME) return undefined
100 getRegisteredPlugins () {
101 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
104 getRegisteredThemes () {
105 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
108 getIdAndPassAuths () {
109 return this.getRegisteredPlugins()
114 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
116 .filter(v => v.idAndPassAuths.length !== 0)
119 getExternalAuths () {
120 return this.getRegisteredPlugins()
125 externalAuths: p.registerHelpers.getExternalAuths()
127 .filter(v => v.externalAuths.length !== 0)
130 getRegisteredSettings (npmName: string) {
131 const result = this.getRegisteredPluginOrTheme(npmName)
132 if (!result || result.type !== PluginType.PLUGIN) return []
134 return result.registerHelpers.getSettings()
137 getRouter (npmName: string) {
138 const result = this.getRegisteredPluginOrTheme(npmName)
139 if (!result || result.type !== PluginType.PLUGIN) return null
141 return result.registerHelpers.getRouter()
144 getTranslations (locale: string) {
145 return this.translations[locale] || {}
148 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
149 const auth = this.getAuth(token.User.pluginAuth, token.authName)
150 if (!auth) return true
152 if (auth.hookTokenValidity) {
154 const { valid } = await auth.hookTokenValidity({ token, type })
156 if (valid === false) {
157 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
162 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
170 // ###################### External events ######################
172 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
173 const auth = this.getAuth(npmName, authName)
175 if (auth?.onLogout) {
176 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
179 // Force await, in case or onLogout returns a promise
180 const result = await auth.onLogout(user, req)
182 return typeof result === 'string'
186 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
193 async onSettingsChanged (name: string, settings: any) {
194 const registered = this.getRegisteredPluginByShortName(name)
196 logger.error('Cannot find plugin %s to call on settings changed.', name)
199 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
203 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
208 // ###################### Hooks ######################
210 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
211 if (!this.hooks[hookName]) return Promise.resolve(result)
213 const hookType = getHookType(hookName)
215 for (const hook of this.hooks[hookName]) {
216 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
218 result = await internalRunHook(hook.handler, hookType, result, params, err => {
219 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
226 // ###################### Registration ######################
228 async registerPluginsAndThemes () {
229 await this.resetCSSGlobalFile()
231 const plugins = await PluginModel.listEnabledPluginsAndThemes()
233 for (const plugin of plugins) {
235 await this.registerPluginOrTheme(plugin)
237 // Try to unregister the plugin
239 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
241 // we don't care if we cannot unregister it
244 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
248 this.sortHooksByPriority()
251 // Don't need the plugin type since themes cannot register server code
252 async unregister (npmName: string) {
253 logger.info('Unregister plugin %s.', npmName)
255 const plugin = this.getRegisteredPluginOrTheme(npmName)
258 throw new Error(`Unknown plugin ${npmName} to unregister`)
261 delete this.registeredPlugins[plugin.npmName]
263 this.deleteTranslations(plugin.npmName)
265 if (plugin.type === PluginType.PLUGIN) {
266 await plugin.unregister()
268 // Remove hooks of this plugin
269 for (const key of Object.keys(this.hooks)) {
270 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
273 const store = plugin.registerHelpers
274 store.reinitVideoConstants(plugin.npmName)
275 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
277 logger.info('Regenerating registered plugin CSS to global file.')
278 await this.regeneratePluginGlobalCSS()
282 // ###################### Installation ######################
284 async install (toInstall: string, version?: string, fromDisk = false) {
285 let plugin: PluginModel
288 logger.info('Installing plugin %s.', toInstall)
292 ? await installNpmPluginFromDisk(toInstall)
293 : await installNpmPlugin(toInstall, version)
295 npmName = fromDisk ? basename(toInstall) : toInstall
296 const pluginType = PluginModel.getTypeFromNpmName(npmName)
297 const pluginName = PluginModel.normalizePluginName(npmName)
299 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
301 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
303 [ plugin ] = await PluginModel.upsert({
305 description: packageJSON.description,
306 homepage: packageJSON.homepage,
308 version: packageJSON.version,
311 peertubeEngine: packageJSON.engine.peertube
312 }, { returning: true })
314 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
317 await removeNpmPlugin(npmName)
319 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
325 logger.info('Successful installation of plugin %s.', toInstall)
327 await this.registerPluginOrTheme(plugin)
332 async update (toUpdate: string, fromDisk = false) {
333 const npmName = fromDisk ? basename(toUpdate) : toUpdate
335 logger.info('Updating plugin %s.', npmName)
337 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
340 const plugin = await PluginModel.loadByNpmName(toUpdate)
341 version = plugin.latestVersion
344 // Unregister old hooks
345 await this.unregister(npmName)
347 return this.install(toUpdate, version, fromDisk)
350 async uninstall (npmName: string) {
351 logger.info('Uninstalling plugin %s.', npmName)
354 await this.unregister(npmName)
356 logger.warn('Cannot unregister plugin %s.', npmName, { err })
359 const plugin = await PluginModel.loadByNpmName(npmName)
360 if (!plugin || plugin.uninstalled === true) {
361 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
365 plugin.enabled = false
366 plugin.uninstalled = true
370 await removeNpmPlugin(npmName)
372 logger.info('Plugin %s uninstalled.', npmName)
375 // ###################### Private register ######################
377 private async registerPluginOrTheme (plugin: PluginModel) {
378 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
380 logger.info('Registering plugin or theme %s.', npmName)
382 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
383 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
385 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
387 let library: PluginLibrary
388 let registerHelpers: RegisterHelpers
389 if (plugin.type === PluginType.PLUGIN) {
390 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
391 library = result.library
392 registerHelpers = result.registerStore
395 const clientScripts: { [id: string]: ClientScript } = {}
396 for (const c of packageJSON.clientScripts) {
397 clientScripts[c.script] = c
400 this.registeredPlugins[npmName] = {
404 version: plugin.version,
405 description: plugin.description,
406 peertubeEngine: plugin.peertubeEngine,
408 staticDirs: packageJSON.staticDirs,
410 css: packageJSON.css,
411 registerHelpers: registerHelpers || undefined,
412 unregister: library ? library.unregister : undefined
415 await this.addTranslations(plugin, npmName, packageJSON.translations)
418 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
419 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
421 // Delete cache if needed
422 const modulePath = join(pluginPath, packageJSON.library)
424 const library: PluginLibrary = require(modulePath)
426 if (!isLibraryCodeValid(library)) {
427 throw new Error('Library code is not valid (miss register or unregister function)')
430 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
432 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
434 library.register(registerOptions)
435 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
437 logger.info('Add plugin %s CSS to global file.', npmName)
439 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
441 return { library, registerStore }
444 // ###################### Translations ######################
446 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
447 for (const locale of Object.keys(translationPaths)) {
448 const path = translationPaths[locale]
449 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
451 const completeLocale = getCompleteLocale(locale)
453 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
454 this.translations[completeLocale][npmName] = json
456 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
460 private deleteTranslations (npmName: string) {
461 for (const locale of Object.keys(this.translations)) {
462 delete this.translations[locale][npmName]
464 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
468 // ###################### CSS ######################
470 private resetCSSGlobalFile () {
471 ClientHtml.invalidCache()
473 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
476 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
477 for (const cssPath of cssRelativePaths) {
478 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
481 ClientHtml.invalidCache()
484 private concatFiles (input: string, output: string) {
485 return new Promise<void>((res, rej) => {
486 const inputStream = createReadStream(input)
487 const outputStream = createWriteStream(output, { flags: 'a' })
489 inputStream.pipe(outputStream)
491 inputStream.on('end', () => res())
492 inputStream.on('error', err => rej(err))
496 private async regeneratePluginGlobalCSS () {
497 await this.resetCSSGlobalFile()
499 for (const plugin of this.getRegisteredPlugins()) {
500 await this.addCSSToGlobalFile(plugin.path, plugin.css)
504 // ###################### Utils ######################
506 private sortHooksByPriority () {
507 for (const hookName of Object.keys(this.hooks)) {
508 this.hooks[hookName].sort((a, b) => {
509 return b.priority - a.priority
514 private getPackageJSON (pluginName: string, pluginType: PluginType) {
515 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
517 return readJSON(pluginPath) as Promise<PluginPackageJson>
520 private getPluginPath (pluginName: string, pluginType: PluginType) {
521 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
523 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
526 private getAuth (npmName: string, authName: string) {
527 const plugin = this.getRegisteredPluginOrTheme(npmName)
528 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
530 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
531 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
533 return auths.find(a => a.authName === authName)
536 // ###################### Private getters ######################
538 private getRegisteredPluginsOrThemes (type: PluginType) {
539 const plugins: RegisteredPlugin[] = []
541 for (const npmName of Object.keys(this.registeredPlugins)) {
542 const plugin = this.registeredPlugins[npmName]
543 if (plugin.type !== type) continue
551 // ###################### Generate register helpers ######################
553 private getRegisterHelpers (
556 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
557 const onHookAdded = (options: RegisterServerHookOptions) => {
558 if (!this.hooks[options.target]) this.hooks[options.target] = []
560 this.hooks[options.target].push({
562 pluginName: plugin.name,
563 handler: options.handler,
564 priority: options.priority || 0
568 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
571 registerStore: registerHelpers,
572 registerOptions: registerHelpers.buildRegisterHelpers()
576 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
577 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
578 if (!packageJSON.css) packageJSON.css = []
579 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
580 if (!packageJSON.translations) packageJSON.translations = {}
582 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
583 if (!packageJSONValid) {
584 const formattedFields = badFields.map(f => `"${f}"`)
587 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
591 static get Instance () {
592 return this.instance || (this.instance = new this())