]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
381a894736795777bd57197354500ead1953d8c6
[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 { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model'
13 import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model'
14 import { ServerHook, ServerHookName, serverHookObject } from '../../../shared/models/plugins/server-hook.model'
15 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
16 import { RegisterServerOptions } from '../../typings/plugins/register-server-option.model'
17 import { PluginLibrary } from '../../typings/plugins'
18 import { ClientHtml } from '../client-html'
19 import { RegisterServerHookOptions } from '../../../shared/models/plugins/register-server-hook.model'
20 import { RegisterServerSettingOptions } from '../../../shared/models/plugins/register-server-setting.model'
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 ]: RegisterServerSettingOptions[] } = {}
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 ClientHtml.invalidCache()
321
322 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
323 }
324
325 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
326 for (const cssPath of cssRelativePaths) {
327 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
328 }
329
330 ClientHtml.invalidCache()
331 }
332
333 private concatFiles (input: string, output: string) {
334 return new Promise<void>((res, rej) => {
335 const inputStream = createReadStream(input)
336 const outputStream = createWriteStream(output, { flags: 'a' })
337
338 inputStream.pipe(outputStream)
339
340 inputStream.on('end', () => res())
341 inputStream.on('error', err => rej(err))
342 })
343 }
344
345 private async regeneratePluginGlobalCSS () {
346 await this.resetCSSGlobalFile()
347
348 for (const key of Object.keys(this.getRegisteredPlugins())) {
349 const plugin = this.registeredPlugins[key]
350
351 await this.addCSSToGlobalFile(plugin.path, plugin.css)
352 }
353 }
354
355 // ###################### Utils ######################
356
357 private sortHooksByPriority () {
358 for (const hookName of Object.keys(this.hooks)) {
359 this.hooks[hookName].sort((a, b) => {
360 return b.priority - a.priority
361 })
362 }
363 }
364
365 private getPackageJSON (pluginName: string, pluginType: PluginType) {
366 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
367
368 return readJSON(pluginPath) as Promise<PluginPackageJson>
369 }
370
371 private getPluginPath (pluginName: string, pluginType: PluginType) {
372 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
373
374 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
375 }
376
377 // ###################### Private getters ######################
378
379 private getRegisteredPluginsOrThemes (type: PluginType) {
380 const plugins: RegisteredPlugin[] = []
381
382 for (const npmName of Object.keys(this.registeredPlugins)) {
383 const plugin = this.registeredPlugins[ npmName ]
384 if (plugin.type !== type) continue
385
386 plugins.push(plugin)
387 }
388
389 return plugins
390 }
391
392 // ###################### Generate register helpers ######################
393
394 private getRegisterHelpers (npmName: string, plugin: PluginModel): RegisterServerOptions {
395 const registerHook = (options: RegisterServerHookOptions) => {
396 if (serverHookObject[options.target] !== true) {
397 logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, npmName)
398 return
399 }
400
401 if (!this.hooks[options.target]) this.hooks[options.target] = []
402
403 this.hooks[options.target].push({
404 npmName,
405 pluginName: plugin.name,
406 handler: options.handler,
407 priority: options.priority || 0
408 })
409 }
410
411 const registerSetting = (options: RegisterServerSettingOptions) => {
412 if (!this.settings[npmName]) this.settings[npmName] = []
413
414 this.settings[npmName].push(options)
415 }
416
417 const settingsManager: PluginSettingsManager = {
418 getSetting: (name: string) => PluginModel.getSetting(plugin.name, plugin.type, name),
419
420 setSetting: (name: string, value: string) => PluginModel.setSetting(plugin.name, plugin.type, name, value)
421 }
422
423 const storageManager: PluginStorageManager = {
424 getData: (key: string) => PluginModel.getData(plugin.name, plugin.type, key),
425
426 storeData: (key: string, data: any) => PluginModel.storeData(plugin.name, plugin.type, key, data)
427 }
428
429 const peertubeHelpers = {
430 logger
431 }
432
433 return {
434 registerHook,
435 registerSetting,
436 settingsManager,
437 storageManager,
438 peertubeHelpers
439 }
440 }
441
442 static get Instance () {
443 return this.instance || (this.instance = new this())
444 }
445 }