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