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 { 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'
14 export interface RegisteredPlugin {
18 peertubeEngine: string
24 staticDirs: { [name: string]: string }
28 // Only if this is a plugin
32 export interface HookInformationValue {
38 export class PluginManager {
40 private static instance: PluginManager
42 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
43 private hooks: { [ name: string ]: HookInformationValue[] } = {}
45 private constructor () {
48 async registerPlugins () {
49 const plugins = await PluginModel.listEnabledPluginsAndThemes()
51 for (const plugin of plugins) {
53 await this.registerPluginOrTheme(plugin)
55 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
59 this.sortHooksByPriority()
62 getRegisteredPlugin (name: string) {
63 return this.registeredPlugins[ name ]
66 getRegisteredTheme (name: string) {
67 const registered = this.getRegisteredPlugin(name)
69 if (!registered || registered.type !== PluginType.THEME) return undefined
74 async unregister (name: string) {
75 const plugin = this.getRegisteredPlugin(name)
78 throw new Error(`Unknown plugin ${name} to unregister`)
81 if (plugin.type === PluginType.THEME) {
82 throw new Error(`Cannot unregister ${name}: this is a theme`)
85 await plugin.unregister()
88 async install (toInstall: string, version: string, fromDisk = false) {
89 let plugin: PluginModel
92 logger.info('Installing plugin %s.', toInstall)
96 ? await installNpmPluginFromDisk(toInstall)
97 : await installNpmPlugin(toInstall, version)
99 name = fromDisk ? basename(toInstall) : toInstall
100 const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
101 const pluginName = this.normalizePluginName(name)
103 const packageJSON = this.getPackageJSON(pluginName, pluginType)
104 if (!isPackageJSONValid(packageJSON, pluginType)) {
105 throw new Error('PackageJSON is invalid.')
108 [ plugin ] = await PluginModel.upsert({
110 description: packageJSON.description,
112 version: packageJSON.version,
115 peertubeEngine: packageJSON.engine.peertube
116 }, { returning: true })
118 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
121 await removeNpmPlugin(name)
123 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
129 logger.info('Successful installation of plugin %s.', toInstall)
131 await this.registerPluginOrTheme(plugin)
134 async uninstall (packageName: string) {
135 await PluginModel.uninstall(this.normalizePluginName(packageName))
137 await removeNpmPlugin(packageName)
140 private async registerPluginOrTheme (plugin: PluginModel) {
141 logger.info('Registering plugin or theme %s.', plugin.name)
143 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
144 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
146 if (!isPackageJSONValid(packageJSON, plugin.type)) {
147 throw new Error('Package.JSON is invalid.')
150 let library: PluginLibrary
151 if (plugin.type === PluginType.PLUGIN) {
152 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
155 this.registeredPlugins[ plugin.name ] = {
158 version: plugin.version,
159 description: plugin.description,
160 peertubeEngine: plugin.peertubeEngine,
162 staticDirs: packageJSON.staticDirs,
163 css: packageJSON.css,
164 unregister: library ? library.unregister : undefined
168 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
169 const registerHook = (options: RegisterHookOptions) => {
170 if (!this.hooks[options.target]) this.hooks[options.target] = []
172 this.hooks[options.target].push({
173 pluginName: plugin.name,
174 handler: options.handler,
175 priority: options.priority || 0
179 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
181 if (!isLibraryCodeValid(library)) {
182 throw new Error('Library code is not valid (miss register or unregister function)')
185 library.register({ registerHook })
187 logger.info('Add plugin %s CSS to global file.', plugin.name)
189 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
194 private sortHooksByPriority () {
195 for (const hookName of Object.keys(this.hooks)) {
196 this.hooks[hookName].sort((a, b) => {
197 return b.priority - a.priority
202 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
203 for (const cssPath of cssRelativePaths) {
204 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
208 private concatFiles (input: string, output: string) {
209 return new Promise<void>((res, rej) => {
210 const outputStream = createWriteStream(input)
211 const inputStream = createReadStream(output)
213 inputStream.pipe(outputStream)
215 inputStream.on('end', () => res())
216 inputStream.on('error', err => rej(err))
220 private getPackageJSON (pluginName: string, pluginType: PluginType) {
221 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
223 return require(pluginPath) as PluginPackageJson
226 private getPluginPath (pluginName: string, pluginType: PluginType) {
227 const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
229 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
232 private normalizePluginName (name: string) {
233 return name.replace(/^peertube-((theme)|(plugin))-/, '')
236 static get Instance () {
237 return this.instance || (this.instance = new this())