aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/root-helpers
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/root-helpers')
-rw-r--r--client/src/root-helpers/index.ts1
-rw-r--r--client/src/root-helpers/plugins-manager.ts251
-rw-r--r--client/src/root-helpers/plugins.ts126
3 files changed, 252 insertions, 126 deletions
diff --git a/client/src/root-helpers/index.ts b/client/src/root-helpers/index.ts
index 036a7677d..d62f07f9e 100644
--- a/client/src/root-helpers/index.ts
+++ b/client/src/root-helpers/index.ts
@@ -2,3 +2,4 @@ export * from './users'
2export * from './bytes' 2export * from './bytes'
3export * from './peertube-web-storage' 3export * from './peertube-web-storage'
4export * from './utils' 4export * from './utils'
5export * from './plugins-manager'
diff --git a/client/src/root-helpers/plugins-manager.ts b/client/src/root-helpers/plugins-manager.ts
new file mode 100644
index 000000000..f919db8af
--- /dev/null
+++ b/client/src/root-helpers/plugins-manager.ts
@@ -0,0 +1,251 @@
1import * as debug from 'debug'
2import { ReplaySubject } from 'rxjs'
3import { first, shareReplay } from 'rxjs/operators'
4import { RegisterClientHelpers } from 'src/types/register-client-option.model'
5import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
6import {
7 ClientHookName,
8 clientHookObject,
9 ClientScript,
10 HTMLServerConfig,
11 PluginClientScope,
12 PluginType,
13 RegisterClientFormFieldOptions,
14 RegisterClientHookOptions,
15 RegisterClientSettingsScript,
16 RegisterClientVideoFieldOptions,
17 ServerConfigPlugin
18} from '../../../shared/models'
19import { environment } from '../environments/environment'
20import { ClientScript as ClientScriptModule } from '../types/client-script.model'
21
22interface HookStructValue extends RegisterClientHookOptions {
23 plugin: ServerConfigPlugin
24 clientScript: ClientScript
25}
26
27type Hooks = { [ name: string ]: HookStructValue[] }
28
29type PluginInfo = {
30 plugin: ServerConfigPlugin
31 clientScript: ClientScript
32 pluginType: PluginType
33 isTheme: boolean
34}
35
36type PeertubeHelpersFactory = (pluginInfo: PluginInfo) => RegisterClientHelpers
37type OnFormFields = (options: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => void
38type OnSettingsScripts = (pluginInfo: PluginInfo, options: RegisterClientSettingsScript) => void
39
40const logger = debug('peertube:plugins')
41
42class PluginsManager {
43 private hooks: Hooks = {}
44
45 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
46
47 private loadedScripts: { [ script: string ]: boolean } = {}
48 private loadedScopes: PluginClientScope[] = []
49 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
50
51 private pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
52 common: new ReplaySubject<boolean>(1),
53 'admin-plugin': new ReplaySubject<boolean>(1),
54 search: new ReplaySubject<boolean>(1),
55 'video-watch': new ReplaySubject<boolean>(1),
56 signup: new ReplaySubject<boolean>(1),
57 login: new ReplaySubject<boolean>(1),
58 'video-edit': new ReplaySubject<boolean>(1),
59 embed: new ReplaySubject<boolean>(1)
60 }
61
62 private readonly peertubeHelpersFactory: PeertubeHelpersFactory
63 private readonly onFormFields: OnFormFields
64 private readonly onSettingsScripts: OnSettingsScripts
65
66 constructor (options: {
67 peertubeHelpersFactory: PeertubeHelpersFactory
68 onFormFields?: OnFormFields
69 onSettingsScripts?: OnSettingsScripts
70 }) {
71 this.peertubeHelpersFactory = options.peertubeHelpersFactory
72 this.onFormFields = options.onFormFields
73 this.onSettingsScripts = options.onSettingsScripts
74 }
75
76 static getPluginPathPrefix (isTheme: boolean) {
77 return isTheme ? '/themes' : '/plugins'
78 }
79
80 loadPluginsList (config: HTMLServerConfig) {
81 for (const plugin of config.plugin.registered) {
82 this.addPlugin(plugin)
83 }
84 }
85
86 async runHook<T> (hookName: ClientHookName, result?: T, params?: any) {
87 if (!this.hooks[hookName]) return result
88
89 const hookType = getHookType(hookName)
90
91 for (const hook of this.hooks[hookName]) {
92 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
93
94 result = await internalRunHook(hook.handler, hookType, result, params, err => {
95 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
96 })
97 }
98
99 return result
100 }
101
102 ensurePluginsAreLoaded (scope: PluginClientScope) {
103 this.loadPluginsByScope(scope)
104
105 return this.pluginsLoaded[scope].asObservable()
106 .pipe(first(), shareReplay())
107 .toPromise()
108 }
109
110 async reloadLoadedScopes () {
111 for (const scope of this.loadedScopes) {
112 await this.loadPluginsByScope(scope, true)
113 }
114 }
115
116 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
117 const pathPrefix = PluginsManager.getPluginPathPrefix(isTheme)
118
119 for (const key of Object.keys(plugin.clientScripts)) {
120 const clientScript = plugin.clientScripts[key]
121
122 for (const scope of clientScript.scopes) {
123 if (!this.scopes[scope]) this.scopes[scope] = []
124
125 this.scopes[scope].push({
126 plugin,
127 clientScript: {
128 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
129 scopes: clientScript.scopes
130 },
131 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
132 isTheme
133 })
134
135 this.loadedScripts[clientScript.script] = false
136 }
137 }
138 }
139
140 removePlugin (plugin: ServerConfigPlugin) {
141 for (const key of Object.keys(this.scopes)) {
142 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
143 }
144 }
145
146 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
147 if (this.loadingScopes[scope]) return
148 if (!isReload && this.loadedScopes.includes(scope)) return
149
150 this.loadingScopes[scope] = true
151
152 logger('Loading scope %s', scope)
153
154 try {
155 if (!isReload) this.loadedScopes.push(scope)
156
157 const toLoad = this.scopes[ scope ]
158 if (!Array.isArray(toLoad)) {
159 this.loadingScopes[scope] = false
160 this.pluginsLoaded[scope].next(true)
161
162 logger('Nothing to load for scope %s', scope)
163 return
164 }
165
166 const promises: Promise<any>[] = []
167 for (const pluginInfo of toLoad) {
168 const clientScript = pluginInfo.clientScript
169
170 if (this.loadedScripts[ clientScript.script ]) continue
171
172 promises.push(this.loadPlugin(pluginInfo))
173
174 this.loadedScripts[ clientScript.script ] = true
175 }
176
177 await Promise.all(promises)
178
179 this.pluginsLoaded[scope].next(true)
180 this.loadingScopes[scope] = false
181
182 logger('Scope %s loaded', scope)
183 } catch (err) {
184 console.error('Cannot load plugins by scope %s.', scope, err)
185 }
186 }
187
188 private loadPlugin (pluginInfo: PluginInfo) {
189 const { plugin, clientScript } = pluginInfo
190
191 const registerHook = (options: RegisterClientHookOptions) => {
192 if (clientHookObject[options.target] !== true) {
193 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
194 return
195 }
196
197 if (!this.hooks[options.target]) this.hooks[options.target] = []
198
199 this.hooks[options.target].push({
200 plugin,
201 clientScript,
202 target: options.target,
203 handler: options.handler,
204 priority: options.priority || 0
205 })
206 }
207
208 const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => {
209 if (!this.onFormFields) {
210 throw new Error('Video field registration is not supported')
211 }
212
213 return this.onFormFields(commonOptions, videoFormOptions)
214 }
215
216 const registerSettingsScript = (options: RegisterClientSettingsScript) => {
217 if (!this.onSettingsScripts) {
218 throw new Error('Registering settings script is not supported')
219 }
220
221 return this.onSettingsScripts(pluginInfo, options)
222 }
223
224 const peertubeHelpers = this.peertubeHelpersFactory(pluginInfo)
225
226 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
227
228 const absURL = (environment.apiUrl || window.location.origin) + clientScript.script
229 return import(/* webpackIgnore: true */ absURL)
230 .then((script: ClientScriptModule) => script.register({ registerHook, registerVideoField, registerSettingsScript, peertubeHelpers }))
231 .then(() => this.sortHooksByPriority())
232 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
233 }
234
235 private sortHooksByPriority () {
236 for (const hookName of Object.keys(this.hooks)) {
237 this.hooks[hookName].sort((a, b) => {
238 return b.priority - a.priority
239 })
240 }
241 }
242}
243
244export {
245 PluginsManager,
246
247 PluginInfo,
248 PeertubeHelpersFactory,
249 OnFormFields,
250 OnSettingsScripts
251}
diff --git a/client/src/root-helpers/plugins.ts b/client/src/root-helpers/plugins.ts
deleted file mode 100644
index 10c111a8c..000000000
--- a/client/src/root-helpers/plugins.ts
+++ /dev/null
@@ -1,126 +0,0 @@
1import { RegisterClientHelpers } from 'src/types/register-client-option.model'
2import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
3import {
4 ClientHookName,
5 clientHookObject,
6 ClientScript,
7 PluginType,
8 RegisterClientFormFieldOptions,
9 RegisterClientHookOptions,
10 RegisterClientSettingsScript,
11 RegisterClientVideoFieldOptions,
12 ServerConfigPlugin
13} from '../../../shared/models'
14import { environment } from '../environments/environment'
15import { ClientScript as ClientScriptModule } from '../types/client-script.model'
16
17interface HookStructValue extends RegisterClientHookOptions {
18 plugin: ServerConfigPlugin
19 clientScript: ClientScript
20}
21
22type Hooks = { [ name: string ]: HookStructValue[] }
23
24type PluginInfo = {
25 plugin: ServerConfigPlugin
26 clientScript: ClientScript
27 pluginType: PluginType
28 isTheme: boolean
29}
30
31type FormFields = {
32 video: {
33 commonOptions: RegisterClientFormFieldOptions
34 videoFormOptions: RegisterClientVideoFieldOptions
35 }[]
36}
37
38async function runHook<T> (hooks: Hooks, hookName: ClientHookName, result?: T, params?: any) {
39 if (!hooks[hookName]) return result
40
41 const hookType = getHookType(hookName)
42
43 for (const hook of hooks[hookName]) {
44 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
45
46 result = await internalRunHook(hook.handler, hookType, result, params, err => {
47 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
48 })
49 }
50
51 return result
52}
53
54function loadPlugin (options: {
55 hooks: Hooks
56 pluginInfo: PluginInfo
57 peertubeHelpersFactory: (pluginInfo: PluginInfo) => RegisterClientHelpers
58 formFields?: FormFields
59 onSettingsScripts?: (options: RegisterClientSettingsScript) => void
60}) {
61 const { hooks, pluginInfo, peertubeHelpersFactory, formFields, onSettingsScripts } = options
62 const { plugin, clientScript } = pluginInfo
63
64 const registerHook = (options: RegisterClientHookOptions) => {
65 if (clientHookObject[options.target] !== true) {
66 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
67 return
68 }
69
70 if (!hooks[options.target]) hooks[options.target] = []
71
72 hooks[options.target].push({
73 plugin,
74 clientScript,
75 target: options.target,
76 handler: options.handler,
77 priority: options.priority || 0
78 })
79 }
80
81 const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => {
82 if (!formFields) {
83 throw new Error('Video field registration is not supported')
84 }
85
86 formFields.video.push({
87 commonOptions,
88 videoFormOptions
89 })
90 }
91
92 const registerSettingsScript = (options: RegisterClientSettingsScript) => {
93 if (!onSettingsScripts) {
94 throw new Error('Registering settings script is not supported')
95 }
96
97 return onSettingsScripts(options)
98 }
99
100 const peertubeHelpers = peertubeHelpersFactory(pluginInfo)
101
102 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
103
104 const absURL = (environment.apiUrl || window.location.origin) + clientScript.script
105 return import(/* webpackIgnore: true */ absURL)
106 .then((script: ClientScriptModule) => script.register({ registerHook, registerVideoField, registerSettingsScript, peertubeHelpers }))
107 .then(() => sortHooksByPriority(hooks))
108 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
109}
110
111export {
112 HookStructValue,
113 Hooks,
114 PluginInfo,
115 FormFields,
116 loadPlugin,
117 runHook
118}
119
120function sortHooksByPriority (hooks: Hooks) {
121 for (const hookName of Object.keys(hooks)) {
122 hooks[hookName].sort((a, b) => {
123 return b.priority - a.priority
124 })
125 }
126}