1 import { createReadStream, createWriteStream } from 'fs'
2 import { outputFile, readJSON } from 'fs-extra'
3 import { basename, join } from 'path'
4 import { MOAuthTokenUser, MUser } from '@server/types/models'
5 import { RegisterServerHookOptions } from '@shared/models/plugins/register-server-hook.model'
6 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
10 PluginTranslationPaths as PackagePluginTranslations
11 } from '../../../shared/models/plugins/plugin-package-json.model'
12 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
13 import { PluginType } from '../../../shared/models/plugins/plugin.type'
14 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model'
15 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
16 import { logger } from '../../helpers/logger'
17 import { CONFIG } from '../../initializers/config'
18 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
19 import { PluginModel } from '../../models/server/plugin'
20 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
21 import { ClientHtml } from '../client-html'
22 import { RegisterHelpersStore } from './register-helpers-store'
23 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
25 export interface RegisteredPlugin {
30 peertubeEngine: string
36 staticDirs: { [name: string]: string }
37 clientScripts: { [name: string]: ClientScript }
41 // Only if this is a plugin
42 registerHelpersStore?: RegisterHelpersStore
46 export interface HookInformationValue {
53 type PluginLocalesTranslations = {
54 [locale: string]: PluginTranslation
57 export class PluginManager implements ServerHook {
59 private static instance: PluginManager
61 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
63 private hooks: { [name: string]: HookInformationValue[] } = {}
64 private translations: PluginLocalesTranslations = {}
66 private constructor () {
69 // ###################### Getters ######################
71 isRegistered (npmName: string) {
72 return !!this.getRegisteredPluginOrTheme(npmName)
75 getRegisteredPluginOrTheme (npmName: string) {
76 return this.registeredPlugins[npmName]
79 getRegisteredPluginByShortName (name: string) {
80 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
81 const registered = this.getRegisteredPluginOrTheme(npmName)
83 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
88 getRegisteredThemeByShortName (name: string) {
89 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
90 const registered = this.getRegisteredPluginOrTheme(npmName)
92 if (!registered || registered.type !== PluginType.THEME) return undefined
97 getRegisteredPlugins () {
98 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
101 getRegisteredThemes () {
102 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
105 getIdAndPassAuths () {
106 return this.getRegisteredPlugins()
111 idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths()
113 .filter(v => v.idAndPassAuths.length !== 0)
116 getExternalAuths () {
117 return this.getRegisteredPlugins()
122 externalAuths: p.registerHelpersStore.getExternalAuths()
124 .filter(v => v.externalAuths.length !== 0)
127 getRegisteredSettings (npmName: string) {
128 const result = this.getRegisteredPluginOrTheme(npmName)
129 if (!result || result.type !== PluginType.PLUGIN) return []
131 return result.registerHelpersStore.getSettings()
134 getRouter (npmName: string) {
135 const result = this.getRegisteredPluginOrTheme(npmName)
136 if (!result || result.type !== PluginType.PLUGIN) return null
138 return result.registerHelpersStore.getRouter()
141 getTranslations (locale: string) {
142 return this.translations[locale] || {}
145 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
146 const auth = this.getAuth(token.User.pluginAuth, token.authName)
147 if (!auth) return true
149 if (auth.hookTokenValidity) {
151 const { valid } = await auth.hookTokenValidity({ token, type })
153 if (valid === false) {
154 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
159 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
167 // ###################### External events ######################
169 onLogout (npmName: string, authName: string, user: MUser) {
170 const auth = this.getAuth(npmName, authName)
172 if (auth?.onLogout) {
173 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
178 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
183 onSettingsChanged (name: string, settings: any) {
184 const registered = this.getRegisteredPluginByShortName(name)
186 logger.error('Cannot find plugin %s to call on settings changed.', name)
189 for (const cb of registered.registerHelpersStore.getOnSettingsChangedCallbacks()) {
193 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
198 // ###################### Hooks ######################
200 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
201 if (!this.hooks[hookName]) return Promise.resolve(result)
203 const hookType = getHookType(hookName)
205 for (const hook of this.hooks[hookName]) {
206 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
208 result = await internalRunHook(hook.handler, hookType, result, params, err => {
209 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
216 // ###################### Registration ######################
218 async registerPluginsAndThemes () {
219 await this.resetCSSGlobalFile()
221 const plugins = await PluginModel.listEnabledPluginsAndThemes()
223 for (const plugin of plugins) {
225 await this.registerPluginOrTheme(plugin)
227 // Try to unregister the plugin
229 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
231 // we don't care if we cannot unregister it
234 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
238 this.sortHooksByPriority()
241 // Don't need the plugin type since themes cannot register server code
242 async unregister (npmName: string) {
243 logger.info('Unregister plugin %s.', npmName)
245 const plugin = this.getRegisteredPluginOrTheme(npmName)
248 throw new Error(`Unknown plugin ${npmName} to unregister`)
251 delete this.registeredPlugins[plugin.npmName]
253 this.deleteTranslations(plugin.npmName)
255 if (plugin.type === PluginType.PLUGIN) {
256 await plugin.unregister()
258 // Remove hooks of this plugin
259 for (const key of Object.keys(this.hooks)) {
260 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
263 const store = plugin.registerHelpersStore
264 store.reinitVideoConstants(plugin.npmName)
266 logger.info('Regenerating registered plugin CSS to global file.')
267 await this.regeneratePluginGlobalCSS()
271 // ###################### Installation ######################
273 async install (toInstall: string, version?: string, fromDisk = false) {
274 let plugin: PluginModel
277 logger.info('Installing plugin %s.', toInstall)
281 ? await installNpmPluginFromDisk(toInstall)
282 : await installNpmPlugin(toInstall, version)
284 npmName = fromDisk ? basename(toInstall) : toInstall
285 const pluginType = PluginModel.getTypeFromNpmName(npmName)
286 const pluginName = PluginModel.normalizePluginName(npmName)
288 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
290 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
292 [ plugin ] = await PluginModel.upsert({
294 description: packageJSON.description,
295 homepage: packageJSON.homepage,
297 version: packageJSON.version,
300 peertubeEngine: packageJSON.engine.peertube
301 }, { returning: true })
303 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
306 await removeNpmPlugin(npmName)
308 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
314 logger.info('Successful installation of plugin %s.', toInstall)
316 await this.registerPluginOrTheme(plugin)
321 async update (toUpdate: string, version?: string, fromDisk = false) {
322 const npmName = fromDisk ? basename(toUpdate) : toUpdate
324 logger.info('Updating plugin %s.', npmName)
326 // Unregister old hooks
327 await this.unregister(npmName)
329 return this.install(toUpdate, version, fromDisk)
332 async uninstall (npmName: string) {
333 logger.info('Uninstalling plugin %s.', npmName)
336 await this.unregister(npmName)
338 logger.warn('Cannot unregister plugin %s.', npmName, { err })
341 const plugin = await PluginModel.loadByNpmName(npmName)
342 if (!plugin || plugin.uninstalled === true) {
343 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
347 plugin.enabled = false
348 plugin.uninstalled = true
352 await removeNpmPlugin(npmName)
354 logger.info('Plugin %s uninstalled.', npmName)
357 // ###################### Private register ######################
359 private async registerPluginOrTheme (plugin: PluginModel) {
360 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
362 logger.info('Registering plugin or theme %s.', npmName)
364 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
365 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
367 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
369 let library: PluginLibrary
370 let registerHelpersStore: RegisterHelpersStore
371 if (plugin.type === PluginType.PLUGIN) {
372 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
373 library = result.library
374 registerHelpersStore = result.registerStore
377 const clientScripts: { [id: string]: ClientScript } = {}
378 for (const c of packageJSON.clientScripts) {
379 clientScripts[c.script] = c
382 this.registeredPlugins[npmName] = {
386 version: plugin.version,
387 description: plugin.description,
388 peertubeEngine: plugin.peertubeEngine,
390 staticDirs: packageJSON.staticDirs,
392 css: packageJSON.css,
393 registerHelpersStore: registerHelpersStore || undefined,
394 unregister: library ? library.unregister : undefined
397 await this.addTranslations(plugin, npmName, packageJSON.translations)
400 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
401 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
403 // Delete cache if needed
404 const modulePath = join(pluginPath, packageJSON.library)
405 delete require.cache[modulePath]
406 const library: PluginLibrary = require(modulePath)
408 if (!isLibraryCodeValid(library)) {
409 throw new Error('Library code is not valid (miss register or unregister function)')
412 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
413 library.register(registerOptions)
414 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
416 logger.info('Add plugin %s CSS to global file.', npmName)
418 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
420 return { library, registerStore }
423 // ###################### Translations ######################
425 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
426 for (const locale of Object.keys(translationPaths)) {
427 const path = translationPaths[locale]
428 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
430 if (!this.translations[locale]) this.translations[locale] = {}
431 this.translations[locale][npmName] = json
433 logger.info('Added locale %s of plugin %s.', locale, npmName)
437 private deleteTranslations (npmName: string) {
438 for (const locale of Object.keys(this.translations)) {
439 delete this.translations[locale][npmName]
441 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
445 // ###################### CSS ######################
447 private resetCSSGlobalFile () {
448 ClientHtml.invalidCache()
450 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
453 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
454 for (const cssPath of cssRelativePaths) {
455 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
458 ClientHtml.invalidCache()
461 private concatFiles (input: string, output: string) {
462 return new Promise<void>((res, rej) => {
463 const inputStream = createReadStream(input)
464 const outputStream = createWriteStream(output, { flags: 'a' })
466 inputStream.pipe(outputStream)
468 inputStream.on('end', () => res())
469 inputStream.on('error', err => rej(err))
473 private async regeneratePluginGlobalCSS () {
474 await this.resetCSSGlobalFile()
476 for (const plugin of this.getRegisteredPlugins()) {
477 await this.addCSSToGlobalFile(plugin.path, plugin.css)
481 // ###################### Utils ######################
483 private sortHooksByPriority () {
484 for (const hookName of Object.keys(this.hooks)) {
485 this.hooks[hookName].sort((a, b) => {
486 return b.priority - a.priority
491 private getPackageJSON (pluginName: string, pluginType: PluginType) {
492 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
494 return readJSON(pluginPath) as Promise<PluginPackageJson>
497 private getPluginPath (pluginName: string, pluginType: PluginType) {
498 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
500 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
503 private getAuth (npmName: string, authName: string) {
504 const plugin = this.getRegisteredPluginOrTheme(npmName)
505 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
507 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpersStore.getIdAndPassAuths()
508 auths = auths.concat(plugin.registerHelpersStore.getExternalAuths())
510 return auths.find(a => a.authName === authName)
513 // ###################### Private getters ######################
515 private getRegisteredPluginsOrThemes (type: PluginType) {
516 const plugins: RegisteredPlugin[] = []
518 for (const npmName of Object.keys(this.registeredPlugins)) {
519 const plugin = this.registeredPlugins[npmName]
520 if (plugin.type !== type) continue
528 // ###################### Generate register helpers ######################
530 private getRegisterHelpers (
533 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
534 const onHookAdded = (options: RegisterServerHookOptions) => {
535 if (!this.hooks[options.target]) this.hooks[options.target] = []
537 this.hooks[options.target].push({
539 pluginName: plugin.name,
540 handler: options.handler,
541 priority: options.priority || 0
545 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
548 registerStore: registerHelpersStore,
549 registerOptions: registerHelpersStore.buildRegisterHelpers()
553 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
554 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
555 if (!packageJSON.css) packageJSON.css = []
556 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
557 if (!packageJSON.translations) packageJSON.translations = {}
559 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
560 if (!packageJSONValid) {
561 const formattedFields = badFields.map(f => `"${f}"`)
564 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
568 static get Instance () {
569 return this.instance || (this.instance = new this())