]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
44530d203b06d1bc48ce5e7d8a12138443053b11
[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, serverHookObject } 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 { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
22 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
23 import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model'
24 import { buildRegisterHelpers, reinitVideoConstants } from './register-helpers'
25
26 export interface RegisteredPlugin {
27 npmName: string
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 }
38 clientScripts: { [name: string]: ClientScript }
39
40 css: string[]
41
42 // Only if this is a plugin
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 private settings: { [name: string]: RegisterServerSettingOptions[] } = {}
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 getRegisteredPlugin (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 getRegisteredTheme (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 getRegisteredSettings (npmName: string) {
106 return this.settings[npmName] || []
107 }
108
109 getTranslations (locale: string) {
110 return this.translations[locale] || {}
111 }
112
113 // ###################### Hooks ######################
114
115 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
116 if (!this.hooks[hookName]) return Promise.resolve(result)
117
118 const hookType = getHookType(hookName)
119
120 for (const hook of this.hooks[hookName]) {
121 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
122
123 result = await internalRunHook(hook.handler, hookType, result, params, err => {
124 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
125 })
126 }
127
128 return result
129 }
130
131 // ###################### Registration ######################
132
133 async registerPluginsAndThemes () {
134 await this.resetCSSGlobalFile()
135
136 const plugins = await PluginModel.listEnabledPluginsAndThemes()
137
138 for (const plugin of plugins) {
139 try {
140 await this.registerPluginOrTheme(plugin)
141 } catch (err) {
142 // Try to unregister the plugin
143 try {
144 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
145 } catch {
146 // we don't care if we cannot unregister it
147 }
148
149 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
150 }
151 }
152
153 this.sortHooksByPriority()
154 }
155
156 // Don't need the plugin type since themes cannot register server code
157 async unregister (npmName: string) {
158 logger.info('Unregister plugin %s.', npmName)
159
160 const plugin = this.getRegisteredPluginOrTheme(npmName)
161
162 if (!plugin) {
163 throw new Error(`Unknown plugin ${npmName} to unregister`)
164 }
165
166 delete this.registeredPlugins[plugin.npmName]
167 delete this.settings[plugin.npmName]
168
169 this.deleteTranslations(plugin.npmName)
170
171 if (plugin.type === PluginType.PLUGIN) {
172 await plugin.unregister()
173
174 // Remove hooks of this plugin
175 for (const key of Object.keys(this.hooks)) {
176 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
177 }
178
179 reinitVideoConstants(plugin.npmName)
180
181 logger.info('Regenerating registered plugin CSS to global file.')
182 await this.regeneratePluginGlobalCSS()
183 }
184 }
185
186 // ###################### Installation ######################
187
188 async install (toInstall: string, version?: string, fromDisk = false) {
189 let plugin: PluginModel
190 let npmName: string
191
192 logger.info('Installing plugin %s.', toInstall)
193
194 try {
195 fromDisk
196 ? await installNpmPluginFromDisk(toInstall)
197 : await installNpmPlugin(toInstall, version)
198
199 npmName = fromDisk ? basename(toInstall) : toInstall
200 const pluginType = PluginModel.getTypeFromNpmName(npmName)
201 const pluginName = PluginModel.normalizePluginName(npmName)
202
203 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
204
205 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
206
207 [ plugin ] = await PluginModel.upsert({
208 name: pluginName,
209 description: packageJSON.description,
210 homepage: packageJSON.homepage,
211 type: pluginType,
212 version: packageJSON.version,
213 enabled: true,
214 uninstalled: false,
215 peertubeEngine: packageJSON.engine.peertube
216 }, { returning: true })
217 } catch (err) {
218 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
219
220 try {
221 await removeNpmPlugin(npmName)
222 } catch (err) {
223 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
224 }
225
226 throw err
227 }
228
229 logger.info('Successful installation of plugin %s.', toInstall)
230
231 await this.registerPluginOrTheme(plugin)
232
233 return plugin
234 }
235
236 async update (toUpdate: string, version?: string, fromDisk = false) {
237 const npmName = fromDisk ? basename(toUpdate) : toUpdate
238
239 logger.info('Updating plugin %s.', npmName)
240
241 // Unregister old hooks
242 await this.unregister(npmName)
243
244 return this.install(toUpdate, version, fromDisk)
245 }
246
247 async uninstall (npmName: string) {
248 logger.info('Uninstalling plugin %s.', npmName)
249
250 try {
251 await this.unregister(npmName)
252 } catch (err) {
253 logger.warn('Cannot unregister plugin %s.', npmName, { err })
254 }
255
256 const plugin = await PluginModel.loadByNpmName(npmName)
257 if (!plugin || plugin.uninstalled === true) {
258 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
259 return
260 }
261
262 plugin.enabled = false
263 plugin.uninstalled = true
264
265 await plugin.save()
266
267 await removeNpmPlugin(npmName)
268
269 logger.info('Plugin %s uninstalled.', npmName)
270 }
271
272 // ###################### Private register ######################
273
274 private async registerPluginOrTheme (plugin: PluginModel) {
275 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
276
277 logger.info('Registering plugin or theme %s.', npmName)
278
279 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
280 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
281
282 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
283
284 let library: PluginLibrary
285 if (plugin.type === PluginType.PLUGIN) {
286 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
287 }
288
289 const clientScripts: { [id: string]: ClientScript } = {}
290 for (const c of packageJSON.clientScripts) {
291 clientScripts[c.script] = c
292 }
293
294 this.registeredPlugins[npmName] = {
295 npmName,
296 name: plugin.name,
297 type: plugin.type,
298 version: plugin.version,
299 description: plugin.description,
300 peertubeEngine: plugin.peertubeEngine,
301 path: pluginPath,
302 staticDirs: packageJSON.staticDirs,
303 clientScripts,
304 css: packageJSON.css,
305 unregister: library ? library.unregister : undefined
306 }
307
308 await this.addTranslations(plugin, npmName, packageJSON.translations)
309 }
310
311 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
312 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
313
314 // Delete cache if needed
315 const modulePath = join(pluginPath, packageJSON.library)
316 delete require.cache[modulePath]
317 const library: PluginLibrary = require(modulePath)
318
319 if (!isLibraryCodeValid(library)) {
320 throw new Error('Library code is not valid (miss register or unregister function)')
321 }
322
323 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
324 library.register(registerHelpers)
325 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
326
327 logger.info('Add plugin %s CSS to global file.', npmName)
328
329 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
330
331 return library
332 }
333
334 // ###################### Translations ######################
335
336 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) {
337 for (const locale of Object.keys(translationPaths)) {
338 const path = translationPaths[locale]
339 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
340
341 if (!this.translations[locale]) this.translations[locale] = {}
342 this.translations[locale][npmName] = json
343
344 logger.info('Added locale %s of plugin %s.', locale, npmName)
345 }
346 }
347
348 private deleteTranslations (npmName: string) {
349 for (const locale of Object.keys(this.translations)) {
350 delete this.translations[locale][npmName]
351
352 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
353 }
354 }
355
356 // ###################### CSS ######################
357
358 private resetCSSGlobalFile () {
359 ClientHtml.invalidCache()
360
361 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
362 }
363
364 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
365 for (const cssPath of cssRelativePaths) {
366 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
367 }
368
369 ClientHtml.invalidCache()
370 }
371
372 private concatFiles (input: string, output: string) {
373 return new Promise<void>((res, rej) => {
374 const inputStream = createReadStream(input)
375 const outputStream = createWriteStream(output, { flags: 'a' })
376
377 inputStream.pipe(outputStream)
378
379 inputStream.on('end', () => res())
380 inputStream.on('error', err => rej(err))
381 })
382 }
383
384 private async regeneratePluginGlobalCSS () {
385 await this.resetCSSGlobalFile()
386
387 for (const plugin of this.getRegisteredPlugins()) {
388 await this.addCSSToGlobalFile(plugin.path, plugin.css)
389 }
390 }
391
392 // ###################### Utils ######################
393
394 private sortHooksByPriority () {
395 for (const hookName of Object.keys(this.hooks)) {
396 this.hooks[hookName].sort((a, b) => {
397 return b.priority - a.priority
398 })
399 }
400 }
401
402 private getPackageJSON (pluginName: string, pluginType: PluginType) {
403 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
404
405 return readJSON(pluginPath) as Promise<PluginPackageJson>
406 }
407
408 private getPluginPath (pluginName: string, pluginType: PluginType) {
409 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
410
411 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
412 }
413
414 // ###################### Private getters ######################
415
416 private getRegisteredPluginsOrThemes (type: PluginType) {
417 const plugins: RegisteredPlugin[] = []
418
419 for (const npmName of Object.keys(this.registeredPlugins)) {
420 const plugin = this.registeredPlugins[npmName]
421 if (plugin.type !== type) continue
422
423 plugins.push(plugin)
424 }
425
426 return plugins
427 }
428
429 // ###################### Generate register helpers ######################
430
431 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
432 const registerHook = (options: RegisterServerHookOptions) => {
433 if (serverHookObject[options.target] !== true) {
434 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
435 return
436 }
437
438 if (!this.hooks[options.target]) this.hooks[options.target] = []
439
440 this.hooks[options.target].push({
441 npmName,
442 pluginName: plugin.name,
443 handler: options.handler,
444 priority: options.priority || 0
445 })
446 }
447
448 const registerSetting = (options: RegisterServerSettingOptions) => {
449 if (!this.settings[npmName]) this.settings[npmName] = []
450
451 this.settings[npmName].push(options)
452 }
453
454 const registerHelpers = buildRegisterHelpers(npmName, plugin)
455
456 return Object.assign(registerHelpers, {
457 registerHook,
458 registerSetting
459 })
460 }
461
462 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
463 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
464 if (!packageJSON.css) packageJSON.css = []
465 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
466 if (!packageJSON.translations) packageJSON.translations = {}
467
468 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
469 if (!packageJSONValid) {
470 const formattedFields = badFields.map(f => `"${f}"`)
471 .join(', ')
472
473 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
474 }
475 }
476
477 static get Instance () {
478 return this.instance || (this.instance = new this())
479 }
480 }