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