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