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