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