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