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 isRegistered (npmName: string) {
59 return !!this.getRegisteredPluginOrTheme(npmName)
62 getRegisteredPluginOrTheme (npmName: string) {
63 return this.registeredPlugins[npmName]
66 getRegisteredPlugin (name: string) {
67 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
68 const registered = this.getRegisteredPluginOrTheme(npmName)
70 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
75 getRegisteredTheme (name: string) {
76 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
77 const registered = this.getRegisteredPluginOrTheme(npmName)
79 if (!registered || registered.type !== PluginType.THEME) return undefined
84 getRegisteredPlugins () {
85 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
88 getRegisteredThemes () {
89 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
92 getRegisteredSettings (npmName: string) {
93 return this.settings[npmName] || []
96 // ###################### Hooks ######################
98 async runHook (hookName: string, param?: any) {
101 if (!this.hooks[hookName]) return result
103 const wait = hookName.startsWith('static:')
105 for (const hook of this.hooks[hookName]) {
107 const p = hook.handler(param)
111 } else if (p.catch) {
112 p.catch(err => logger.warn('Hook %s of plugin %s thrown an error.', hookName, hook.pluginName, { err }))
115 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
122 // ###################### Registration ######################
124 async registerPluginsAndThemes () {
125 await this.resetCSSGlobalFile()
127 const plugins = await PluginModel.listEnabledPluginsAndThemes()
129 for (const plugin of plugins) {
131 await this.registerPluginOrTheme(plugin)
133 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
137 this.sortHooksByPriority()
140 // Don't need the plugin type since themes cannot register server code
141 async unregister (npmName: string) {
142 logger.info('Unregister plugin %s.', npmName)
144 const plugin = this.getRegisteredPluginOrTheme(npmName)
147 throw new Error(`Unknown plugin ${npmName} to unregister`)
150 if (plugin.type === PluginType.PLUGIN) {
151 await plugin.unregister()
153 // Remove hooks of this plugin
154 for (const key of Object.keys(this.hooks)) {
155 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
158 logger.info('Regenerating registered plugin CSS to global file.')
159 await this.regeneratePluginGlobalCSS()
162 delete this.registeredPlugins[plugin.npmName]
165 // ###################### Installation ######################
167 async install (toInstall: string, version?: string, fromDisk = false) {
168 let plugin: PluginModel
171 logger.info('Installing plugin %s.', toInstall)
175 ? await installNpmPluginFromDisk(toInstall)
176 : await installNpmPlugin(toInstall, version)
178 npmName = fromDisk ? basename(toInstall) : toInstall
179 const pluginType = PluginModel.getTypeFromNpmName(npmName)
180 const pluginName = PluginModel.normalizePluginName(npmName)
182 const packageJSON = this.getPackageJSON(pluginName, pluginType)
183 if (!isPackageJSONValid(packageJSON, pluginType)) {
184 throw new Error('PackageJSON is invalid.')
187 [ plugin ] = await PluginModel.upsert({
189 description: packageJSON.description,
190 homepage: packageJSON.homepage,
192 version: packageJSON.version,
195 peertubeEngine: packageJSON.engine.peertube
196 }, { returning: true })
198 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
201 await removeNpmPlugin(npmName)
203 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
209 logger.info('Successful installation of plugin %s.', toInstall)
211 await this.registerPluginOrTheme(plugin)
216 async update (toUpdate: string, version?: string, fromDisk = false) {
217 const npmName = fromDisk ? basename(toUpdate) : toUpdate
219 logger.info('Updating plugin %s.', npmName)
221 // Unregister old hooks
222 await this.unregister(npmName)
224 return this.install(toUpdate, version, fromDisk)
227 async uninstall (npmName: string) {
228 logger.info('Uninstalling plugin %s.', npmName)
231 await this.unregister(npmName)
233 logger.warn('Cannot unregister plugin %s.', npmName, { err })
236 const plugin = await PluginModel.loadByNpmName(npmName)
237 if (!plugin || plugin.uninstalled === true) {
238 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
242 plugin.enabled = false
243 plugin.uninstalled = true
247 await removeNpmPlugin(npmName)
249 logger.info('Plugin %s uninstalled.', npmName)
252 // ###################### Private register ######################
254 private async registerPluginOrTheme (plugin: PluginModel) {
255 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
257 logger.info('Registering plugin or theme %s.', npmName)
259 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
260 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
262 if (!isPackageJSONValid(packageJSON, plugin.type)) {
263 throw new Error('Package.JSON is invalid.')
266 let library: PluginLibrary
267 if (plugin.type === PluginType.PLUGIN) {
268 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
271 const clientScripts: { [id: string]: ClientScript } = {}
272 for (const c of packageJSON.clientScripts) {
273 clientScripts[c.script] = c
276 this.registeredPlugins[ npmName ] = {
280 version: plugin.version,
281 description: plugin.description,
282 peertubeEngine: plugin.peertubeEngine,
284 staticDirs: packageJSON.staticDirs,
286 css: packageJSON.css,
287 unregister: library ? library.unregister : undefined
291 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
292 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
294 const registerHook = (options: RegisterHookOptions) => {
295 if (!this.hooks[options.target]) this.hooks[options.target] = []
297 this.hooks[options.target].push({
299 pluginName: plugin.name,
300 handler: options.handler,
301 priority: options.priority || 0
305 const registerSetting = (options: RegisterSettingOptions) => {
306 if (!this.settings[npmName]) this.settings[npmName] = []
308 this.settings[npmName].push(options)
311 const settingsManager: PluginSettingsManager = {
312 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
314 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
317 const storageManager: PluginStorageManager = {
318 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
320 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
323 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
325 if (!isLibraryCodeValid(library)) {
326 throw new Error('Library code is not valid (miss register or unregister function)')
334 }).catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
336 logger.info('Add plugin %s CSS to global file.', npmName)
338 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
343 // ###################### CSS ######################
345 private resetCSSGlobalFile () {
346 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
349 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
350 for (const cssPath of cssRelativePaths) {
351 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
355 private concatFiles (input: string, output: string) {
356 return new Promise<void>((res, rej) => {
357 const inputStream = createReadStream(input)
358 const outputStream = createWriteStream(output, { flags: 'a' })
360 inputStream.pipe(outputStream)
362 inputStream.on('end', () => res())
363 inputStream.on('error', err => rej(err))
367 private async regeneratePluginGlobalCSS () {
368 await this.resetCSSGlobalFile()
370 for (const key of Object.keys(this.getRegisteredPlugins())) {
371 const plugin = this.registeredPlugins[key]
373 await this.addCSSToGlobalFile(plugin.path, plugin.css)
377 // ###################### Utils ######################
379 private sortHooksByPriority () {
380 for (const hookName of Object.keys(this.hooks)) {
381 this.hooks[hookName].sort((a, b) => {
382 return b.priority - a.priority
387 private getPackageJSON (pluginName: string, pluginType: PluginType) {
388 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
390 return require(pluginPath) as PluginPackageJson
393 private getPluginPath (pluginName: string, pluginType: PluginType) {
394 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
396 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
399 // ###################### Private getters ######################
401 private getRegisteredPluginsOrThemes (type: PluginType) {
402 const plugins: RegisteredPlugin[] = []
404 for (const npmName of Object.keys(this.registeredPlugins)) {
405 const plugin = this.registeredPlugins[ npmName ]
406 if (plugin.type !== type) continue
414 static get Instance () {
415 return this.instance || (this.instance = new this())