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