]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
WIP plugins: add plugin settings/uninstall in client
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
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
17 export interface RegisteredPlugin {
18 name: string
19 version: string
20 description: string
21 peertubeEngine: string
22
23 type: PluginType
24
25 path: string
26
27 staticDirs: { [name: string]: string }
28 clientScripts: { [name: string]: ClientScript }
29
30 css: string[]
31
32 // Only if this is a plugin
33 unregister?: Function
34 }
35
36 export interface HookInformationValue {
37 pluginName: string
38 handler: Function
39 priority: number
40 }
41
42 export class PluginManager {
43
44 private static instance: PluginManager
45
46 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
47 private settings: { [ name: string ]: RegisterSettingOptions[] } = {}
48 private hooks: { [ name: string ]: HookInformationValue[] } = {}
49
50 private constructor () {
51 }
52
53 // ###################### Getters ######################
54
55 getRegisteredPluginOrTheme (name: string) {
56 return this.registeredPlugins[name]
57 }
58
59 getRegisteredPlugin (name: string) {
60 const registered = this.getRegisteredPluginOrTheme(name)
61
62 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
63
64 return registered
65 }
66
67 getRegisteredTheme (name: string) {
68 const registered = this.getRegisteredPluginOrTheme(name)
69
70 if (!registered || registered.type !== PluginType.THEME) return undefined
71
72 return registered
73 }
74
75 getRegisteredPlugins () {
76 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
77 }
78
79 getRegisteredThemes () {
80 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
81 }
82
83 getSettings (name: string) {
84 return this.settings[name] || []
85 }
86
87 // ###################### Hooks ######################
88
89 async runHook (hookName: string, param?: any) {
90 let result = param
91
92 if (!this.hooks[hookName]) return result
93
94 const wait = hookName.startsWith('static:')
95
96 for (const hook of this.hooks[hookName]) {
97 try {
98 if (wait) {
99 result = await hook.handler(param)
100 } else {
101 result = hook.handler()
102 }
103 } catch (err) {
104 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
105 }
106 }
107
108 return result
109 }
110
111 // ###################### Registration ######################
112
113 async registerPluginsAndThemes () {
114 await this.resetCSSGlobalFile()
115
116 const plugins = await PluginModel.listEnabledPluginsAndThemes()
117
118 for (const plugin of plugins) {
119 try {
120 await this.registerPluginOrTheme(plugin)
121 } catch (err) {
122 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
123 }
124 }
125
126 this.sortHooksByPriority()
127 }
128
129 async unregister (name: string) {
130 const plugin = this.getRegisteredPlugin(name)
131
132 if (!plugin) {
133 throw new Error(`Unknown plugin ${name} to unregister`)
134 }
135
136 if (plugin.type === PluginType.THEME) {
137 throw new Error(`Cannot unregister ${name}: this is a theme`)
138 }
139
140 await plugin.unregister()
141
142 // Remove hooks of this plugin
143 for (const key of Object.keys(this.hooks)) {
144 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== name)
145 }
146
147 delete this.registeredPlugins[plugin.name]
148
149 logger.info('Regenerating registered plugin CSS to global file.')
150 await this.regeneratePluginGlobalCSS()
151 }
152
153 // ###################### Installation ######################
154
155 async install (toInstall: string, version?: string, fromDisk = false) {
156 let plugin: PluginModel
157 let name: string
158
159 logger.info('Installing plugin %s.', toInstall)
160
161 try {
162 fromDisk
163 ? await installNpmPluginFromDisk(toInstall)
164 : await installNpmPlugin(toInstall, version)
165
166 name = fromDisk ? basename(toInstall) : toInstall
167 const pluginType = PluginModel.getTypeFromNpmName(name)
168 const pluginName = PluginModel.normalizePluginName(name)
169
170 const packageJSON = this.getPackageJSON(pluginName, pluginType)
171 if (!isPackageJSONValid(packageJSON, pluginType)) {
172 throw new Error('PackageJSON is invalid.')
173 }
174
175 [ plugin ] = await PluginModel.upsert({
176 name: pluginName,
177 description: packageJSON.description,
178 homepage: packageJSON.homepage,
179 type: pluginType,
180 version: packageJSON.version,
181 enabled: true,
182 uninstalled: false,
183 peertubeEngine: packageJSON.engine.peertube
184 }, { returning: true })
185 } catch (err) {
186 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
187
188 try {
189 await removeNpmPlugin(name)
190 } catch (err) {
191 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
192 }
193
194 throw err
195 }
196
197 logger.info('Successful installation of plugin %s.', toInstall)
198
199 await this.registerPluginOrTheme(plugin)
200 }
201
202 async uninstall (npmName: string) {
203 logger.info('Uninstalling plugin %s.', npmName)
204
205 const pluginName = PluginModel.normalizePluginName(npmName)
206
207 try {
208 await this.unregister(pluginName)
209 } catch (err) {
210 logger.warn('Cannot unregister plugin %s.', pluginName, { err })
211 }
212
213 const plugin = await PluginModel.loadByNpmName(npmName)
214 if (!plugin || plugin.uninstalled === true) {
215 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
216 return
217 }
218
219 plugin.enabled = false
220 plugin.uninstalled = true
221
222 await plugin.save()
223
224 await removeNpmPlugin(npmName)
225
226 logger.info('Plugin %s uninstalled.', npmName)
227 }
228
229 // ###################### Private register ######################
230
231 private async registerPluginOrTheme (plugin: PluginModel) {
232 logger.info('Registering plugin or theme %s.', plugin.name)
233
234 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
235 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
236
237 if (!isPackageJSONValid(packageJSON, plugin.type)) {
238 throw new Error('Package.JSON is invalid.')
239 }
240
241 let library: PluginLibrary
242 if (plugin.type === PluginType.PLUGIN) {
243 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
244 }
245
246 const clientScripts: { [id: string]: ClientScript } = {}
247 for (const c of packageJSON.clientScripts) {
248 clientScripts[c.script] = c
249 }
250
251 this.registeredPlugins[ plugin.name ] = {
252 name: plugin.name,
253 type: plugin.type,
254 version: plugin.version,
255 description: plugin.description,
256 peertubeEngine: plugin.peertubeEngine,
257 path: pluginPath,
258 staticDirs: packageJSON.staticDirs,
259 clientScripts,
260 css: packageJSON.css,
261 unregister: library ? library.unregister : undefined
262 }
263 }
264
265 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
266 const registerHook = (options: RegisterHookOptions) => {
267 if (!this.hooks[options.target]) this.hooks[options.target] = []
268
269 this.hooks[options.target].push({
270 pluginName: plugin.name,
271 handler: options.handler,
272 priority: options.priority || 0
273 })
274 }
275
276 const registerSetting = (options: RegisterSettingOptions) => {
277 if (!this.settings[plugin.name]) this.settings[plugin.name] = []
278
279 this.settings[plugin.name].push(options)
280 }
281
282 const settingsManager: PluginSettingsManager = {
283 getSetting: (name: string) => PluginModel.getSetting(plugin.name, name),
284
285 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, name, value)
286 }
287
288 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
289
290 if (!isLibraryCodeValid(library)) {
291 throw new Error('Library code is not valid (miss register or unregister function)')
292 }
293
294 library.register({ registerHook, registerSetting, settingsManager })
295
296 logger.info('Add plugin %s CSS to global file.', plugin.name)
297
298 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
299
300 return library
301 }
302
303 // ###################### CSS ######################
304
305 private resetCSSGlobalFile () {
306 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
307 }
308
309 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
310 for (const cssPath of cssRelativePaths) {
311 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
312 }
313 }
314
315 private concatFiles (input: string, output: string) {
316 return new Promise<void>((res, rej) => {
317 const inputStream = createReadStream(input)
318 const outputStream = createWriteStream(output, { flags: 'a' })
319
320 inputStream.pipe(outputStream)
321
322 inputStream.on('end', () => res())
323 inputStream.on('error', err => rej(err))
324 })
325 }
326
327 private async regeneratePluginGlobalCSS () {
328 await this.resetCSSGlobalFile()
329
330 for (const key of Object.keys(this.registeredPlugins)) {
331 const plugin = this.registeredPlugins[key]
332
333 await this.addCSSToGlobalFile(plugin.path, plugin.css)
334 }
335 }
336
337 // ###################### Utils ######################
338
339 private sortHooksByPriority () {
340 for (const hookName of Object.keys(this.hooks)) {
341 this.hooks[hookName].sort((a, b) => {
342 return b.priority - a.priority
343 })
344 }
345 }
346
347 private getPackageJSON (pluginName: string, pluginType: PluginType) {
348 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
349
350 return require(pluginPath) as PluginPackageJson
351 }
352
353 private getPluginPath (pluginName: string, pluginType: PluginType) {
354 const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
355
356 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
357 }
358
359 // ###################### Private getters ######################
360
361 private getRegisteredPluginsOrThemes (type: PluginType) {
362 const plugins: RegisteredPlugin[] = []
363
364 for (const pluginName of Object.keys(this.registeredPlugins)) {
365 const plugin = this.registeredPlugins[ pluginName ]
366 if (plugin.type !== type) continue
367
368 plugins.push(plugin)
369 }
370
371 return plugins
372 }
373
374 static get Instance () {
375 return this.instance || (this.instance = new this())
376 }
377 }