1 import { PluginModel } from '../../models/server/plugin'
2 import { logger } from '../../helpers/logger'
3 import { RegisterHookOptions } from '../../../shared/models/plugins/register.model'
4 import { basename, join } from 'path'
5 import { CONFIG } from '../../initializers/config'
6 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
7 import { ClientScript, PluginPackageJson } from '../../../shared/models/plugins/plugin-package-json.model'
8 import { PluginLibrary } from '../../../shared/models/plugins/plugin-library.model'
9 import { createReadStream, createWriteStream } from 'fs'
10 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
11 import { PluginType } from '../../../shared/models/plugins/plugin.type'
12 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
13 import { outputFile } from 'fs-extra'
14 import { ServerConfigPlugin } from '../../../shared/models/server'
16 export interface RegisteredPlugin {
20 peertubeEngine: string
26 staticDirs: { [name: string]: string }
27 clientScripts: { [name: string]: ClientScript }
31 // Only if this is a plugin
35 export interface HookInformationValue {
41 export class PluginManager {
43 private static instance: PluginManager
45 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
46 private hooks: { [ name: string ]: HookInformationValue[] } = {}
48 private constructor () {
51 async registerPluginsAndThemes () {
52 await this.resetCSSGlobalFile()
54 const plugins = await PluginModel.listEnabledPluginsAndThemes()
56 for (const plugin of plugins) {
58 await this.registerPluginOrTheme(plugin)
60 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
64 this.sortHooksByPriority()
67 getRegisteredPluginOrTheme (name: string) {
68 return this.registeredPlugins[name]
71 getRegisteredPlugin (name: string) {
72 const registered = this.getRegisteredPluginOrTheme(name)
74 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
79 getRegisteredTheme (name: string) {
80 const registered = this.getRegisteredPluginOrTheme(name)
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 async runHook (hookName: string, param?: any) {
98 const wait = hookName.startsWith('static:')
100 for (const hook of this.hooks[hookName]) {
102 if (wait) result = await hook.handler(param)
103 else result = hook.handler()
105 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
112 async unregister (name: string) {
113 const plugin = this.getRegisteredPlugin(name)
116 throw new Error(`Unknown plugin ${name} to unregister`)
119 if (plugin.type === PluginType.THEME) {
120 throw new Error(`Cannot unregister ${name}: this is a theme`)
123 await plugin.unregister()
125 // Remove hooks of this plugin
126 for (const key of Object.keys(this.hooks)) {
127 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== name)
130 delete this.registeredPlugins[plugin.name]
132 logger.info('Regenerating registered plugin CSS to global file.')
133 await this.regeneratePluginGlobalCSS()
136 async install (toInstall: string, version: string, fromDisk = false) {
137 let plugin: PluginModel
140 logger.info('Installing plugin %s.', toInstall)
144 ? await installNpmPluginFromDisk(toInstall)
145 : await installNpmPlugin(toInstall, version)
147 name = fromDisk ? basename(toInstall) : toInstall
148 const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
149 const pluginName = this.normalizePluginName(name)
151 const packageJSON = this.getPackageJSON(pluginName, pluginType)
152 if (!isPackageJSONValid(packageJSON, pluginType)) {
153 throw new Error('PackageJSON is invalid.')
156 [ plugin ] = await PluginModel.upsert({
158 description: packageJSON.description,
160 version: packageJSON.version,
163 peertubeEngine: packageJSON.engine.peertube
164 }, { returning: true })
166 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
169 await removeNpmPlugin(name)
171 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
177 logger.info('Successful installation of plugin %s.', toInstall)
179 await this.registerPluginOrTheme(plugin)
182 async uninstall (packageName: string) {
183 logger.info('Uninstalling plugin %s.', packageName)
185 const pluginName = this.normalizePluginName(packageName)
188 await this.unregister(pluginName)
190 logger.warn('Cannot unregister plugin %s.', pluginName, { err })
193 const plugin = await PluginModel.load(pluginName)
194 if (!plugin || plugin.uninstalled === true) {
195 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', packageName)
199 plugin.enabled = false
200 plugin.uninstalled = true
204 await removeNpmPlugin(packageName)
206 logger.info('Plugin %s uninstalled.', packageName)
209 private async registerPluginOrTheme (plugin: PluginModel) {
210 logger.info('Registering plugin or theme %s.', plugin.name)
212 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
213 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
215 if (!isPackageJSONValid(packageJSON, plugin.type)) {
216 throw new Error('Package.JSON is invalid.')
219 let library: PluginLibrary
220 if (plugin.type === PluginType.PLUGIN) {
221 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
224 const clientScripts: { [id: string]: ClientScript } = {}
225 for (const c of packageJSON.clientScripts) {
226 clientScripts[c.script] = c
229 this.registeredPlugins[ plugin.name ] = {
232 version: plugin.version,
233 description: plugin.description,
234 peertubeEngine: plugin.peertubeEngine,
236 staticDirs: packageJSON.staticDirs,
238 css: packageJSON.css,
239 unregister: library ? library.unregister : undefined
243 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
244 const registerHook = (options: RegisterHookOptions) => {
245 if (!this.hooks[options.target]) this.hooks[options.target] = []
247 this.hooks[options.target].push({
248 pluginName: plugin.name,
249 handler: options.handler,
250 priority: options.priority || 0
254 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
256 if (!isLibraryCodeValid(library)) {
257 throw new Error('Library code is not valid (miss register or unregister function)')
260 library.register({ registerHook })
262 logger.info('Add plugin %s CSS to global file.', plugin.name)
264 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
269 private sortHooksByPriority () {
270 for (const hookName of Object.keys(this.hooks)) {
271 this.hooks[hookName].sort((a, b) => {
272 return b.priority - a.priority
277 private resetCSSGlobalFile () {
278 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
281 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
282 for (const cssPath of cssRelativePaths) {
283 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
287 private concatFiles (input: string, output: string) {
288 return new Promise<void>((res, rej) => {
289 const inputStream = createReadStream(input)
290 const outputStream = createWriteStream(output, { flags: 'a' })
292 inputStream.pipe(outputStream)
294 inputStream.on('end', () => res())
295 inputStream.on('error', err => rej(err))
299 private getPackageJSON (pluginName: string, pluginType: PluginType) {
300 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
302 return require(pluginPath) as PluginPackageJson
305 private getPluginPath (pluginName: string, pluginType: PluginType) {
306 const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
308 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
311 private normalizePluginName (name: string) {
312 return name.replace(/^peertube-((theme)|(plugin))-/, '')
315 private async regeneratePluginGlobalCSS () {
316 await this.resetCSSGlobalFile()
318 for (const key of Object.keys(this.registeredPlugins)) {
319 const plugin = this.registeredPlugins[key]
321 await this.addCSSToGlobalFile(plugin.path, plugin.css)
325 private getRegisteredPluginsOrThemes (type: PluginType) {
326 const plugins: RegisteredPlugin[] = []
328 for (const pluginName of Object.keys(this.registeredPlugins)) {
329 const plugin = this.registeredPlugins[ pluginName ]
330 if (plugin.type !== type) continue
338 static get Instance () {
339 return this.instance || (this.instance = new this())