]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
Translate plugin settings
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
1 import { firstValueFrom, Observable, of } from 'rxjs'
2 import { catchError, map, shareReplay } from 'rxjs/operators'
3 import { HttpClient } from '@angular/common/http'
4 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
5 import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
6 import { AuthService } from '@app/core/auth'
7 import { Notifier } from '@app/core/notification'
8 import { MarkdownService } from '@app/core/renderer'
9 import { RestExtractor } from '@app/core/rest'
10 import { ServerService } from '@app/core/server/server.service'
11 import { getDevLocale, isOnDevLocale } from '@app/helpers'
12 import { CustomModalComponent } from '@app/modal/custom-modal.component'
13 import { PluginInfo, PluginsManager } from '@root-helpers/plugins-manager'
14 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
15 import {
16 ClientHook,
17 ClientHookName,
18 PluginClientScope,
19 PluginTranslation,
20 PluginType,
21 PublicServerSetting,
22 RegisterClientFormFieldOptions,
23 RegisterClientRouteOptions,
24 RegisterClientSettingsScriptOptions,
25 RegisterClientVideoFieldOptions,
26 ServerConfigPlugin
27 } from '@shared/models'
28 import { environment } from '../../../environments/environment'
29 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
30
31 type FormFields = {
32 video: {
33 pluginInfo: PluginInfo
34 commonOptions: RegisterClientFormFieldOptions
35 videoFormOptions: RegisterClientVideoFieldOptions
36 }[]
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 translationsObservable: Observable<PluginTranslation>
45
46 customModal: CustomModalComponent
47
48 private formFields: FormFields = {
49 video: []
50 }
51 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScriptOptions } = {}
52 private clientRoutes: { [ route: string ]: RegisterClientRouteOptions } = {}
53
54 private pluginsManager: PluginsManager
55
56 constructor (
57 private authService: AuthService,
58 private notifier: Notifier,
59 private markdownRenderer: MarkdownService,
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 this.pluginsManager = new PluginsManager({
69 peertubeHelpersFactory: this.buildPeerTubeHelpers.bind(this),
70 onFormFields: this.onFormFields.bind(this),
71 onSettingsScripts: this.onSettingsScripts.bind(this),
72 onClientRoute: this.onClientRoute.bind(this)
73 })
74 }
75
76 initializePlugins () {
77 this.pluginsManager.loadPluginsList(this.server.getHTMLConfig())
78
79 this.pluginsManager.ensurePluginsAreLoaded('common')
80 }
81
82 initializeCustomModal (customModal: CustomModalComponent) {
83 this.customModal = customModal
84 }
85
86 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
87 return this.zone.runOutsideAngular(() => {
88 return this.pluginsManager.runHook(hookName, result, params)
89 })
90 }
91
92 ensurePluginsAreLoaded (scope: PluginClientScope) {
93 return this.pluginsManager.ensurePluginsAreLoaded(scope)
94 }
95
96 reloadLoadedScopes () {
97 return this.pluginsManager.reloadLoadedScopes()
98 }
99
100 getPluginsManager () {
101 return this.pluginsManager
102 }
103
104 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
105 return this.pluginsManager.addPlugin(plugin, isTheme)
106 }
107
108 removePlugin (plugin: ServerConfigPlugin) {
109 return this.pluginsManager.removePlugin(plugin)
110 }
111
112 nameToNpmName (name: string, type: PluginType) {
113 const prefix = type === PluginType.PLUGIN
114 ? 'peertube-plugin-'
115 : 'peertube-theme-'
116
117 return prefix + name
118 }
119
120 getRegisteredVideoFormFields (type: VideoEditType) {
121 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
122 }
123
124 getRegisteredSettingsScript (npmName: string) {
125 return this.settingsScripts[npmName]
126 }
127
128 getRegisteredClientRoute (route: string) {
129 return this.clientRoutes[route]
130 }
131
132 getAllRegisteredClientRoutes () {
133 return Object.keys(this.clientRoutes)
134 }
135
136 async translateSetting (npmName: string, setting: RegisterClientFormFieldOptions) {
137 for (const key of [ 'label', 'html', 'descriptionHTML' ]) {
138 if (setting[key]) setting[key] = await this.translateBy(npmName, setting[key])
139 }
140
141 if (Array.isArray(setting.options)) {
142 const newOptions = []
143
144 for (const o of setting.options) {
145 newOptions.push({
146 value: o.value,
147 label: await this.translateBy(npmName, o.label)
148 })
149 }
150
151 setting.options = newOptions
152 }
153 }
154
155 translateBy (npmName: string, toTranslate: string) {
156 const obs = this.translationsObservable
157 .pipe(
158 map(allTranslations => allTranslations[npmName]),
159 map(translations => peertubeTranslate(toTranslate, translations))
160 )
161
162 return firstValueFrom(obs)
163 }
164
165 private onFormFields (
166 pluginInfo: PluginInfo,
167 commonOptions: RegisterClientFormFieldOptions,
168 videoFormOptions: RegisterClientVideoFieldOptions
169 ) {
170 this.formFields.video.push({
171 pluginInfo,
172 commonOptions,
173 videoFormOptions
174 })
175 }
176
177 private onSettingsScripts (pluginInfo: PluginInfo, options: RegisterClientSettingsScriptOptions) {
178 this.settingsScripts[pluginInfo.plugin.npmName] = options
179 }
180
181 private onClientRoute (options: RegisterClientRouteOptions) {
182 const route = options.route.startsWith('/')
183 ? options.route
184 : `/${options.route}`
185
186 this.clientRoutes[route] = options
187 }
188
189 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
190 const { plugin } = pluginInfo
191 const npmName = pluginInfo.plugin.npmName
192
193 return {
194 getBaseStaticRoute: () => {
195 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
196 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
197 },
198
199 getBaseRouterRoute: () => {
200 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
201 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
202 },
203
204 getBasePluginClientPath: () => {
205 return '/p'
206 },
207
208 getSettings: () => {
209 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
210
211 const obs = this.authHttp.get<PublicServerSetting>(path)
212 .pipe(
213 map(p => p.publicSettings),
214 catchError(res => this.restExtractor.handleError(res))
215 )
216
217 return firstValueFrom(obs)
218 },
219
220 getServerConfig: () => {
221 const obs = this.server.getConfig()
222 .pipe(catchError(res => this.restExtractor.handleError(res)))
223
224 return firstValueFrom(obs)
225 },
226
227 isLoggedIn: () => {
228 return this.authService.isLoggedIn()
229 },
230
231 getAuthHeader: () => {
232 if (!this.authService.isLoggedIn()) return undefined
233
234 const value = this.authService.getRequestHeaderValue()
235 return { Authorization: value }
236 },
237
238 notifier: {
239 info: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.info(text, title, timeout)),
240 error: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.error(text, title, timeout)),
241 success: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.success(text, title, timeout))
242 },
243
244 showModal: (input: {
245 title: string
246 content: string
247 close?: boolean
248 cancel?: { value: string, action?: () => void }
249 confirm?: { value: string, action?: () => void }
250 }) => {
251 this.zone.run(() => this.customModal.show(input))
252 },
253
254 markdownRenderer: {
255 textMarkdownToHTML: (textMarkdown: string) => {
256 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
257 },
258
259 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
260 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
261 }
262 },
263
264 translate: (value: string) => {
265 return this.translateBy(npmName, value)
266 }
267 }
268 }
269
270 private loadTranslations () {
271 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
272
273 // Default locale, nothing to translate
274 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
275
276 this.translationsObservable = this.authHttp
277 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
278 .pipe(shareReplay())
279 }
280 }