]>
Commit | Line | Data |
---|---|---|
2b36e477 | 1 | /* eslint-disable @typescript-eslint/no-implied-eval */ |
72f611ca | 2 | import * as debug from 'debug' |
1378c0d3 | 3 | import { firstValueFrom, ReplaySubject } from 'rxjs' |
72f611ca | 4 | import { first, shareReplay } from 'rxjs/operators' |
5 | import { RegisterClientHelpers } from 'src/types/register-client-option.model' | |
2570fd9c | 6 | import { getExternalAuthHref, getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks' |
72f611ca | 7 | import { |
8 | ClientHookName, | |
9 | clientHookObject, | |
c7cdac44 | 10 | ClientScriptJSON, |
72f611ca | 11 | HTMLServerConfig, |
12 | PluginClientScope, | |
13 | PluginType, | |
14 | RegisterClientFormFieldOptions, | |
15 | RegisterClientHookOptions, | |
d63e6d46 C |
16 | RegisterClientRouteOptions, |
17 | RegisterClientSettingsScriptOptions, | |
72f611ca | 18 | RegisterClientVideoFieldOptions, |
19 | ServerConfigPlugin | |
c7cdac44 | 20 | } from '@shared/models' |
72f611ca | 21 | import { environment } from '../environments/environment' |
c7cdac44 | 22 | import { ClientScript } from '../types' |
42b40636 | 23 | import { logger } from './logger' |
72f611ca | 24 | |
25 | interface HookStructValue extends RegisterClientHookOptions { | |
26 | plugin: ServerConfigPlugin | |
c7cdac44 | 27 | clientScript: ClientScriptJSON |
72f611ca | 28 | } |
29 | ||
30 | type Hooks = { [ name: string ]: HookStructValue[] } | |
31 | ||
32 | type PluginInfo = { | |
33 | plugin: ServerConfigPlugin | |
c7cdac44 | 34 | clientScript: ClientScriptJSON |
72f611ca | 35 | pluginType: PluginType |
36 | isTheme: boolean | |
37 | } | |
38 | ||
39 | type PeertubeHelpersFactory = (pluginInfo: PluginInfo) => RegisterClientHelpers | |
fb3c9e2b C |
40 | |
41 | type OnFormFields = ( | |
42 | pluginInfo: PluginInfo, | |
43 | options: RegisterClientFormFieldOptions, | |
44 | videoFormOptions: RegisterClientVideoFieldOptions | |
45 | ) => void | |
46 | ||
d63e6d46 | 47 | type OnSettingsScripts = (pluginInfo: PluginInfo, options: RegisterClientSettingsScriptOptions) => void |
fb3c9e2b | 48 | |
d63e6d46 | 49 | type OnClientRoute = (options: RegisterClientRouteOptions) => void |
72f611ca | 50 | |
42b40636 | 51 | const debugLogger = debug('peertube:plugins') |
72f611ca | 52 | |
53 | class PluginsManager { | |
54 | private hooks: Hooks = {} | |
55 | ||
56 | private scopes: { [ scopeName: string ]: PluginInfo[] } = {} | |
57 | ||
58 | private loadedScripts: { [ script: string ]: boolean } = {} | |
59 | private loadedScopes: PluginClientScope[] = [] | |
60 | private loadingScopes: { [id in PluginClientScope]?: boolean } = {} | |
61 | ||
62 | private pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = { | |
63 | common: new ReplaySubject<boolean>(1), | |
64 | 'admin-plugin': new ReplaySubject<boolean>(1), | |
65 | search: new ReplaySubject<boolean>(1), | |
66 | 'video-watch': new ReplaySubject<boolean>(1), | |
67 | signup: new ReplaySubject<boolean>(1), | |
68 | login: new ReplaySubject<boolean>(1), | |
69 | 'video-edit': new ReplaySubject<boolean>(1), | |
f8b4a71d | 70 | embed: new ReplaySubject<boolean>(1), |
9ca0f688 C |
71 | 'my-library': new ReplaySubject<boolean>(1), |
72 | 'video-channel': new ReplaySubject<boolean>(1) | |
72f611ca | 73 | } |
74 | ||
75 | private readonly peertubeHelpersFactory: PeertubeHelpersFactory | |
76 | private readonly onFormFields: OnFormFields | |
77 | private readonly onSettingsScripts: OnSettingsScripts | |
d63e6d46 | 78 | private readonly onClientRoute: OnClientRoute |
72f611ca | 79 | |
80 | constructor (options: { | |
81 | peertubeHelpersFactory: PeertubeHelpersFactory | |
82 | onFormFields?: OnFormFields | |
83 | onSettingsScripts?: OnSettingsScripts | |
d63e6d46 | 84 | onClientRoute?: OnClientRoute |
72f611ca | 85 | }) { |
86 | this.peertubeHelpersFactory = options.peertubeHelpersFactory | |
87 | this.onFormFields = options.onFormFields | |
88 | this.onSettingsScripts = options.onSettingsScripts | |
d63e6d46 | 89 | this.onClientRoute = options.onClientRoute |
72f611ca | 90 | } |
91 | ||
92 | static getPluginPathPrefix (isTheme: boolean) { | |
93 | return isTheme ? '/themes' : '/plugins' | |
94 | } | |
95 | ||
2570fd9c C |
96 | static getDefaultLoginHref (apiUrl: string, serverConfig: HTMLServerConfig) { |
97 | if (!serverConfig || serverConfig.client.menu.login.redirectOnSingleExternalAuth !== true) return undefined | |
0bc53e20 | 98 | |
2570fd9c C |
99 | const externalAuths = serverConfig.plugin.registeredExternalAuths |
100 | if (externalAuths.length !== 1) return undefined | |
101 | ||
102 | return getExternalAuthHref(apiUrl, externalAuths[0]) | |
0bc53e20 C |
103 | } |
104 | ||
72f611ca | 105 | loadPluginsList (config: HTMLServerConfig) { |
106 | for (const plugin of config.plugin.registered) { | |
107 | this.addPlugin(plugin) | |
108 | } | |
109 | } | |
110 | ||
2e5dd0be C |
111 | async runHook<T> (hookName: ClientHookName, resultArg?: T | Promise<T>, params?: any) { |
112 | if (!this.hooks[hookName]) { | |
113 | // eslint-disable-next-line no-return-await | |
114 | return await resultArg | |
115 | } | |
72f611ca | 116 | |
117 | const hookType = getHookType(hookName) | |
118 | ||
2e5dd0be C |
119 | let result = await resultArg |
120 | ||
72f611ca | 121 | for (const hook of this.hooks[hookName]) { |
42b40636 | 122 | logger.info(`Running hook ${hookName} of plugin ${hook.plugin.name}`) |
72f611ca | 123 | |
22df69fd C |
124 | result = await internalRunHook({ |
125 | handler: hook.handler, | |
126 | hookType, | |
127 | result, | |
128 | params, | |
129 | onError: err => { | |
130 | logger.error(`Cannot run hook ${hookName} of script ${hook.clientScript.script} of plugin ${hook.plugin.name}`, err) | |
131 | } | |
72f611ca | 132 | }) |
133 | } | |
134 | ||
135 | return result | |
136 | } | |
137 | ||
138 | ensurePluginsAreLoaded (scope: PluginClientScope) { | |
139 | this.loadPluginsByScope(scope) | |
140 | ||
1378c0d3 | 141 | const obs = this.pluginsLoaded[scope].asObservable() |
72f611ca | 142 | .pipe(first(), shareReplay()) |
1378c0d3 C |
143 | |
144 | return firstValueFrom(obs) | |
72f611ca | 145 | } |
146 | ||
147 | async reloadLoadedScopes () { | |
148 | for (const scope of this.loadedScopes) { | |
149 | await this.loadPluginsByScope(scope, true) | |
150 | } | |
151 | } | |
152 | ||
153 | addPlugin (plugin: ServerConfigPlugin, isTheme = false) { | |
154 | const pathPrefix = PluginsManager.getPluginPathPrefix(isTheme) | |
155 | ||
156 | for (const key of Object.keys(plugin.clientScripts)) { | |
157 | const clientScript = plugin.clientScripts[key] | |
158 | ||
159 | for (const scope of clientScript.scopes) { | |
160 | if (!this.scopes[scope]) this.scopes[scope] = [] | |
161 | ||
162 | this.scopes[scope].push({ | |
163 | plugin, | |
164 | clientScript: { | |
165 | script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`, | |
166 | scopes: clientScript.scopes | |
167 | }, | |
168 | pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN, | |
169 | isTheme | |
170 | }) | |
171 | ||
172 | this.loadedScripts[clientScript.script] = false | |
173 | } | |
174 | } | |
175 | } | |
176 | ||
177 | removePlugin (plugin: ServerConfigPlugin) { | |
178 | for (const key of Object.keys(this.scopes)) { | |
179 | this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name) | |
180 | } | |
181 | } | |
182 | ||
183 | async loadPluginsByScope (scope: PluginClientScope, isReload = false) { | |
184 | if (this.loadingScopes[scope]) return | |
185 | if (!isReload && this.loadedScopes.includes(scope)) return | |
186 | ||
187 | this.loadingScopes[scope] = true | |
188 | ||
42b40636 | 189 | debugLogger('Loading scope %s', scope) |
72f611ca | 190 | |
191 | try { | |
192 | if (!isReload) this.loadedScopes.push(scope) | |
193 | ||
9df52d66 | 194 | const toLoad = this.scopes[scope] |
72f611ca | 195 | if (!Array.isArray(toLoad)) { |
196 | this.loadingScopes[scope] = false | |
197 | this.pluginsLoaded[scope].next(true) | |
198 | ||
42b40636 | 199 | debugLogger('Nothing to load for scope %s', scope) |
72f611ca | 200 | return |
201 | } | |
202 | ||
203 | const promises: Promise<any>[] = [] | |
204 | for (const pluginInfo of toLoad) { | |
205 | const clientScript = pluginInfo.clientScript | |
206 | ||
9df52d66 | 207 | if (this.loadedScripts[clientScript.script]) continue |
72f611ca | 208 | |
209 | promises.push(this.loadPlugin(pluginInfo)) | |
210 | ||
9df52d66 | 211 | this.loadedScripts[clientScript.script] = true |
72f611ca | 212 | } |
213 | ||
214 | await Promise.all(promises) | |
215 | ||
216 | this.pluginsLoaded[scope].next(true) | |
217 | this.loadingScopes[scope] = false | |
218 | ||
42b40636 | 219 | debugLogger('Scope %s loaded', scope) |
72f611ca | 220 | } catch (err) { |
42b40636 | 221 | logger.error(`Cannot load plugins by scope ${scope}`, err) |
72f611ca | 222 | } |
223 | } | |
224 | ||
225 | private loadPlugin (pluginInfo: PluginInfo) { | |
226 | const { plugin, clientScript } = pluginInfo | |
227 | ||
228 | const registerHook = (options: RegisterClientHookOptions) => { | |
229 | if (clientHookObject[options.target] !== true) { | |
42b40636 | 230 | logger.error(`Unknown hook ${options.target} of plugin ${plugin.name}. Skipping.`) |
72f611ca | 231 | return |
232 | } | |
233 | ||
234 | if (!this.hooks[options.target]) this.hooks[options.target] = [] | |
235 | ||
236 | this.hooks[options.target].push({ | |
237 | plugin, | |
238 | clientScript, | |
239 | target: options.target, | |
240 | handler: options.handler, | |
241 | priority: options.priority || 0 | |
242 | }) | |
243 | } | |
244 | ||
245 | const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => { | |
246 | if (!this.onFormFields) { | |
247 | throw new Error('Video field registration is not supported') | |
248 | } | |
249 | ||
fb3c9e2b | 250 | return this.onFormFields(pluginInfo, commonOptions, videoFormOptions) |
72f611ca | 251 | } |
252 | ||
d63e6d46 | 253 | const registerSettingsScript = (options: RegisterClientSettingsScriptOptions) => { |
72f611ca | 254 | if (!this.onSettingsScripts) { |
255 | throw new Error('Registering settings script is not supported') | |
256 | } | |
257 | ||
258 | return this.onSettingsScripts(pluginInfo, options) | |
259 | } | |
260 | ||
d63e6d46 C |
261 | const registerClientRoute = (options: RegisterClientRouteOptions) => { |
262 | if (!this.onClientRoute) { | |
263 | throw new Error('Registering client route is not supported') | |
264 | } | |
265 | ||
266 | return this.onClientRoute(options) | |
267 | } | |
268 | ||
72f611ca | 269 | const peertubeHelpers = this.peertubeHelpersFactory(pluginInfo) |
270 | ||
42b40636 | 271 | logger.info(`Loading script ${clientScript.script} of plugin ${plugin.name}`) |
72f611ca | 272 | |
273 | const absURL = (environment.apiUrl || window.location.origin) + clientScript.script | |
2b36e477 | 274 | return dynamicImport(absURL) |
c7cdac44 | 275 | .then((script: ClientScript) => { |
d63e6d46 C |
276 | return script.register({ |
277 | registerHook, | |
278 | registerVideoField, | |
279 | registerSettingsScript, | |
280 | registerClientRoute, | |
281 | peertubeHelpers | |
282 | }) | |
283 | }) | |
72f611ca | 284 | .then(() => this.sortHooksByPriority()) |
42b40636 | 285 | .catch(err => logger.error(`Cannot import or register plugin ${pluginInfo.plugin.name}`, err)) |
72f611ca | 286 | } |
287 | ||
288 | private sortHooksByPriority () { | |
289 | for (const hookName of Object.keys(this.hooks)) { | |
290 | this.hooks[hookName].sort((a, b) => { | |
291 | return b.priority - a.priority | |
292 | }) | |
293 | } | |
294 | } | |
295 | } | |
296 | ||
297 | export { | |
298 | PluginsManager, | |
299 | ||
300 | PluginInfo, | |
301 | PeertubeHelpersFactory, | |
302 | OnFormFields, | |
303 | OnSettingsScripts | |
304 | } | |
2b36e477 C |
305 | |
306 | // --------------------------------------------------------------------------- | |
307 | ||
308 | async function dynamicImport (url: string) { | |
309 | try { | |
310 | // eslint-disable-next-line no-new-func | |
311 | return new Function(`return import('${url}')`)() | |
312 | } catch { | |
42b40636 | 313 | logger.info('Fallback to import polyfill') |
2b36e477 C |
314 | |
315 | return new Promise((resolve, reject) => { | |
316 | const vector = '$importModule$' + Math.random().toString(32).slice(2) | |
317 | const script = document.createElement('script') | |
318 | ||
319 | const destructor = () => { | |
320 | delete window[vector] | |
321 | script.onerror = null | |
322 | script.onload = null | |
323 | script.remove() | |
324 | URL.revokeObjectURL(script.src) | |
325 | script.src = '' | |
326 | } | |
327 | ||
328 | script.defer = true | |
329 | script.type = 'module' | |
330 | ||
331 | script.onerror = () => { | |
332 | reject(new Error(`Failed to import: ${url}`)) | |
333 | destructor() | |
334 | } | |
335 | script.onload = () => { | |
336 | resolve(window[vector]) | |
337 | destructor() | |
338 | } | |
339 | const loader = `import * as m from "${url}"; window.${vector} = m;` // export Module | |
340 | const blob = new Blob([ loader ], { type: 'text/javascript' }) | |
341 | script.src = URL.createObjectURL(blob) | |
342 | ||
343 | document.head.appendChild(script) | |
344 | }) | |
345 | } | |
346 | } |