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 onLogout (npmName: string, authName: string, user: MUser) {
148 const auth = this.getAuth(npmName, authName)
150 if (auth?.onLogout) {
151 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
156 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
161 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
162 const auth = this.getAuth(token.User.pluginAuth, token.authName)
163 if (!auth) return true
165 if (auth.hookTokenValidity) {
167 const { valid } = await auth.hookTokenValidity({ token, type })
169 if (valid === false) {
170 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
175 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
183 // ###################### Hooks ######################
185 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
186 if (!this.hooks[hookName]) return Promise.resolve(result)
188 const hookType = getHookType(hookName)
190 for (const hook of this.hooks[hookName]) {
191 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
193 result = await internalRunHook(hook.handler, hookType, result, params, err => {
194 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
201 // ###################### Registration ######################
203 async registerPluginsAndThemes () {
204 await this.resetCSSGlobalFile()
206 const plugins = await PluginModel.listEnabledPluginsAndThemes()
208 for (const plugin of plugins) {
210 await this.registerPluginOrTheme(plugin)
212 // Try to unregister the plugin
214 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
216 // we don't care if we cannot unregister it
219 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
223 this.sortHooksByPriority()
226 // Don't need the plugin type since themes cannot register server code
227 async unregister (npmName: string) {
228 logger.info('Unregister plugin %s.', npmName)
230 const plugin = this.getRegisteredPluginOrTheme(npmName)
233 throw new Error(`Unknown plugin ${npmName} to unregister`)
236 delete this.registeredPlugins[plugin.npmName]
238 this.deleteTranslations(plugin.npmName)
240 if (plugin.type === PluginType.PLUGIN) {
241 await plugin.unregister()
243 // Remove hooks of this plugin
244 for (const key of Object.keys(this.hooks)) {
245 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
248 const store = plugin.registerHelpersStore
249 store.reinitVideoConstants(plugin.npmName)
251 logger.info('Regenerating registered plugin CSS to global file.')
252 await this.regeneratePluginGlobalCSS()
256 // ###################### Installation ######################
258 async install (toInstall: string, version?: string, fromDisk = false) {
259 let plugin: PluginModel
262 logger.info('Installing plugin %s.', toInstall)
266 ? await installNpmPluginFromDisk(toInstall)
267 : await installNpmPlugin(toInstall, version)
269 npmName = fromDisk ? basename(toInstall) : toInstall
270 const pluginType = PluginModel.getTypeFromNpmName(npmName)
271 const pluginName = PluginModel.normalizePluginName(npmName)
273 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
275 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
277 [ plugin ] = await PluginModel.upsert({
279 description: packageJSON.description,
280 homepage: packageJSON.homepage,
282 version: packageJSON.version,
285 peertubeEngine: packageJSON.engine.peertube
286 }, { returning: true })
288 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
291 await removeNpmPlugin(npmName)
293 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
299 logger.info('Successful installation of plugin %s.', toInstall)
301 await this.registerPluginOrTheme(plugin)
306 async update (toUpdate: string, version?: string, fromDisk = false) {
307 const npmName = fromDisk ? basename(toUpdate) : toUpdate
309 logger.info('Updating plugin %s.', npmName)
311 // Unregister old hooks
312 await this.unregister(npmName)
314 return this.install(toUpdate, version, fromDisk)
317 async uninstall (npmName: string) {
318 logger.info('Uninstalling plugin %s.', npmName)
321 await this.unregister(npmName)
323 logger.warn('Cannot unregister plugin %s.', npmName, { err })
326 const plugin = await PluginModel.loadByNpmName(npmName)
327 if (!plugin || plugin.uninstalled === true) {
328 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
332 plugin.enabled = false
333 plugin.uninstalled = true
337 await removeNpmPlugin(npmName)
339 logger.info('Plugin %s uninstalled.', npmName)
342 // ###################### Private register ######################
344 private async registerPluginOrTheme (plugin: PluginModel) {
345 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
347 logger.info('Registering plugin or theme %s.', npmName)
349 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
350 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
352 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
354 let library: PluginLibrary
355 let registerHelpersStore: RegisterHelpersStore
356 if (plugin.type === PluginType.PLUGIN) {
357 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
358 library = result.library
359 registerHelpersStore = result.registerStore
362 const clientScripts: { [id: string]: ClientScript } = {}
363 for (const c of packageJSON.clientScripts) {
364 clientScripts[c.script] = c
367 this.registeredPlugins[npmName] = {
371 version: plugin.version,
372 description: plugin.description,
373 peertubeEngine: plugin.peertubeEngine,
375 staticDirs: packageJSON.staticDirs,
377 css: packageJSON.css,
378 registerHelpersStore: registerHelpersStore || undefined,
379 unregister: library ? library.unregister : undefined
382 await this.addTranslations(plugin, npmName, packageJSON.translations)
385 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
386 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
388 // Delete cache if needed
389 const modulePath = join(pluginPath, packageJSON.library)
390 delete require.cache[modulePath]
391 const library: PluginLibrary = require(modulePath)
393 if (!isLibraryCodeValid(library)) {
394 throw new Error('Library code is not valid (miss register or unregister function)')
397 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
398 library.register(registerOptions)
399 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
401 logger.info('Add plugin %s CSS to global file.', npmName)
403 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
405 return { library, registerStore }
408 // ###################### Translations ######################
410 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
411 for (const locale of Object.keys(translationPaths)) {
412 const path = translationPaths[locale]
413 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
415 if (!this.translations[locale]) this.translations[locale] = {}
416 this.translations[locale][npmName] = json
418 logger.info('Added locale %s of plugin %s.', locale, npmName)
422 private deleteTranslations (npmName: string) {
423 for (const locale of Object.keys(this.translations)) {
424 delete this.translations[locale][npmName]
426 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
430 // ###################### CSS ######################
432 private resetCSSGlobalFile () {
433 ClientHtml.invalidCache()
435 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
438 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
439 for (const cssPath of cssRelativePaths) {
440 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
443 ClientHtml.invalidCache()
446 private concatFiles (input: string, output: string) {
447 return new Promise<void>((res, rej) => {
448 const inputStream = createReadStream(input)
449 const outputStream = createWriteStream(output, { flags: 'a' })
451 inputStream.pipe(outputStream)
453 inputStream.on('end', () => res())
454 inputStream.on('error', err => rej(err))
458 private async regeneratePluginGlobalCSS () {
459 await this.resetCSSGlobalFile()
461 for (const plugin of this.getRegisteredPlugins()) {
462 await this.addCSSToGlobalFile(plugin.path, plugin.css)
466 // ###################### Utils ######################
468 private sortHooksByPriority () {
469 for (const hookName of Object.keys(this.hooks)) {
470 this.hooks[hookName].sort((a, b) => {
471 return b.priority - a.priority
476 private getPackageJSON (pluginName: string, pluginType: PluginType) {
477 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
479 return readJSON(pluginPath) as Promise<PluginPackageJson>
482 private getPluginPath (pluginName: string, pluginType: PluginType) {
483 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
485 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
488 private getAuth (npmName: string, authName: string) {
489 const plugin = this.getRegisteredPluginOrTheme(npmName)
490 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
492 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpersStore.getIdAndPassAuths()
493 auths = auths.concat(plugin.registerHelpersStore.getExternalAuths())
495 return auths.find(a => a.authName === authName)
498 // ###################### Private getters ######################
500 private getRegisteredPluginsOrThemes (type: PluginType) {
501 const plugins: RegisteredPlugin[] = []
503 for (const npmName of Object.keys(this.registeredPlugins)) {
504 const plugin = this.registeredPlugins[npmName]
505 if (plugin.type !== type) continue
513 // ###################### Generate register helpers ######################
515 private getRegisterHelpers (
518 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
519 const onHookAdded = (options: RegisterServerHookOptions) => {
520 if (!this.hooks[options.target]) this.hooks[options.target] = []
522 this.hooks[options.target].push({
524 pluginName: plugin.name,
525 handler: options.handler,
526 priority: options.priority || 0
530 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
533 registerStore: registerHelpersStore,
534 registerOptions: registerHelpersStore.buildRegisterHelpers()
538 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
539 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
540 if (!packageJSON.css) packageJSON.css = []
541 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
542 if (!packageJSON.translations) packageJSON.translations = {}
544 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
545 if (!packageJSONValid) {
546 const formattedFields = badFields.map(f => `"${f}"`)
549 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
553 static get Instance () {
554 return this.instance || (this.instance = new this())