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'
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()
107 .map(p => ({ npmName: p.npmName, idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths() }))
108 .filter(v => v.idAndPassAuths.length !== 0)
111 getExternalAuths () {
112 return this.getRegisteredPlugins()
113 .map(p => ({ npmName: p.npmName, externalAuths: p.registerHelpersStore.getExternalAuths() }))
114 .filter(v => v.externalAuths.length !== 0)
117 getRegisteredSettings (npmName: string) {
118 const result = this.getRegisteredPluginOrTheme(npmName)
119 if (!result || result.type !== PluginType.PLUGIN) return []
121 return result.registerHelpersStore.getSettings()
124 getRouter (npmName: string) {
125 const result = this.getRegisteredPluginOrTheme(npmName)
126 if (!result || result.type !== PluginType.PLUGIN) return null
128 return result.registerHelpersStore.getRouter()
131 getTranslations (locale: string) {
132 return this.translations[locale] || {}
135 onLogout (npmName: string, authName: string) {
136 const plugin = this.getRegisteredPluginOrTheme(npmName)
137 if (!plugin || plugin.type !== PluginType.PLUGIN) return
139 const auth = plugin.registerHelpersStore.getIdAndPassAuths()
140 .find(a => a.authName === authName)
146 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
151 // ###################### Hooks ######################
153 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
154 if (!this.hooks[hookName]) return Promise.resolve(result)
156 const hookType = getHookType(hookName)
158 for (const hook of this.hooks[hookName]) {
159 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
161 result = await internalRunHook(hook.handler, hookType, result, params, err => {
162 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
169 // ###################### Registration ######################
171 async registerPluginsAndThemes () {
172 await this.resetCSSGlobalFile()
174 const plugins = await PluginModel.listEnabledPluginsAndThemes()
176 for (const plugin of plugins) {
178 await this.registerPluginOrTheme(plugin)
180 // Try to unregister the plugin
182 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
184 // we don't care if we cannot unregister it
187 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
191 this.sortHooksByPriority()
194 // Don't need the plugin type since themes cannot register server code
195 async unregister (npmName: string) {
196 logger.info('Unregister plugin %s.', npmName)
198 const plugin = this.getRegisteredPluginOrTheme(npmName)
201 throw new Error(`Unknown plugin ${npmName} to unregister`)
204 delete this.registeredPlugins[plugin.npmName]
206 this.deleteTranslations(plugin.npmName)
208 if (plugin.type === PluginType.PLUGIN) {
209 await plugin.unregister()
211 // Remove hooks of this plugin
212 for (const key of Object.keys(this.hooks)) {
213 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
216 const store = plugin.registerHelpersStore
217 store.reinitVideoConstants(plugin.npmName)
219 logger.info('Regenerating registered plugin CSS to global file.')
220 await this.regeneratePluginGlobalCSS()
224 // ###################### Installation ######################
226 async install (toInstall: string, version?: string, fromDisk = false) {
227 let plugin: PluginModel
230 logger.info('Installing plugin %s.', toInstall)
234 ? await installNpmPluginFromDisk(toInstall)
235 : await installNpmPlugin(toInstall, version)
237 npmName = fromDisk ? basename(toInstall) : toInstall
238 const pluginType = PluginModel.getTypeFromNpmName(npmName)
239 const pluginName = PluginModel.normalizePluginName(npmName)
241 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
243 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
245 [ plugin ] = await PluginModel.upsert({
247 description: packageJSON.description,
248 homepage: packageJSON.homepage,
250 version: packageJSON.version,
253 peertubeEngine: packageJSON.engine.peertube
254 }, { returning: true })
256 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
259 await removeNpmPlugin(npmName)
261 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
267 logger.info('Successful installation of plugin %s.', toInstall)
269 await this.registerPluginOrTheme(plugin)
274 async update (toUpdate: string, version?: string, fromDisk = false) {
275 const npmName = fromDisk ? basename(toUpdate) : toUpdate
277 logger.info('Updating plugin %s.', npmName)
279 // Unregister old hooks
280 await this.unregister(npmName)
282 return this.install(toUpdate, version, fromDisk)
285 async uninstall (npmName: string) {
286 logger.info('Uninstalling plugin %s.', npmName)
289 await this.unregister(npmName)
291 logger.warn('Cannot unregister plugin %s.', npmName, { err })
294 const plugin = await PluginModel.loadByNpmName(npmName)
295 if (!plugin || plugin.uninstalled === true) {
296 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
300 plugin.enabled = false
301 plugin.uninstalled = true
305 await removeNpmPlugin(npmName)
307 logger.info('Plugin %s uninstalled.', npmName)
310 // ###################### Private register ######################
312 private async registerPluginOrTheme (plugin: PluginModel) {
313 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
315 logger.info('Registering plugin or theme %s.', npmName)
317 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
318 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
320 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
322 let library: PluginLibrary
323 let registerHelpersStore: RegisterHelpersStore
324 if (plugin.type === PluginType.PLUGIN) {
325 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
326 library = result.library
327 registerHelpersStore = result.registerStore
330 const clientScripts: { [id: string]: ClientScript } = {}
331 for (const c of packageJSON.clientScripts) {
332 clientScripts[c.script] = c
335 this.registeredPlugins[npmName] = {
339 version: plugin.version,
340 description: plugin.description,
341 peertubeEngine: plugin.peertubeEngine,
343 staticDirs: packageJSON.staticDirs,
345 css: packageJSON.css,
346 registerHelpersStore: registerHelpersStore || undefined,
347 unregister: library ? library.unregister : undefined
350 await this.addTranslations(plugin, npmName, packageJSON.translations)
353 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
354 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
356 // Delete cache if needed
357 const modulePath = join(pluginPath, packageJSON.library)
358 delete require.cache[modulePath]
359 const library: PluginLibrary = require(modulePath)
361 if (!isLibraryCodeValid(library)) {
362 throw new Error('Library code is not valid (miss register or unregister function)')
365 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
366 library.register(registerOptions)
367 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
369 logger.info('Add plugin %s CSS to global file.', npmName)
371 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
373 return { library, registerStore }
376 // ###################### Translations ######################
378 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
379 for (const locale of Object.keys(translationPaths)) {
380 const path = translationPaths[locale]
381 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
383 if (!this.translations[locale]) this.translations[locale] = {}
384 this.translations[locale][npmName] = json
386 logger.info('Added locale %s of plugin %s.', locale, npmName)
390 private deleteTranslations (npmName: string) {
391 for (const locale of Object.keys(this.translations)) {
392 delete this.translations[locale][npmName]
394 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
398 // ###################### CSS ######################
400 private resetCSSGlobalFile () {
401 ClientHtml.invalidCache()
403 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
406 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
407 for (const cssPath of cssRelativePaths) {
408 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
411 ClientHtml.invalidCache()
414 private concatFiles (input: string, output: string) {
415 return new Promise<void>((res, rej) => {
416 const inputStream = createReadStream(input)
417 const outputStream = createWriteStream(output, { flags: 'a' })
419 inputStream.pipe(outputStream)
421 inputStream.on('end', () => res())
422 inputStream.on('error', err => rej(err))
426 private async regeneratePluginGlobalCSS () {
427 await this.resetCSSGlobalFile()
429 for (const plugin of this.getRegisteredPlugins()) {
430 await this.addCSSToGlobalFile(plugin.path, plugin.css)
434 // ###################### Utils ######################
436 private sortHooksByPriority () {
437 for (const hookName of Object.keys(this.hooks)) {
438 this.hooks[hookName].sort((a, b) => {
439 return b.priority - a.priority
444 private getPackageJSON (pluginName: string, pluginType: PluginType) {
445 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
447 return readJSON(pluginPath) as Promise<PluginPackageJson>
450 private getPluginPath (pluginName: string, pluginType: PluginType) {
451 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
453 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
456 // ###################### Private getters ######################
458 private getRegisteredPluginsOrThemes (type: PluginType) {
459 const plugins: RegisteredPlugin[] = []
461 for (const npmName of Object.keys(this.registeredPlugins)) {
462 const plugin = this.registeredPlugins[npmName]
463 if (plugin.type !== type) continue
471 // ###################### Generate register helpers ######################
473 private getRegisterHelpers (
476 ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } {
477 const onHookAdded = (options: RegisterServerHookOptions) => {
478 if (!this.hooks[options.target]) this.hooks[options.target] = []
480 this.hooks[options.target].push({
482 pluginName: plugin.name,
483 handler: options.handler,
484 priority: options.priority || 0
488 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
491 registerStore: registerHelpersStore,
492 registerOptions: registerHelpersStore.buildRegisterHelpers()
496 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
497 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
498 if (!packageJSON.css) packageJSON.css = []
499 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
500 if (!packageJSON.translations) packageJSON.translations = {}
502 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
503 if (!packageJSONValid) {
504 const formattedFields = badFields.map(f => `"${f}"`)
507 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
511 static get Instance () {
512 return this.instance || (this.instance = new this())