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 } from '@server/typings/models'
26 export interface RegisteredPlugin {
31 peertubeEngine: string
37 staticDirs: { [name: string]: string }
38 clientScripts: { [name: string]: ClientScript }
42 // Only if this is a plugin
43 registerHelpersStore?: RegisterHelpersStore
47 export interface HookInformationValue {
54 type PluginLocalesTranslations = {
55 [locale: string]: PluginTranslation
58 export class PluginManager implements ServerHook {
60 private static instance: PluginManager
62 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
64 private hooks: { [name: string]: HookInformationValue[] } = {}
65 private translations: PluginLocalesTranslations = {}
67 private constructor () {
70 // ###################### Getters ######################
72 isRegistered (npmName: string) {
73 return !!this.getRegisteredPluginOrTheme(npmName)
76 getRegisteredPluginOrTheme (npmName: string) {
77 return this.registeredPlugins[npmName]
80 getRegisteredPluginByShortName (name: string) {
81 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
82 const registered = this.getRegisteredPluginOrTheme(npmName)
84 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
89 getRegisteredThemeByShortName (name: string) {
90 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
91 const registered = this.getRegisteredPluginOrTheme(npmName)
93 if (!registered || registered.type !== PluginType.THEME) return undefined
98 getRegisteredPlugins () {
99 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
102 getRegisteredThemes () {
103 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
106 getIdAndPassAuths () {
107 return this.getRegisteredPlugins()
108 .map(p => ({ npmName: p.npmName, idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths() }))
109 .filter(v => v.idAndPassAuths.length !== 0)
112 getExternalAuths () {
113 return this.getRegisteredPlugins()
114 .map(p => ({ npmName: p.npmName, externalAuths: p.registerHelpersStore.getExternalAuths() }))
115 .filter(v => v.externalAuths.length !== 0)
118 getRegisteredSettings (npmName: string) {
119 const result = this.getRegisteredPluginOrTheme(npmName)
120 if (!result || result.type !== PluginType.PLUGIN) return []
122 return result.registerHelpersStore.getSettings()
125 getRouter (npmName: string) {
126 const result = this.getRegisteredPluginOrTheme(npmName)
127 if (!result || result.type !== PluginType.PLUGIN) return null
129 return result.registerHelpersStore.getRouter()
132 getTranslations (locale: string) {
133 return this.translations[locale] || {}
136 onLogout (npmName: string, authName: string) {
137 const auth = this.getAuth(npmName, authName)
139 if (auth?.onLogout) {
140 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
145 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
150 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
151 const auth = this.getAuth(token.User.pluginAuth, token.authName)
152 if (!auth) return true
154 if (auth.hookTokenValidity) {
156 const { valid } = await auth.hookTokenValidity({ token, type })
158 if (valid === false) {
159 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
164 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
172 // ###################### Hooks ######################
174 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
175 if (!this.hooks[hookName]) return Promise.resolve(result)
177 const hookType = getHookType(hookName)
179 for (const hook of this.hooks[hookName]) {
180 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
182 result = await internalRunHook(hook.handler, hookType, result, params, err => {
183 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
190 // ###################### Registration ######################
192 async registerPluginsAndThemes () {
193 await this.resetCSSGlobalFile()
195 const plugins = await PluginModel.listEnabledPluginsAndThemes()
197 for (const plugin of plugins) {
199 await this.registerPluginOrTheme(plugin)
201 // Try to unregister the plugin
203 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
205 // we don't care if we cannot unregister it
208 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
212 this.sortHooksByPriority()
215 // Don't need the plugin type since themes cannot register server code
216 async unregister (npmName: string) {
217 logger.info('Unregister plugin %s.', npmName)
219 const plugin = this.getRegisteredPluginOrTheme(npmName)
222 throw new Error(`Unknown plugin ${npmName} to unregister`)
225 delete this.registeredPlugins[plugin.npmName]
227 this.deleteTranslations(plugin.npmName)
229 if (plugin.type === PluginType.PLUGIN) {
230 await plugin.unregister()
232 // Remove hooks of this plugin
233 for (const key of Object.keys(this.hooks)) {
234 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
237 const store = plugin.registerHelpersStore
238 store.reinitVideoConstants(plugin.npmName)
240 logger.info('Regenerating registered plugin CSS to global file.')
241 await this.regeneratePluginGlobalCSS()
245 // ###################### Installation ######################
247 async install (toInstall: string, version?: string, fromDisk = false) {
248 let plugin: PluginModel
251 logger.info('Installing plugin %s.', toInstall)
255 ? await installNpmPluginFromDisk(toInstall)
256 : await installNpmPlugin(toInstall, version)
258 npmName = fromDisk ? basename(toInstall) : toInstall
259 const pluginType = PluginModel.getTypeFromNpmName(npmName)
260 const pluginName = PluginModel.normalizePluginName(npmName)
262 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
264 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
266 [ plugin ] = await PluginModel.upsert({
268 description: packageJSON.description,
269 homepage: packageJSON.homepage,
271 version: packageJSON.version,
274 peertubeEngine: packageJSON.engine.peertube
275 }, { returning: true })
277 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
280 await removeNpmPlugin(npmName)
282 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
288 logger.info('Successful installation of plugin %s.', toInstall)
290 await this.registerPluginOrTheme(plugin)
295 async update (toUpdate: string, version?: string, fromDisk = false) {
296 const npmName = fromDisk ? basename(toUpdate) : toUpdate
298 logger.info('Updating plugin %s.', npmName)
300 // Unregister old hooks
301 await this.unregister(npmName)
303 return this.install(toUpdate, version, fromDisk)
306 async uninstall (npmName: string) {
307 logger.info('Uninstalling plugin %s.', npmName)
310 await this.unregister(npmName)
312 logger.warn('Cannot unregister plugin %s.', npmName, { err })
315 const plugin = await PluginModel.loadByNpmName(npmName)
316 if (!plugin || plugin.uninstalled === true) {
317 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
321 plugin.enabled = false
322 plugin.uninstalled = true
326 await removeNpmPlugin(npmName)
328 logger.info('Plugin %s uninstalled.', npmName)
331 // ###################### Private register ######################
333 private async registerPluginOrTheme (plugin: PluginModel) {
334 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
336 logger.info('Registering plugin or theme %s.', npmName)
338 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
339 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
341 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
343 let library: PluginLibrary
344 let registerHelpersStore: RegisterHelpersStore
345 if (plugin.type === PluginType.PLUGIN) {
346 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
347 library = result.library
348 registerHelpersStore = result.registerStore
351 const clientScripts: { [id: string]: ClientScript } = {}
352 for (const c of packageJSON.clientScripts) {
353 clientScripts[c.script] = c
356 this.registeredPlugins[npmName] = {
360 version: plugin.version,
361 description: plugin.description,
362 peertubeEngine: plugin.peertubeEngine,
364 staticDirs: packageJSON.staticDirs,
366 css: packageJSON.css,
367 registerHelpersStore: registerHelpersStore || undefined,
368 unregister: library ? library.unregister : undefined
371 await this.addTranslations(plugin, npmName, packageJSON.translations)
374 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
375 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
377 // Delete cache if needed
378 const modulePath = join(pluginPath, packageJSON.library)
379 delete require.cache[modulePath]
380 const library: PluginLibrary = require(modulePath)
382 if (!isLibraryCodeValid(library)) {
383 throw new Error('Library code is not valid (miss register or unregister function)')
386 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
387 library.register(registerOptions)
388 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
390 logger.info('Add plugin %s CSS to global file.', npmName)
392 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
394 return { library, registerStore }
397 // ###################### Translations ######################
399 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
400 for (const locale of Object.keys(translationPaths)) {
401 const path = translationPaths[locale]
402 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
404 if (!this.translations[locale]) this.translations[locale] = {}
405 this.translations[locale][npmName] = json
407 logger.info('Added locale %s of plugin %s.', locale, npmName)
411 private deleteTranslations (npmName: string) {
412 for (const locale of Object.keys(this.translations)) {
413 delete this.translations[locale][npmName]
415 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
419 // ###################### CSS ######################
421 private resetCSSGlobalFile () {
422 ClientHtml.invalidCache()
424 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
427 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
428 for (const cssPath of cssRelativePaths) {
429 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
432 ClientHtml.invalidCache()
435 private concatFiles (input: string, output: string) {
436 return new Promise<void>((res, rej) => {
437 const inputStream = createReadStream(input)
438 const outputStream = createWriteStream(output, { flags: 'a' })
440 inputStream.pipe(outputStream)
442 inputStream.on('end', () => res())
443 inputStream.on('error', err => rej(err))
447 private async regeneratePluginGlobalCSS () {
448 await this.resetCSSGlobalFile()
450 for (const plugin of this.getRegisteredPlugins()) {
451 await this.addCSSToGlobalFile(plugin.path, plugin.css)
455 // ###################### Utils ######################
457 private sortHooksByPriority () {
458 for (const hookName of Object.keys(this.hooks)) {
459 this.hooks[hookName].sort((a, b) => {
460 return b.priority - a.priority
465 private getPackageJSON (pluginName: string, pluginType: PluginType) {
466 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
468 return readJSON(pluginPath) as Promise<PluginPackageJson>
471 private getPluginPath (pluginName: string, pluginType: PluginType) {
472 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
474 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
477 private getAuth (npmName: string, authName: string) {
478 const plugin = this.getRegisteredPluginOrTheme(npmName)
479 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
481 return plugin.registerHelpersStore.getIdAndPassAuths()
482 .find(a => a.authName === authName)
485 // ###################### Private getters ######################
487 private getRegisteredPluginsOrThemes (type: PluginType) {
488 const plugins: RegisteredPlugin[] = []
490 for (const npmName of Object.keys(this.registeredPlugins)) {
491 const plugin = this.registeredPlugins[npmName]
492 if (plugin.type !== type) continue
500 // ###################### Generate register helpers ######################
502 private getRegisterHelpers (
505 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
506 const onHookAdded = (options: RegisterServerHookOptions) => {
507 if (!this.hooks[options.target]) this.hooks[options.target] = []
509 this.hooks[options.target].push({
511 pluginName: plugin.name,
512 handler: options.handler,
513 priority: options.priority || 0
517 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
520 registerStore: registerHelpersStore,
521 registerOptions: registerHelpersStore.buildRegisterHelpers()
525 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
526 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
527 if (!packageJSON.css) packageJSON.css = []
528 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
529 if (!packageJSON.translations) packageJSON.translations = {}
531 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
532 if (!packageJSONValid) {
533 const formattedFields = badFields.map(f => `"${f}"`)
536 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
540 static get Instance () {
541 return this.instance || (this.instance = new this())