1 import { PluginModel } from '../../models/server/plugin'
2 import { logger } from '../../helpers/logger'
3 import { basename, join } from 'path'
4 import { CONFIG } from '../../initializers/config'
5 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
9 PluginTranslationPaths as PackagePluginTranslations
10 } from '../../../shared/models/plugins/plugin-package-json.model'
11 import { createReadStream, createWriteStream } from 'fs'
12 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
13 import { PluginType } from '../../../shared/models/plugins/plugin.type'
14 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
15 import { outputFile, readJSON } from 'fs-extra'
16 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model'
17 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
18 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
19 import { PluginLibrary } from '../../typings/plugins'
20 import { ClientHtml } from '../client-html'
21 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
22 import { RegisterHelpersStore } from './register-helpers-store'
23 import { RegisterServerHookOptions } from '@shared/models/plugins/register-server-hook.model'
24 import { MOAuthTokenUser, MUser } from '@server/typings/models'
25 import { RegisterServerAuthPassOptions, RegisterServerAuthExternalOptions } from '@shared/models/plugins/register-server-auth.model'
27 export interface RegisteredPlugin {
32 peertubeEngine: string
38 staticDirs: { [name: string]: string }
39 clientScripts: { [name: string]: ClientScript }
43 // Only if this is a plugin
44 registerHelpersStore?: RegisterHelpersStore
48 export interface HookInformationValue {
55 type PluginLocalesTranslations = {
56 [locale: string]: PluginTranslation
59 export class PluginManager implements ServerHook {
61 private static instance: PluginManager
63 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
65 private hooks: { [name: string]: HookInformationValue[] } = {}
66 private translations: PluginLocalesTranslations = {}
68 private constructor () {
71 // ###################### Getters ######################
73 isRegistered (npmName: string) {
74 return !!this.getRegisteredPluginOrTheme(npmName)
77 getRegisteredPluginOrTheme (npmName: string) {
78 return this.registeredPlugins[npmName]
81 getRegisteredPluginByShortName (name: string) {
82 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
83 const registered = this.getRegisteredPluginOrTheme(npmName)
85 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
90 getRegisteredThemeByShortName (name: string) {
91 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
92 const registered = this.getRegisteredPluginOrTheme(npmName)
94 if (!registered || registered.type !== PluginType.THEME) return undefined
99 getRegisteredPlugins () {
100 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
103 getRegisteredThemes () {
104 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
107 getIdAndPassAuths () {
108 return this.getRegisteredPlugins()
113 idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths()
115 .filter(v => v.idAndPassAuths.length !== 0)
118 getExternalAuths () {
119 return this.getRegisteredPlugins()
124 externalAuths: p.registerHelpersStore.getExternalAuths()
126 .filter(v => v.externalAuths.length !== 0)
129 getRegisteredSettings (npmName: string) {
130 const result = this.getRegisteredPluginOrTheme(npmName)
131 if (!result || result.type !== PluginType.PLUGIN) return []
133 return result.registerHelpersStore.getSettings()
136 getRouter (npmName: string) {
137 const result = this.getRegisteredPluginOrTheme(npmName)
138 if (!result || result.type !== PluginType.PLUGIN) return null
140 return result.registerHelpersStore.getRouter()
143 getTranslations (locale: string) {
144 return this.translations[locale] || {}
147 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
148 const auth = this.getAuth(token.User.pluginAuth, token.authName)
149 if (!auth) return true
151 if (auth.hookTokenValidity) {
153 const { valid } = await auth.hookTokenValidity({ token, type })
155 if (valid === false) {
156 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
161 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
169 // ###################### External events ######################
171 onLogout (npmName: string, authName: string, user: MUser) {
172 const auth = this.getAuth(npmName, authName)
174 if (auth?.onLogout) {
175 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
180 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
185 onSettingsChanged (name: string, settings: any) {
186 const registered = this.getRegisteredPluginByShortName(name)
188 logger.error('Cannot find plugin %s to call on settings changed.', name)
191 for (const cb of registered.registerHelpersStore.getOnSettingsChangedCallbacks()) {
195 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
200 // ###################### Hooks ######################
202 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
203 if (!this.hooks[hookName]) return Promise.resolve(result)
205 const hookType = getHookType(hookName)
207 for (const hook of this.hooks[hookName]) {
208 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
210 result = await internalRunHook(hook.handler, hookType, result, params, err => {
211 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
218 // ###################### Registration ######################
220 async registerPluginsAndThemes () {
221 await this.resetCSSGlobalFile()
223 const plugins = await PluginModel.listEnabledPluginsAndThemes()
225 for (const plugin of plugins) {
227 await this.registerPluginOrTheme(plugin)
229 // Try to unregister the plugin
231 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
233 // we don't care if we cannot unregister it
236 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
240 this.sortHooksByPriority()
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)
247 const plugin = this.getRegisteredPluginOrTheme(npmName)
250 throw new Error(`Unknown plugin ${npmName} to unregister`)
253 delete this.registeredPlugins[plugin.npmName]
255 this.deleteTranslations(plugin.npmName)
257 if (plugin.type === PluginType.PLUGIN) {
258 await plugin.unregister()
260 // Remove hooks of this plugin
261 for (const key of Object.keys(this.hooks)) {
262 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
265 const store = plugin.registerHelpersStore
266 store.reinitVideoConstants(plugin.npmName)
268 logger.info('Regenerating registered plugin CSS to global file.')
269 await this.regeneratePluginGlobalCSS()
273 // ###################### Installation ######################
275 async install (toInstall: string, version?: string, fromDisk = false) {
276 let plugin: PluginModel
279 logger.info('Installing plugin %s.', toInstall)
283 ? await installNpmPluginFromDisk(toInstall)
284 : await installNpmPlugin(toInstall, version)
286 npmName = fromDisk ? basename(toInstall) : toInstall
287 const pluginType = PluginModel.getTypeFromNpmName(npmName)
288 const pluginName = PluginModel.normalizePluginName(npmName)
290 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
292 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
294 [ plugin ] = await PluginModel.upsert({
296 description: packageJSON.description,
297 homepage: packageJSON.homepage,
299 version: packageJSON.version,
302 peertubeEngine: packageJSON.engine.peertube
303 }, { returning: true })
305 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
308 await removeNpmPlugin(npmName)
310 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
316 logger.info('Successful installation of plugin %s.', toInstall)
318 await this.registerPluginOrTheme(plugin)
323 async update (toUpdate: string, version?: string, fromDisk = false) {
324 const npmName = fromDisk ? basename(toUpdate) : toUpdate
326 logger.info('Updating plugin %s.', npmName)
328 // Unregister old hooks
329 await this.unregister(npmName)
331 return this.install(toUpdate, version, fromDisk)
334 async uninstall (npmName: string) {
335 logger.info('Uninstalling plugin %s.', npmName)
338 await this.unregister(npmName)
340 logger.warn('Cannot unregister plugin %s.', npmName, { err })
343 const plugin = await PluginModel.loadByNpmName(npmName)
344 if (!plugin || plugin.uninstalled === true) {
345 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
349 plugin.enabled = false
350 plugin.uninstalled = true
354 await removeNpmPlugin(npmName)
356 logger.info('Plugin %s uninstalled.', npmName)
359 // ###################### Private register ######################
361 private async registerPluginOrTheme (plugin: PluginModel) {
362 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
364 logger.info('Registering plugin or theme %s.', npmName)
366 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
367 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
369 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
371 let library: PluginLibrary
372 let registerHelpersStore: RegisterHelpersStore
373 if (plugin.type === PluginType.PLUGIN) {
374 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
375 library = result.library
376 registerHelpersStore = result.registerStore
379 const clientScripts: { [id: string]: ClientScript } = {}
380 for (const c of packageJSON.clientScripts) {
381 clientScripts[c.script] = c
384 this.registeredPlugins[npmName] = {
388 version: plugin.version,
389 description: plugin.description,
390 peertubeEngine: plugin.peertubeEngine,
392 staticDirs: packageJSON.staticDirs,
394 css: packageJSON.css,
395 registerHelpersStore: registerHelpersStore || undefined,
396 unregister: library ? library.unregister : undefined
399 await this.addTranslations(plugin, npmName, packageJSON.translations)
402 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
403 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
405 // Delete cache if needed
406 const modulePath = join(pluginPath, packageJSON.library)
407 delete require.cache[modulePath]
408 const library: PluginLibrary = require(modulePath)
410 if (!isLibraryCodeValid(library)) {
411 throw new Error('Library code is not valid (miss register or unregister function)')
414 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
415 library.register(registerOptions)
416 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
418 logger.info('Add plugin %s CSS to global file.', npmName)
420 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
422 return { library, registerStore }
425 // ###################### Translations ######################
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))
432 if (!this.translations[locale]) this.translations[locale] = {}
433 this.translations[locale][npmName] = json
435 logger.info('Added locale %s of plugin %s.', locale, npmName)
439 private deleteTranslations (npmName: string) {
440 for (const locale of Object.keys(this.translations)) {
441 delete this.translations[locale][npmName]
443 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
447 // ###################### CSS ######################
449 private resetCSSGlobalFile () {
450 ClientHtml.invalidCache()
452 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
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)
460 ClientHtml.invalidCache()
463 private concatFiles (input: string, output: string) {
464 return new Promise<void>((res, rej) => {
465 const inputStream = createReadStream(input)
466 const outputStream = createWriteStream(output, { flags: 'a' })
468 inputStream.pipe(outputStream)
470 inputStream.on('end', () => res())
471 inputStream.on('error', err => rej(err))
475 private async regeneratePluginGlobalCSS () {
476 await this.resetCSSGlobalFile()
478 for (const plugin of this.getRegisteredPlugins()) {
479 await this.addCSSToGlobalFile(plugin.path, plugin.css)
483 // ###################### Utils ######################
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
493 private getPackageJSON (pluginName: string, pluginType: PluginType) {
494 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
496 return readJSON(pluginPath) as Promise<PluginPackageJson>
499 private getPluginPath (pluginName: string, pluginType: PluginType) {
500 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
502 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
505 private getAuth (npmName: string, authName: string) {
506 const plugin = this.getRegisteredPluginOrTheme(npmName)
507 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
509 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpersStore.getIdAndPassAuths()
510 auths = auths.concat(plugin.registerHelpersStore.getExternalAuths())
512 return auths.find(a => a.authName === authName)
515 // ###################### Private getters ######################
517 private getRegisteredPluginsOrThemes (type: PluginType) {
518 const plugins: RegisteredPlugin[] = []
520 for (const npmName of Object.keys(this.registeredPlugins)) {
521 const plugin = this.registeredPlugins[npmName]
522 if (plugin.type !== type) continue
530 // ###################### Generate register helpers ######################
532 private getRegisterHelpers (
535 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
536 const onHookAdded = (options: RegisterServerHookOptions) => {
537 if (!this.hooks[options.target]) this.hooks[options.target] = []
539 this.hooks[options.target].push({
541 pluginName: plugin.name,
542 handler: options.handler,
543 priority: options.priority || 0
547 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
550 registerStore: registerHelpersStore,
551 registerOptions: registerHelpersStore.buildRegisterHelpers()
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 = {}
561 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
562 if (!packageJSONValid) {
563 const formattedFields = badFields.map(f => `"${f}"`)
566 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
570 static get Instance () {
571 return this.instance || (this.instance = new this())