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]) {
108 result = await hook.handler(param)
110 result = hook.handler()
113 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
120 // ###################### Registration ######################
122 async registerPluginsAndThemes () {
123 await this.resetCSSGlobalFile()
125 const plugins = await PluginModel.listEnabledPluginsAndThemes()
127 for (const plugin of plugins) {
129 await this.registerPluginOrTheme(plugin)
131 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
135 this.sortHooksByPriority()
138 // Don't need the plugin type since themes cannot register server code
139 async unregister (npmName: string) {
140 logger.info('Unregister plugin %s.', npmName)
142 const plugin = this.getRegisteredPluginOrTheme(npmName)
145 throw new Error(`Unknown plugin ${npmName} to unregister`)
148 if (plugin.type === PluginType.PLUGIN) {
149 await plugin.unregister()
151 // Remove hooks of this plugin
152 for (const key of Object.keys(this.hooks)) {
153 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
156 logger.info('Regenerating registered plugin CSS to global file.')
157 await this.regeneratePluginGlobalCSS()
160 delete this.registeredPlugins[plugin.npmName]
163 // ###################### Installation ######################
165 async install (toInstall: string, version?: string, fromDisk = false) {
166 let plugin: PluginModel
169 logger.info('Installing plugin %s.', toInstall)
173 ? await installNpmPluginFromDisk(toInstall)
174 : await installNpmPlugin(toInstall, version)
176 npmName = fromDisk ? basename(toInstall) : toInstall
177 const pluginType = PluginModel.getTypeFromNpmName(npmName)
178 const pluginName = PluginModel.normalizePluginName(npmName)
180 const packageJSON = this.getPackageJSON(pluginName, pluginType)
181 if (!isPackageJSONValid(packageJSON, pluginType)) {
182 throw new Error('PackageJSON is invalid.')
185 [ plugin ] = await PluginModel.upsert({
187 description: packageJSON.description,
188 homepage: packageJSON.homepage,
190 version: packageJSON.version,
193 peertubeEngine: packageJSON.engine.peertube
194 }, { returning: true })
196 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
199 await removeNpmPlugin(npmName)
201 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
207 logger.info('Successful installation of plugin %s.', toInstall)
209 await this.registerPluginOrTheme(plugin)
214 async update (toUpdate: string, version?: string, fromDisk = false) {
215 const npmName = fromDisk ? basename(toUpdate) : toUpdate
217 logger.info('Updating plugin %s.', npmName)
219 // Unregister old hooks
220 await this.unregister(npmName)
222 return this.install(toUpdate, version, fromDisk)
225 async uninstall (npmName: string) {
226 logger.info('Uninstalling plugin %s.', npmName)
229 await this.unregister(npmName)
231 logger.warn('Cannot unregister plugin %s.', npmName, { err })
234 const plugin = await PluginModel.loadByNpmName(npmName)
235 if (!plugin || plugin.uninstalled === true) {
236 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
240 plugin.enabled = false
241 plugin.uninstalled = true
245 await removeNpmPlugin(npmName)
247 logger.info('Plugin %s uninstalled.', npmName)
250 // ###################### Private register ######################
252 private async registerPluginOrTheme (plugin: PluginModel) {
253 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
255 logger.info('Registering plugin or theme %s.', npmName)
257 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
258 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
260 if (!isPackageJSONValid(packageJSON, plugin.type)) {
261 throw new Error('Package.JSON is invalid.')
264 let library: PluginLibrary
265 if (plugin.type === PluginType.PLUGIN) {
266 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
269 const clientScripts: { [id: string]: ClientScript } = {}
270 for (const c of packageJSON.clientScripts) {
271 clientScripts[c.script] = c
274 this.registeredPlugins[ npmName ] = {
278 version: plugin.version,
279 description: plugin.description,
280 peertubeEngine: plugin.peertubeEngine,
282 staticDirs: packageJSON.staticDirs,
284 css: packageJSON.css,
285 unregister: library ? library.unregister : undefined
289 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
290 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
292 const registerHook = (options: RegisterHookOptions) => {
293 if (!this.hooks[options.target]) this.hooks[options.target] = []
295 this.hooks[options.target].push({
297 pluginName: plugin.name,
298 handler: options.handler,
299 priority: options.priority || 0
303 const registerSetting = (options: RegisterSettingOptions) => {
304 if (!this.settings[npmName]) this.settings[npmName] = []
306 this.settings[npmName].push(options)
309 const settingsManager: PluginSettingsManager = {
310 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
312 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
315 const storageManager: PluginStorageManager = {
316 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
318 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
321 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
323 if (!isLibraryCodeValid(library)) {
324 throw new Error('Library code is not valid (miss register or unregister function)')
334 logger.info('Add plugin %s CSS to global file.', npmName)
336 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
341 // ###################### CSS ######################
343 private resetCSSGlobalFile () {
344 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
347 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
348 for (const cssPath of cssRelativePaths) {
349 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
353 private concatFiles (input: string, output: string) {
354 return new Promise<void>((res, rej) => {
355 const inputStream = createReadStream(input)
356 const outputStream = createWriteStream(output, { flags: 'a' })
358 inputStream.pipe(outputStream)
360 inputStream.on('end', () => res())
361 inputStream.on('error', err => rej(err))
365 private async regeneratePluginGlobalCSS () {
366 await this.resetCSSGlobalFile()
368 for (const key of Object.keys(this.registeredPlugins)) {
369 const plugin = this.registeredPlugins[key]
371 await this.addCSSToGlobalFile(plugin.path, plugin.css)
375 // ###################### Utils ######################
377 private sortHooksByPriority () {
378 for (const hookName of Object.keys(this.hooks)) {
379 this.hooks[hookName].sort((a, b) => {
380 return b.priority - a.priority
385 private getPackageJSON (pluginName: string, pluginType: PluginType) {
386 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
388 return require(pluginPath) as PluginPackageJson
391 private getPluginPath (pluginName: string, pluginType: PluginType) {
392 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
394 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
397 // ###################### Private getters ######################
399 private getRegisteredPluginsOrThemes (type: PluginType) {
400 const plugins: RegisteredPlugin[] = []
402 for (const npmName of Object.keys(this.registeredPlugins)) {
403 const plugin = this.registeredPlugins[ npmName ]
404 if (plugin.type !== type) continue
412 static get Instance () {
413 return this.instance || (this.instance = new this())