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