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'
17 import { ServerHookName, ServerHook } from '../../../shared/models/plugins/server-hook.model'
18 import { isCatchable, isPromise } from '../../../shared/core-utils/miscs/miscs'
19 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
20 import { HookType } from '../../../shared/models/plugins/hook-type.enum'
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 ]: RegisterSettingOptions[] } = {}
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 (hookName: ServerHookName, param?: any) {
105 if (!this.hooks[hookName]) return result
107 const hookType = getHookType(hookName)
109 for (const hook of this.hooks[hookName]) {
110 result = await internalRunHook(hook.handler, hookType, param, 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 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
133 this.sortHooksByPriority()
136 // Don't need the plugin type since themes cannot register server code
137 async unregister (npmName: string) {
138 logger.info('Unregister plugin %s.', npmName)
140 const plugin = this.getRegisteredPluginOrTheme(npmName)
143 throw new Error(`Unknown plugin ${npmName} to unregister`)
146 if (plugin.type === PluginType.PLUGIN) {
147 await plugin.unregister()
149 // Remove hooks of this plugin
150 for (const key of Object.keys(this.hooks)) {
151 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
154 logger.info('Regenerating registered plugin CSS to global file.')
155 await this.regeneratePluginGlobalCSS()
158 delete this.registeredPlugins[plugin.npmName]
161 // ###################### Installation ######################
163 async install (toInstall: string, version?: string, fromDisk = false) {
164 let plugin: PluginModel
167 logger.info('Installing plugin %s.', toInstall)
171 ? await installNpmPluginFromDisk(toInstall)
172 : await installNpmPlugin(toInstall, version)
174 npmName = fromDisk ? basename(toInstall) : toInstall
175 const pluginType = PluginModel.getTypeFromNpmName(npmName)
176 const pluginName = PluginModel.normalizePluginName(npmName)
178 const packageJSON = this.getPackageJSON(pluginName, pluginType)
179 if (!isPackageJSONValid(packageJSON, pluginType)) {
180 throw new Error('PackageJSON is invalid.')
183 [ plugin ] = await PluginModel.upsert({
185 description: packageJSON.description,
186 homepage: packageJSON.homepage,
188 version: packageJSON.version,
191 peertubeEngine: packageJSON.engine.peertube
192 }, { returning: true })
194 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
197 await removeNpmPlugin(npmName)
199 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
205 logger.info('Successful installation of plugin %s.', toInstall)
207 await this.registerPluginOrTheme(plugin)
212 async update (toUpdate: string, version?: string, fromDisk = false) {
213 const npmName = fromDisk ? basename(toUpdate) : toUpdate
215 logger.info('Updating plugin %s.', npmName)
217 // Unregister old hooks
218 await this.unregister(npmName)
220 return this.install(toUpdate, version, fromDisk)
223 async uninstall (npmName: string) {
224 logger.info('Uninstalling plugin %s.', npmName)
227 await this.unregister(npmName)
229 logger.warn('Cannot unregister plugin %s.', npmName, { err })
232 const plugin = await PluginModel.loadByNpmName(npmName)
233 if (!plugin || plugin.uninstalled === true) {
234 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
238 plugin.enabled = false
239 plugin.uninstalled = true
243 await removeNpmPlugin(npmName)
245 logger.info('Plugin %s uninstalled.', npmName)
248 // ###################### Private register ######################
250 private async registerPluginOrTheme (plugin: PluginModel) {
251 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
253 logger.info('Registering plugin or theme %s.', npmName)
255 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
256 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
258 if (!isPackageJSONValid(packageJSON, plugin.type)) {
259 throw new Error('Package.JSON is invalid.')
262 let library: PluginLibrary
263 if (plugin.type === PluginType.PLUGIN) {
264 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
267 const clientScripts: { [id: string]: ClientScript } = {}
268 for (const c of packageJSON.clientScripts) {
269 clientScripts[c.script] = c
272 this.registeredPlugins[ npmName ] = {
276 version: plugin.version,
277 description: plugin.description,
278 peertubeEngine: plugin.peertubeEngine,
280 staticDirs: packageJSON.staticDirs,
282 css: packageJSON.css,
283 unregister: library ? library.unregister : undefined
287 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
288 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
290 const registerHook = (options: RegisterHookOptions) => {
291 if (!this.hooks[options.target]) this.hooks[options.target] = []
293 this.hooks[options.target].push({
295 pluginName: plugin.name,
296 handler: options.handler,
297 priority: options.priority || 0
301 const registerSetting = (options: RegisterSettingOptions) => {
302 if (!this.settings[npmName]) this.settings[npmName] = []
304 this.settings[npmName].push(options)
307 const settingsManager: PluginSettingsManager = {
308 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
310 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
313 const storageManager: PluginStorageManager = {
314 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
316 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
319 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
321 if (!isLibraryCodeValid(library)) {
322 throw new Error('Library code is not valid (miss register or unregister function)')
330 }).catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
332 logger.info('Add plugin %s CSS to global file.', npmName)
334 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
339 // ###################### CSS ######################
341 private resetCSSGlobalFile () {
342 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
345 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
346 for (const cssPath of cssRelativePaths) {
347 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
351 private concatFiles (input: string, output: string) {
352 return new Promise<void>((res, rej) => {
353 const inputStream = createReadStream(input)
354 const outputStream = createWriteStream(output, { flags: 'a' })
356 inputStream.pipe(outputStream)
358 inputStream.on('end', () => res())
359 inputStream.on('error', err => rej(err))
363 private async regeneratePluginGlobalCSS () {
364 await this.resetCSSGlobalFile()
366 for (const key of Object.keys(this.getRegisteredPlugins())) {
367 const plugin = this.registeredPlugins[key]
369 await this.addCSSToGlobalFile(plugin.path, plugin.css)
373 // ###################### Utils ######################
375 private sortHooksByPriority () {
376 for (const hookName of Object.keys(this.hooks)) {
377 this.hooks[hookName].sort((a, b) => {
378 return b.priority - a.priority
383 private getPackageJSON (pluginName: string, pluginType: PluginType) {
384 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
386 return require(pluginPath) as PluginPackageJson
389 private getPluginPath (pluginName: string, pluginType: PluginType) {
390 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
392 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
395 // ###################### Private getters ######################
397 private getRegisteredPluginsOrThemes (type: PluginType) {
398 const plugins: RegisteredPlugin[] = []
400 for (const npmName of Object.keys(this.registeredPlugins)) {
401 const plugin = this.registeredPlugins[ npmName ]
402 if (plugin.type !== type) continue
410 static get Instance () {
411 return this.instance || (this.instance = new this())