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