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