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