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 { ApplicationModel } from '@server/models/application/application'
7 import { MOAuthTokenUser, MUser } from '@server/types/models'
8 import { getCompleteLocale } from '@shared/core-utils'
13 PluginTranslationPathsJSON,
14 RegisterServerHookOptions
15 } from '@shared/models'
16 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
17 import { PluginType } from '../../../shared/models/plugins/plugin.type'
18 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
19 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
20 import { logger } from '../../helpers/logger'
21 import { CONFIG } from '../../initializers/config'
22 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
23 import { PluginModel } from '../../models/server/plugin'
24 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
25 import { ClientHtml } from '../client-html'
26 import { RegisterHelpers } from './register-helpers'
27 import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn'
29 export interface RegisteredPlugin {
34 peertubeEngine: string
40 staticDirs: { [name: string]: string }
41 clientScripts: { [name: string]: ClientScriptJSON }
45 // Only if this is a plugin
46 registerHelpers?: RegisterHelpers
50 export interface HookInformationValue {
57 type PluginLocalesTranslations = {
58 [locale: string]: PluginTranslation
61 export class PluginManager implements ServerHook {
63 private static instance: PluginManager
65 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
67 private hooks: { [name: string]: HookInformationValue[] } = {}
68 private translations: PluginLocalesTranslations = {}
70 private constructor () {
73 // ###################### Getters ######################
75 isRegistered (npmName: string) {
76 return !!this.getRegisteredPluginOrTheme(npmName)
79 getRegisteredPluginOrTheme (npmName: string) {
80 return this.registeredPlugins[npmName]
83 getRegisteredPluginByShortName (name: string) {
84 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
85 const registered = this.getRegisteredPluginOrTheme(npmName)
87 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
92 getRegisteredThemeByShortName (name: string) {
93 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
94 const registered = this.getRegisteredPluginOrTheme(npmName)
96 if (!registered || registered.type !== PluginType.THEME) return undefined
101 getRegisteredPlugins () {
102 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
105 getRegisteredThemes () {
106 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
109 getIdAndPassAuths () {
110 return this.getRegisteredPlugins()
115 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
117 .filter(v => v.idAndPassAuths.length !== 0)
120 getExternalAuths () {
121 return this.getRegisteredPlugins()
126 externalAuths: p.registerHelpers.getExternalAuths()
128 .filter(v => v.externalAuths.length !== 0)
131 getRegisteredSettings (npmName: string) {
132 const result = this.getRegisteredPluginOrTheme(npmName)
133 if (!result || result.type !== PluginType.PLUGIN) return []
135 return result.registerHelpers.getSettings()
138 getRouter (npmName: string) {
139 const result = this.getRegisteredPluginOrTheme(npmName)
140 if (!result || result.type !== PluginType.PLUGIN) return null
142 return result.registerHelpers.getRouter()
145 getTranslations (locale: string) {
146 return this.translations[locale] || {}
149 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
150 const auth = this.getAuth(token.User.pluginAuth, token.authName)
151 if (!auth) return true
153 if (auth.hookTokenValidity) {
155 const { valid } = await auth.hookTokenValidity({ token, type })
157 if (valid === false) {
158 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
163 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
171 // ###################### External events ######################
173 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
174 const auth = this.getAuth(npmName, authName)
176 if (auth?.onLogout) {
177 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
180 // Force await, in case or onLogout returns a promise
181 const result = await auth.onLogout(user, req)
183 return typeof result === 'string'
187 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
194 async onSettingsChanged (name: string, settings: any) {
195 const registered = this.getRegisteredPluginByShortName(name)
197 logger.error('Cannot find plugin %s to call on settings changed.', name)
200 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
204 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
209 // ###################### Hooks ######################
211 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
212 if (!this.hooks[hookName]) return Promise.resolve(result)
214 const hookType = getHookType(hookName)
216 for (const hook of this.hooks[hookName]) {
217 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
219 result = await internalRunHook({
220 handler: hook.handler,
224 onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
231 // ###################### Registration ######################
233 async registerPluginsAndThemes () {
234 await this.resetCSSGlobalFile()
236 const plugins = await PluginModel.listEnabledPluginsAndThemes()
238 for (const plugin of plugins) {
240 await this.registerPluginOrTheme(plugin)
242 // Try to unregister the plugin
244 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
246 // we don't care if we cannot unregister it
249 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
253 this.sortHooksByPriority()
256 // Don't need the plugin type since themes cannot register server code
257 async unregister (npmName: string) {
258 logger.info('Unregister plugin %s.', npmName)
260 const plugin = this.getRegisteredPluginOrTheme(npmName)
263 throw new Error(`Unknown plugin ${npmName} to unregister`)
266 delete this.registeredPlugins[plugin.npmName]
268 this.deleteTranslations(plugin.npmName)
270 if (plugin.type === PluginType.PLUGIN) {
271 await plugin.unregister()
273 // Remove hooks of this plugin
274 for (const key of Object.keys(this.hooks)) {
275 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
278 const store = plugin.registerHelpers
279 store.reinitVideoConstants(plugin.npmName)
280 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
282 logger.info('Regenerating registered plugin CSS to global file.')
283 await this.regeneratePluginGlobalCSS()
286 ClientHtml.invalidCache()
289 // ###################### Installation ######################
291 async install (toInstall: string, version?: string, fromDisk = false) {
292 let plugin: PluginModel
295 logger.info('Installing plugin %s.', toInstall)
299 ? await installNpmPluginFromDisk(toInstall)
300 : await installNpmPlugin(toInstall, version)
302 npmName = fromDisk ? basename(toInstall) : toInstall
303 const pluginType = PluginModel.getTypeFromNpmName(npmName)
304 const pluginName = PluginModel.normalizePluginName(npmName)
306 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
308 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
310 [ plugin ] = await PluginModel.upsert({
312 description: packageJSON.description,
313 homepage: packageJSON.homepage,
315 version: packageJSON.version,
318 peertubeEngine: packageJSON.engine.peertube
319 }, { returning: true })
321 logger.info('Successful installation of plugin %s.', toInstall)
323 await this.registerPluginOrTheme(plugin)
325 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
328 await this.uninstall(npmName)
330 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
333 await removeNpmPlugin(npmName)
335 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
345 async update (toUpdate: string, fromDisk = false) {
346 const npmName = fromDisk ? basename(toUpdate) : toUpdate
348 logger.info('Updating plugin %s.', npmName)
350 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
353 const plugin = await PluginModel.loadByNpmName(toUpdate)
354 version = plugin.latestVersion
357 // Unregister old hooks
358 await this.unregister(npmName)
360 return this.install(toUpdate, version, fromDisk)
363 async uninstall (npmName: string) {
364 logger.info('Uninstalling plugin %s.', npmName)
367 await this.unregister(npmName)
369 logger.warn('Cannot unregister plugin %s.', npmName, { err })
372 const plugin = await PluginModel.loadByNpmName(npmName)
373 if (!plugin || plugin.uninstalled === true) {
374 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
378 plugin.enabled = false
379 plugin.uninstalled = true
383 await removeNpmPlugin(npmName)
385 logger.info('Plugin %s uninstalled.', npmName)
388 async rebuildNativePluginsIfNeeded () {
389 if (!await ApplicationModel.nodeABIChanged()) return
391 return rebuildNativePlugins()
394 // ###################### Private register ######################
396 private async registerPluginOrTheme (plugin: PluginModel) {
397 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
399 logger.info('Registering plugin or theme %s.', npmName)
401 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
402 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
404 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
406 let library: PluginLibrary
407 let registerHelpers: RegisterHelpers
408 if (plugin.type === PluginType.PLUGIN) {
409 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
410 library = result.library
411 registerHelpers = result.registerStore
414 const clientScripts: { [id: string]: ClientScriptJSON } = {}
415 for (const c of packageJSON.clientScripts) {
416 clientScripts[c.script] = c
419 this.registeredPlugins[npmName] = {
423 version: plugin.version,
424 description: plugin.description,
425 peertubeEngine: plugin.peertubeEngine,
427 staticDirs: packageJSON.staticDirs,
429 css: packageJSON.css,
430 registerHelpers: registerHelpers || undefined,
431 unregister: library ? library.unregister : undefined
434 await this.addTranslations(plugin, npmName, packageJSON.translations)
436 ClientHtml.invalidCache()
439 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
440 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
442 // Delete cache if needed
443 const modulePath = join(pluginPath, packageJSON.library)
444 decachePlugin(pluginPath, modulePath)
445 const library: PluginLibrary = require(modulePath)
447 if (!isLibraryCodeValid(library)) {
448 throw new Error('Library code is not valid (miss register or unregister function)')
451 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
453 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
455 await library.register(registerOptions)
457 logger.info('Add plugin %s CSS to global file.', npmName)
459 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
461 return { library, registerStore }
464 // ###################### Translations ######################
466 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
467 for (const locale of Object.keys(translationPaths)) {
468 const path = translationPaths[locale]
469 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
471 const completeLocale = getCompleteLocale(locale)
473 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
474 this.translations[completeLocale][npmName] = json
476 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
480 private deleteTranslations (npmName: string) {
481 for (const locale of Object.keys(this.translations)) {
482 delete this.translations[locale][npmName]
484 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
488 // ###################### CSS ######################
490 private resetCSSGlobalFile () {
491 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
494 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
495 for (const cssPath of cssRelativePaths) {
496 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
500 private concatFiles (input: string, output: string) {
501 return new Promise<void>((res, rej) => {
502 const inputStream = createReadStream(input)
503 const outputStream = createWriteStream(output, { flags: 'a' })
505 inputStream.pipe(outputStream)
507 inputStream.on('end', () => res())
508 inputStream.on('error', err => rej(err))
512 private async regeneratePluginGlobalCSS () {
513 await this.resetCSSGlobalFile()
515 for (const plugin of this.getRegisteredPlugins()) {
516 await this.addCSSToGlobalFile(plugin.path, plugin.css)
520 // ###################### Utils ######################
522 private sortHooksByPriority () {
523 for (const hookName of Object.keys(this.hooks)) {
524 this.hooks[hookName].sort((a, b) => {
525 return b.priority - a.priority
530 private getPackageJSON (pluginName: string, pluginType: PluginType) {
531 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
533 return readJSON(pluginPath) as Promise<PluginPackageJSON>
536 private getPluginPath (pluginName: string, pluginType: PluginType) {
537 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
539 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
542 private getAuth (npmName: string, authName: string) {
543 const plugin = this.getRegisteredPluginOrTheme(npmName)
544 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
546 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
547 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
549 return auths.find(a => a.authName === authName)
552 // ###################### Private getters ######################
554 private getRegisteredPluginsOrThemes (type: PluginType) {
555 const plugins: RegisteredPlugin[] = []
557 for (const npmName of Object.keys(this.registeredPlugins)) {
558 const plugin = this.registeredPlugins[npmName]
559 if (plugin.type !== type) continue
567 // ###################### Generate register helpers ######################
569 private getRegisterHelpers (
572 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
573 const onHookAdded = (options: RegisterServerHookOptions) => {
574 if (!this.hooks[options.target]) this.hooks[options.target] = []
576 this.hooks[options.target].push({
578 pluginName: plugin.name,
579 handler: options.handler,
580 priority: options.priority || 0
584 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
587 registerStore: registerHelpers,
588 registerOptions: registerHelpers.buildRegisterHelpers()
592 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
593 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
594 if (!packageJSON.css) packageJSON.css = []
595 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
596 if (!packageJSON.translations) packageJSON.translations = {}
598 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
599 if (!packageJSONValid) {
600 const formattedFields = badFields.map(f => `"${f}"`)
603 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
607 static get Instance () {
608 return this.instance || (this.instance = new this())