]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
Automatically rebuild native modules on ABI change
[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 { ApplicationModel } from '@server/models/application/application'
7 import { MOAuthTokenUser, MUser } from '@server/types/models'
8 import { getCompleteLocale } from '@shared/core-utils'
9 import {
10 ClientScriptJSON,
11 PluginPackageJSON,
12 PluginTranslation,
13 PluginTranslationPathsJSON,
14 RegisterServerHookOptions
15 } from '@shared/models'
16 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
17 import { PluginType } from '../../../shared/models/plugins/plugin.type'
18 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
19 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
20 import { logger } from '../../helpers/logger'
21 import { CONFIG } from '../../initializers/config'
22 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
23 import { PluginModel } from '../../models/server/plugin'
24 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
25 import { ClientHtml } from '../client-html'
26 import { RegisterHelpers } from './register-helpers'
27 import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn'
28
29 export interface RegisteredPlugin {
30 npmName: string
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 }
41 clientScripts: { [name: string]: ClientScriptJSON }
42
43 css: string[]
44
45 // Only if this is a plugin
46 registerHelpers?: RegisterHelpers
47 unregister?: Function
48 }
49
50 export interface HookInformationValue {
51 npmName: string
52 pluginName: string
53 handler: Function
54 priority: number
55 }
56
57 type PluginLocalesTranslations = {
58 [locale: string]: PluginTranslation
59 }
60
61 export class PluginManager implements ServerHook {
62
63 private static instance: PluginManager
64
65 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
66
67 private hooks: { [name: string]: HookInformationValue[] } = {}
68 private translations: PluginLocalesTranslations = {}
69
70 private constructor () {
71 }
72
73 // ###################### Getters ######################
74
75 isRegistered (npmName: string) {
76 return !!this.getRegisteredPluginOrTheme(npmName)
77 }
78
79 getRegisteredPluginOrTheme (npmName: string) {
80 return this.registeredPlugins[npmName]
81 }
82
83 getRegisteredPluginByShortName (name: string) {
84 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
85 const registered = this.getRegisteredPluginOrTheme(npmName)
86
87 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
88
89 return registered
90 }
91
92 getRegisteredThemeByShortName (name: string) {
93 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
94 const registered = this.getRegisteredPluginOrTheme(npmName)
95
96 if (!registered || registered.type !== PluginType.THEME) return undefined
97
98 return registered
99 }
100
101 getRegisteredPlugins () {
102 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
103 }
104
105 getRegisteredThemes () {
106 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
107 }
108
109 getIdAndPassAuths () {
110 return this.getRegisteredPlugins()
111 .map(p => ({
112 npmName: p.npmName,
113 name: p.name,
114 version: p.version,
115 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
116 }))
117 .filter(v => v.idAndPassAuths.length !== 0)
118 }
119
120 getExternalAuths () {
121 return this.getRegisteredPlugins()
122 .map(p => ({
123 npmName: p.npmName,
124 name: p.name,
125 version: p.version,
126 externalAuths: p.registerHelpers.getExternalAuths()
127 }))
128 .filter(v => v.externalAuths.length !== 0)
129 }
130
131 getRegisteredSettings (npmName: string) {
132 const result = this.getRegisteredPluginOrTheme(npmName)
133 if (!result || result.type !== PluginType.PLUGIN) return []
134
135 return result.registerHelpers.getSettings()
136 }
137
138 getRouter (npmName: string) {
139 const result = this.getRegisteredPluginOrTheme(npmName)
140 if (!result || result.type !== PluginType.PLUGIN) return null
141
142 return result.registerHelpers.getRouter()
143 }
144
145 getTranslations (locale: string) {
146 return this.translations[locale] || {}
147 }
148
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
171 // ###################### External events ######################
172
173 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
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 {
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
186 } catch (err) {
187 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
188 }
189 }
190
191 return undefined
192 }
193
194 async onSettingsChanged (name: string, settings: any) {
195 const registered = this.getRegisteredPluginByShortName(name)
196 if (!registered) {
197 logger.error('Cannot find plugin %s to call on settings changed.', name)
198 }
199
200 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
201 try {
202 await cb(settings)
203 } catch (err) {
204 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
205 }
206 }
207 }
208
209 // ###################### Hooks ######################
210
211 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
212 if (!this.hooks[hookName]) return Promise.resolve(result)
213
214 const hookType = getHookType(hookName)
215
216 for (const hook of this.hooks[hookName]) {
217 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
218
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 }) }
225 })
226 }
227
228 return result
229 }
230
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) {
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
249 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
250 }
251 }
252
253 this.sortHooksByPriority()
254 }
255
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)
261
262 if (!plugin) {
263 throw new Error(`Unknown plugin ${npmName} to unregister`)
264 }
265
266 delete this.registeredPlugins[plugin.npmName]
267
268 this.deleteTranslations(plugin.npmName)
269
270 if (plugin.type === PluginType.PLUGIN) {
271 await plugin.unregister()
272
273 // Remove hooks of this plugin
274 for (const key of Object.keys(this.hooks)) {
275 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
276 }
277
278 const store = plugin.registerHelpers
279 store.reinitVideoConstants(plugin.npmName)
280 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
281
282 logger.info('Regenerating registered plugin CSS to global file.')
283 await this.regeneratePluginGlobalCSS()
284 }
285
286 ClientHtml.invalidCache()
287 }
288
289 // ###################### Installation ######################
290
291 async install (toInstall: string, version?: string, fromDisk = false) {
292 let plugin: PluginModel
293 let npmName: string
294
295 logger.info('Installing plugin %s.', toInstall)
296
297 try {
298 fromDisk
299 ? await installNpmPluginFromDisk(toInstall)
300 : await installNpmPlugin(toInstall, version)
301
302 npmName = fromDisk ? basename(toInstall) : toInstall
303 const pluginType = PluginModel.getTypeFromNpmName(npmName)
304 const pluginName = PluginModel.normalizePluginName(npmName)
305
306 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
307
308 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
309
310 [ plugin ] = await PluginModel.upsert({
311 name: pluginName,
312 description: packageJSON.description,
313 homepage: packageJSON.homepage,
314 type: pluginType,
315 version: packageJSON.version,
316 enabled: true,
317 uninstalled: false,
318 peertubeEngine: packageJSON.engine.peertube
319 }, { returning: true })
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 })
326
327 try {
328 await this.uninstall(npmName)
329 } catch (err) {
330 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
331
332 try {
333 await removeNpmPlugin(npmName)
334 } catch (err) {
335 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
336 }
337 }
338
339 throw rootErr
340 }
341
342 return plugin
343 }
344
345 async update (toUpdate: string, fromDisk = false) {
346 const npmName = fromDisk ? basename(toUpdate) : toUpdate
347
348 logger.info('Updating plugin %s.', npmName)
349
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
357 // Unregister old hooks
358 await this.unregister(npmName)
359
360 return this.install(toUpdate, version, fromDisk)
361 }
362
363 async uninstall (npmName: string) {
364 logger.info('Uninstalling plugin %s.', npmName)
365
366 try {
367 await this.unregister(npmName)
368 } catch (err) {
369 logger.warn('Cannot unregister plugin %s.', npmName, { err })
370 }
371
372 const plugin = await PluginModel.loadByNpmName(npmName)
373 if (!plugin || plugin.uninstalled === true) {
374 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
375 return
376 }
377
378 plugin.enabled = false
379 plugin.uninstalled = true
380
381 await plugin.save()
382
383 await removeNpmPlugin(npmName)
384
385 logger.info('Plugin %s uninstalled.', npmName)
386 }
387
388 async rebuildNativePluginsIfNeeded () {
389 if (!await ApplicationModel.nodeABIChanged()) return
390
391 return rebuildNativePlugins()
392 }
393
394 // ###################### Private register ######################
395
396 private async registerPluginOrTheme (plugin: PluginModel) {
397 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
398
399 logger.info('Registering plugin or theme %s.', npmName)
400
401 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
402 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
403
404 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
405
406 let library: PluginLibrary
407 let registerHelpers: RegisterHelpers
408 if (plugin.type === PluginType.PLUGIN) {
409 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
410 library = result.library
411 registerHelpers = result.registerStore
412 }
413
414 const clientScripts: { [id: string]: ClientScriptJSON } = {}
415 for (const c of packageJSON.clientScripts) {
416 clientScripts[c.script] = c
417 }
418
419 this.registeredPlugins[npmName] = {
420 npmName,
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,
428 clientScripts,
429 css: packageJSON.css,
430 registerHelpers: registerHelpers || undefined,
431 unregister: library ? library.unregister : undefined
432 }
433
434 await this.addTranslations(plugin, npmName, packageJSON.translations)
435
436 ClientHtml.invalidCache()
437 }
438
439 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
440 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
441
442 // Delete cache if needed
443 const modulePath = join(pluginPath, packageJSON.library)
444 decachePlugin(pluginPath, modulePath)
445 const library: PluginLibrary = require(modulePath)
446
447 if (!isLibraryCodeValid(library)) {
448 throw new Error('Library code is not valid (miss register or unregister function)')
449 }
450
451 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
452
453 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
454
455 await library.register(registerOptions)
456
457 logger.info('Add plugin %s CSS to global file.', npmName)
458
459 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
460
461 return { library, registerStore }
462 }
463
464 // ###################### Translations ######################
465
466 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
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
471 const completeLocale = getCompleteLocale(locale)
472
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)
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
488 // ###################### CSS ######################
489
490 private resetCSSGlobalFile () {
491 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
492 }
493
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) => {
502 const inputStream = createReadStream(input)
503 const outputStream = createWriteStream(output, { flags: 'a' })
504
505 inputStream.pipe(outputStream)
506
507 inputStream.on('end', () => res())
508 inputStream.on('error', err => rej(err))
509 })
510 }
511
512 private async regeneratePluginGlobalCSS () {
513 await this.resetCSSGlobalFile()
514
515 for (const plugin of this.getRegisteredPlugins()) {
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
530 private getPackageJSON (pluginName: string, pluginType: PluginType) {
531 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
532
533 return readJSON(pluginPath) as Promise<PluginPackageJSON>
534 }
535
536 private getPluginPath (pluginName: string, pluginType: PluginType) {
537 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
538
539 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
540 }
541
542 private getAuth (npmName: string, authName: string) {
543 const plugin = this.getRegisteredPluginOrTheme(npmName)
544 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
545
546 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
547 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
548
549 return auths.find(a => a.authName === authName)
550 }
551
552 // ###################### Private getters ######################
553
554 private getRegisteredPluginsOrThemes (type: PluginType) {
555 const plugins: RegisteredPlugin[] = []
556
557 for (const npmName of Object.keys(this.registeredPlugins)) {
558 const plugin = this.registeredPlugins[npmName]
559 if (plugin.type !== type) continue
560
561 plugins.push(plugin)
562 }
563
564 return plugins
565 }
566
567 // ###################### Generate register helpers ######################
568
569 private getRegisterHelpers (
570 npmName: string,
571 plugin: PluginModel
572 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
573 const onHookAdded = (options: RegisterServerHookOptions) => {
574 if (!this.hooks[options.target]) this.hooks[options.target] = []
575
576 this.hooks[options.target].push({
577 npmName,
578 pluginName: plugin.name,
579 handler: options.handler,
580 priority: options.priority || 0
581 })
582 }
583
584 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
585
586 return {
587 registerStore: registerHelpers,
588 registerOptions: registerHelpers.buildRegisterHelpers()
589 }
590 }
591
592 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
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}"`)
601 .join(', ')
602
603 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
604 }
605 }
606
607 static get Instance () {
608 return this.instance || (this.instance = new this())
609 }
610 }