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