]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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'
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
42 unregister?: Function
43}
44
45export interface HookInformationValue {
b5f919ac 46 npmName: string
345da516
C
47 pluginName: string
48 handler: Function
49 priority: number
50}
51
d75db01f 52type PluginLocalesTranslations = {
a1587156 53 [locale: string]: PluginTranslation
d75db01f
C
54}
55
b4055e1c 56export class PluginManager implements ServerHook {
345da516
C
57
58 private static instance: PluginManager
59
a1587156 60 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
a1587156 61 private hooks: { [name: string]: HookInformationValue[] } = {}
d75db01f 62 private translations: PluginLocalesTranslations = {}
345da516 63
5e2b2e27
C
64 private registerHelpersStore: { [npmName: string]: RegisterHelpersStore } = {}
65
345da516
C
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
345da516 79 getRegisteredPlugin (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
88 getRegisteredTheme (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
b5f919ac 105 getRegisteredSettings (npmName: string) {
5e2b2e27
C
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()
ad91e700
C
117 }
118
d75db01f
C
119 getTranslations (locale: string) {
120 return this.translations[locale] || {}
121 }
122
ad91e700
C
123 // ###################### Hooks ######################
124
a1587156 125 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
89cd1275 126 if (!this.hooks[hookName]) return Promise.resolve(result)
dba85a1e 127
b4055e1c 128 const hookType = getHookType(hookName)
18a6f04c
C
129
130 for (const hook of this.hooks[hookName]) {
89cd1275
C
131 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
132
133 result = await internalRunHook(hook.handler, hookType, result, params, err => {
18a6f04c 134 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
b4055e1c 135 })
18a6f04c
C
136 }
137
138 return result
139 }
140
ad91e700
C
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) {
587568e1
C
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
ad91e700
C
159 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
160 }
161 }
162
163 this.sortHooksByPriority()
164 }
165
b5f919ac
C
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)
345da516
C
171
172 if (!plugin) {
b5f919ac 173 throw new Error(`Unknown plugin ${npmName} to unregister`)
345da516
C
174 }
175
60cfd4cb
C
176 delete this.registeredPlugins[plugin.npmName]
177
d75db01f
C
178 this.deleteTranslations(plugin.npmName)
179
b5f919ac
C
180 if (plugin.type === PluginType.PLUGIN) {
181 await plugin.unregister()
345da516 182
b5f919ac
C
183 // Remove hooks of this plugin
184 for (const key of Object.keys(this.hooks)) {
98da1a7b 185 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
b5f919ac 186 }
2c053942 187
5e2b2e27
C
188 const store = this.registerHelpersStore[plugin.npmName]
189 store.reinitVideoConstants(plugin.npmName)
190
191 delete this.registerHelpersStore[plugin.npmName]
ee286591 192
b5f919ac
C
193 logger.info('Regenerating registered plugin CSS to global file.')
194 await this.regeneratePluginGlobalCSS()
2c053942 195 }
345da516
C
196 }
197
ad91e700
C
198 // ###################### Installation ######################
199
200 async install (toInstall: string, version?: string, fromDisk = false) {
f023a19c 201 let plugin: PluginModel
b5f919ac 202 let npmName: string
f023a19c
C
203
204 logger.info('Installing plugin %s.', toInstall)
205
206 try {
207 fromDisk
208 ? await installNpmPluginFromDisk(toInstall)
209 : await installNpmPlugin(toInstall, version)
210
b5f919ac
C
211 npmName = fromDisk ? basename(toInstall) : toInstall
212 const pluginType = PluginModel.getTypeFromNpmName(npmName)
213 const pluginName = PluginModel.normalizePluginName(npmName)
f023a19c 214
09071200 215 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
9157d598
C
216
217 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
f023a19c
C
218
219 [ plugin ] = await PluginModel.upsert({
220 name: pluginName,
221 description: packageJSON.description,
dba85a1e 222 homepage: packageJSON.homepage,
f023a19c
C
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 {
b5f919ac 233 await removeNpmPlugin(npmName)
f023a19c
C
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)
b5f919ac
C
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)
f023a19c
C
257 }
258
dba85a1e
C
259 async uninstall (npmName: string) {
260 logger.info('Uninstalling plugin %s.', npmName)
2c053942 261
2c053942 262 try {
b5f919ac 263 await this.unregister(npmName)
2c053942 264 } catch (err) {
b5f919ac 265 logger.warn('Cannot unregister plugin %s.', npmName, { err })
2c053942
C
266 }
267
dba85a1e 268 const plugin = await PluginModel.loadByNpmName(npmName)
2c053942 269 if (!plugin || plugin.uninstalled === true) {
dba85a1e 270 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
2c053942
C
271 return
272 }
273
274 plugin.enabled = false
275 plugin.uninstalled = true
276
277 await plugin.save()
f023a19c 278
dba85a1e 279 await removeNpmPlugin(npmName)
2c053942 280
dba85a1e 281 logger.info('Plugin %s uninstalled.', npmName)
f023a19c
C
282 }
283
ad91e700
C
284 // ###################### Private register ######################
285
345da516 286 private async registerPluginOrTheme (plugin: PluginModel) {
b5f919ac
C
287 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
288
289 logger.info('Registering plugin or theme %s.', npmName)
345da516 290
09071200 291 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
f023a19c 292 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
345da516 293
9157d598 294 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
345da516
C
295
296 let library: PluginLibrary
297 if (plugin.type === PluginType.PLUGIN) {
298 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
299 }
300
2c053942
C
301 const clientScripts: { [id: string]: ClientScript } = {}
302 for (const c of packageJSON.clientScripts) {
303 clientScripts[c.script] = c
304 }
305
a1587156 306 this.registeredPlugins[npmName] = {
b5f919ac 307 npmName,
345da516
C
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,
2c053942 315 clientScripts,
345da516
C
316 css: packageJSON.css,
317 unregister: library ? library.unregister : undefined
318 }
d75db01f
C
319
320 await this.addTranslations(plugin, npmName, packageJSON.translations)
345da516
C
321 }
322
323 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
b5f919ac
C
324 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
325
09071200
C
326 // Delete cache if needed
327 const modulePath = join(pluginPath, packageJSON.library)
328 delete require.cache[modulePath]
329 const library: PluginLibrary = require(modulePath)
f023a19c 330
345da516
C
331 if (!isLibraryCodeValid(library)) {
332 throw new Error('Library code is not valid (miss register or unregister function)')
333 }
334
32fe0013
C
335 const registerHelpers = this.getRegisterHelpers(npmName, plugin)
336 library.register(registerHelpers)
337 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
345da516 338
b5f919ac 339 logger.info('Add plugin %s CSS to global file.', npmName)
345da516
C
340
341 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
342
343 return library
344 }
345
d75db01f
C
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
ad91e700 368 // ###################### CSS ######################
345da516 369
2c053942 370 private resetCSSGlobalFile () {
3e753302
C
371 ClientHtml.invalidCache()
372
2c053942
C
373 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
374 }
375
345da516
C
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 }
a8b666e9
C
380
381 ClientHtml.invalidCache()
345da516
C
382 }
383
384 private concatFiles (input: string, output: string) {
385 return new Promise<void>((res, rej) => {
2c053942
C
386 const inputStream = createReadStream(input)
387 const outputStream = createWriteStream(output, { flags: 'a' })
345da516
C
388
389 inputStream.pipe(outputStream)
390
391 inputStream.on('end', () => res())
392 inputStream.on('error', err => rej(err))
393 })
394 }
395
ad91e700
C
396 private async regeneratePluginGlobalCSS () {
397 await this.resetCSSGlobalFile()
398
1198edf4 399 for (const plugin of this.getRegisteredPlugins()) {
ad91e700
C
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
f023a19c
C
414 private getPackageJSON (pluginName: string, pluginType: PluginType) {
415 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
416
09071200 417 return readJSON(pluginPath) as Promise<PluginPackageJson>
f023a19c
C
418 }
419
420 private getPluginPath (pluginName: string, pluginType: PluginType) {
b5f919ac 421 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
f023a19c 422
b5f919ac 423 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
f023a19c
C
424 }
425
ad91e700 426 // ###################### Private getters ######################
2c053942 427
7cd4d2ba
C
428 private getRegisteredPluginsOrThemes (type: PluginType) {
429 const plugins: RegisteredPlugin[] = []
430
b5f919ac 431 for (const npmName of Object.keys(this.registeredPlugins)) {
a1587156 432 const plugin = this.registeredPlugins[npmName]
7cd4d2ba
C
433 if (plugin.type !== type) continue
434
435 plugins.push(plugin)
436 }
437
438 return plugins
439 }
440
32fe0013
C
441 // ###################### Generate register helpers ######################
442
9ae88819 443 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
5e2b2e27 444 const onHookAdded = (options: RegisterServerHookOptions) => {
32fe0013
C
445 if (!this.hooks[options.target]) this.hooks[options.target] = []
446
447 this.hooks[options.target].push({
5e2b2e27 448 npmName: npmName,
32fe0013
C
449 pluginName: plugin.name,
450 handler: options.handler,
451 priority: options.priority || 0
452 })
453 }
454
5e2b2e27
C
455 const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this))
456 this.registerHelpersStore[npmName] = registerHelpersStore
32fe0013 457
5e2b2e27 458 return registerHelpersStore.buildRegisterHelpers()
ee286591
C
459 }
460
9157d598
C
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}"`)
a1587156 470 .join(', ')
9157d598
C
471
472 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
473 }
474 }
475
345da516
C
476 static get Instance () {
477 return this.instance || (this.instance = new this())
478 }
479}