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