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