]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
444162a0328ac1e1aa415a549f9bc571b1e66643
[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 {
7 ClientScript,
8 PluginPackageJson,
9 PluginTranslationPaths as PackagePluginTranslations
10 } from '../../../shared/models/plugins/plugin-package-json.model'
11 import { createReadStream, createWriteStream } from 'fs'
12 import { PLUGIN_GLOBAL_CSS_PATH, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../../initializers/constants'
13 import { PluginType } from '../../../shared/models/plugins/plugin.type'
14 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
15 import { outputFile, readJSON } from 'fs-extra'
16 import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
17 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
18 import { ServerHook, ServerHookName, serverHookObject } from '../../../shared/models/plugins/server-hook.model'
19 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
20 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
21 import { PluginLibrary } from '../../typings/plugins'
22 import { ClientHtml } from '../client-html'
23 import { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
24 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
25 import { PluginVideoLanguageManager } from '../../../shared/models/plugins/plugin-video-language-manager.model'
26 import { PluginVideoCategoryManager } from '../../../shared/models/plugins/plugin-video-category-manager.model'
27 import { PluginVideoLicenceManager } from '../../../shared/models/plugins/plugin-video-licence-manager.model'
28 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
29
30 export interface RegisteredPlugin {
31 npmName: string
32 name: string
33 version: string
34 description: string
35 peertubeEngine: string
36
37 type: PluginType
38
39 path: string
40
41 staticDirs: { [name: string]: string }
42 clientScripts: { [name: string]: ClientScript }
43
44 css: string[]
45
46 // Only if this is a plugin
47 unregister?: Function
48 }
49
50 export interface HookInformationValue {
51 npmName: string
52 pluginName: string
53 handler: Function
54 priority: number
55 }
56
57 type AlterableVideoConstant = 'language' | 'licence' | 'category'
58 type VideoConstant = { [ key in number | string ]: string }
59 type UpdatedVideoConstant = {
60 [ name in AlterableVideoConstant ]: {
61 [ npmName: string ]: {
62 added: { key: number | string, label: string }[],
63 deleted: { key: number | string, label: string }[]
64 }
65 }
66 }
67
68 type PluginLocalesTranslations = {
69 [ locale: string ]: PluginTranslation
70 }
71
72 export class PluginManager implements ServerHook {
73
74 private static instance: PluginManager
75
76 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
77 private settings: { [ name: string ]: RegisterServerSettingOptions[] } = {}
78 private hooks: { [ name: string ]: HookInformationValue[] } = {}
79 private translations: PluginLocalesTranslations = {}
80
81 private updatedVideoConstants: UpdatedVideoConstant = {
82 language: {},
83 licence: {},
84 category: {}
85 }
86
87 private constructor () {
88 }
89
90 // ###################### Getters ######################
91
92 isRegistered (npmName: string) {
93 return !!this.getRegisteredPluginOrTheme(npmName)
94 }
95
96 getRegisteredPluginOrTheme (npmName: string) {
97 return this.registeredPlugins[npmName]
98 }
99
100 getRegisteredPlugin (name: string) {
101 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
102 const registered = this.getRegisteredPluginOrTheme(npmName)
103
104 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
105
106 return registered
107 }
108
109 getRegisteredTheme (name: string) {
110 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
111 const registered = this.getRegisteredPluginOrTheme(npmName)
112
113 if (!registered || registered.type !== PluginType.THEME) return undefined
114
115 return registered
116 }
117
118 getRegisteredPlugins () {
119 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
120 }
121
122 getRegisteredThemes () {
123 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
124 }
125
126 getRegisteredSettings (npmName: string) {
127 return this.settings[npmName] || []
128 }
129
130 getTranslations (locale: string) {
131 return this.translations[locale] || {}
132 }
133
134 // ###################### Hooks ######################
135
136 async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
137 if (!this.hooks[hookName]) return Promise.resolve(result)
138
139 const hookType = getHookType(hookName)
140
141 for (const hook of this.hooks[hookName]) {
142 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
143
144 result = await internalRunHook(hook.handler, hookType, result, params, err => {
145 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
146 })
147 }
148
149 return result
150 }
151
152 // ###################### Registration ######################
153
154 async registerPluginsAndThemes () {
155 await this.resetCSSGlobalFile()
156
157 const plugins = await PluginModel.listEnabledPluginsAndThemes()
158
159 for (const plugin of plugins) {
160 try {
161 await this.registerPluginOrTheme(plugin)
162 } catch (err) {
163 // Try to unregister the plugin
164 try {
165 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
166 } catch {
167 // we don't care if we cannot unregister it
168 }
169
170 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
171 }
172 }
173
174 this.sortHooksByPriority()
175 }
176
177 // Don't need the plugin type since themes cannot register server code
178 async unregister (npmName: string) {
179 logger.info('Unregister plugin %s.', npmName)
180
181 const plugin = this.getRegisteredPluginOrTheme(npmName)
182
183 if (!plugin) {
184 throw new Error(`Unknown plugin ${npmName} to unregister`)
185 }
186
187 delete this.registeredPlugins[plugin.npmName]
188 delete this.settings[plugin.npmName]
189
190 this.deleteTranslations(plugin.npmName)
191
192 if (plugin.type === PluginType.PLUGIN) {
193 await plugin.unregister()
194
195 // Remove hooks of this plugin
196 for (const key of Object.keys(this.hooks)) {
197 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== npmName)
198 }
199
200 this.reinitVideoConstants(plugin.npmName)
201
202 logger.info('Regenerating registered plugin CSS to global file.')
203 await this.regeneratePluginGlobalCSS()
204 }
205 }
206
207 // ###################### Installation ######################
208
209 async install (toInstall: string, version?: string, fromDisk = false) {
210 let plugin: PluginModel
211 let npmName: string
212
213 logger.info('Installing plugin %s.', toInstall)
214
215 try {
216 fromDisk
217 ? await installNpmPluginFromDisk(toInstall)
218 : await installNpmPlugin(toInstall, version)
219
220 npmName = fromDisk ? basename(toInstall) : toInstall
221 const pluginType = PluginModel.getTypeFromNpmName(npmName)
222 const pluginName = PluginModel.normalizePluginName(npmName)
223
224 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
225 if (!isPackageJSONValid(packageJSON, pluginType)) {
226 throw new Error('PackageJSON is invalid.')
227 }
228
229 [ plugin ] = await PluginModel.upsert({
230 name: pluginName,
231 description: packageJSON.description,
232 homepage: packageJSON.homepage,
233 type: pluginType,
234 version: packageJSON.version,
235 enabled: true,
236 uninstalled: false,
237 peertubeEngine: packageJSON.engine.peertube
238 }, { returning: true })
239 } catch (err) {
240 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
241
242 try {
243 await removeNpmPlugin(npmName)
244 } catch (err) {
245 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
246 }
247
248 throw err
249 }
250
251 logger.info('Successful installation of plugin %s.', toInstall)
252
253 await this.registerPluginOrTheme(plugin)
254
255 return plugin
256 }
257
258 async update (toUpdate: string, version?: string, fromDisk = false) {
259 const npmName = fromDisk ? basename(toUpdate) : toUpdate
260
261 logger.info('Updating plugin %s.', npmName)
262
263 // Unregister old hooks
264 await this.unregister(npmName)
265
266 return this.install(toUpdate, version, fromDisk)
267 }
268
269 async uninstall (npmName: string) {
270 logger.info('Uninstalling plugin %s.', npmName)
271
272 try {
273 await this.unregister(npmName)
274 } catch (err) {
275 logger.warn('Cannot unregister plugin %s.', npmName, { err })
276 }
277
278 const plugin = await PluginModel.loadByNpmName(npmName)
279 if (!plugin || plugin.uninstalled === true) {
280 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
281 return
282 }
283
284 plugin.enabled = false
285 plugin.uninstalled = true
286
287 await plugin.save()
288
289 await removeNpmPlugin(npmName)
290
291 logger.info('Plugin %s uninstalled.', npmName)
292 }
293
294 // ###################### Private register ######################
295
296 private async registerPluginOrTheme (plugin: PluginModel) {
297 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
298
299 logger.info('Registering plugin or theme %s.', npmName)
300
301 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
302 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
303
304 if (!isPackageJSONValid(packageJSON, plugin.type)) {
305 throw new Error('Package.JSON is invalid.')
306 }
307
308 let library: PluginLibrary
309 if (plugin.type === PluginType.PLUGIN) {
310 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
311 }
312
313 const clientScripts: { [id: string]: ClientScript } = {}
314 for (const c of packageJSON.clientScripts) {
315 clientScripts[c.script] = c
316 }
317
318 this.registeredPlugins[ npmName ] = {
319 npmName,
320 name: plugin.name,
321 type: plugin.type,
322 version: plugin.version,
323 description: plugin.description,
324 peertubeEngine: plugin.peertubeEngine,
325 path: pluginPath,
326 staticDirs: packageJSON.staticDirs,
327 clientScripts,
328 css: packageJSON.css,
329 unregister: library ? library.unregister : undefined
330 }
331
332 await this.addTranslations(plugin, npmName, packageJSON.translations)
333 }
334
335 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
336 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
337
338 // Delete cache if needed
339 const modulePath = join(pluginPath, packageJSON.library)
340 delete require.cache[modulePath]
341 const library: PluginLibrary = require(modulePath)
342
343 if (!isLibraryCodeValid(library)) {
344 throw new Error('Library code is not valid (miss register or unregister function)')
345 }
346
347 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
348 library.register(registerHelpers)
349 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
350
351 logger.info('Add plugin %s CSS to global file.', npmName)
352
353 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
354
355 return library
356 }
357
358 // ###################### Translations ######################
359
360 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
361 for (const locale of Object.keys(translationPaths)) {
362 const path = translationPaths[locale]
363 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
364
365 if (!this.translations[locale]) this.translations[locale] = {}
366 this.translations[locale][npmName] = json
367
368 logger.info('Added locale %s of plugin %s.', locale, npmName)
369 }
370 }
371
372 private deleteTranslations (npmName: string) {
373 for (const locale of Object.keys(this.translations)) {
374 delete this.translations[locale][npmName]
375
376 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
377 }
378 }
379
380 // ###################### CSS ######################
381
382 private resetCSSGlobalFile () {
383 ClientHtml.invalidCache()
384
385 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
386 }
387
388 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
389 for (const cssPath of cssRelativePaths) {
390 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
391 }
392
393 ClientHtml.invalidCache()
394 }
395
396 private concatFiles (input: string, output: string) {
397 return new Promise<void>((res, rej) => {
398 const inputStream = createReadStream(input)
399 const outputStream = createWriteStream(output, { flags: 'a' })
400
401 inputStream.pipe(outputStream)
402
403 inputStream.on('end', () => res())
404 inputStream.on('error', err => rej(err))
405 })
406 }
407
408 private async regeneratePluginGlobalCSS () {
409 await this.resetCSSGlobalFile()
410
411 for (const plugin of this.getRegisteredPlugins()) {
412 await this.addCSSToGlobalFile(plugin.path, plugin.css)
413 }
414 }
415
416 // ###################### Utils ######################
417
418 private sortHooksByPriority () {
419 for (const hookName of Object.keys(this.hooks)) {
420 this.hooks[hookName].sort((a, b) => {
421 return b.priority - a.priority
422 })
423 }
424 }
425
426 private getPackageJSON (pluginName: string, pluginType: PluginType) {
427 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
428
429 return readJSON(pluginPath) as Promise<PluginPackageJson>
430 }
431
432 private getPluginPath (pluginName: string, pluginType: PluginType) {
433 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
434
435 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
436 }
437
438 // ###################### Private getters ######################
439
440 private getRegisteredPluginsOrThemes (type: PluginType) {
441 const plugins: RegisteredPlugin[] = []
442
443 for (const npmName of Object.keys(this.registeredPlugins)) {
444 const plugin = this.registeredPlugins[ npmName ]
445 if (plugin.type !== type) continue
446
447 plugins.push(plugin)
448 }
449
450 return plugins
451 }
452
453 // ###################### Generate register helpers ######################
454
455 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
456 const registerHook = (options: RegisterServerHookOptions) => {
457 if (serverHookObject[options.target] !== true) {
458 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
459 return
460 }
461
462 if (!this.hooks[options.target]) this.hooks[options.target] = []
463
464 this.hooks[options.target].push({
465 npmName,
466 pluginName: plugin.name,
467 handler: options.handler,
468 priority: options.priority || 0
469 })
470 }
471
472 const registerSetting = (options: RegisterServerSettingOptions) => {
473 if (!this.settings[npmName]) this.settings[npmName] = []
474
475 this.settings[npmName].push(options)
476 }
477
478 const settingsManager: PluginSettingsManager = {
479 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
480
481 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
482 }
483
484 const storageManager: PluginStorageManager = {
485 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
486
487 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
488 }
489
490 const videoLanguageManager: PluginVideoLanguageManager = {
491 addLanguage: (key: string, label: string) => this.addConstant({ npmName, type: 'language', obj: VIDEO_LANGUAGES, key, label }),
492
493 deleteLanguage: (key: string) => this.deleteConstant({ npmName, type: 'language', obj: VIDEO_LANGUAGES, key })
494 }
495
496 const videoCategoryManager: PluginVideoCategoryManager = {
497 addCategory: (key: number, label: string) => this.addConstant({ npmName, type: 'category', obj: VIDEO_CATEGORIES, key, label }),
498
499 deleteCategory: (key: number) => this.deleteConstant({ npmName, type: 'category', obj: VIDEO_CATEGORIES, key })
500 }
501
502 const videoLicenceManager: PluginVideoLicenceManager = {
503 addLicence: (key: number, label: string) => this.addConstant({ npmName, type: 'licence', obj: VIDEO_LICENCES, key, label }),
504
505 deleteLicence: (key: number) => this.deleteConstant({ npmName, type: 'licence', obj: VIDEO_LICENCES, key })
506 }
507
508 const peertubeHelpers = {
509 logger
510 }
511
512 return {
513 registerHook,
514 registerSetting,
515 settingsManager,
516 storageManager,
517 videoLanguageManager,
518 videoCategoryManager,
519 videoLicenceManager,
520 peertubeHelpers
521 }
522 }
523
524 private addConstant <T extends string | number> (parameters: {
525 npmName: string,
526 type: AlterableVideoConstant,
527 obj: VideoConstant,
528 key: T,
529 label: string
530 }) {
531 const { npmName, type, obj, key, label } = parameters
532
533 if (obj[key]) {
534 logger.warn('Cannot add %s %s by plugin %s: key already exists.', type, npmName, key)
535 return false
536 }
537
538 if (!this.updatedVideoConstants[type][npmName]) {
539 this.updatedVideoConstants[type][npmName] = {
540 added: [],
541 deleted: []
542 }
543 }
544
545 this.updatedVideoConstants[type][npmName].added.push({ key, label })
546 obj[key] = label
547
548 return true
549 }
550
551 private deleteConstant <T extends string | number> (parameters: {
552 npmName: string,
553 type: AlterableVideoConstant,
554 obj: VideoConstant,
555 key: T
556 }) {
557 const { npmName, type, obj, key } = parameters
558
559 if (!obj[key]) {
560 logger.warn('Cannot delete %s %s by plugin %s: key does not exist.', type, npmName, key)
561 return false
562 }
563
564 if (!this.updatedVideoConstants[type][npmName]) {
565 this.updatedVideoConstants[type][npmName] = {
566 added: [],
567 deleted: []
568 }
569 }
570
571 this.updatedVideoConstants[type][npmName].deleted.push({ key, label: obj[key] })
572 delete obj[key]
573
574 return true
575 }
576
577 private reinitVideoConstants (npmName: string) {
578 const hash = {
579 language: VIDEO_LANGUAGES,
580 licence: VIDEO_LICENCES,
581 category: VIDEO_CATEGORIES
582 }
583 const types: AlterableVideoConstant[] = [ 'language', 'licence', 'category' ]
584
585 for (const type of types) {
586 const updatedConstants = this.updatedVideoConstants[type][npmName]
587 if (!updatedConstants) continue
588
589 for (const added of updatedConstants.added) {
590 delete hash[type][added.key]
591 }
592
593 for (const deleted of updatedConstants.deleted) {
594 hash[type][deleted.key] = deleted.label
595 }
596
597 delete this.updatedVideoConstants[type][npmName]
598 }
599 }
600
601 static get Instance () {
602 return this.instance || (this.instance = new this())
603 }
604 }