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