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 { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
13 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
14 import { ServerHook, ServerHookName, serverHookObject } from '../../../shared/models/plugins/server-hook.model'
15 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
16 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
17 import { PluginLibrary } from '../../typings/plugins'
18 import { ClientHtml } from '../client-html'
19 import { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
20 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
22 export interface RegisteredPlugin {
27 peertubeEngine: string
33 staticDirs: { [name: string]: string }
34 clientScripts: { [name: string]: ClientScript }
38 // Only if this is a plugin
42 export interface HookInformationValue {
49 export class PluginManager implements ServerHook {
51 private static instance: PluginManager
53 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
54 private settings: { [ name: string ]: RegisterServerSettingOptions[] } = {}
55 private hooks: { [ name: string ]: HookInformationValue[] } = {}
57 private constructor () {
60 // ###################### Getters ######################
62 isRegistered (npmName: string) {
63 return !!this.getRegisteredPluginOrTheme(npmName)
66 getRegisteredPluginOrTheme (npmName: string) {
67 return this.registeredPlugins[npmName]
70 getRegisteredPlugin (name: string) {
71 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
72 const registered = this.getRegisteredPluginOrTheme(npmName)
74 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
79 getRegisteredTheme (name: string) {
80 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
81 const registered = this.getRegisteredPluginOrTheme(npmName)
83 if (!registered || registered.type !== PluginType.THEME) return undefined
88 getRegisteredPlugins () {
89 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
92 getRegisteredThemes () {
93 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
96 getRegisteredSettings (npmName: string) {
97 return this.settings[npmName] || []
100 // ###################### Hooks ######################
102 async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
103 if (!this.hooks[hookName]) return Promise.resolve(result)
105 const hookType = getHookType(hookName)
107 for (const hook of this.hooks[hookName]) {
108 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
110 result = await internalRunHook(hook.handler, hookType, result, params, err => {
111 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
118 // ###################### Registration ######################
120 async registerPluginsAndThemes () {
121 await this.resetCSSGlobalFile()
123 const plugins = await PluginModel.listEnabledPluginsAndThemes()
125 for (const plugin of plugins) {
127 await this.registerPluginOrTheme(plugin)
129 // Try to unregister the plugin
131 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
133 // we don't care if we cannot unregister it
136 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
140 this.sortHooksByPriority()
143 // Don't need the plugin type since themes cannot register server code
144 async unregister (npmName: string) {
145 logger.info('Unregister plugin %s.', npmName)
147 const plugin = this.getRegisteredPluginOrTheme(npmName)
150 throw new Error(`Unknown plugin ${npmName} to unregister`)
153 delete this.registeredPlugins[plugin.npmName]
155 if (plugin.type === PluginType.PLUGIN) {
156 await plugin.unregister()
158 // Remove hooks of this plugin
159 for (const key of Object.keys(this.hooks)) {
160 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
163 logger.info('Regenerating registered plugin CSS to global file.')
164 await this.regeneratePluginGlobalCSS()
168 // ###################### Installation ######################
170 async install (toInstall: string, version?: string, fromDisk = false) {
171 let plugin: PluginModel
174 logger.info('Installing plugin %s.', toInstall)
178 ? await installNpmPluginFromDisk(toInstall)
179 : await installNpmPlugin(toInstall, version)
181 npmName = fromDisk ? basename(toInstall) : toInstall
182 const pluginType = PluginModel.getTypeFromNpmName(npmName)
183 const pluginName = PluginModel.normalizePluginName(npmName)
185 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
186 if (!isPackageJSONValid(packageJSON, pluginType)) {
187 throw new Error('PackageJSON is invalid.')
190 [ plugin ] = await PluginModel.upsert({
192 description: packageJSON.description,
193 homepage: packageJSON.homepage,
195 version: packageJSON.version,
198 peertubeEngine: packageJSON.engine.peertube
199 }, { returning: true })
201 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
204 await removeNpmPlugin(npmName)
206 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
212 logger.info('Successful installation of plugin %s.', toInstall)
214 await this.registerPluginOrTheme(plugin)
219 async update (toUpdate: string, version?: string, fromDisk = false) {
220 const npmName = fromDisk ? basename(toUpdate) : toUpdate
222 logger.info('Updating plugin %s.', npmName)
224 // Unregister old hooks
225 await this.unregister(npmName)
227 return this.install(toUpdate, version, fromDisk)
230 async uninstall (npmName: string) {
231 logger.info('Uninstalling plugin %s.', npmName)
234 await this.unregister(npmName)
236 logger.warn('Cannot unregister plugin %s.', npmName, { err })
239 const plugin = await PluginModel.loadByNpmName(npmName)
240 if (!plugin || plugin.uninstalled === true) {
241 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
245 plugin.enabled = false
246 plugin.uninstalled = true
250 await removeNpmPlugin(npmName)
252 logger.info('Plugin %s uninstalled.', npmName)
255 // ###################### Private register ######################
257 private async registerPluginOrTheme (plugin: PluginModel) {
258 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
260 logger.info('Registering plugin or theme %s.', npmName)
262 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
263 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
265 if (!isPackageJSONValid(packageJSON, plugin.type)) {
266 throw new Error('Package.JSON is invalid.')
269 let library: PluginLibrary
270 if (plugin.type === PluginType.PLUGIN) {
271 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
274 const clientScripts: { [id: string]: ClientScript } = {}
275 for (const c of packageJSON.clientScripts) {
276 clientScripts[c.script] = c
279 this.registeredPlugins[ npmName ] = {
283 version: plugin.version,
284 description: plugin.description,
285 peertubeEngine: plugin.peertubeEngine,
287 staticDirs: packageJSON.staticDirs,
289 css: packageJSON.css,
290 unregister: library ? library.unregister : undefined
294 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
295 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
297 // Delete cache if needed
298 const modulePath = join(pluginPath, packageJSON.library)
299 delete require.cache[modulePath]
300 const library: PluginLibrary = require(modulePath)
302 if (!isLibraryCodeValid(library)) {
303 throw new Error('Library code is not valid (miss register or unregister function)')
306 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
307 library.register(registerHelpers)
308 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
310 logger.info('Add plugin %s CSS to global file.', npmName)
312 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
317 // ###################### CSS ######################
319 private resetCSSGlobalFile () {
320 ClientHtml.invalidCache()
322 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
325 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
326 for (const cssPath of cssRelativePaths) {
327 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
330 ClientHtml.invalidCache()
333 private concatFiles (input: string, output: string) {
334 return new Promise<void>((res, rej) => {
335 const inputStream = createReadStream(input)
336 const outputStream = createWriteStream(output, { flags: 'a' })
338 inputStream.pipe(outputStream)
340 inputStream.on('end', () => res())
341 inputStream.on('error', err => rej(err))
345 private async regeneratePluginGlobalCSS () {
346 await this.resetCSSGlobalFile()
348 for (const key of Object.keys(this.getRegisteredPlugins())) {
349 const plugin = this.registeredPlugins[key]
351 await this.addCSSToGlobalFile(plugin.path, plugin.css)
355 // ###################### Utils ######################
357 private sortHooksByPriority () {
358 for (const hookName of Object.keys(this.hooks)) {
359 this.hooks[hookName].sort((a, b) => {
360 return b.priority - a.priority
365 private getPackageJSON (pluginName: string, pluginType: PluginType) {
366 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
368 return readJSON(pluginPath) as Promise<PluginPackageJson>
371 private getPluginPath (pluginName: string, pluginType: PluginType) {
372 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
374 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
377 // ###################### Private getters ######################
379 private getRegisteredPluginsOrThemes (type: PluginType) {
380 const plugins: RegisteredPlugin[] = []
382 for (const npmName of Object.keys(this.registeredPlugins)) {
383 const plugin = this.registeredPlugins[ npmName ]
384 if (plugin.type !== type) continue
392 // ###################### Generate register helpers ######################
394 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
395 const registerHook = (options: RegisterServerHookOptions) => {
396 if (serverHookObject[options.target] !== true) {
397 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
401 if (!this.hooks[options.target]) this.hooks[options.target] = []
403 this.hooks[options.target].push({
405 pluginName: plugin.name,
406 handler: options.handler,
407 priority: options.priority || 0
411 const registerSetting = (options: RegisterServerSettingOptions) => {
412 if (!this.settings[npmName]) this.settings[npmName] = []
414 this.settings[npmName].push(options)
417 const settingsManager: PluginSettingsManager = {
418 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
420 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
423 const storageManager: PluginStorageManager = {
424 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
426 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
429 const peertubeHelpers = {
442 static get Instance () {
443 return this.instance || (this.instance = new this())