]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
Add custom modal to plugin helpers (#2631)
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
1 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { getCompleteLocale, isDefaultLocale, peertubeTranslate, ServerConfigPlugin } from '@shared/models'
4 import { ServerService } from '@app/core/server/server.service'
5 import { ClientScript } from '@shared/models/plugins/plugin-package-json.model'
6 import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
7 import { environment } from '../../../environments/environment'
8 import { Observable, of, ReplaySubject } from 'rxjs'
9 import { catchError, first, map, shareReplay } from 'rxjs/operators'
10 import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
11 import { ClientHook, ClientHookName, clientHookObject } from '@shared/models/plugins/client-hook.model'
12 import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
13 import { RegisterClientHookOptions } from '@shared/models/plugins/register-client-hook.model'
14 import { HttpClient } from '@angular/common/http'
15 import { AuthService, Notifier } from '@app/core'
16 import { RestExtractor } from '@app/shared/rest'
17 import { PluginType } from '@shared/models/plugins/plugin.type'
18 import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
19 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
20 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
21 import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
22 import { importModule } from '@app/shared/misc/utils'
23 import { CustomModalComponent } from '@app/modal/custom-modal.component'
24
25 interface HookStructValue extends RegisterClientHookOptions {
26 plugin: ServerConfigPlugin
27 clientScript: ClientScript
28 }
29
30 type PluginInfo = {
31 plugin: ServerConfigPlugin
32 clientScript: ClientScript
33 pluginType: PluginType
34 isTheme: boolean
35 }
36
37 @Injectable()
38 export class PluginService implements ClientHook {
39 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
40 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
41
42 pluginsBuilt = new ReplaySubject<boolean>(1)
43
44 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
45 common: new ReplaySubject<boolean>(1),
46 search: new ReplaySubject<boolean>(1),
47 'video-watch': new ReplaySubject<boolean>(1),
48 signup: new ReplaySubject<boolean>(1)
49 }
50
51 translationsObservable: Observable<PluginTranslation>
52
53 customModal: CustomModalComponent
54
55 private plugins: ServerConfigPlugin[] = []
56 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
57 private loadedScripts: { [ script: string ]: boolean } = {}
58 private loadedScopes: PluginClientScope[] = []
59 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
60
61 private hooks: { [ name: string ]: HookStructValue[] } = {}
62
63 constructor (
64 private router: Router,
65 private authService: AuthService,
66 private notifier: Notifier,
67 private server: ServerService,
68 private zone: NgZone,
69 private authHttp: HttpClient,
70 private restExtractor: RestExtractor,
71 @Inject(LOCALE_ID) private localeId: string
72 ) {
73 this.loadTranslations()
74 }
75
76 initializePlugins () {
77 this.server.getConfig()
78 .subscribe(config => {
79 this.plugins = config.plugin.registered
80
81 this.buildScopeStruct()
82
83 this.pluginsBuilt.next(true)
84 })
85 }
86
87 initializeCustomModal (customModal: CustomModalComponent) {
88 this.customModal = customModal
89 }
90
91 ensurePluginsAreBuilt () {
92 return this.pluginsBuilt.asObservable()
93 .pipe(first(), shareReplay())
94 .toPromise()
95 }
96
97 ensurePluginsAreLoaded (scope: PluginClientScope) {
98 this.loadPluginsByScope(scope)
99
100 return this.pluginsLoaded[scope].asObservable()
101 .pipe(first(), shareReplay())
102 .toPromise()
103 }
104
105 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
106 const pathPrefix = this.getPluginPathPrefix(isTheme)
107
108 for (const key of Object.keys(plugin.clientScripts)) {
109 const clientScript = plugin.clientScripts[key]
110
111 for (const scope of clientScript.scopes) {
112 if (!this.scopes[scope]) this.scopes[scope] = []
113
114 this.scopes[scope].push({
115 plugin,
116 clientScript: {
117 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
118 scopes: clientScript.scopes
119 },
120 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
121 isTheme
122 })
123
124 this.loadedScripts[clientScript.script] = false
125 }
126 }
127 }
128
129 removePlugin (plugin: ServerConfigPlugin) {
130 for (const key of Object.keys(this.scopes)) {
131 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
132 }
133 }
134
135 async reloadLoadedScopes () {
136 for (const scope of this.loadedScopes) {
137 await this.loadPluginsByScope(scope, true)
138 }
139 }
140
141 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
142 if (this.loadingScopes[scope]) return
143 if (!isReload && this.loadedScopes.includes(scope)) return
144
145 this.loadingScopes[scope] = true
146
147 try {
148 await this.ensurePluginsAreBuilt()
149
150 if (!isReload) this.loadedScopes.push(scope)
151
152 const toLoad = this.scopes[ scope ]
153 if (!Array.isArray(toLoad)) {
154 this.loadingScopes[scope] = false
155 this.pluginsLoaded[scope].next(true)
156
157 return
158 }
159
160 const promises: Promise<any>[] = []
161 for (const pluginInfo of toLoad) {
162 const clientScript = pluginInfo.clientScript
163
164 if (this.loadedScripts[ clientScript.script ]) continue
165
166 promises.push(this.loadPlugin(pluginInfo))
167
168 this.loadedScripts[ clientScript.script ] = true
169 }
170
171 await Promise.all(promises)
172
173 this.pluginsLoaded[scope].next(true)
174 this.loadingScopes[scope] = false
175 } catch (err) {
176 console.error('Cannot load plugins by scope %s.', scope, err)
177 }
178 }
179
180 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
181 return this.zone.runOutsideAngular(async () => {
182 if (!this.hooks[ hookName ]) return result
183
184 const hookType = getHookType(hookName)
185
186 for (const hook of this.hooks[ hookName ]) {
187 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
188
189 result = await internalRunHook(hook.handler, hookType, result, params, err => {
190 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
191 })
192 }
193
194 return result
195 })
196 }
197
198 nameToNpmName (name: string, type: PluginType) {
199 const prefix = type === PluginType.PLUGIN
200 ? 'peertube-plugin-'
201 : 'peertube-theme-'
202
203 return prefix + name
204 }
205
206 pluginTypeFromNpmName (npmName: string) {
207 return npmName.startsWith('peertube-plugin-')
208 ? PluginType.PLUGIN
209 : PluginType.THEME
210 }
211
212 private loadPlugin (pluginInfo: PluginInfo) {
213 const { plugin, clientScript } = pluginInfo
214
215 const registerHook = (options: RegisterClientHookOptions) => {
216 if (clientHookObject[options.target] !== true) {
217 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
218 return
219 }
220
221 if (!this.hooks[options.target]) this.hooks[options.target] = []
222
223 this.hooks[options.target].push({
224 plugin,
225 clientScript,
226 target: options.target,
227 handler: options.handler,
228 priority: options.priority || 0
229 })
230 }
231
232 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
233
234 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
235
236 return this.zone.runOutsideAngular(() => {
237 return importModule(clientScript.script)
238 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
239 .then(() => this.sortHooksByPriority())
240 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
241 })
242 }
243
244 private buildScopeStruct () {
245 for (const plugin of this.plugins) {
246 this.addPlugin(plugin)
247 }
248 }
249
250 private sortHooksByPriority () {
251 for (const hookName of Object.keys(this.hooks)) {
252 this.hooks[hookName].sort((a, b) => {
253 return b.priority - a.priority
254 })
255 }
256 }
257
258 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
259 const { plugin } = pluginInfo
260 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
261
262 return {
263 getBaseStaticRoute: () => {
264 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
265 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
266 },
267
268 getSettings: () => {
269 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
270
271 return this.authHttp.get<PublicServerSetting>(path)
272 .pipe(
273 map(p => p.publicSettings),
274 catchError(res => this.restExtractor.handleError(res))
275 )
276 .toPromise()
277 },
278
279 isLoggedIn: () => {
280 return this.authService.isLoggedIn()
281 },
282
283 notifier: {
284 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
285 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
286 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
287 },
288
289 showModal: (input: {
290 title: string,
291 content: string,
292 close?: boolean,
293 cancel?: { value: string, action?: () => void },
294 confirm?: { value: string, action?: () => void }
295 }) => {
296 this.customModal.show(input)
297 },
298
299 translate: (value: string) => {
300 return this.translationsObservable
301 .pipe(map(allTranslations => allTranslations[npmName]))
302 .pipe(map(translations => peertubeTranslate(value, translations)))
303 .toPromise()
304 }
305 }
306 }
307
308 private loadTranslations () {
309 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
310
311 // Default locale, nothing to translate
312 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
313
314 this.translationsObservable = this.authHttp
315 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
316 .pipe(shareReplay())
317 }
318
319 private getPluginPathPrefix (isTheme: boolean) {
320 return isTheme ? '/themes' : '/plugins'
321 }
322 }