]>
Commit | Line | Data |
---|---|---|
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 { createReadStream, createWriteStream } from 'fs' | |
8 | import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants' | |
9 | import { PluginType } from '../../../shared/models/plugins/plugin.type' | |
10 | import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn' | |
11 | import { outputFile, readJSON } from 'fs-extra' | |
12 | import { RegisterSettingOptions } from '../../../shared/models/plugins/register-setting.model' | |
13 | import { RegisterHookOptions } from '../../../shared/models/plugins/register-hook.model' | |
14 | import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model' | |
15 | import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model' | |
16 | import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model' | |
17 | import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks' | |
18 | import { RegisterOptions } from '../../typings/plugins/register-options.model' | |
19 | import { PluginLibrary } from '../../typings/plugins' | |
20 | ||
21 | export interface RegisteredPlugin { | |
22 | npmName: string | |
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 } | |
33 | clientScripts: { [name: string]: ClientScript } | |
34 | ||
35 | css: string[] | |
36 | ||
37 | // Only if this is a plugin | |
38 | unregister?: Function | |
39 | } | |
40 | ||
41 | export interface HookInformationValue { | |
42 | npmName: string | |
43 | pluginName: string | |
44 | handler: Function | |
45 | priority: number | |
46 | } | |
47 | ||
48 | export class PluginManager implements ServerHook { | |
49 | ||
50 | private static instance: PluginManager | |
51 | ||
52 | private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {} | |
53 | private settings: { [ name: string ]: RegisterSettingOptions[] } = {} | |
54 | private hooks: { [ name: string ]: HookInformationValue[] } = {} | |
55 | ||
56 | private constructor () { | |
57 | } | |
58 | ||
59 | // ###################### Getters ###################### | |
60 | ||
61 | isRegistered (npmName: string) { | |
62 | return !!this.getRegisteredPluginOrTheme(npmName) | |
63 | } | |
64 | ||
65 | getRegisteredPluginOrTheme (npmName: string) { | |
66 | return this.registeredPlugins[npmName] | |
67 | } | |
68 | ||
69 | getRegisteredPlugin (name: string) { | |
70 | const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN) | |
71 | const registered = this.getRegisteredPluginOrTheme(npmName) | |
72 | ||
73 | if (!registered || registered.type !== PluginType.PLUGIN) return undefined | |
74 | ||
75 | return registered | |
76 | } | |
77 | ||
78 | getRegisteredTheme (name: string) { | |
79 | const npmName = PluginModel.buildNpmName(name, PluginType.THEME) | |
80 | const registered = this.getRegisteredPluginOrTheme(npmName) | |
81 | ||
82 | if (!registered || registered.type !== PluginType.THEME) return undefined | |
83 | ||
84 | return registered | |
85 | } | |
86 | ||
87 | getRegisteredPlugins () { | |
88 | return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN) | |
89 | } | |
90 | ||
91 | getRegisteredThemes () { | |
92 | return this.getRegisteredPluginsOrThemes(PluginType.THEME) | |
93 | } | |
94 | ||
95 | getRegisteredSettings (npmName: string) { | |
96 | return this.settings[npmName] || [] | |
97 | } | |
98 | ||
99 | // ###################### Hooks ###################### | |
100 | ||
101 | async runHook <T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> { | |
102 | if (!this.hooks[hookName]) return Promise.resolve(result) | |
103 | ||
104 | const hookType = getHookType(hookName) | |
105 | ||
106 | for (const hook of this.hooks[hookName]) { | |
107 | logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName) | |
108 | ||
109 | result = await internalRunHook(hook.handler, hookType, result, params, err => { | |
110 | logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) | |
111 | }) | |
112 | } | |
113 | ||
114 | return result | |
115 | } | |
116 | ||
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 | ||
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) | |
140 | ||
141 | if (!plugin) { | |
142 | throw new Error(`Unknown plugin ${npmName} to unregister`) | |
143 | } | |
144 | ||
145 | delete this.registeredPlugins[plugin.npmName] | |
146 | ||
147 | if (plugin.type === PluginType.PLUGIN) { | |
148 | await plugin.unregister() | |
149 | ||
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 | } | |
154 | ||
155 | logger.info('Regenerating registered plugin CSS to global file.') | |
156 | await this.regeneratePluginGlobalCSS() | |
157 | } | |
158 | } | |
159 | ||
160 | // ###################### Installation ###################### | |
161 | ||
162 | async install (toInstall: string, version?: string, fromDisk = false) { | |
163 | let plugin: PluginModel | |
164 | let npmName: string | |
165 | ||
166 | logger.info('Installing plugin %s.', toInstall) | |
167 | ||
168 | try { | |
169 | fromDisk | |
170 | ? await installNpmPluginFromDisk(toInstall) | |
171 | : await installNpmPlugin(toInstall, version) | |
172 | ||
173 | npmName = fromDisk ? basename(toInstall) : toInstall | |
174 | const pluginType = PluginModel.getTypeFromNpmName(npmName) | |
175 | const pluginName = PluginModel.normalizePluginName(npmName) | |
176 | ||
177 | const packageJSON = await this.getPackageJSON(pluginName, pluginType) | |
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, | |
185 | homepage: packageJSON.homepage, | |
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 { | |
196 | await removeNpmPlugin(npmName) | |
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) | |
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) | |
220 | } | |
221 | ||
222 | async uninstall (npmName: string) { | |
223 | logger.info('Uninstalling plugin %s.', npmName) | |
224 | ||
225 | try { | |
226 | await this.unregister(npmName) | |
227 | } catch (err) { | |
228 | logger.warn('Cannot unregister plugin %s.', npmName, { err }) | |
229 | } | |
230 | ||
231 | const plugin = await PluginModel.loadByNpmName(npmName) | |
232 | if (!plugin || plugin.uninstalled === true) { | |
233 | logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName) | |
234 | return | |
235 | } | |
236 | ||
237 | plugin.enabled = false | |
238 | plugin.uninstalled = true | |
239 | ||
240 | await plugin.save() | |
241 | ||
242 | await removeNpmPlugin(npmName) | |
243 | ||
244 | logger.info('Plugin %s uninstalled.', npmName) | |
245 | } | |
246 | ||
247 | // ###################### Private register ###################### | |
248 | ||
249 | private async registerPluginOrTheme (plugin: PluginModel) { | |
250 | const npmName = PluginModel.buildNpmName(plugin.name, plugin.type) | |
251 | ||
252 | logger.info('Registering plugin or theme %s.', npmName) | |
253 | ||
254 | const packageJSON = await this.getPackageJSON(plugin.name, plugin.type) | |
255 | const pluginPath = this.getPluginPath(plugin.name, plugin.type) | |
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 | ||
266 | const clientScripts: { [id: string]: ClientScript } = {} | |
267 | for (const c of packageJSON.clientScripts) { | |
268 | clientScripts[c.script] = c | |
269 | } | |
270 | ||
271 | this.registeredPlugins[ npmName ] = { | |
272 | npmName, | |
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, | |
280 | clientScripts, | |
281 | css: packageJSON.css, | |
282 | unregister: library ? library.unregister : undefined | |
283 | } | |
284 | } | |
285 | ||
286 | private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) { | |
287 | const npmName = PluginModel.buildNpmName(plugin.name, plugin.type) | |
288 | ||
289 | // Delete cache if needed | |
290 | const modulePath = join(pluginPath, packageJSON.library) | |
291 | delete require.cache[modulePath] | |
292 | const library: PluginLibrary = require(modulePath) | |
293 | ||
294 | if (!isLibraryCodeValid(library)) { | |
295 | throw new Error('Library code is not valid (miss register or unregister function)') | |
296 | } | |
297 | ||
298 | const registerHelpers = this.getRegisterHelpers(npmName, plugin) | |
299 | library.register(registerHelpers) | |
300 | .catch(err => logger.error('Cannot register plugin %s.', npmName, { err })) | |
301 | ||
302 | logger.info('Add plugin %s CSS to global file.', npmName) | |
303 | ||
304 | await this.addCSSToGlobalFile(pluginPath, packageJSON.css) | |
305 | ||
306 | return library | |
307 | } | |
308 | ||
309 | // ###################### CSS ###################### | |
310 | ||
311 | private resetCSSGlobalFile () { | |
312 | return outputFile(PLUGIN_GLOBAL_CSS_PATH, '') | |
313 | } | |
314 | ||
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) => { | |
323 | const inputStream = createReadStream(input) | |
324 | const outputStream = createWriteStream(output, { flags: 'a' }) | |
325 | ||
326 | inputStream.pipe(outputStream) | |
327 | ||
328 | inputStream.on('end', () => res()) | |
329 | inputStream.on('error', err => rej(err)) | |
330 | }) | |
331 | } | |
332 | ||
333 | private async regeneratePluginGlobalCSS () { | |
334 | await this.resetCSSGlobalFile() | |
335 | ||
336 | for (const key of Object.keys(this.getRegisteredPlugins())) { | |
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 | ||
353 | private getPackageJSON (pluginName: string, pluginType: PluginType) { | |
354 | const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json') | |
355 | ||
356 | return readJSON(pluginPath) as Promise<PluginPackageJson> | |
357 | } | |
358 | ||
359 | private getPluginPath (pluginName: string, pluginType: PluginType) { | |
360 | const npmName = PluginModel.buildNpmName(pluginName, pluginType) | |
361 | ||
362 | return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName) | |
363 | } | |
364 | ||
365 | // ###################### Private getters ###################### | |
366 | ||
367 | private getRegisteredPluginsOrThemes (type: PluginType) { | |
368 | const plugins: RegisteredPlugin[] = [] | |
369 | ||
370 | for (const npmName of Object.keys(this.registeredPlugins)) { | |
371 | const plugin = this.registeredPlugins[ npmName ] | |
372 | if (plugin.type !== type) continue | |
373 | ||
374 | plugins.push(plugin) | |
375 | } | |
376 | ||
377 | return plugins | |
378 | } | |
379 | ||
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 | ||
425 | static get Instance () { | |
426 | return this.instance || (this.instance = new this()) | |
427 | } | |
428 | } |