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