WIP plugins: install/uninstall
[oweals/peertube.git] / server / lib / plugins / plugin-manager.ts
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'
13
14 export interface RegisteredPlugin {
15   name: string
16   version: string
17   description: string
18   peertubeEngine: string
19
20   type: PluginType
21
22   path: string
23
24   staticDirs: { [name: string]: string }
25
26   css: string[]
27
28   // Only if this is a plugin
29   unregister?: Function
30 }
31
32 export interface HookInformationValue {
33   pluginName: string
34   handler: Function
35   priority: number
36 }
37
38 export class PluginManager {
39
40   private static instance: PluginManager
41
42   private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
43   private hooks: { [ name: string ]: HookInformationValue[] } = {}
44
45   private constructor () {
46   }
47
48   async registerPlugins () {
49     const plugins = await PluginModel.listEnabledPluginsAndThemes()
50
51     for (const plugin of plugins) {
52       try {
53         await this.registerPluginOrTheme(plugin)
54       } catch (err) {
55         logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
56       }
57     }
58
59     this.sortHooksByPriority()
60   }
61
62   getRegisteredPlugin (name: string) {
63     return this.registeredPlugins[ name ]
64   }
65
66   getRegisteredTheme (name: string) {
67     const registered = this.getRegisteredPlugin(name)
68
69     if (!registered || registered.type !== PluginType.THEME) return undefined
70
71     return registered
72   }
73
74   async unregister (name: string) {
75     const plugin = this.getRegisteredPlugin(name)
76
77     if (!plugin) {
78       throw new Error(`Unknown plugin ${name} to unregister`)
79     }
80
81     if (plugin.type === PluginType.THEME) {
82       throw new Error(`Cannot unregister ${name}: this is a theme`)
83     }
84
85     await plugin.unregister()
86   }
87
88   async install (toInstall: string, version: string, fromDisk = false) {
89     let plugin: PluginModel
90     let name: string
91
92     logger.info('Installing plugin %s.', toInstall)
93
94     try {
95       fromDisk
96         ? await installNpmPluginFromDisk(toInstall)
97         : await installNpmPlugin(toInstall, version)
98
99       name = fromDisk ? basename(toInstall) : toInstall
100       const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
101       const pluginName = this.normalizePluginName(name)
102
103       const packageJSON = this.getPackageJSON(pluginName, pluginType)
104       if (!isPackageJSONValid(packageJSON, pluginType)) {
105         throw new Error('PackageJSON is invalid.')
106       }
107
108       [ plugin ] = await PluginModel.upsert({
109         name: pluginName,
110         description: packageJSON.description,
111         type: pluginType,
112         version: packageJSON.version,
113         enabled: true,
114         uninstalled: false,
115         peertubeEngine: packageJSON.engine.peertube
116       }, { returning: true })
117     } catch (err) {
118       logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
119
120       try {
121         await removeNpmPlugin(name)
122       } catch (err) {
123         logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
124       }
125
126       throw err
127     }
128
129     logger.info('Successful installation of plugin %s.', toInstall)
130
131     await this.registerPluginOrTheme(plugin)
132   }
133
134   async uninstall (packageName: string) {
135     await PluginModel.uninstall(this.normalizePluginName(packageName))
136
137     await removeNpmPlugin(packageName)
138   }
139
140   private async registerPluginOrTheme (plugin: PluginModel) {
141     logger.info('Registering plugin or theme %s.', plugin.name)
142
143     const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
144     const pluginPath = this.getPluginPath(plugin.name, plugin.type)
145
146     if (!isPackageJSONValid(packageJSON, plugin.type)) {
147       throw new Error('Package.JSON is invalid.')
148     }
149
150     let library: PluginLibrary
151     if (plugin.type === PluginType.PLUGIN) {
152       library = await this.registerPlugin(plugin, pluginPath, packageJSON)
153     }
154
155     this.registeredPlugins[ plugin.name ] = {
156       name: plugin.name,
157       type: plugin.type,
158       version: plugin.version,
159       description: plugin.description,
160       peertubeEngine: plugin.peertubeEngine,
161       path: pluginPath,
162       staticDirs: packageJSON.staticDirs,
163       css: packageJSON.css,
164       unregister: library ? library.unregister : undefined
165     }
166   }
167
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] = []
171
172       this.hooks[options.target].push({
173         pluginName: plugin.name,
174         handler: options.handler,
175         priority: options.priority || 0
176       })
177     }
178
179     const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
180
181     if (!isLibraryCodeValid(library)) {
182       throw new Error('Library code is not valid (miss register or unregister function)')
183     }
184
185     library.register({ registerHook })
186
187     logger.info('Add plugin %s CSS to global file.', plugin.name)
188
189     await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
190
191     return library
192   }
193
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
198       })
199     }
200   }
201
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)
205     }
206   }
207
208   private concatFiles (input: string, output: string) {
209     return new Promise<void>((res, rej) => {
210       const outputStream = createWriteStream(input)
211       const inputStream = createReadStream(output)
212
213       inputStream.pipe(outputStream)
214
215       inputStream.on('end', () => res())
216       inputStream.on('error', err => rej(err))
217     })
218   }
219
220   private getPackageJSON (pluginName: string, pluginType: PluginType) {
221     const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
222
223     return require(pluginPath) as PluginPackageJson
224   }
225
226   private getPluginPath (pluginName: string, pluginType: PluginType) {
227     const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
228
229     return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
230   }
231
232   private normalizePluginName (name: string) {
233     return name.replace(/^peertube-((theme)|(plugin))-/, '')
234   }
235
236   static get Instance () {
237     return this.instance || (this.instance = new this())
238   }
239 }