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