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, serverHookObject } 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 { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
22 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
23 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
24 import { buildRegisterHelpers, reinitVideoConstants } from './register-helpers'
26 export interface RegisteredPlugin {
31 peertubeEngine: string
37 staticDirs: { [name: string]: string }
38 clientScripts: { [name: string]: ClientScript }
42 // Only if this is a plugin
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 } = {}
62 private settings: { [name: string]: RegisterServerSettingOptions[] } = {}
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 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 return this.settings[npmName] || []
109 getTranslations (locale: string) {
110 return this.translations[locale] || {}
113 // ###################### Hooks ######################
115 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
116 if (!this.hooks[hookName]) return Promise.resolve(result)
118 const hookType = getHookType(hookName)
120 for (const hook of this.hooks[hookName]) {
121 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
123 result = await internalRunHook(hook.handler, hookType, result, params, err => {
124 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
131 // ###################### Registration ######################
133 async registerPluginsAndThemes () {
134 await this.resetCSSGlobalFile()
136 const plugins = await PluginModel.listEnabledPluginsAndThemes()
138 for (const plugin of plugins) {
140 await this.registerPluginOrTheme(plugin)
142 // Try to unregister the plugin
144 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
146 // we don't care if we cannot unregister it
149 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
153 this.sortHooksByPriority()
156 // Don't need the plugin type since themes cannot register server code
157 async unregister (npmName: string) {
158 logger.info('Unregister plugin %s.', npmName)
160 const plugin = this.getRegisteredPluginOrTheme(npmName)
163 throw new Error(`Unknown plugin ${npmName} to unregister`)
166 delete this.registeredPlugins[plugin.npmName]
167 delete this.settings[plugin.npmName]
169 this.deleteTranslations(plugin.npmName)
171 if (plugin.type === PluginType.PLUGIN) {
172 await plugin.unregister()
174 // Remove hooks of this plugin
175 for (const key of Object.keys(this.hooks)) {
176 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
179 reinitVideoConstants(plugin.npmName)
181 logger.info('Regenerating registered plugin CSS to global file.')
182 await this.regeneratePluginGlobalCSS()
186 // ###################### Installation ######################
188 async install (toInstall: string, version?: string, fromDisk = false) {
189 let plugin: PluginModel
192 logger.info('Installing plugin %s.', toInstall)
196 ? await installNpmPluginFromDisk(toInstall)
197 : await installNpmPlugin(toInstall, version)
199 npmName = fromDisk ? basename(toInstall) : toInstall
200 const pluginType = PluginModel.getTypeFromNpmName(npmName)
201 const pluginName = PluginModel.normalizePluginName(npmName)
203 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
205 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
207 [ plugin ] = await PluginModel.upsert({
209 description: packageJSON.description,
210 homepage: packageJSON.homepage,
212 version: packageJSON.version,
215 peertubeEngine: packageJSON.engine.peertube
216 }, { returning: true })
218 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
221 await removeNpmPlugin(npmName)
223 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
229 logger.info('Successful installation of plugin %s.', toInstall)
231 await this.registerPluginOrTheme(plugin)
236 async update (toUpdate: string, version?: string, fromDisk = false) {
237 const npmName = fromDisk ? basename(toUpdate) : toUpdate
239 logger.info('Updating plugin %s.', npmName)
241 // Unregister old hooks
242 await this.unregister(npmName)
244 return this.install(toUpdate, version, fromDisk)
247 async uninstall (npmName: string) {
248 logger.info('Uninstalling plugin %s.', npmName)
251 await this.unregister(npmName)
253 logger.warn('Cannot unregister plugin %s.', npmName, { err })
256 const plugin = await PluginModel.loadByNpmName(npmName)
257 if (!plugin || plugin.uninstalled === true) {
258 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
262 plugin.enabled = false
263 plugin.uninstalled = true
267 await removeNpmPlugin(npmName)
269 logger.info('Plugin %s uninstalled.', npmName)
272 // ###################### Private register ######################
274 private async registerPluginOrTheme (plugin: PluginModel) {
275 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
277 logger.info('Registering plugin or theme %s.', npmName)
279 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
280 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
282 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
284 let library: PluginLibrary
285 if (plugin.type === PluginType.PLUGIN) {
286 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
289 const clientScripts: { [id: string]: ClientScript } = {}
290 for (const c of packageJSON.clientScripts) {
291 clientScripts[c.script] = c
294 this.registeredPlugins[npmName] = {
298 version: plugin.version,
299 description: plugin.description,
300 peertubeEngine: plugin.peertubeEngine,
302 staticDirs: packageJSON.staticDirs,
304 css: packageJSON.css,
305 unregister: library ? library.unregister : undefined
308 await this.addTranslations(plugin, npmName, packageJSON.translations)
311 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
312 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
314 // Delete cache if needed
315 const modulePath = join(pluginPath, packageJSON.library)
316 delete require.cache[modulePath]
317 const library: PluginLibrary = require(modulePath)
319 if (!isLibraryCodeValid(library)) {
320 throw new Error('Library code is not valid (miss register or unregister function)')
323 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
324 library.register(registerHelpers)
325 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
327 logger.info('Add plugin %s CSS to global file.', npmName)
329 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
334 // ###################### Translations ######################
336 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
337 for (const locale of Object.keys(translationPaths)) {
338 const path = translationPaths[locale]
339 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
341 if (!this.translations[locale]) this.translations[locale] = {}
342 this.translations[locale][npmName] = json
344 logger.info('Added locale %s of plugin %s.', locale, npmName)
348 private deleteTranslations (npmName: string) {
349 for (const locale of Object.keys(this.translations)) {
350 delete this.translations[locale][npmName]
352 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
356 // ###################### CSS ######################
358 private resetCSSGlobalFile () {
359 ClientHtml.invalidCache()
361 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
364 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
365 for (const cssPath of cssRelativePaths) {
366 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
369 ClientHtml.invalidCache()
372 private concatFiles (input: string, output: string) {
373 return new Promise<void>((res, rej) => {
374 const inputStream = createReadStream(input)
375 const outputStream = createWriteStream(output, { flags: 'a' })
377 inputStream.pipe(outputStream)
379 inputStream.on('end', () => res())
380 inputStream.on('error', err => rej(err))
384 private async regeneratePluginGlobalCSS () {
385 await this.resetCSSGlobalFile()
387 for (const plugin of this.getRegisteredPlugins()) {
388 await this.addCSSToGlobalFile(plugin.path, plugin.css)
392 // ###################### Utils ######################
394 private sortHooksByPriority () {
395 for (const hookName of Object.keys(this.hooks)) {
396 this.hooks[hookName].sort((a, b) => {
397 return b.priority - a.priority
402 private getPackageJSON (pluginName: string, pluginType: PluginType) {
403 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
405 return readJSON(pluginPath) as Promise<PluginPackageJson>
408 private getPluginPath (pluginName: string, pluginType: PluginType) {
409 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
411 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
414 // ###################### Private getters ######################
416 private getRegisteredPluginsOrThemes (type: PluginType) {
417 const plugins: RegisteredPlugin[] = []
419 for (const npmName of Object.keys(this.registeredPlugins)) {
420 const plugin = this.registeredPlugins[npmName]
421 if (plugin.type !== type) continue
429 // ###################### Generate register helpers ######################
431 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
432 const registerHook = (options: RegisterServerHookOptions) => {
433 if (serverHookObject[options.target] !== true) {
434 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
438 if (!this.hooks[options.target]) this.hooks[options.target] = []
440 this.hooks[options.target].push({
442 pluginName: plugin.name,
443 handler: options.handler,
444 priority: options.priority || 0
448 const registerSetting = (options: RegisterServerSettingOptions) => {
449 if (!this.settings[npmName]) this.settings[npmName] = []
451 this.settings[npmName].push(options)
454 const registerHelpers = buildRegisterHelpers(npmName, plugin)
456 return Object.assign(registerHelpers, {
462 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
463 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
464 if (!packageJSON.css) packageJSON.css = []
465 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
466 if (!packageJSON.translations) packageJSON.translations = {}
468 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
469 if (!packageJSONValid) {
470 const formattedFields = badFields.map(f => `"${f}"`)
473 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
477 static get Instance () {
478 return this.instance || (this.instance = new this())