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
45 export interface HookInformationValue {
52 type PluginLocalesTranslations = {
53 [locale: string]: PluginTranslation
56 export class PluginManager implements ServerHook {
58 private static instance: PluginManager
60 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
61 private hooks: { [name: string]: HookInformationValue[] } = {}
62 private translations: PluginLocalesTranslations = {}
64 private registerHelpersStore: { [npmName: string]: RegisterHelpersStore } = {}
66 private constructor () {
69 // ###################### Getters ######################
71 isRegistered (npmName: string) {
72 return !!this.getRegisteredPluginOrTheme(npmName)
75 getRegisteredPluginOrTheme (npmName: string) {
76 return this.registeredPlugins[npmName]
79 getRegisteredPlugin (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 getRegisteredTheme (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 getRegisteredSettings (npmName: string) {
106 const store = this.registerHelpersStore[npmName]
107 if (store) return store.getSettings()
112 getRouter (npmName: string) {
113 const store = this.registerHelpersStore[npmName]
114 if (!store) return null
116 return store.getRouter()
119 getTranslations (locale: string) {
120 return this.translations[locale] || {}
123 // ###################### Hooks ######################
125 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
126 if (!this.hooks[hookName]) return Promise.resolve(result)
128 const hookType = getHookType(hookName)
130 for (const hook of this.hooks[hookName]) {
131 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
133 result = await internalRunHook(hook.handler, hookType, result, params, err => {
134 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
141 // ###################### Registration ######################
143 async registerPluginsAndThemes () {
144 await this.resetCSSGlobalFile()
146 const plugins = await PluginModel.listEnabledPluginsAndThemes()
148 for (const plugin of plugins) {
150 await this.registerPluginOrTheme(plugin)
152 // Try to unregister the plugin
154 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
156 // we don't care if we cannot unregister it
159 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
163 this.sortHooksByPriority()
166 // Don't need the plugin type since themes cannot register server code
167 async unregister (npmName: string) {
168 logger.info('Unregister plugin %s.', npmName)
170 const plugin = this.getRegisteredPluginOrTheme(npmName)
173 throw new Error(`Unknown plugin ${npmName} to unregister`)
176 delete this.registeredPlugins[plugin.npmName]
178 this.deleteTranslations(plugin.npmName)
180 if (plugin.type === PluginType.PLUGIN) {
181 await plugin.unregister()
183 // Remove hooks of this plugin
184 for (const key of Object.keys(this.hooks)) {
185 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
188 const store = this.registerHelpersStore[plugin.npmName]
189 store.reinitVideoConstants(plugin.npmName)
191 delete this.registerHelpersStore[plugin.npmName]
193 logger.info('Regenerating registered plugin CSS to global file.')
194 await this.regeneratePluginGlobalCSS()
198 // ###################### Installation ######################
200 async install (toInstall: string, version?: string, fromDisk = false) {
201 let plugin: PluginModel
204 logger.info('Installing plugin %s.', toInstall)
208 ? await installNpmPluginFromDisk(toInstall)
209 : await installNpmPlugin(toInstall, version)
211 npmName = fromDisk ? basename(toInstall) : toInstall
212 const pluginType = PluginModel.getTypeFromNpmName(npmName)
213 const pluginName = PluginModel.normalizePluginName(npmName)
215 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
217 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
219 [ plugin ] = await PluginModel.upsert({
221 description: packageJSON.description,
222 homepage: packageJSON.homepage,
224 version: packageJSON.version,
227 peertubeEngine: packageJSON.engine.peertube
228 }, { returning: true })
230 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
233 await removeNpmPlugin(npmName)
235 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
241 logger.info('Successful installation of plugin %s.', toInstall)
243 await this.registerPluginOrTheme(plugin)
248 async update (toUpdate: string, version?: string, fromDisk = false) {
249 const npmName = fromDisk ? basename(toUpdate) : toUpdate
251 logger.info('Updating plugin %s.', npmName)
253 // Unregister old hooks
254 await this.unregister(npmName)
256 return this.install(toUpdate, version, fromDisk)
259 async uninstall (npmName: string) {
260 logger.info('Uninstalling plugin %s.', npmName)
263 await this.unregister(npmName)
265 logger.warn('Cannot unregister plugin %s.', npmName, { err })
268 const plugin = await PluginModel.loadByNpmName(npmName)
269 if (!plugin || plugin.uninstalled === true) {
270 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
274 plugin.enabled = false
275 plugin.uninstalled = true
279 await removeNpmPlugin(npmName)
281 logger.info('Plugin %s uninstalled.', npmName)
284 // ###################### Private register ######################
286 private async registerPluginOrTheme (plugin: PluginModel) {
287 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
289 logger.info('Registering plugin or theme %s.', npmName)
291 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
292 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
294 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
296 let library: PluginLibrary
297 if (plugin.type === PluginType.PLUGIN) {
298 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
301 const clientScripts: { [id: string]: ClientScript } = {}
302 for (const c of packageJSON.clientScripts) {
303 clientScripts[c.script] = c
306 this.registeredPlugins[npmName] = {
310 version: plugin.version,
311 description: plugin.description,
312 peertubeEngine: plugin.peertubeEngine,
314 staticDirs: packageJSON.staticDirs,
316 css: packageJSON.css,
317 unregister: library ? library.unregister : undefined
320 await this.addTranslations(plugin, npmName, packageJSON.translations)
323 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
324 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
326 // Delete cache if needed
327 const modulePath = join(pluginPath, packageJSON.library)
328 delete require.cache[modulePath]
329 const library: PluginLibrary = require(modulePath)
331 if (!isLibraryCodeValid(library)) {
332 throw new Error('Library code is not valid (miss register or unregister function)')
335 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
336 library.register(registerHelpers)
337 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
339 logger.info('Add plugin %s CSS to global file.', npmName)
341 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
346 // ###################### Translations ######################
348 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
349 for (const locale of Object.keys(translationPaths)) {
350 const path = translationPaths[locale]
351 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
353 if (!this.translations[locale]) this.translations[locale] = {}
354 this.translations[locale][npmName] = json
356 logger.info('Added locale %s of plugin %s.', locale, npmName)
360 private deleteTranslations (npmName: string) {
361 for (const locale of Object.keys(this.translations)) {
362 delete this.translations[locale][npmName]
364 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
368 // ###################### CSS ######################
370 private resetCSSGlobalFile () {
371 ClientHtml.invalidCache()
373 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
376 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
377 for (const cssPath of cssRelativePaths) {
378 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
381 ClientHtml.invalidCache()
384 private concatFiles (input: string, output: string) {
385 return new Promise<void>((res, rej) => {
386 const inputStream = createReadStream(input)
387 const outputStream = createWriteStream(output, { flags: 'a' })
389 inputStream.pipe(outputStream)
391 inputStream.on('end', () => res())
392 inputStream.on('error', err => rej(err))
396 private async regeneratePluginGlobalCSS () {
397 await this.resetCSSGlobalFile()
399 for (const plugin of this.getRegisteredPlugins()) {
400 await this.addCSSToGlobalFile(plugin.path, plugin.css)
404 // ###################### Utils ######################
406 private sortHooksByPriority () {
407 for (const hookName of Object.keys(this.hooks)) {
408 this.hooks[hookName].sort((a, b) => {
409 return b.priority - a.priority
414 private getPackageJSON (pluginName: string, pluginType: PluginType) {
415 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
417 return readJSON(pluginPath) as Promise<PluginPackageJson>
420 private getPluginPath (pluginName: string, pluginType: PluginType) {
421 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
423 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
426 // ###################### Private getters ######################
428 private getRegisteredPluginsOrThemes (type: PluginType) {
429 const plugins: RegisteredPlugin[] = []
431 for (const npmName of Object.keys(this.registeredPlugins)) {
432 const plugin = this.registeredPlugins[npmName]
433 if (plugin.type !== type) continue
441 // ###################### Generate register helpers ######################
443 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
444 const onHookAdded = (options: RegisterServerHookOptions) => {
445 if (!this.hooks[options.target]) this.hooks[options.target] = []
447 this.hooks[options.target].push({
449 pluginName: plugin.name,
450 handler: options.handler,
451 priority: options.priority || 0
455 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
456 this.registerHelpersStore[npmName] = registerHelpersStore
458 return registerHelpersStore.buildRegisterHelpers()
461 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
462 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
463 if (!packageJSON.css) packageJSON.css = []
464 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
465 if (!packageJSON.translations) packageJSON.translations = {}
467 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
468 if (!packageJSONValid) {
469 const formattedFields = badFields.map(f => `"${f}"`)
472 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
476 static get Instance () {
477 return this.instance || (this.instance = new this())