]>
Commit | Line | Data |
---|---|---|
1 | import { createReadStream, createWriteStream } from 'fs' | |
2 | import { outputFile, readJSON } from 'fs-extra' | |
3 | import { basename, join } from 'path' | |
4 | import { MOAuthTokenUser, MUser } from '@server/types/models' | |
5 | import { RegisterServerHookOptions } from '@shared/models/plugins/register-server-hook.model' | |
6 | import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks' | |
7 | import { | |
8 | ClientScript, | |
9 | PluginPackageJson, | |
10 | PluginTranslationPaths as PackagePluginTranslations | |
11 | } from '../../../shared/models/plugins/plugin-package-json.model' | |
12 | import { PluginTranslation } from '../../../shared/models/plugins/plugin-translation.model' | |
13 | import { PluginType } from '../../../shared/models/plugins/plugin.type' | |
14 | import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server-hook.model' | |
15 | import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins' | |
16 | import { logger } from '../../helpers/logger' | |
17 | import { CONFIG } from '../../initializers/config' | |
18 | import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants' | |
19 | import { PluginModel } from '../../models/server/plugin' | |
20 | import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins' | |
21 | import { ClientHtml } from '../client-html' | |
22 | import { RegisterHelpersStore } from './register-helpers-store' | |
23 | import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn' | |
24 | ||
25 | export interface RegisteredPlugin { | |
26 | npmName: string | |
27 | name: string | |
28 | version: string | |
29 | description: string | |
30 | peertubeEngine: string | |
31 | ||
32 | type: PluginType | |
33 | ||
34 | path: string | |
35 | ||
36 | staticDirs: { [name: string]: string } | |
37 | clientScripts: { [name: string]: ClientScript } | |
38 | ||
39 | css: string[] | |
40 | ||
41 | // Only if this is a plugin | |
42 | registerHelpersStore?: RegisterHelpersStore | |
43 | unregister?: Function | |
44 | } | |
45 | ||
46 | export interface HookInformationValue { | |
47 | npmName: string | |
48 | pluginName: string | |
49 | handler: Function | |
50 | priority: number | |
51 | } | |
52 | ||
53 | type PluginLocalesTranslations = { | |
54 | [locale: string]: PluginTranslation | |
55 | } | |
56 | ||
57 | export class PluginManager implements ServerHook { | |
58 | ||
59 | private static instance: PluginManager | |
60 | ||
61 | private registeredPlugins: { [name: string]: RegisteredPlugin } = {} | |
62 | ||
63 | private hooks: { [name: string]: HookInformationValue[] } = {} | |
64 | private translations: PluginLocalesTranslations = {} | |
65 | ||
66 | private constructor () { | |
67 | } | |
68 | ||
69 | // ###################### Getters ###################### | |
70 | ||
71 | isRegistered (npmName: string) { | |
72 | return !!this.getRegisteredPluginOrTheme(npmName) | |
73 | } | |
74 | ||
75 | getRegisteredPluginOrTheme (npmName: string) { | |
76 | return this.registeredPlugins[npmName] | |
77 | } | |
78 | ||
79 | getRegisteredPluginByShortName (name: string) { | |
80 | const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN) | |
81 | const registered = this.getRegisteredPluginOrTheme(npmName) | |
82 | ||
83 | if (!registered || registered.type !== PluginType.PLUGIN) return undefined | |
84 | ||
85 | return registered | |
86 | } | |
87 | ||
88 | getRegisteredThemeByShortName (name: string) { | |
89 | const npmName = PluginModel.buildNpmName(name, PluginType.THEME) | |
90 | const registered = this.getRegisteredPluginOrTheme(npmName) | |
91 | ||
92 | if (!registered || registered.type !== PluginType.THEME) return undefined | |
93 | ||
94 | return registered | |
95 | } | |
96 | ||
97 | getRegisteredPlugins () { | |
98 | return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN) | |
99 | } | |
100 | ||
101 | getRegisteredThemes () { | |
102 | return this.getRegisteredPluginsOrThemes(PluginType.THEME) | |
103 | } | |
104 | ||
105 | getIdAndPassAuths () { | |
106 | return this.getRegisteredPlugins() | |
107 | .map(p => ({ | |
108 | npmName: p.npmName, | |
109 | name: p.name, | |
110 | version: p.version, | |
111 | idAndPassAuths: p.registerHelpersStore.getIdAndPassAuths() | |
112 | })) | |
113 | .filter(v => v.idAndPassAuths.length !== 0) | |
114 | } | |
115 | ||
116 | getExternalAuths () { | |
117 | return this.getRegisteredPlugins() | |
118 | .map(p => ({ | |
119 | npmName: p.npmName, | |
120 | name: p.name, | |
121 | version: p.version, | |
122 | externalAuths: p.registerHelpersStore.getExternalAuths() | |
123 | })) | |
124 | .filter(v => v.externalAuths.length !== 0) | |
125 | } | |
126 | ||
127 | getRegisteredSettings (npmName: string) { | |
128 | const result = this.getRegisteredPluginOrTheme(npmName) | |
129 | if (!result || result.type !== PluginType.PLUGIN) return [] | |
130 | ||
131 | return result.registerHelpersStore.getSettings() | |
132 | } | |
133 | ||
134 | getRouter (npmName: string) { | |
135 | const result = this.getRegisteredPluginOrTheme(npmName) | |
136 | if (!result || result.type !== PluginType.PLUGIN) return null | |
137 | ||
138 | return result.registerHelpersStore.getRouter() | |
139 | } | |
140 | ||
141 | getTranslations (locale: string) { | |
142 | return this.translations[locale] || {} | |
143 | } | |
144 | ||
145 | async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') { | |
146 | const auth = this.getAuth(token.User.pluginAuth, token.authName) | |
147 | if (!auth) return true | |
148 | ||
149 | if (auth.hookTokenValidity) { | |
150 | try { | |
151 | const { valid } = await auth.hookTokenValidity({ token, type }) | |
152 | ||
153 | if (valid === false) { | |
154 | logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth) | |
155 | } | |
156 | ||
157 | return valid | |
158 | } catch (err) { | |
159 | logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err }) | |
160 | return true | |
161 | } | |
162 | } | |
163 | ||
164 | return true | |
165 | } | |
166 | ||
167 | // ###################### External events ###################### | |
168 | ||
169 | onLogout (npmName: string, authName: string, user: MUser) { | |
170 | const auth = this.getAuth(npmName, authName) | |
171 | ||
172 | if (auth?.onLogout) { | |
173 | logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName) | |
174 | ||
175 | try { | |
176 | auth.onLogout(user) | |
177 | } catch (err) { | |
178 | logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err }) | |
179 | } | |
180 | } | |
181 | } | |
182 | ||
183 | onSettingsChanged (name: string, settings: any) { | |
184 | const registered = this.getRegisteredPluginByShortName(name) | |
185 | if (!registered) { | |
186 | logger.error('Cannot find plugin %s to call on settings changed.', name) | |
187 | } | |
188 | ||
189 | for (const cb of registered.registerHelpersStore.getOnSettingsChangedCallbacks()) { | |
190 | try { | |
191 | cb(settings) | |
192 | } catch (err) { | |
193 | logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err }) | |
194 | } | |
195 | } | |
196 | } | |
197 | ||
198 | // ###################### Hooks ###################### | |
199 | ||
200 | async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> { | |
201 | if (!this.hooks[hookName]) return Promise.resolve(result) | |
202 | ||
203 | const hookType = getHookType(hookName) | |
204 | ||
205 | for (const hook of this.hooks[hookName]) { | |
206 | logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName) | |
207 | ||
208 | result = await internalRunHook(hook.handler, hookType, result, params, err => { | |
209 | logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) | |
210 | }) | |
211 | } | |
212 | ||
213 | return result | |
214 | } | |
215 | ||
216 | // ###################### Registration ###################### | |
217 | ||
218 | async registerPluginsAndThemes () { | |
219 | await this.resetCSSGlobalFile() | |
220 | ||
221 | const plugins = await PluginModel.listEnabledPluginsAndThemes() | |
222 | ||
223 | for (const plugin of plugins) { | |
224 | try { | |
225 | await this.registerPluginOrTheme(plugin) | |
226 | } catch (err) { | |
227 | // Try to unregister the plugin | |
228 | try { | |
229 | await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type)) | |
230 | } catch { | |
231 | // we don't care if we cannot unregister it | |
232 | } | |
233 | ||
234 | logger.error('Cannot register plugin %s, skipping.', plugin.name, { err }) | |
235 | } | |
236 | } | |
237 | ||
238 | this.sortHooksByPriority() | |
239 | } | |
240 | ||
241 | // Don't need the plugin type since themes cannot register server code | |
242 | async unregister (npmName: string) { | |
243 | logger.info('Unregister plugin %s.', npmName) | |
244 | ||
245 | const plugin = this.getRegisteredPluginOrTheme(npmName) | |
246 | ||
247 | if (!plugin) { | |
248 | throw new Error(`Unknown plugin ${npmName} to unregister`) | |
249 | } | |
250 | ||
251 | delete this.registeredPlugins[plugin.npmName] | |
252 | ||
253 | this.deleteTranslations(plugin.npmName) | |
254 | ||
255 | if (plugin.type === PluginType.PLUGIN) { | |
256 | await plugin.unregister() | |
257 | ||
258 | // Remove hooks of this plugin | |
259 | for (const key of Object.keys(this.hooks)) { | |
260 | this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName) | |
261 | } | |
262 | ||
263 | const store = plugin.registerHelpersStore | |
264 | store.reinitVideoConstants(plugin.npmName) | |
265 | ||
266 | logger.info('Regenerating registered plugin CSS to global file.') | |
267 | await this.regeneratePluginGlobalCSS() | |
268 | } | |
269 | } | |
270 | ||
271 | // ###################### Installation ###################### | |
272 | ||
273 | async install (toInstall: string, version?: string, fromDisk = false) { | |
274 | let plugin: PluginModel | |
275 | let npmName: string | |
276 | ||
277 | logger.info('Installing plugin %s.', toInstall) | |
278 | ||
279 | try { | |
280 | fromDisk | |
281 | ? await installNpmPluginFromDisk(toInstall) | |
282 | : await installNpmPlugin(toInstall, version) | |
283 | ||
284 | npmName = fromDisk ? basename(toInstall) : toInstall | |
285 | const pluginType = PluginModel.getTypeFromNpmName(npmName) | |
286 | const pluginName = PluginModel.normalizePluginName(npmName) | |
287 | ||
288 | const packageJSON = await this.getPackageJSON(pluginName, pluginType) | |
289 | ||
290 | this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType); | |
291 | ||
292 | [ plugin ] = await PluginModel.upsert({ | |
293 | name: pluginName, | |
294 | description: packageJSON.description, | |
295 | homepage: packageJSON.homepage, | |
296 | type: pluginType, | |
297 | version: packageJSON.version, | |
298 | enabled: true, | |
299 | uninstalled: false, | |
300 | peertubeEngine: packageJSON.engine.peertube | |
301 | }, { returning: true }) | |
302 | } catch (err) { | |
303 | logger.error('Cannot install plugin %s, removing it...', toInstall, { err }) | |
304 | ||
305 | try { | |
306 | await removeNpmPlugin(npmName) | |
307 | } catch (err) { | |
308 | logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err }) | |
309 | } | |
310 | ||
311 | throw err | |
312 | } | |
313 | ||
314 | logger.info('Successful installation of plugin %s.', toInstall) | |
315 | ||
316 | await this.registerPluginOrTheme(plugin) | |
317 | ||
318 | return plugin | |
319 | } | |
320 | ||
321 | async update (toUpdate: string, version?: string, fromDisk = false) { | |
322 | const npmName = fromDisk ? basename(toUpdate) : toUpdate | |
323 | ||
324 | logger.info('Updating plugin %s.', npmName) | |
325 | ||
326 | // Unregister old hooks | |
327 | await this.unregister(npmName) | |
328 | ||
329 | return this.install(toUpdate, version, fromDisk) | |
330 | } | |
331 | ||
332 | async uninstall (npmName: string) { | |
333 | logger.info('Uninstalling plugin %s.', npmName) | |
334 | ||
335 | try { | |
336 | await this.unregister(npmName) | |
337 | } catch (err) { | |
338 | logger.warn('Cannot unregister plugin %s.', npmName, { err }) | |
339 | } | |
340 | ||
341 | const plugin = await PluginModel.loadByNpmName(npmName) | |
342 | if (!plugin || plugin.uninstalled === true) { | |
343 | logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName) | |
344 | return | |
345 | } | |
346 | ||
347 | plugin.enabled = false | |
348 | plugin.uninstalled = true | |
349 | ||
350 | await plugin.save() | |
351 | ||
352 | await removeNpmPlugin(npmName) | |
353 | ||
354 | logger.info('Plugin %s uninstalled.', npmName) | |
355 | } | |
356 | ||
357 | // ###################### Private register ###################### | |
358 | ||
359 | private async registerPluginOrTheme (plugin: PluginModel) { | |
360 | const npmName = PluginModel.buildNpmName(plugin.name, plugin.type) | |
361 | ||
362 | logger.info('Registering plugin or theme %s.', npmName) | |
363 | ||
364 | const packageJSON = await this.getPackageJSON(plugin.name, plugin.type) | |
365 | const pluginPath = this.getPluginPath(plugin.name, plugin.type) | |
366 | ||
367 | this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type) | |
368 | ||
369 | let library: PluginLibrary | |
370 | let registerHelpersStore: RegisterHelpersStore | |
371 | if (plugin.type === PluginType.PLUGIN) { | |
372 | const result = await this.registerPlugin(plugin, pluginPath, packageJSON) | |
373 | library = result.library | |
374 | registerHelpersStore = result.registerStore | |
375 | } | |
376 | ||
377 | const clientScripts: { [id: string]: ClientScript } = {} | |
378 | for (const c of packageJSON.clientScripts) { | |
379 | clientScripts[c.script] = c | |
380 | } | |
381 | ||
382 | this.registeredPlugins[npmName] = { | |
383 | npmName, | |
384 | name: plugin.name, | |
385 | type: plugin.type, | |
386 | version: plugin.version, | |
387 | description: plugin.description, | |
388 | peertubeEngine: plugin.peertubeEngine, | |
389 | path: pluginPath, | |
390 | staticDirs: packageJSON.staticDirs, | |
391 | clientScripts, | |
392 | css: packageJSON.css, | |
393 | registerHelpersStore: registerHelpersStore || undefined, | |
394 | unregister: library ? library.unregister : undefined | |
395 | } | |
396 | ||
397 | await this.addTranslations(plugin, npmName, packageJSON.translations) | |
398 | } | |
399 | ||
400 | private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) { | |
401 | const npmName = PluginModel.buildNpmName(plugin.name, plugin.type) | |
402 | ||
403 | // Delete cache if needed | |
404 | const modulePath = join(pluginPath, packageJSON.library) | |
405 | delete require.cache[modulePath] | |
406 | const library: PluginLibrary = require(modulePath) | |
407 | ||
408 | if (!isLibraryCodeValid(library)) { | |
409 | throw new Error('Library code is not valid (miss register or unregister function)') | |
410 | } | |
411 | ||
412 | const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin) | |
413 | library.register(registerOptions) | |
414 | .catch(err => logger.error('Cannot register plugin %s.', npmName, { err })) | |
415 | ||
416 | logger.info('Add plugin %s CSS to global file.', npmName) | |
417 | ||
418 | await this.addCSSToGlobalFile(pluginPath, packageJSON.css) | |
419 | ||
420 | return { library, registerStore } | |
421 | } | |
422 | ||
423 | // ###################### Translations ###################### | |
424 | ||
425 | private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PackagePluginTranslations) { | |
426 | for (const locale of Object.keys(translationPaths)) { | |
427 | const path = translationPaths[locale] | |
428 | const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path)) | |
429 | ||
430 | if (!this.translations[locale]) this.translations[locale] = {} | |
431 | this.translations[locale][npmName] = json | |
432 | ||
433 | logger.info('Added locale %s of plugin %s.', locale, npmName) | |
434 | } | |
435 | } | |
436 | ||
437 | private deleteTranslations (npmName: string) { | |
438 | for (const locale of Object.keys(this.translations)) { | |
439 | delete this.translations[locale][npmName] | |
440 | ||
441 | logger.info('Deleted locale %s of plugin %s.', locale, npmName) | |
442 | } | |
443 | } | |
444 | ||
445 | // ###################### CSS ###################### | |
446 | ||
447 | private resetCSSGlobalFile () { | |
448 | ClientHtml.invalidCache() | |
449 | ||
450 | return outputFile(PLUGIN_GLOBAL_CSS_PATH, '') | |
451 | } | |
452 | ||
453 | private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) { | |
454 | for (const cssPath of cssRelativePaths) { | |
455 | await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH) | |
456 | } | |
457 | ||
458 | ClientHtml.invalidCache() | |
459 | } | |
460 | ||
461 | private concatFiles (input: string, output: string) { | |
462 | return new Promise<void>((res, rej) => { | |
463 | const inputStream = createReadStream(input) | |
464 | const outputStream = createWriteStream(output, { flags: 'a' }) | |
465 | ||
466 | inputStream.pipe(outputStream) | |
467 | ||
468 | inputStream.on('end', () => res()) | |
469 | inputStream.on('error', err => rej(err)) | |
470 | }) | |
471 | } | |
472 | ||
473 | private async regeneratePluginGlobalCSS () { | |
474 | await this.resetCSSGlobalFile() | |
475 | ||
476 | for (const plugin of this.getRegisteredPlugins()) { | |
477 | await this.addCSSToGlobalFile(plugin.path, plugin.css) | |
478 | } | |
479 | } | |
480 | ||
481 | // ###################### Utils ###################### | |
482 | ||
483 | private sortHooksByPriority () { | |
484 | for (const hookName of Object.keys(this.hooks)) { | |
485 | this.hooks[hookName].sort((a, b) => { | |
486 | return b.priority - a.priority | |
487 | }) | |
488 | } | |
489 | } | |
490 | ||
491 | private getPackageJSON (pluginName: string, pluginType: PluginType) { | |
492 | const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json') | |
493 | ||
494 | return readJSON(pluginPath) as Promise<PluginPackageJson> | |
495 | } | |
496 | ||
497 | private getPluginPath (pluginName: string, pluginType: PluginType) { | |
498 | const npmName = PluginModel.buildNpmName(pluginName, pluginType) | |
499 | ||
500 | return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName) | |
501 | } | |
502 | ||
503 | private getAuth (npmName: string, authName: string) { | |
504 | const plugin = this.getRegisteredPluginOrTheme(npmName) | |
505 | if (!plugin || plugin.type !== PluginType.PLUGIN) return null | |
506 | ||
507 | let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpersStore.getIdAndPassAuths() | |
508 | auths = auths.concat(plugin.registerHelpersStore.getExternalAuths()) | |
509 | ||
510 | return auths.find(a => a.authName === authName) | |
511 | } | |
512 | ||
513 | // ###################### Private getters ###################### | |
514 | ||
515 | private getRegisteredPluginsOrThemes (type: PluginType) { | |
516 | const plugins: RegisteredPlugin[] = [] | |
517 | ||
518 | for (const npmName of Object.keys(this.registeredPlugins)) { | |
519 | const plugin = this.registeredPlugins[npmName] | |
520 | if (plugin.type !== type) continue | |
521 | ||
522 | plugins.push(plugin) | |
523 | } | |
524 | ||
525 | return plugins | |
526 | } | |
527 | ||
528 | // ###################### Generate register helpers ###################### | |
529 | ||
530 | private getRegisterHelpers ( | |
531 | npmName: string, | |
532 | plugin: PluginModel | |
533 | ): { registerStore: RegisterHelpersStore, registerOptions: RegisterServerOptions } { | |
534 | const onHookAdded = (options: RegisterServerHookOptions) => { | |
535 | if (!this.hooks[options.target]) this.hooks[options.target] = [] | |
536 | ||
537 | this.hooks[options.target].push({ | |
538 | npmName: npmName, | |
539 | pluginName: plugin.name, | |
540 | handler: options.handler, | |
541 | priority: options.priority || 0 | |
542 | }) | |
543 | } | |
544 | ||
545 | const registerHelpersStore = new RegisterHelpersStore(npmName, plugin, onHookAdded.bind(this)) | |
546 | ||
547 | return { | |
548 | registerStore: registerHelpersStore, | |
549 | registerOptions: registerHelpersStore.buildRegisterHelpers() | |
550 | } | |
551 | } | |
552 | ||
553 | private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) { | |
554 | if (!packageJSON.staticDirs) packageJSON.staticDirs = {} | |
555 | if (!packageJSON.css) packageJSON.css = [] | |
556 | if (!packageJSON.clientScripts) packageJSON.clientScripts = [] | |
557 | if (!packageJSON.translations) packageJSON.translations = {} | |
558 | ||
559 | const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType) | |
560 | if (!packageJSONValid) { | |
561 | const formattedFields = badFields.map(f => `"${f}"`) | |
562 | .join(', ') | |
563 | ||
564 | throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`) | |
565 | } | |
566 | } | |
567 | ||
568 | static get Instance () { | |
569 | return this.instance || (this.instance = new this()) | |
570 | } | |
571 | } |