]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
Tests that show the bug.
[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 { RegisterHelpers } from './register-helpers'
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 registerHelpers?: RegisterHelpers
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.registerHelpers.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.registerHelpers.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.registerHelpers.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.registerHelpers.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.registerHelpers.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.registerHelpers
272 store.reinitVideoConstants(plugin.npmName)
273 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
274
275 logger.info('Regenerating registered plugin CSS to global file.')
276 await this.regeneratePluginGlobalCSS()
277 }
278 }
279
280 // ###################### Installation ######################
281
282 async install (toInstall: string, version?: string, fromDisk = false) {
283 let plugin: PluginModel
284 let npmName: string
285
286 logger.info('Installing plugin %s.', toInstall)
287
288 try {
289 fromDisk
290 ? await installNpmPluginFromDisk(toInstall)
291 : await installNpmPlugin(toInstall, version)
292
293 npmName = fromDisk ? basename(toInstall) : toInstall
294 const pluginType = PluginModel.getTypeFromNpmName(npmName)
295 const pluginName = PluginModel.normalizePluginName(npmName)
296
297 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
298
299 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
300
301 [ plugin ] = await PluginModel.upsert({
302 name: pluginName,
303 description: packageJSON.description,
304 homepage: packageJSON.homepage,
305 type: pluginType,
306 version: packageJSON.version,
307 enabled: true,
308 uninstalled: false,
309 peertubeEngine: packageJSON.engine.peertube
310 }, { returning: true })
311 } catch (err) {
312 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
313
314 try {
315 await removeNpmPlugin(npmName)
316 } catch (err) {
317 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
318 }
319
320 throw err
321 }
322
323 logger.info('Successful installation of plugin %s.', toInstall)
324
325 await this.registerPluginOrTheme(plugin)
326
327 return plugin
328 }
329
330 async update (toUpdate: string, version?: string, fromDisk = false) {
331 const npmName = fromDisk ? basename(toUpdate) : toUpdate
332
333 logger.info('Updating plugin %s.', npmName)
334
335 // Unregister old hooks
336 await this.unregister(npmName)
337
338 return this.install(toUpdate, version, fromDisk)
339 }
340
341 async uninstall (npmName: string) {
342 logger.info('Uninstalling plugin %s.', npmName)
343
344 try {
345 await this.unregister(npmName)
346 } catch (err) {
347 logger.warn('Cannot unregister plugin %s.', npmName, { err })
348 }
349
350 const plugin = await PluginModel.loadByNpmName(npmName)
351 if (!plugin || plugin.uninstalled === true) {
352 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
353 return
354 }
355
356 plugin.enabled = false
357 plugin.uninstalled = true
358
359 await plugin.save()
360
361 await removeNpmPlugin(npmName)
362
363 logger.info('Plugin %s uninstalled.', npmName)
364 }
365
366 // ###################### Private register ######################
367
368 private async registerPluginOrTheme (plugin: PluginModel) {
369 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
370
371 logger.info('Registering plugin or theme %s.', npmName)
372
373 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
374 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
375
376 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
377
378 let library: PluginLibrary
379 let registerHelpers: RegisterHelpers
380 if (plugin.type === PluginType.PLUGIN) {
381 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
382 library = result.library
383 registerHelpers = result.registerStore
384 }
385
386 const clientScripts: { [id: string]: ClientScript } = {}
387 for (const c of packageJSON.clientScripts) {
388 clientScripts[c.script] = c
389 }
390
391 this.registeredPlugins[npmName] = {
392 npmName,
393 name: plugin.name,
394 type: plugin.type,
395 version: plugin.version,
396 description: plugin.description,
397 peertubeEngine: plugin.peertubeEngine,
398 path: pluginPath,
399 staticDirs: packageJSON.staticDirs,
400 clientScripts,
401 css: packageJSON.css,
402 registerHelpers: registerHelpers || undefined,
403 unregister: library ? library.unregister : undefined
404 }
405
406 await this.addTranslations(plugin, npmName, packageJSON.translations)
407 }
408
409 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
410 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
411
412 // Delete cache if needed
413 const modulePath = join(pluginPath, packageJSON.library)
414 delete require.cache[modulePath]
415 const library: PluginLibrary = require(modulePath)
416
417 if (!isLibraryCodeValid(library)) {
418 throw new Error('Library code is not valid (miss register or unregister function)')
419 }
420
421 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
422 library.register(registerOptions)
423 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
424
425 logger.info('Add plugin %s CSS to global file.', npmName)
426
427 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
428
429 return { library, registerStore }
430 }
431
432 // ###################### Translations ######################
433
434 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
435 for (const locale of Object.keys(translationPaths)) {
436 const path = translationPaths[locale]
437 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
438
439 if (!this.translations[locale]) this.translations[locale] = {}
440 this.translations[locale][npmName] = json
441
442 logger.info('Added locale %s of plugin %s.', locale, npmName)
443 }
444 }
445
446 private deleteTranslations (npmName: string) {
447 for (const locale of Object.keys(this.translations)) {
448 delete this.translations[locale][npmName]
449
450 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
451 }
452 }
453
454 // ###################### CSS ######################
455
456 private resetCSSGlobalFile () {
457 ClientHtml.invalidCache()
458
459 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
460 }
461
462 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
463 for (const cssPath of cssRelativePaths) {
464 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
465 }
466
467 ClientHtml.invalidCache()
468 }
469
470 private concatFiles (input: string, output: string) {
471 return new Promise<void>((res, rej) => {
472 const inputStream = createReadStream(input)
473 const outputStream = createWriteStream(output, { flags: 'a' })
474
475 inputStream.pipe(outputStream)
476
477 inputStream.on('end', () => res())
478 inputStream.on('error', err => rej(err))
479 })
480 }
481
482 private async regeneratePluginGlobalCSS () {
483 await this.resetCSSGlobalFile()
484
485 for (const plugin of this.getRegisteredPlugins()) {
486 await this.addCSSToGlobalFile(plugin.path, plugin.css)
487 }
488 }
489
490 // ###################### Utils ######################
491
492 private sortHooksByPriority () {
493 for (const hookName of Object.keys(this.hooks)) {
494 this.hooks[hookName].sort((a, b) => {
495 return b.priority - a.priority
496 })
497 }
498 }
499
500 private getPackageJSON (pluginName: string, pluginType: PluginType) {
501 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
502
503 return readJSON(pluginPath) as Promise<PluginPackageJson>
504 }
505
506 private getPluginPath (pluginName: string, pluginType: PluginType) {
507 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
508
509 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
510 }
511
512 private getAuth (npmName: string, authName: string) {
513 const plugin = this.getRegisteredPluginOrTheme(npmName)
514 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
515
516 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
517 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
518
519 return auths.find(a => a.authName === authName)
520 }
521
522 // ###################### Private getters ######################
523
524 private getRegisteredPluginsOrThemes (type: PluginType) {
525 const plugins: RegisteredPlugin[] = []
526
527 for (const npmName of Object.keys(this.registeredPlugins)) {
528 const plugin = this.registeredPlugins[npmName]
529 if (plugin.type !== type) continue
530
531 plugins.push(plugin)
532 }
533
534 return plugins
535 }
536
537 // ###################### Generate register helpers ######################
538
539 private getRegisterHelpers (
540 npmName: string,
541 plugin: PluginModel
542 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
543 const onHookAdded = (options: RegisterServerHookOptions) => {
544 if (!this.hooks[options.target]) this.hooks[options.target] = []
545
546 this.hooks[options.target].push({
547 npmName: npmName,
548 pluginName: plugin.name,
549 handler: options.handler,
550 priority: options.priority || 0
551 })
552 }
553
554 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
555
556 return {
557 registerStore: registerHelpers,
558 registerOptions: registerHelpers.buildRegisterHelpers()
559 }
560 }
561
562 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
563 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
564 if (!packageJSON.css) packageJSON.css = []
565 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
566 if (!packageJSON.translations) packageJSON.translations = {}
567
568 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
569 if (!packageJSONValid) {
570 const formattedFields = badFields.map(f => `"${f}"`)
571 .join(', ')
572
573 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
574 }
575 }
576
577 static get Instance () {
578 return this.instance || (this.instance = new this())
579 }
580 }