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'
6 import { ClientScript, PluginPackageJson } from '../../../shared/models/plugins/plugin-package-json.model'
7 import { PluginLibrary } from '../../../shared/models/plugins/plugin-library.model'
8 import { createReadStream, createWriteStream } from 'fs'
9 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
10 import { PluginType } from '../../../shared/models/plugins/plugin.type'
11 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
12 import { outputFile } from 'fs-extra'
13 import { RegisterSettingOptions } from '../../../shared/models/plugins/register-setting.model'
14 import { RegisterHookOptions } from '../../../shared/models/plugins/register-hook.model'
15 import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
17 export interface RegisteredPlugin {
22 peertubeEngine: string
28 staticDirs: { [name: string]: string }
29 clientScripts: { [name: string]: ClientScript }
33 // Only if this is a plugin
37 export interface HookInformationValue {
44 export class PluginManager {
46 private static instance: PluginManager
48 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
49 private settings: { [ name: string ]: RegisterSettingOptions[] } = {}
50 private hooks: { [ name: string ]: HookInformationValue[] } = {}
52 private constructor () {
55 // ###################### Getters ######################
57 getRegisteredPluginOrTheme (npmName: string) {
58 return this.registeredPlugins[npmName]
61 getRegisteredPlugin (name: string) {
62 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
63 const registered = this.getRegisteredPluginOrTheme(npmName)
65 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
70 getRegisteredTheme (name: string) {
71 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
72 const registered = this.getRegisteredPluginOrTheme(npmName)
74 if (!registered || registered.type !== PluginType.THEME) return undefined
79 getRegisteredPlugins () {
80 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
83 getRegisteredThemes () {
84 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
87 getRegisteredSettings (npmName: string) {
88 return this.settings[npmName] || []
91 // ###################### Hooks ######################
93 async runHook (hookName: string, param?: any) {
96 if (!this.hooks[hookName]) return result
98 const wait = hookName.startsWith('static:')
100 for (const hook of this.hooks[hookName]) {
103 result = await hook.handler(param)
105 result = hook.handler()
108 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
115 // ###################### Registration ######################
117 async registerPluginsAndThemes () {
118 await this.resetCSSGlobalFile()
120 const plugins = await PluginModel.listEnabledPluginsAndThemes()
122 for (const plugin of plugins) {
124 await this.registerPluginOrTheme(plugin)
126 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
130 this.sortHooksByPriority()
133 // Don't need the plugin type since themes cannot register server code
134 async unregister (npmName: string) {
135 logger.info('Unregister plugin %s.', npmName)
137 const plugin = this.getRegisteredPluginOrTheme(npmName)
140 throw new Error(`Unknown plugin ${npmName} to unregister`)
143 if (plugin.type === PluginType.PLUGIN) {
144 await plugin.unregister()
146 // Remove hooks of this plugin
147 for (const key of Object.keys(this.hooks)) {
148 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
151 logger.info('Regenerating registered plugin CSS to global file.')
152 await this.regeneratePluginGlobalCSS()
155 delete this.registeredPlugins[plugin.npmName]
158 // ###################### Installation ######################
160 async install (toInstall: string, version?: string, fromDisk = false) {
161 let plugin: PluginModel
164 logger.info('Installing plugin %s.', toInstall)
168 ? await installNpmPluginFromDisk(toInstall)
169 : await installNpmPlugin(toInstall, version)
171 npmName = fromDisk ? basename(toInstall) : toInstall
172 const pluginType = PluginModel.getTypeFromNpmName(npmName)
173 const pluginName = PluginModel.normalizePluginName(npmName)
175 const packageJSON = this.getPackageJSON(pluginName, pluginType)
176 if (!isPackageJSONValid(packageJSON, pluginType)) {
177 throw new Error('PackageJSON is invalid.')
180 [ plugin ] = await PluginModel.upsert({
182 description: packageJSON.description,
183 homepage: packageJSON.homepage,
185 version: packageJSON.version,
188 peertubeEngine: packageJSON.engine.peertube
189 }, { returning: true })
191 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
194 await removeNpmPlugin(npmName)
196 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
202 logger.info('Successful installation of plugin %s.', toInstall)
204 await this.registerPluginOrTheme(plugin)
209 async update (toUpdate: string, version?: string, fromDisk = false) {
210 const npmName = fromDisk ? basename(toUpdate) : toUpdate
212 logger.info('Updating plugin %s.', npmName)
214 // Unregister old hooks
215 await this.unregister(npmName)
217 return this.install(toUpdate, version, fromDisk)
220 async uninstall (npmName: string) {
221 logger.info('Uninstalling plugin %s.', npmName)
224 await this.unregister(npmName)
226 logger.warn('Cannot unregister plugin %s.', npmName, { err })
229 const plugin = await PluginModel.loadByNpmName(npmName)
230 if (!plugin || plugin.uninstalled === true) {
231 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
235 plugin.enabled = false
236 plugin.uninstalled = true
240 await removeNpmPlugin(npmName)
242 logger.info('Plugin %s uninstalled.', npmName)
245 // ###################### Private register ######################
247 private async registerPluginOrTheme (plugin: PluginModel) {
248 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
250 logger.info('Registering plugin or theme %s.', npmName)
252 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
253 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
255 if (!isPackageJSONValid(packageJSON, plugin.type)) {
256 throw new Error('Package.JSON is invalid.')
259 let library: PluginLibrary
260 if (plugin.type === PluginType.PLUGIN) {
261 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
264 const clientScripts: { [id: string]: ClientScript } = {}
265 for (const c of packageJSON.clientScripts) {
266 clientScripts[c.script] = c
269 this.registeredPlugins[ npmName ] = {
273 version: plugin.version,
274 description: plugin.description,
275 peertubeEngine: plugin.peertubeEngine,
277 staticDirs: packageJSON.staticDirs,
279 css: packageJSON.css,
280 unregister: library ? library.unregister : undefined
284 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
285 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
287 const registerHook = (options: RegisterHookOptions) => {
288 if (!this.hooks[options.target]) this.hooks[options.target] = []
290 this.hooks[options.target].push({
292 pluginName: plugin.name,
293 handler: options.handler,
294 priority: options.priority || 0
298 const registerSetting = (options: RegisterSettingOptions) => {
299 if (!this.settings[npmName]) this.settings[npmName] = []
301 this.settings[npmName].push(options)
304 const settingsManager: PluginSettingsManager = {
305 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
307 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
310 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
312 if (!isLibraryCodeValid(library)) {
313 throw new Error('Library code is not valid (miss register or unregister function)')
316 library.register({ registerHook, registerSetting, settingsManager })
318 logger.info('Add plugin %s CSS to global file.', npmName)
320 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
325 // ###################### CSS ######################
327 private resetCSSGlobalFile () {
328 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
331 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
332 for (const cssPath of cssRelativePaths) {
333 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
337 private concatFiles (input: string, output: string) {
338 return new Promise<void>((res, rej) => {
339 const inputStream = createReadStream(input)
340 const outputStream = createWriteStream(output, { flags: 'a' })
342 inputStream.pipe(outputStream)
344 inputStream.on('end', () => res())
345 inputStream.on('error', err => rej(err))
349 private async regeneratePluginGlobalCSS () {
350 await this.resetCSSGlobalFile()
352 for (const key of Object.keys(this.registeredPlugins)) {
353 const plugin = this.registeredPlugins[key]
355 await this.addCSSToGlobalFile(plugin.path, plugin.css)
359 // ###################### Utils ######################
361 private sortHooksByPriority () {
362 for (const hookName of Object.keys(this.hooks)) {
363 this.hooks[hookName].sort((a, b) => {
364 return b.priority - a.priority
369 private getPackageJSON (pluginName: string, pluginType: PluginType) {
370 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
372 return require(pluginPath) as PluginPackageJson
375 private getPluginPath (pluginName: string, pluginType: PluginType) {
376 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
378 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
381 // ###################### Private getters ######################
383 private getRegisteredPluginsOrThemes (type: PluginType) {
384 const plugins: RegisteredPlugin[] = []
386 for (const npmName of Object.keys(this.registeredPlugins)) {
387 const plugin = this.registeredPlugins[ npmName ]
388 if (plugin.type !== type) continue
396 static get Instance () {
397 return this.instance || (this.instance = new this())