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 { createReadStream, createWriteStream } from 'fs'
8 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
9 import { PluginType } from '../../../shared/models/plugins/plugin.type'
10 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
11 import { outputFile, readJSON } from 'fs-extra'
12 import { RegisterSettingOptions } from '../../../shared/models/plugins/register-setting.model'
13 import { RegisterHookOptions } from '../../../shared/models/plugins/register-hook.model'
14 import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
15 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
16 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model'
17 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
18 import { RegisterOptions } from '../../typings/plugins/register-options.model'
19 import { PluginLibrary } from '../../typings/plugins'
21 export interface RegisteredPlugin {
26 peertubeEngine: string
32 staticDirs: { [name: string]: string }
33 clientScripts: { [name: string]: ClientScript }
37 // Only if this is a plugin
41 export interface HookInformationValue {
48 export class PluginManager implements ServerHook {
50 private static instance: PluginManager
52 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
53 private settings: { [ name: string ]: RegisterSettingOptions[] } = {}
54 private hooks: { [ name: string ]: HookInformationValue[] } = {}
56 private constructor () {
59 // ###################### Getters ######################
61 isRegistered (npmName: string) {
62 return !!this.getRegisteredPluginOrTheme(npmName)
65 getRegisteredPluginOrTheme (npmName: string) {
66 return this.registeredPlugins[npmName]
69 getRegisteredPlugin (name: string) {
70 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
71 const registered = this.getRegisteredPluginOrTheme(npmName)
73 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
78 getRegisteredTheme (name: string) {
79 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
80 const registered = this.getRegisteredPluginOrTheme(npmName)
82 if (!registered || registered.type !== PluginType.THEME) return undefined
87 getRegisteredPlugins () {
88 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
91 getRegisteredThemes () {
92 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
95 getRegisteredSettings (npmName: string) {
96 return this.settings[npmName] || []
99 // ###################### Hooks ######################
101 async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
102 if (!this.hooks[hookName]) return Promise.resolve(result)
104 const hookType = getHookType(hookName)
106 for (const hook of this.hooks[hookName]) {
107 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
109 result = await internalRunHook(hook.handler, hookType, result, params, err => {
110 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
117 // ###################### Registration ######################
119 async registerPluginsAndThemes () {
120 await this.resetCSSGlobalFile()
122 const plugins = await PluginModel.listEnabledPluginsAndThemes()
124 for (const plugin of plugins) {
126 await this.registerPluginOrTheme(plugin)
128 // Try to unregister the plugin
130 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
132 // we don't care if we cannot unregister it
135 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
139 this.sortHooksByPriority()
142 // Don't need the plugin type since themes cannot register server code
143 async unregister (npmName: string) {
144 logger.info('Unregister plugin %s.', npmName)
146 const plugin = this.getRegisteredPluginOrTheme(npmName)
149 throw new Error(`Unknown plugin ${npmName} to unregister`)
152 delete this.registeredPlugins[plugin.npmName]
154 if (plugin.type === PluginType.PLUGIN) {
155 await plugin.unregister()
157 // Remove hooks of this plugin
158 for (const key of Object.keys(this.hooks)) {
159 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
162 logger.info('Regenerating registered plugin CSS to global file.')
163 await this.regeneratePluginGlobalCSS()
167 // ###################### Installation ######################
169 async install (toInstall: string, version?: string, fromDisk = false) {
170 let plugin: PluginModel
173 logger.info('Installing plugin %s.', toInstall)
177 ? await installNpmPluginFromDisk(toInstall)
178 : await installNpmPlugin(toInstall, version)
180 npmName = fromDisk ? basename(toInstall) : toInstall
181 const pluginType = PluginModel.getTypeFromNpmName(npmName)
182 const pluginName = PluginModel.normalizePluginName(npmName)
184 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
185 if (!isPackageJSONValid(packageJSON, pluginType)) {
186 throw new Error('PackageJSON is invalid.')
189 [ plugin ] = await PluginModel.upsert({
191 description: packageJSON.description,
192 homepage: packageJSON.homepage,
194 version: packageJSON.version,
197 peertubeEngine: packageJSON.engine.peertube
198 }, { returning: true })
200 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
203 await removeNpmPlugin(npmName)
205 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
211 logger.info('Successful installation of plugin %s.', toInstall)
213 await this.registerPluginOrTheme(plugin)
218 async update (toUpdate: string, version?: string, fromDisk = false) {
219 const npmName = fromDisk ? basename(toUpdate) : toUpdate
221 logger.info('Updating plugin %s.', npmName)
223 // Unregister old hooks
224 await this.unregister(npmName)
226 return this.install(toUpdate, version, fromDisk)
229 async uninstall (npmName: string) {
230 logger.info('Uninstalling plugin %s.', npmName)
233 await this.unregister(npmName)
235 logger.warn('Cannot unregister plugin %s.', npmName, { err })
238 const plugin = await PluginModel.loadByNpmName(npmName)
239 if (!plugin || plugin.uninstalled === true) {
240 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
244 plugin.enabled = false
245 plugin.uninstalled = true
249 await removeNpmPlugin(npmName)
251 logger.info('Plugin %s uninstalled.', npmName)
254 // ###################### Private register ######################
256 private async registerPluginOrTheme (plugin: PluginModel) {
257 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
259 logger.info('Registering plugin or theme %s.', npmName)
261 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
262 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
264 if (!isPackageJSONValid(packageJSON, plugin.type)) {
265 throw new Error('Package.JSON is invalid.')
268 let library: PluginLibrary
269 if (plugin.type === PluginType.PLUGIN) {
270 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
273 const clientScripts: { [id: string]: ClientScript } = {}
274 for (const c of packageJSON.clientScripts) {
275 clientScripts[c.script] = c
278 this.registeredPlugins[ npmName ] = {
282 version: plugin.version,
283 description: plugin.description,
284 peertubeEngine: plugin.peertubeEngine,
286 staticDirs: packageJSON.staticDirs,
288 css: packageJSON.css,
289 unregister: library ? library.unregister : undefined
293 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
294 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
296 // Delete cache if needed
297 const modulePath = join(pluginPath, packageJSON.library)
298 delete require.cache[modulePath]
299 const library: PluginLibrary = require(modulePath)
301 if (!isLibraryCodeValid(library)) {
302 throw new Error('Library code is not valid (miss register or unregister function)')
305 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
306 library.register(registerHelpers)
307 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
309 logger.info('Add plugin %s CSS to global file.', npmName)
311 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
316 // ###################### CSS ######################
318 private resetCSSGlobalFile () {
319 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
322 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
323 for (const cssPath of cssRelativePaths) {
324 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
328 private concatFiles (input: string, output: string) {
329 return new Promise<void>((res, rej) => {
330 const inputStream = createReadStream(input)
331 const outputStream = createWriteStream(output, { flags: 'a' })
333 inputStream.pipe(outputStream)
335 inputStream.on('end', () => res())
336 inputStream.on('error', err => rej(err))
340 private async regeneratePluginGlobalCSS () {
341 await this.resetCSSGlobalFile()
343 for (const key of Object.keys(this.getRegisteredPlugins())) {
344 const plugin = this.registeredPlugins[key]
346 await this.addCSSToGlobalFile(plugin.path, plugin.css)
350 // ###################### Utils ######################
352 private sortHooksByPriority () {
353 for (const hookName of Object.keys(this.hooks)) {
354 this.hooks[hookName].sort((a, b) => {
355 return b.priority - a.priority
360 private getPackageJSON (pluginName: string, pluginType: PluginType) {
361 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
363 return readJSON(pluginPath) as Promise<PluginPackageJson>
366 private getPluginPath (pluginName: string, pluginType: PluginType) {
367 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
369 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
372 // ###################### Private getters ######################
374 private getRegisteredPluginsOrThemes (type: PluginType) {
375 const plugins: RegisteredPlugin[] = []
377 for (const npmName of Object.keys(this.registeredPlugins)) {
378 const plugin = this.registeredPlugins[ npmName ]
379 if (plugin.type !== type) continue
387 // ###################### Generate register helpers ######################
389 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterOptions {
390 const registerHook = (options: RegisterHookOptions) => {
391 if (!this.hooks[options.target]) this.hooks[options.target] = []
393 this.hooks[options.target].push({
395 pluginName: plugin.name,
396 handler: options.handler,
397 priority: options.priority || 0
401 const registerSetting = (options: RegisterSettingOptions) => {
402 if (!this.settings[npmName]) this.settings[npmName] = []
404 this.settings[npmName].push(options)
407 const settingsManager: PluginSettingsManager = {
408 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
410 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
413 const storageManager: PluginStorageManager = {
414 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
416 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
419 const peertubeHelpers = {
432 static get Instance () {
433 return this.instance || (this.instance = new this())