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'
16 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
18 export interface RegisteredPlugin {
23 peertubeEngine: string
29 staticDirs: { [name: string]: string }
30 clientScripts: { [name: string]: ClientScript }
34 // Only if this is a plugin
38 export interface HookInformationValue {
45 export class PluginManager {
47 private static instance: PluginManager
49 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
50 private settings: { [ name: string ]: RegisterSettingOptions[] } = {}
51 private hooks: { [ name: string ]: HookInformationValue[] } = {}
53 private constructor () {
56 // ###################### Getters ######################
58 getRegisteredPluginOrTheme (npmName: string) {
59 return this.registeredPlugins[npmName]
62 getRegisteredPlugin (name: string) {
63 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
64 const registered = this.getRegisteredPluginOrTheme(npmName)
66 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
71 getRegisteredTheme (name: string) {
72 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
73 const registered = this.getRegisteredPluginOrTheme(npmName)
75 if (!registered || registered.type !== PluginType.THEME) return undefined
80 getRegisteredPlugins () {
81 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
84 getRegisteredThemes () {
85 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
88 getRegisteredSettings (npmName: string) {
89 return this.settings[npmName] || []
92 // ###################### Hooks ######################
94 async runHook (hookName: string, param?: any) {
97 if (!this.hooks[hookName]) return result
99 const wait = hookName.startsWith('static:')
101 for (const hook of this.hooks[hookName]) {
104 result = await hook.handler(param)
106 result = hook.handler()
109 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
116 // ###################### Registration ######################
118 async registerPluginsAndThemes () {
119 await this.resetCSSGlobalFile()
121 const plugins = await PluginModel.listEnabledPluginsAndThemes()
123 for (const plugin of plugins) {
125 await this.registerPluginOrTheme(plugin)
127 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
131 this.sortHooksByPriority()
134 // Don't need the plugin type since themes cannot register server code
135 async unregister (npmName: string) {
136 logger.info('Unregister plugin %s.', npmName)
138 const plugin = this.getRegisteredPluginOrTheme(npmName)
141 throw new Error(`Unknown plugin ${npmName} to unregister`)
144 if (plugin.type === PluginType.PLUGIN) {
145 await plugin.unregister()
147 // Remove hooks of this plugin
148 for (const key of Object.keys(this.hooks)) {
149 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
152 logger.info('Regenerating registered plugin CSS to global file.')
153 await this.regeneratePluginGlobalCSS()
156 delete this.registeredPlugins[plugin.npmName]
159 // ###################### Installation ######################
161 async install (toInstall: string, version?: string, fromDisk = false) {
162 let plugin: PluginModel
165 logger.info('Installing plugin %s.', toInstall)
169 ? await installNpmPluginFromDisk(toInstall)
170 : await installNpmPlugin(toInstall, version)
172 npmName = fromDisk ? basename(toInstall) : toInstall
173 const pluginType = PluginModel.getTypeFromNpmName(npmName)
174 const pluginName = PluginModel.normalizePluginName(npmName)
176 const packageJSON = this.getPackageJSON(pluginName, pluginType)
177 if (!isPackageJSONValid(packageJSON, pluginType)) {
178 throw new Error('PackageJSON is invalid.')
181 [ plugin ] = await PluginModel.upsert({
183 description: packageJSON.description,
184 homepage: packageJSON.homepage,
186 version: packageJSON.version,
189 peertubeEngine: packageJSON.engine.peertube
190 }, { returning: true })
192 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
195 await removeNpmPlugin(npmName)
197 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
203 logger.info('Successful installation of plugin %s.', toInstall)
205 await this.registerPluginOrTheme(plugin)
210 async update (toUpdate: string, version?: string, fromDisk = false) {
211 const npmName = fromDisk ? basename(toUpdate) : toUpdate
213 logger.info('Updating plugin %s.', npmName)
215 // Unregister old hooks
216 await this.unregister(npmName)
218 return this.install(toUpdate, version, fromDisk)
221 async uninstall (npmName: string) {
222 logger.info('Uninstalling plugin %s.', npmName)
225 await this.unregister(npmName)
227 logger.warn('Cannot unregister plugin %s.', npmName, { err })
230 const plugin = await PluginModel.loadByNpmName(npmName)
231 if (!plugin || plugin.uninstalled === true) {
232 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
236 plugin.enabled = false
237 plugin.uninstalled = true
241 await removeNpmPlugin(npmName)
243 logger.info('Plugin %s uninstalled.', npmName)
246 // ###################### Private register ######################
248 private async registerPluginOrTheme (plugin: PluginModel) {
249 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
251 logger.info('Registering plugin or theme %s.', npmName)
253 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
254 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
256 if (!isPackageJSONValid(packageJSON, plugin.type)) {
257 throw new Error('Package.JSON is invalid.')
260 let library: PluginLibrary
261 if (plugin.type === PluginType.PLUGIN) {
262 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
265 const clientScripts: { [id: string]: ClientScript } = {}
266 for (const c of packageJSON.clientScripts) {
267 clientScripts[c.script] = c
270 this.registeredPlugins[ npmName ] = {
274 version: plugin.version,
275 description: plugin.description,
276 peertubeEngine: plugin.peertubeEngine,
278 staticDirs: packageJSON.staticDirs,
280 css: packageJSON.css,
281 unregister: library ? library.unregister : undefined
285 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
286 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
288 const registerHook = (options: RegisterHookOptions) => {
289 if (!this.hooks[options.target]) this.hooks[options.target] = []
291 this.hooks[options.target].push({
293 pluginName: plugin.name,
294 handler: options.handler,
295 priority: options.priority || 0
299 const registerSetting = (options: RegisterSettingOptions) => {
300 if (!this.settings[npmName]) this.settings[npmName] = []
302 this.settings[npmName].push(options)
305 const settingsManager: PluginSettingsManager = {
306 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
308 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
311 const storageManager: PluginStorageManager = {
312 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
314 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
317 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
319 if (!isLibraryCodeValid(library)) {
320 throw new Error('Library code is not valid (miss register or unregister function)')
330 logger.info('Add plugin %s CSS to global file.', npmName)
332 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
337 // ###################### CSS ######################
339 private resetCSSGlobalFile () {
340 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
343 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
344 for (const cssPath of cssRelativePaths) {
345 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
349 private concatFiles (input: string, output: string) {
350 return new Promise<void>((res, rej) => {
351 const inputStream = createReadStream(input)
352 const outputStream = createWriteStream(output, { flags: 'a' })
354 inputStream.pipe(outputStream)
356 inputStream.on('end', () => res())
357 inputStream.on('error', err => rej(err))
361 private async regeneratePluginGlobalCSS () {
362 await this.resetCSSGlobalFile()
364 for (const key of Object.keys(this.registeredPlugins)) {
365 const plugin = this.registeredPlugins[key]
367 await this.addCSSToGlobalFile(plugin.path, plugin.css)
371 // ###################### Utils ######################
373 private sortHooksByPriority () {
374 for (const hookName of Object.keys(this.hooks)) {
375 this.hooks[hookName].sort((a, b) => {
376 return b.priority - a.priority
381 private getPackageJSON (pluginName: string, pluginType: PluginType) {
382 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
384 return require(pluginPath) as PluginPackageJson
387 private getPluginPath (pluginName: string, pluginType: PluginType) {
388 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
390 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
393 // ###################### Private getters ######################
395 private getRegisteredPluginsOrThemes (type: PluginType) {
396 const plugins: RegisteredPlugin[] = []
398 for (const npmName of Object.keys(this.registeredPlugins)) {
399 const plugin = this.registeredPlugins[ npmName ]
400 if (plugin.type !== type) continue
408 static get Instance () {
409 return this.instance || (this.instance = new this())