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