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