]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
Add setting helper to client plugins
[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 { createReadStream, createWriteStream } from 'fs'
8 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
9 import { PluginType } from '../../../shared/models/plugins/plugin.type'
10 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
11 import { outputFile, readJSON } from 'fs-extra'
12 import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
13 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
14 import { ServerHook, ServerHookName, serverHookObject } from '../../../shared/models/plugins/server-hook.model'
15 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
16 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
17 import { PluginLibrary } from '../../typings/plugins'
18 import { ClientHtml } from '../client-html'
19 import { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
20 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
21
22 export interface RegisteredPlugin {
23 npmName: string
24 name: string
25 version: string
26 description: string
27 peertubeEngine: string
28
29 type: PluginType
30
31 path: string
32
33 staticDirs: { [name: string]: string }
34 clientScripts: { [name: string]: ClientScript }
35
36 css: string[]
37
38 // Only if this is a plugin
39 unregister?: Function
40 }
41
42 export interface HookInformationValue {
43 npmName: string
44 pluginName: string
45 handler: Function
46 priority: number
47 }
48
49 export class PluginManager implements ServerHook {
50
51 private static instance: PluginManager
52
53 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
54 private settings: { [ name: string ]: RegisterServerSettingOptions[] } = {}
55 private hooks: { [ name: string ]: HookInformationValue[] } = {}
56
57 private constructor () {
58 }
59
60 // ###################### Getters ######################
61
62 isRegistered (npmName: string) {
63 return !!this.getRegisteredPluginOrTheme(npmName)
64 }
65
66 getRegisteredPluginOrTheme (npmName: string) {
67 return this.registeredPlugins[npmName]
68 }
69
70 getRegisteredPlugin (name: string) {
71 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
72 const registered = this.getRegisteredPluginOrTheme(npmName)
73
74 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
75
76 return registered
77 }
78
79 getRegisteredTheme (name: string) {
80 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
81 const registered = this.getRegisteredPluginOrTheme(npmName)
82
83 if (!registered || registered.type !== PluginType.THEME) return undefined
84
85 return registered
86 }
87
88 getRegisteredPlugins () {
89 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
90 }
91
92 getRegisteredThemes () {
93 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
94 }
95
96 getRegisteredSettings (npmName: string) {
97 return this.settings[npmName] || []
98 }
99
100 // ###################### Hooks ######################
101
102 async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
103 if (!this.hooks[hookName]) return Promise.resolve(result)
104
105 const hookType = getHookType(hookName)
106
107 for (const hook of this.hooks[hookName]) {
108 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
109
110 result = await internalRunHook(hook.handler, hookType, result, params, err => {
111 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
112 })
113 }
114
115 return result
116 }
117
118 // ###################### Registration ######################
119
120 async registerPluginsAndThemes () {
121 await this.resetCSSGlobalFile()
122
123 const plugins = await PluginModel.listEnabledPluginsAndThemes()
124
125 for (const plugin of plugins) {
126 try {
127 await this.registerPluginOrTheme(plugin)
128 } catch (err) {
129 // Try to unregister the plugin
130 try {
131 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
132 } catch {
133 // we don't care if we cannot unregister it
134 }
135
136 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
137 }
138 }
139
140 this.sortHooksByPriority()
141 }
142
143 // Don't need the plugin type since themes cannot register server code
144 async unregister (npmName: string) {
145 logger.info('Unregister plugin %s.', npmName)
146
147 const plugin = this.getRegisteredPluginOrTheme(npmName)
148
149 if (!plugin) {
150 throw new Error(`Unknown plugin ${npmName} to unregister`)
151 }
152
153 delete this.registeredPlugins[plugin.npmName]
154 delete this.settings[plugin.npmName]
155
156 if (plugin.type === PluginType.PLUGIN) {
157 await plugin.unregister()
158
159 // Remove hooks of this plugin
160 for (const key of Object.keys(this.hooks)) {
161 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
162 }
163
164 logger.info('Regenerating registered plugin CSS to global file.')
165 await this.regeneratePluginGlobalCSS()
166 }
167 }
168
169 // ###################### Installation ######################
170
171 async install (toInstall: string, version?: string, fromDisk = false) {
172 let plugin: PluginModel
173 let npmName: string
174
175 logger.info('Installing plugin %s.', toInstall)
176
177 try {
178 fromDisk
179 ? await installNpmPluginFromDisk(toInstall)
180 : await installNpmPlugin(toInstall, version)
181
182 npmName = fromDisk ? basename(toInstall) : toInstall
183 const pluginType = PluginModel.getTypeFromNpmName(npmName)
184 const pluginName = PluginModel.normalizePluginName(npmName)
185
186 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
187 if (!isPackageJSONValid(packageJSON, pluginType)) {
188 throw new Error('PackageJSON is invalid.')
189 }
190
191 [ plugin ] = await PluginModel.upsert({
192 name: pluginName,
193 description: packageJSON.description,
194 homepage: packageJSON.homepage,
195 type: pluginType,
196 version: packageJSON.version,
197 enabled: true,
198 uninstalled: false,
199 peertubeEngine: packageJSON.engine.peertube
200 }, { returning: true })
201 } catch (err) {
202 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
203
204 try {
205 await removeNpmPlugin(npmName)
206 } catch (err) {
207 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
208 }
209
210 throw err
211 }
212
213 logger.info('Successful installation of plugin %s.', toInstall)
214
215 await this.registerPluginOrTheme(plugin)
216
217 return plugin
218 }
219
220 async update (toUpdate: string, version?: string, fromDisk = false) {
221 const npmName = fromDisk ? basename(toUpdate) : toUpdate
222
223 logger.info('Updating plugin %s.', npmName)
224
225 // Unregister old hooks
226 await this.unregister(npmName)
227
228 return this.install(toUpdate, version, fromDisk)
229 }
230
231 async uninstall (npmName: string) {
232 logger.info('Uninstalling plugin %s.', npmName)
233
234 try {
235 await this.unregister(npmName)
236 } catch (err) {
237 logger.warn('Cannot unregister plugin %s.', npmName, { err })
238 }
239
240 const plugin = await PluginModel.loadByNpmName(npmName)
241 if (!plugin || plugin.uninstalled === true) {
242 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
243 return
244 }
245
246 plugin.enabled = false
247 plugin.uninstalled = true
248
249 await plugin.save()
250
251 await removeNpmPlugin(npmName)
252
253 logger.info('Plugin %s uninstalled.', npmName)
254 }
255
256 // ###################### Private register ######################
257
258 private async registerPluginOrTheme (plugin: PluginModel) {
259 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
260
261 logger.info('Registering plugin or theme %s.', npmName)
262
263 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
264 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
265
266 if (!isPackageJSONValid(packageJSON, plugin.type)) {
267 throw new Error('Package.JSON is invalid.')
268 }
269
270 let library: PluginLibrary
271 if (plugin.type === PluginType.PLUGIN) {
272 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
273 }
274
275 const clientScripts: { [id: string]: ClientScript } = {}
276 for (const c of packageJSON.clientScripts) {
277 clientScripts[c.script] = c
278 }
279
280 this.registeredPlugins[ npmName ] = {
281 npmName,
282 name: plugin.name,
283 type: plugin.type,
284 version: plugin.version,
285 description: plugin.description,
286 peertubeEngine: plugin.peertubeEngine,
287 path: pluginPath,
288 staticDirs: packageJSON.staticDirs,
289 clientScripts,
290 css: packageJSON.css,
291 unregister: library ? library.unregister : undefined
292 }
293 }
294
295 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
296 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
297
298 // Delete cache if needed
299 const modulePath = join(pluginPath, packageJSON.library)
300 delete require.cache[modulePath]
301 const library: PluginLibrary = require(modulePath)
302
303 if (!isLibraryCodeValid(library)) {
304 throw new Error('Library code is not valid (miss register or unregister function)')
305 }
306
307 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
308 library.register(registerHelpers)
309 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
310
311 logger.info('Add plugin %s CSS to global file.', npmName)
312
313 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
314
315 return library
316 }
317
318 // ###################### CSS ######################
319
320 private resetCSSGlobalFile () {
321 ClientHtml.invalidCache()
322
323 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
324 }
325
326 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
327 for (const cssPath of cssRelativePaths) {
328 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
329 }
330
331 ClientHtml.invalidCache()
332 }
333
334 private concatFiles (input: string, output: string) {
335 return new Promise<void>((res, rej) => {
336 const inputStream = createReadStream(input)
337 const outputStream = createWriteStream(output, { flags: 'a' })
338
339 inputStream.pipe(outputStream)
340
341 inputStream.on('end', () => res())
342 inputStream.on('error', err => rej(err))
343 })
344 }
345
346 private async regeneratePluginGlobalCSS () {
347 await this.resetCSSGlobalFile()
348
349 for (const key of Object.keys(this.getRegisteredPlugins())) {
350 const plugin = this.registeredPlugins[key]
351
352 await this.addCSSToGlobalFile(plugin.path, plugin.css)
353 }
354 }
355
356 // ###################### Utils ######################
357
358 private sortHooksByPriority () {
359 for (const hookName of Object.keys(this.hooks)) {
360 this.hooks[hookName].sort((a, b) => {
361 return b.priority - a.priority
362 })
363 }
364 }
365
366 private getPackageJSON (pluginName: string, pluginType: PluginType) {
367 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
368
369 return readJSON(pluginPath) as Promise<PluginPackageJson>
370 }
371
372 private getPluginPath (pluginName: string, pluginType: PluginType) {
373 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
374
375 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
376 }
377
378 // ###################### Private getters ######################
379
380 private getRegisteredPluginsOrThemes (type: PluginType) {
381 const plugins: RegisteredPlugin[] = []
382
383 for (const npmName of Object.keys(this.registeredPlugins)) {
384 const plugin = this.registeredPlugins[ npmName ]
385 if (plugin.type !== type) continue
386
387 plugins.push(plugin)
388 }
389
390 return plugins
391 }
392
393 // ###################### Generate register helpers ######################
394
395 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
396 const registerHook = (options: RegisterServerHookOptions) => {
397 if (serverHookObject[options.target] !== true) {
398 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
399 return
400 }
401
402 if (!this.hooks[options.target]) this.hooks[options.target] = []
403
404 this.hooks[options.target].push({
405 npmName,
406 pluginName: plugin.name,
407 handler: options.handler,
408 priority: options.priority || 0
409 })
410 }
411
412 const registerSetting = (options: RegisterServerSettingOptions) => {
413 if (!this.settings[npmName]) this.settings[npmName] = []
414
415 this.settings[npmName].push(options)
416 }
417
418 const settingsManager: PluginSettingsManager = {
419 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
420
421 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
422 }
423
424 const storageManager: PluginStorageManager = {
425 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
426
427 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
428 }
429
430 const peertubeHelpers = {
431 logger
432 }
433
434 return {
435 registerHook,
436 registerSetting,
437 settingsManager,
438 storageManager,
439 peertubeHelpers
440 }
441 }
442
443 static get Instance () {
444 return this.instance || (this.instance = new this())
445 }
446 }