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