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, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } 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 { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
17 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
18 import { ServerHook, ServerHookName, serverHookObject } from '../../../shared/models/plugins/server-hook.model'
19 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
20 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
21 import { PluginLibrary } from '../../typings/plugins'
22 import { ClientHtml } from '../client-html'
23 import { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
24 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
25 import { PluginVideoLanguageManager } from '../../../shared/models/plugins/plugin-video-language-manager.model'
26 import { PluginVideoCategoryManager } from '../../../shared/models/plugins/plugin-video-category-manager.model'
27 import { PluginVideoLicenceManager } from '../../../shared/models/plugins/plugin-video-licence-manager.model'
28 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
30 export interface RegisteredPlugin {
35 peertubeEngine: string
41 staticDirs: { [name: string]: string }
42 clientScripts: { [name: string]: ClientScript }
46 // Only if this is a plugin
50 export interface HookInformationValue {
57 type AlterableVideoConstant = 'language' | 'licence' | 'category'
58 type VideoConstant = { [ key in number | string ]: string }
59 type UpdatedVideoConstant = {
60 [ name in AlterableVideoConstant ]: {
61 [ npmName: string ]: {
62 added: { key: number | string, label: string }[],
63 deleted: { key: number | string, label: string }[]
68 type PluginLocalesTranslations = {
69 [ locale: string ]: PluginTranslation
72 export class PluginManager implements ServerHook {
74 private static instance: PluginManager
76 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
77 private settings: { [ name: string ]: RegisterServerSettingOptions[] } = {}
78 private hooks: { [ name: string ]: HookInformationValue[] } = {}
79 private translations: PluginLocalesTranslations = {}
81 private updatedVideoConstants: UpdatedVideoConstant = {
87 private constructor () {
90 // ###################### Getters ######################
92 isRegistered (npmName: string) {
93 return !!this.getRegisteredPluginOrTheme(npmName)
96 getRegisteredPluginOrTheme (npmName: string) {
97 return this.registeredPlugins[npmName]
100 getRegisteredPlugin (name: string) {
101 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
102 const registered = this.getRegisteredPluginOrTheme(npmName)
104 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
109 getRegisteredTheme (name: string) {
110 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
111 const registered = this.getRegisteredPluginOrTheme(npmName)
113 if (!registered || registered.type !== PluginType.THEME) return undefined
118 getRegisteredPlugins () {
119 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
122 getRegisteredThemes () {
123 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
126 getRegisteredSettings (npmName: string) {
127 return this.settings[npmName] || []
130 getTranslations (locale: string) {
131 return this.translations[locale] || {}
134 // ###################### Hooks ######################
136 async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
137 if (!this.hooks[hookName]) return Promise.resolve(result)
139 const hookType = getHookType(hookName)
141 for (const hook of this.hooks[hookName]) {
142 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
144 result = await internalRunHook(hook.handler, hookType, result, params, err => {
145 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
152 // ###################### Registration ######################
154 async registerPluginsAndThemes () {
155 await this.resetCSSGlobalFile()
157 const plugins = await PluginModel.listEnabledPluginsAndThemes()
159 for (const plugin of plugins) {
161 await this.registerPluginOrTheme(plugin)
163 // Try to unregister the plugin
165 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
167 // we don't care if we cannot unregister it
170 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
174 this.sortHooksByPriority()
177 // Don't need the plugin type since themes cannot register server code
178 async unregister (npmName: string) {
179 logger.info('Unregister plugin %s.', npmName)
181 const plugin = this.getRegisteredPluginOrTheme(npmName)
184 throw new Error(`Unknown plugin ${npmName} to unregister`)
187 delete this.registeredPlugins[plugin.npmName]
188 delete this.settings[plugin.npmName]
190 this.deleteTranslations(plugin.npmName)
192 if (plugin.type === PluginType.PLUGIN) {
193 await plugin.unregister()
195 // Remove hooks of this plugin
196 for (const key of Object.keys(this.hooks)) {
197 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
200 this.reinitVideoConstants(plugin.npmName)
202 logger.info('Regenerating registered plugin CSS to global file.')
203 await this.regeneratePluginGlobalCSS()
207 // ###################### Installation ######################
209 async install (toInstall: string, version?: string, fromDisk = false) {
210 let plugin: PluginModel
213 logger.info('Installing plugin %s.', toInstall)
217 ? await installNpmPluginFromDisk(toInstall)
218 : await installNpmPlugin(toInstall, version)
220 npmName = fromDisk ? basename(toInstall) : toInstall
221 const pluginType = PluginModel.getTypeFromNpmName(npmName)
222 const pluginName = PluginModel.normalizePluginName(npmName)
224 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
226 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
228 [ plugin ] = await PluginModel.upsert({
230 description: packageJSON.description,
231 homepage: packageJSON.homepage,
233 version: packageJSON.version,
236 peertubeEngine: packageJSON.engine.peertube
237 }, { returning: true })
239 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
242 await removeNpmPlugin(npmName)
244 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
250 logger.info('Successful installation of plugin %s.', toInstall)
252 await this.registerPluginOrTheme(plugin)
257 async update (toUpdate: string, version?: string, fromDisk = false) {
258 const npmName = fromDisk ? basename(toUpdate) : toUpdate
260 logger.info('Updating plugin %s.', npmName)
262 // Unregister old hooks
263 await this.unregister(npmName)
265 return this.install(toUpdate, version, fromDisk)
268 async uninstall (npmName: string) {
269 logger.info('Uninstalling plugin %s.', npmName)
272 await this.unregister(npmName)
274 logger.warn('Cannot unregister plugin %s.', npmName, { err })
277 const plugin = await PluginModel.loadByNpmName(npmName)
278 if (!plugin || plugin.uninstalled === true) {
279 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
283 plugin.enabled = false
284 plugin.uninstalled = true
288 await removeNpmPlugin(npmName)
290 logger.info('Plugin %s uninstalled.', npmName)
293 // ###################### Private register ######################
295 private async registerPluginOrTheme (plugin: PluginModel) {
296 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
298 logger.info('Registering plugin or theme %s.', npmName)
300 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
301 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
303 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
305 let library: PluginLibrary
306 if (plugin.type === PluginType.PLUGIN) {
307 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
310 const clientScripts: { [id: string]: ClientScript } = {}
311 for (const c of packageJSON.clientScripts) {
312 clientScripts[c.script] = c
315 this.registeredPlugins[ npmName ] = {
319 version: plugin.version,
320 description: plugin.description,
321 peertubeEngine: plugin.peertubeEngine,
323 staticDirs: packageJSON.staticDirs,
325 css: packageJSON.css,
326 unregister: library ? library.unregister : undefined
329 await this.addTranslations(plugin, npmName, packageJSON.translations)
332 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
333 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
335 // Delete cache if needed
336 const modulePath = join(pluginPath, packageJSON.library)
337 delete require.cache[modulePath]
338 const library: PluginLibrary = require(modulePath)
340 if (!isLibraryCodeValid(library)) {
341 throw new Error('Library code is not valid (miss register or unregister function)')
344 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
345 library.register(registerHelpers)
346 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
348 logger.info('Add plugin %s CSS to global file.', npmName)
350 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
355 // ###################### Translations ######################
357 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
358 for (const locale of Object.keys(translationPaths)) {
359 const path = translationPaths[locale]
360 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
362 if (!this.translations[locale]) this.translations[locale] = {}
363 this.translations[locale][npmName] = json
365 logger.info('Added locale %s of plugin %s.', locale, npmName)
369 private deleteTranslations (npmName: string) {
370 for (const locale of Object.keys(this.translations)) {
371 delete this.translations[locale][npmName]
373 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
377 // ###################### CSS ######################
379 private resetCSSGlobalFile () {
380 ClientHtml.invalidCache()
382 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
385 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
386 for (const cssPath of cssRelativePaths) {
387 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
390 ClientHtml.invalidCache()
393 private concatFiles (input: string, output: string) {
394 return new Promise<void>((res, rej) => {
395 const inputStream = createReadStream(input)
396 const outputStream = createWriteStream(output, { flags: 'a' })
398 inputStream.pipe(outputStream)
400 inputStream.on('end', () => res())
401 inputStream.on('error', err => rej(err))
405 private async regeneratePluginGlobalCSS () {
406 await this.resetCSSGlobalFile()
408 for (const plugin of this.getRegisteredPlugins()) {
409 await this.addCSSToGlobalFile(plugin.path, plugin.css)
413 // ###################### Utils ######################
415 private sortHooksByPriority () {
416 for (const hookName of Object.keys(this.hooks)) {
417 this.hooks[hookName].sort((a, b) => {
418 return b.priority - a.priority
423 private getPackageJSON (pluginName: string, pluginType: PluginType) {
424 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
426 return readJSON(pluginPath) as Promise<PluginPackageJson>
429 private getPluginPath (pluginName: string, pluginType: PluginType) {
430 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
432 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
435 // ###################### Private getters ######################
437 private getRegisteredPluginsOrThemes (type: PluginType) {
438 const plugins: RegisteredPlugin[] = []
440 for (const npmName of Object.keys(this.registeredPlugins)) {
441 const plugin = this.registeredPlugins[ npmName ]
442 if (plugin.type !== type) continue
450 // ###################### Generate register helpers ######################
452 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
453 const registerHook = (options: RegisterServerHookOptions) => {
454 if (serverHookObject[options.target] !== true) {
455 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
459 if (!this.hooks[options.target]) this.hooks[options.target] = []
461 this.hooks[options.target].push({
463 pluginName: plugin.name,
464 handler: options.handler,
465 priority: options.priority || 0
469 const registerSetting = (options: RegisterServerSettingOptions) => {
470 if (!this.settings[npmName]) this.settings[npmName] = []
472 this.settings[npmName].push(options)
475 const settingsManager: PluginSettingsManager = {
476 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
478 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
481 const storageManager: PluginStorageManager = {
482 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
484 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
487 const videoLanguageManager: PluginVideoLanguageManager = {
488 addLanguage: (key: string, label: string) => this.addConstant({ npmName, type: 'language', obj: VIDEO_LANGUAGES, key, label }),
490 deleteLanguage: (key: string) => this.deleteConstant({ npmName, type: 'language', obj: VIDEO_LANGUAGES, key })
493 const videoCategoryManager: PluginVideoCategoryManager = {
494 addCategory: (key: number, label: string) => this.addConstant({ npmName, type: 'category', obj: VIDEO_CATEGORIES, key, label }),
496 deleteCategory: (key: number) => this.deleteConstant({ npmName, type: 'category', obj: VIDEO_CATEGORIES, key })
499 const videoLicenceManager: PluginVideoLicenceManager = {
500 addLicence: (key: number, label: string) => this.addConstant({ npmName, type: 'licence', obj: VIDEO_LICENCES, key, label }),
502 deleteLicence: (key: number) => this.deleteConstant({ npmName, type: 'licence', obj: VIDEO_LICENCES, key })
505 const peertubeHelpers = {
514 videoLanguageManager,
515 videoCategoryManager,
521 private addConstant <T extends string | number> (parameters: {
523 type: AlterableVideoConstant,
528 const { npmName, type, obj, key, label } = parameters
531 logger.warn('Cannot add %s %s by plugin %s: key already exists.', type, npmName, key)
535 if (!this.updatedVideoConstants[type][npmName]) {
536 this.updatedVideoConstants[type][npmName] = {
542 this.updatedVideoConstants[type][npmName].added.push({ key, label })
548 private deleteConstant <T extends string | number> (parameters: {
550 type: AlterableVideoConstant,
554 const { npmName, type, obj, key } = parameters
557 logger.warn('Cannot delete %s %s by plugin %s: key does not exist.', type, npmName, key)
561 if (!this.updatedVideoConstants[type][npmName]) {
562 this.updatedVideoConstants[type][npmName] = {
568 this.updatedVideoConstants[type][npmName].deleted.push({ key, label: obj[key] })
574 private reinitVideoConstants (npmName: string) {
576 language: VIDEO_LANGUAGES,
577 licence: VIDEO_LICENCES,
578 category: VIDEO_CATEGORIES
580 const types: AlterableVideoConstant[] = [ 'language', 'licence', 'category' ]
582 for (const type of types) {
583 const updatedConstants = this.updatedVideoConstants[type][npmName]
584 if (!updatedConstants) continue
586 for (const added of updatedConstants.added) {
587 delete hash[type][added.key]
590 for (const deleted of updatedConstants.deleted) {
591 hash[type][deleted.key] = deleted.label
594 delete this.updatedVideoConstants[type][npmName]
598 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
599 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
600 if (!packageJSON.css) packageJSON.css = []
601 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
602 if (!packageJSON.translations) packageJSON.translations = {}
604 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
605 if (!packageJSONValid) {
606 const formattedFields = badFields.map(f => `"${f}"`)
609 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
613 static get Instance () {
614 return this.instance || (this.instance = new this())