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'
17 export interface RegisteredPlugin {
21 peertubeEngine: string
27 staticDirs: { [name: string]: string }
28 clientScripts: { [name: string]: ClientScript }
32 // Only if this is a plugin
36 export interface HookInformationValue {
42 export class PluginManager {
44 private static instance: PluginManager
46 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
47 private settings: { [ name: string ]: RegisterSettingOptions[] } = {}
48 private hooks: { [ name: string ]: HookInformationValue[] } = {}
50 private constructor () {
53 // ###################### Getters ######################
55 getRegisteredPluginOrTheme (name: string) {
56 return this.registeredPlugins[name]
59 getRegisteredPlugin (name: string) {
60 const registered = this.getRegisteredPluginOrTheme(name)
62 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
67 getRegisteredTheme (name: string) {
68 const registered = this.getRegisteredPluginOrTheme(name)
70 if (!registered || registered.type !== PluginType.THEME) return undefined
75 getRegisteredPlugins () {
76 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
79 getRegisteredThemes () {
80 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
83 getSettings (name: string) {
84 return this.settings[name] || []
87 // ###################### Hooks ######################
89 async runHook (hookName: string, param?: any) {
92 const wait = hookName.startsWith('static:')
94 for (const hook of this.hooks[hookName]) {
97 result = await hook.handler(param)
99 result = hook.handler()
102 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
109 // ###################### Registration ######################
111 async registerPluginsAndThemes () {
112 await this.resetCSSGlobalFile()
114 const plugins = await PluginModel.listEnabledPluginsAndThemes()
116 for (const plugin of plugins) {
118 await this.registerPluginOrTheme(plugin)
120 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
124 this.sortHooksByPriority()
127 async unregister (name: string) {
128 const plugin = this.getRegisteredPlugin(name)
131 throw new Error(`Unknown plugin ${name} to unregister`)
134 if (plugin.type === PluginType.THEME) {
135 throw new Error(`Cannot unregister ${name}: this is a theme`)
138 await plugin.unregister()
140 // Remove hooks of this plugin
141 for (const key of Object.keys(this.hooks)) {
142 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== name)
145 delete this.registeredPlugins[plugin.name]
147 logger.info('Regenerating registered plugin CSS to global file.')
148 await this.regeneratePluginGlobalCSS()
151 // ###################### Installation ######################
153 async install (toInstall: string, version?: string, fromDisk = false) {
154 let plugin: PluginModel
157 logger.info('Installing plugin %s.', toInstall)
161 ? await installNpmPluginFromDisk(toInstall)
162 : await installNpmPlugin(toInstall, version)
164 name = fromDisk ? basename(toInstall) : toInstall
165 const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
166 const pluginName = this.normalizePluginName(name)
168 const packageJSON = this.getPackageJSON(pluginName, pluginType)
169 if (!isPackageJSONValid(packageJSON, pluginType)) {
170 throw new Error('PackageJSON is invalid.')
173 [ plugin ] = await PluginModel.upsert({
175 description: packageJSON.description,
177 version: packageJSON.version,
180 peertubeEngine: packageJSON.engine.peertube
181 }, { returning: true })
183 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
186 await removeNpmPlugin(name)
188 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
194 logger.info('Successful installation of plugin %s.', toInstall)
196 await this.registerPluginOrTheme(plugin)
199 async uninstall (packageName: string) {
200 logger.info('Uninstalling plugin %s.', packageName)
202 const pluginName = this.normalizePluginName(packageName)
205 await this.unregister(pluginName)
207 logger.warn('Cannot unregister plugin %s.', pluginName, { err })
210 const plugin = await PluginModel.load(pluginName)
211 if (!plugin || plugin.uninstalled === true) {
212 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', packageName)
216 plugin.enabled = false
217 plugin.uninstalled = true
221 await removeNpmPlugin(packageName)
223 logger.info('Plugin %s uninstalled.', packageName)
226 // ###################### Private register ######################
228 private async registerPluginOrTheme (plugin: PluginModel) {
229 logger.info('Registering plugin or theme %s.', plugin.name)
231 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
232 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
234 if (!isPackageJSONValid(packageJSON, plugin.type)) {
235 throw new Error('Package.JSON is invalid.')
238 let library: PluginLibrary
239 if (plugin.type === PluginType.PLUGIN) {
240 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
243 const clientScripts: { [id: string]: ClientScript } = {}
244 for (const c of packageJSON.clientScripts) {
245 clientScripts[c.script] = c
248 this.registeredPlugins[ plugin.name ] = {
251 version: plugin.version,
252 description: plugin.description,
253 peertubeEngine: plugin.peertubeEngine,
255 staticDirs: packageJSON.staticDirs,
257 css: packageJSON.css,
258 unregister: library ? library.unregister : undefined
262 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
263 const registerHook = (options: RegisterHookOptions) => {
264 if (!this.hooks[options.target]) this.hooks[options.target] = []
266 this.hooks[options.target].push({
267 pluginName: plugin.name,
268 handler: options.handler,
269 priority: options.priority || 0
273 const registerSetting = (options: RegisterSettingOptions) => {
274 if (!this.settings[plugin.name]) this.settings[plugin.name] = []
276 this.settings[plugin.name].push(options)
279 const settingsManager: PluginSettingsManager = {
280 getSetting: (name: string) => PluginModel.getSetting(plugin.name, name),
282 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, name, value)
285 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
287 if (!isLibraryCodeValid(library)) {
288 throw new Error('Library code is not valid (miss register or unregister function)')
291 library.register({ registerHook, registerSetting, settingsManager })
293 logger.info('Add plugin %s CSS to global file.', plugin.name)
295 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
300 // ###################### CSS ######################
302 private resetCSSGlobalFile () {
303 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
306 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
307 for (const cssPath of cssRelativePaths) {
308 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
312 private concatFiles (input: string, output: string) {
313 return new Promise<void>((res, rej) => {
314 const inputStream = createReadStream(input)
315 const outputStream = createWriteStream(output, { flags: 'a' })
317 inputStream.pipe(outputStream)
319 inputStream.on('end', () => res())
320 inputStream.on('error', err => rej(err))
324 private async regeneratePluginGlobalCSS () {
325 await this.resetCSSGlobalFile()
327 for (const key of Object.keys(this.registeredPlugins)) {
328 const plugin = this.registeredPlugins[key]
330 await this.addCSSToGlobalFile(plugin.path, plugin.css)
334 // ###################### Utils ######################
336 private sortHooksByPriority () {
337 for (const hookName of Object.keys(this.hooks)) {
338 this.hooks[hookName].sort((a, b) => {
339 return b.priority - a.priority
344 private getPackageJSON (pluginName: string, pluginType: PluginType) {
345 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
347 return require(pluginPath) as PluginPackageJson
350 private getPluginPath (pluginName: string, pluginType: PluginType) {
351 const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
353 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
356 private normalizePluginName (name: string) {
357 return name.replace(/^peertube-((theme)|(plugin))-/, '')
360 // ###################### Private getters ######################
362 private getRegisteredPluginsOrThemes (type: PluginType) {
363 const plugins: RegisteredPlugin[] = []
365 for (const pluginName of Object.keys(this.registeredPlugins)) {
366 const plugin = this.registeredPlugins[ pluginName ]
367 if (plugin.type !== type) continue
375 static get Instance () {
376 return this.instance || (this.instance = new this())