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