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