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