]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
Add ability for plugins to register client routes
[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 RegisterClientSettingsScriptOptions,
24 RegisterClientRouteOptions,
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 commonOptions: RegisterClientFormFieldOptions
34 videoFormOptions: RegisterClientVideoFieldOptions
35 }[]
36 }
37
38 @Injectable()
39 export class PluginService implements ClientHook {
40 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
41 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
42
43 translationsObservable: Observable<PluginTranslation>
44
45 customModal: CustomModalComponent
46
47 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
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 translateBy (npmName: string, toTranslate: string) {
138 const helpers = this.helpers[npmName]
139 if (!helpers) {
140 console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName)
141 return toTranslate
142 }
143
144 return helpers.translate(toTranslate)
145 }
146
147 private onFormFields (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) {
148 this.formFields.video.push({
149 commonOptions,
150 videoFormOptions
151 })
152 }
153
154 private onSettingsScripts (pluginInfo: PluginInfo, options: RegisterClientSettingsScriptOptions) {
155 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
156
157 this.settingsScripts[npmName] = options
158 }
159
160 private onClientRoute (options: RegisterClientRouteOptions) {
161 const route = options.route.startsWith('/')
162 ? options.route
163 : `/${options.route}`
164
165 this.clientRoutes[route] = options
166 }
167
168 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
169 const { plugin } = pluginInfo
170 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
171
172 return {
173 getBaseStaticRoute: () => {
174 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
175 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
176 },
177
178 getBaseRouterRoute: () => {
179 const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme)
180 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
181 },
182
183 getBasePluginClientPath: () => {
184 return '/p'
185 },
186
187 getSettings: () => {
188 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
189
190 const obs = this.authHttp.get<PublicServerSetting>(path)
191 .pipe(
192 map(p => p.publicSettings),
193 catchError(res => this.restExtractor.handleError(res))
194 )
195
196 return firstValueFrom(obs)
197 },
198
199 getServerConfig: () => {
200 const obs = this.server.getConfig()
201 .pipe(catchError(res => this.restExtractor.handleError(res)))
202
203 return firstValueFrom(obs)
204 },
205
206 isLoggedIn: () => {
207 return this.authService.isLoggedIn()
208 },
209
210 getAuthHeader: () => {
211 if (!this.authService.isLoggedIn()) return undefined
212
213 const value = this.authService.getRequestHeaderValue()
214 return { Authorization: value }
215 },
216
217 notifier: {
218 info: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.info(text, title, timeout)),
219 error: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.error(text, title, timeout)),
220 success: (text: string, title?: string, timeout?: number) => this.zone.run(() => this.notifier.success(text, title, timeout))
221 },
222
223 showModal: (input: {
224 title: string
225 content: string
226 close?: boolean
227 cancel?: { value: string, action?: () => void }
228 confirm?: { value: string, action?: () => void }
229 }) => {
230 this.zone.run(() => this.customModal.show(input))
231 },
232
233 markdownRenderer: {
234 textMarkdownToHTML: (textMarkdown: string) => {
235 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
236 },
237
238 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
239 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
240 }
241 },
242
243 translate: (value: string) => {
244 const obs = this.translationsObservable
245 .pipe(map(allTranslations => allTranslations[npmName]))
246 .pipe(map(translations => peertubeTranslate(value, translations)))
247
248 return firstValueFrom(obs)
249 }
250 }
251 }
252
253 private loadTranslations () {
254 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
255
256 // Default locale, nothing to translate
257 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
258
259 this.translationsObservable = this.authHttp
260 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
261 .pipe(shareReplay())
262 }
263 }