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