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