]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/plugins/plugin-manager.ts
Merge branch 'release/4.0.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
CommitLineData
41fb13c3 1import express from 'express'
67ed6552 2import { createReadStream, createWriteStream } from 'fs'
302eba0d 3import { ensureDir, outputFile, readJSON } from 'fs-extra'
f023a19c 4import { basename, join } from 'path'
ca87d95b 5import { decachePlugin } from '@server/helpers/decache'
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 })
9c2e051c
C
307
308 logger.info('Successful installation of plugin %s.', toInstall)
309
310 await this.registerPluginOrTheme(plugin)
311 } catch (rootErr) {
312 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
f023a19c
C
313
314 try {
9213df1d 315 await this.uninstall(npmName)
f023a19c 316 } catch (err) {
9c2e051c
C
317 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
318
319 try {
9213df1d 320 await removeNpmPlugin(npmName)
9c2e051c
C
321 } catch (err) {
322 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
323 }
f023a19c
C
324 }
325
9c2e051c 326 throw rootErr
f023a19c
C
327 }
328
b5f919ac
C
329 return plugin
330 }
331
8280d0c2 332 async update (toUpdate: string, fromDisk = false) {
b5f919ac
C
333 const npmName = fromDisk ? basename(toUpdate) : toUpdate
334
335 logger.info('Updating plugin %s.', npmName)
336
8280d0c2
C
337 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
338 let version: string
339 if (!fromDisk) {
340 const plugin = await PluginModel.loadByNpmName(toUpdate)
341 version = plugin.latestVersion
342 }
343
b5f919ac
C
344 // Unregister old hooks
345 await this.unregister(npmName)
346
347 return this.install(toUpdate, version, fromDisk)
f023a19c
C
348 }
349
dba85a1e
C
350 async uninstall (npmName: string) {
351 logger.info('Uninstalling plugin %s.', npmName)
2c053942 352
2c053942 353 try {
b5f919ac 354 await this.unregister(npmName)
2c053942 355 } catch (err) {
b5f919ac 356 logger.warn('Cannot unregister plugin %s.', npmName, { err })
2c053942
C
357 }
358
dba85a1e 359 const plugin = await PluginModel.loadByNpmName(npmName)
2c053942 360 if (!plugin || plugin.uninstalled === true) {
dba85a1e 361 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
2c053942
C
362 return
363 }
364
365 plugin.enabled = false
366 plugin.uninstalled = true
367
368 await plugin.save()
f023a19c 369
dba85a1e 370 await removeNpmPlugin(npmName)
2c053942 371
dba85a1e 372 logger.info('Plugin %s uninstalled.', npmName)
f023a19c
C
373 }
374
ad91e700
C
375 // ###################### Private register ######################
376
345da516 377 private async registerPluginOrTheme (plugin: PluginModel) {
b5f919ac
C
378 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
379
380 logger.info('Registering plugin or theme %s.', npmName)
345da516 381
09071200 382 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
f023a19c 383 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
345da516 384
9157d598 385 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
345da516
C
386
387 let library: PluginLibrary
1896bca0 388 let registerHelpers: RegisterHelpers
345da516 389 if (plugin.type === PluginType.PLUGIN) {
7fed6375
C
390 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
391 library = result.library
1896bca0 392 registerHelpers = result.registerStore
345da516
C
393 }
394
2c053942
C
395 const clientScripts: { [id: string]: ClientScript } = {}
396 for (const c of packageJSON.clientScripts) {
397 clientScripts[c.script] = c
398 }
399
a1587156 400 this.registeredPlugins[npmName] = {
b5f919ac 401 npmName,
345da516
C
402 name: plugin.name,
403 type: plugin.type,
404 version: plugin.version,
405 description: plugin.description,
406 peertubeEngine: plugin.peertubeEngine,
407 path: pluginPath,
408 staticDirs: packageJSON.staticDirs,
2c053942 409 clientScripts,
345da516 410 css: packageJSON.css,
1896bca0 411 registerHelpers: registerHelpers || undefined,
345da516
C
412 unregister: library ? library.unregister : undefined
413 }
d75db01f
C
414
415 await this.addTranslations(plugin, npmName, packageJSON.translations)
345da516
C
416 }
417
418 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
b5f919ac
C
419 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
420
09071200
C
421 // Delete cache if needed
422 const modulePath = join(pluginPath, packageJSON.library)
ca87d95b 423 decachePlugin(pluginPath, modulePath)
09071200 424 const library: PluginLibrary = require(modulePath)
f023a19c 425
345da516
C
426 if (!isLibraryCodeValid(library)) {
427 throw new Error('Library code is not valid (miss register or unregister function)')
428 }
429
7fed6375 430 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
302eba0d
C
431
432 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
433
9c2e051c 434 await library.register(registerOptions)
345da516 435
b5f919ac 436 logger.info('Add plugin %s CSS to global file.', npmName)
345da516
C
437
438 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
439
7fed6375 440 return { library, registerStore }
345da516
C
441 }
442
d75db01f
C
443 // ###################### Translations ######################
444
428ccb8b 445 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPaths) {
d75db01f
C
446 for (const locale of Object.keys(translationPaths)) {
447 const path = translationPaths[locale]
448 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
449
67baf647 450 const completeLocale = getCompleteLocale(locale)
d75db01f 451
67baf647
C
452 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
453 this.translations[completeLocale][npmName] = json
454
455 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
d75db01f
C
456 }
457 }
458
459 private deleteTranslations (npmName: string) {
460 for (const locale of Object.keys(this.translations)) {
461 delete this.translations[locale][npmName]
462
463 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
464 }
465 }
466
ad91e700 467 // ###################### CSS ######################
345da516 468
2c053942 469 private resetCSSGlobalFile () {
3e753302
C
470 ClientHtml.invalidCache()
471
2c053942
C
472 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
473 }
474
345da516
C
475 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
476 for (const cssPath of cssRelativePaths) {
477 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
478 }
a8b666e9
C
479
480 ClientHtml.invalidCache()
345da516
C
481 }
482
483 private concatFiles (input: string, output: string) {
484 return new Promise<void>((res, rej) => {
2c053942
C
485 const inputStream = createReadStream(input)
486 const outputStream = createWriteStream(output, { flags: 'a' })
345da516
C
487
488 inputStream.pipe(outputStream)
489
490 inputStream.on('end', () => res())
491 inputStream.on('error', err => rej(err))
492 })
493 }
494
ad91e700
C
495 private async regeneratePluginGlobalCSS () {
496 await this.resetCSSGlobalFile()
497
1198edf4 498 for (const plugin of this.getRegisteredPlugins()) {
ad91e700
C
499 await this.addCSSToGlobalFile(plugin.path, plugin.css)
500 }
501 }
502
503 // ###################### Utils ######################
504
505 private sortHooksByPriority () {
506 for (const hookName of Object.keys(this.hooks)) {
507 this.hooks[hookName].sort((a, b) => {
508 return b.priority - a.priority
509 })
510 }
511 }
512
f023a19c
C
513 private getPackageJSON (pluginName: string, pluginType: PluginType) {
514 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
515
09071200 516 return readJSON(pluginPath) as Promise<PluginPackageJson>
f023a19c
C
517 }
518
519 private getPluginPath (pluginName: string, pluginType: PluginType) {
b5f919ac 520 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
f023a19c 521
b5f919ac 522 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
f023a19c
C
523 }
524
e307e4fc
C
525 private getAuth (npmName: string, authName: string) {
526 const plugin = this.getRegisteredPluginOrTheme(npmName)
527 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
528
1896bca0
C
529 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
530 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
9107d791
C
531
532 return auths.find(a => a.authName === authName)
e307e4fc
C
533 }
534
ad91e700 535 // ###################### Private getters ######################
2c053942 536
7cd4d2ba
C
537 private getRegisteredPluginsOrThemes (type: PluginType) {
538 const plugins: RegisteredPlugin[] = []
539
b5f919ac 540 for (const npmName of Object.keys(this.registeredPlugins)) {
a1587156 541 const plugin = this.registeredPlugins[npmName]
7cd4d2ba
C
542 if (plugin.type !== type) continue
543
544 plugins.push(plugin)
545 }
546
547 return plugins
548 }
549
32fe0013
C
550 // ###################### Generate register helpers ######################
551
7fed6375
C
552 private getRegisterHelpers (
553 npmName: string,
554 plugin: PluginModel
1896bca0 555 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
5e2b2e27 556 const onHookAdded = (options: RegisterServerHookOptions) => {
32fe0013
C
557 if (!this.hooks[options.target]) this.hooks[options.target] = []
558
559 this.hooks[options.target].push({
5e2b2e27 560 npmName: npmName,
32fe0013
C
561 pluginName: plugin.name,
562 handler: options.handler,
563 priority: options.priority || 0
564 })
565 }
566
1896bca0 567 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
32fe0013 568
7fed6375 569 return {
1896bca0
C
570 registerStore: registerHelpers,
571 registerOptions: registerHelpers.buildRegisterHelpers()
7fed6375 572 }
ee286591
C
573 }
574
9157d598
C
575 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
576 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
577 if (!packageJSON.css) packageJSON.css = []
578 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
579 if (!packageJSON.translations) packageJSON.translations = {}
580
581 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
582 if (!packageJSONValid) {
583 const formattedFields = badFields.map(f => `"${f}"`)
a1587156 584 .join(', ')
9157d598
C
585
586 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
587 }
588 }
589
345da516
C
590 static get Instance () {
591 return this.instance || (this.instance = new this())
592 }
593}