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