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'
23 RegisterClientFormFieldOptions,
24 RegisterClientRouteOptions,
25 RegisterClientSettingsScriptOptions,
26 RegisterClientVideoFieldOptions,
28 } from '@shared/models'
29 import { environment } from '../../../environments/environment'
30 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
34 pluginInfo: PluginInfo
35 commonOptions: RegisterClientFormFieldOptions
36 videoFormOptions: RegisterClientVideoFieldOptions
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'
45 translationsObservable: Observable<PluginTranslation>
47 customModal: CustomModalComponent
49 private formFields: FormFields = {
52 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScriptOptions } = {}
53 private clientRoutes: { [ route: string ]: RegisterClientRouteOptions } = {}
55 private pluginsManager: PluginsManager
58 private authService: AuthService,
59 private notifier: Notifier,
60 private markdownRenderer: MarkdownService,
61 private server: ServerService,
63 private authHttp: HttpClient,
64 private restExtractor: RestExtractor,
65 @Inject(LOCALE_ID) private localeId: string
67 this.loadTranslations()
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)
77 initializePlugins () {
78 this.pluginsManager.loadPluginsList(this.server.getHTMLConfig())
80 this.pluginsManager.ensurePluginsAreLoaded('common')
83 initializeCustomModal (customModal: CustomModalComponent) {
84 this.customModal = customModal
87 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
88 return this.zone.runOutsideAngular(() => {
89 return this.pluginsManager.runHook(hookName, result, params)
93 ensurePluginsAreLoaded (scope: PluginClientScope) {
94 return this.pluginsManager.ensurePluginsAreLoaded(scope)
97 reloadLoadedScopes () {
98 return this.pluginsManager.reloadLoadedScopes()
101 getPluginsManager () {
102 return this.pluginsManager
105 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
106 return this.pluginsManager.addPlugin(plugin, isTheme)
109 removePlugin (plugin: ServerConfigPlugin) {
110 return this.pluginsManager.removePlugin(plugin)
113 nameToNpmName (name: string, type: PluginType) {
114 const prefix = type === PluginType.PLUGIN
121 getRegisteredVideoFormFields (type: VideoEditType) {
122 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
125 getRegisteredSettingsScript (npmName: string) {
126 return this.settingsScripts[npmName]
129 getRegisteredClientRoute (route: string) {
130 return this.clientRoutes[route]
133 getAllRegisteredClientRoutes () {
134 return Object.keys(this.clientRoutes)
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])
142 if (Array.isArray(setting.options)) {
143 const newOptions = []
145 for (const o of setting.options) {
148 label: await this.translateBy(npmName, o.label)
152 setting.options = newOptions
156 translateBy (npmName: string, toTranslate: string) {
157 const obs = this.translationsObservable
159 map(allTranslations => allTranslations[npmName]),
160 map(translations => peertubeTranslate(toTranslate, translations))
163 return firstValueFrom(obs)
166 private onFormFields (
167 pluginInfo: PluginInfo,
168 commonOptions: RegisterClientFormFieldOptions,
169 videoFormOptions: RegisterClientVideoFieldOptions
171 this.formFields.video.push({
178 private onSettingsScripts (pluginInfo: PluginInfo, options: RegisterClientSettingsScriptOptions) {
179 this.settingsScripts[pluginInfo.plugin.npmName] = options
182 private onClientRoute (options: RegisterClientRouteOptions) {
183 const route = options.route.startsWith('/')
185 : `/${options.route}`
187 this.clientRoutes[route] = options
190 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
191 const { plugin } = pluginInfo
192 const npmName = pluginInfo.plugin.npmName
195 getBaseStaticRoute: () => {
196 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
197 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
200 getBaseRouterRoute: () => {
201 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
202 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
205 getBaseWebSocketRoute: () => {
206 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
207 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/ws`
210 getBasePluginClientPath: () => {
215 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
217 const obs = this.authHttp.get<PublicServerSetting>(path)
219 map(p => p.publicSettings),
220 catchError(res => this.restExtractor.handleError(res))
223 return firstValueFrom(obs)
226 getServerConfig: () => {
227 const obs = this.server.getConfig()
228 .pipe(catchError(res => this.restExtractor.handleError(res)))
230 return firstValueFrom(obs)
234 return this.authService.isLoggedIn()
237 getAuthHeader: () => {
238 if (!this.authService.isLoggedIn()) return undefined
240 const value = this.authService.getRequestHeaderValue()
241 return { Authorization: value }
245 info: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.info(text, title, timeout)),
246 error: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.error(text, title, timeout)),
247 success: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.success(text, title, timeout))
254 cancel?: { value: string, action?: () => void }
255 confirm?: { value: string, action?: () => void }
257 this.zone.run(() => this.customModal.show(input))
261 textMarkdownToHTML: (textMarkdown: string) => {
262 return this.markdownRenderer.textMarkdownToHTML({ markdown: textMarkdown })
265 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
266 return this.markdownRenderer.enhancedMarkdownToHTML({ markdown: enhancedMarkdown })
270 translate: (value: string) => {
271 return this.translateBy(npmName, value)
276 private loadTranslations () {
277 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
279 // Default locale, nothing to translate
280 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
282 this.translationsObservable = this.authHttp
283 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')