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