]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
ee80d4d39bc8d5314b472ad27dd045e720141225
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
1 import { Observable, of, ReplaySubject } from 'rxjs'
2 import { catchError, first, 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 { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
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 RegisterClientSettingsScript,
23 ServerConfigPlugin
24 } from '@shared/models'
25 import { environment } from '../../../environments/environment'
26 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
27
28 @Injectable()
29 export class PluginService implements ClientHook {
30 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
31 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
32
33 pluginsBuilt = new ReplaySubject<boolean>(1)
34
35 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
36 common: new ReplaySubject<boolean>(1),
37 'admin-plugin': new ReplaySubject<boolean>(1),
38 search: new ReplaySubject<boolean>(1),
39 'video-watch': new ReplaySubject<boolean>(1),
40 signup: new ReplaySubject<boolean>(1),
41 login: new ReplaySubject<boolean>(1),
42 'video-edit': new ReplaySubject<boolean>(1),
43 embed: new ReplaySubject<boolean>(1)
44 }
45
46 translationsObservable: Observable<PluginTranslation>
47
48 customModal: CustomModalComponent
49
50 private plugins: ServerConfigPlugin[] = []
51 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
52
53 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
54
55 private loadedScripts: { [ script: string ]: boolean } = {}
56 private loadedScopes: PluginClientScope[] = []
57 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
58
59 private hooks: Hooks = {}
60 private formFields: FormFields = {
61 video: []
62 }
63 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
64
65 constructor (
66 private authService: AuthService,
67 private notifier: Notifier,
68 private markdownRenderer: MarkdownService,
69 private server: ServerService,
70 private zone: NgZone,
71 private authHttp: HttpClient,
72 private restExtractor: RestExtractor,
73 @Inject(LOCALE_ID) private localeId: string
74 ) {
75 this.loadTranslations()
76 }
77
78 initializePlugins () {
79 this.server.getConfig()
80 .subscribe(config => {
81 this.plugins = config.plugin.registered
82
83 this.buildScopeStruct()
84
85 this.pluginsBuilt.next(true)
86 })
87 }
88
89 initializeCustomModal (customModal: CustomModalComponent) {
90 this.customModal = customModal
91 }
92
93 ensurePluginsAreBuilt () {
94 return this.pluginsBuilt.asObservable()
95 .pipe(first(), shareReplay())
96 .toPromise()
97 }
98
99 ensurePluginsAreLoaded (scope: PluginClientScope) {
100 this.loadPluginsByScope(scope)
101
102 return this.pluginsLoaded[scope].asObservable()
103 .pipe(first(), shareReplay())
104 .toPromise()
105 }
106
107 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
108 const pathPrefix = this.getPluginPathPrefix(isTheme)
109
110 for (const key of Object.keys(plugin.clientScripts)) {
111 const clientScript = plugin.clientScripts[key]
112
113 for (const scope of clientScript.scopes) {
114 if (!this.scopes[scope]) this.scopes[scope] = []
115
116 this.scopes[scope].push({
117 plugin,
118 clientScript: {
119 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
120 scopes: clientScript.scopes
121 },
122 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
123 isTheme
124 })
125
126 this.loadedScripts[clientScript.script] = false
127 }
128 }
129 }
130
131 removePlugin (plugin: ServerConfigPlugin) {
132 for (const key of Object.keys(this.scopes)) {
133 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
134 }
135 }
136
137 async reloadLoadedScopes () {
138 for (const scope of this.loadedScopes) {
139 await this.loadPluginsByScope(scope, true)
140 }
141 }
142
143 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
144 if (this.loadingScopes[scope]) return
145 if (!isReload && this.loadedScopes.includes(scope)) return
146
147 this.loadingScopes[scope] = true
148
149 try {
150 await this.ensurePluginsAreBuilt()
151
152 if (!isReload) this.loadedScopes.push(scope)
153
154 const toLoad = this.scopes[ scope ]
155 if (!Array.isArray(toLoad)) {
156 this.loadingScopes[scope] = false
157 this.pluginsLoaded[scope].next(true)
158
159 return
160 }
161
162 const promises: Promise<any>[] = []
163 for (const pluginInfo of toLoad) {
164 const clientScript = pluginInfo.clientScript
165
166 if (this.loadedScripts[ clientScript.script ]) continue
167
168 promises.push(this.loadPlugin(pluginInfo))
169
170 this.loadedScripts[ clientScript.script ] = true
171 }
172
173 await Promise.all(promises)
174
175 this.pluginsLoaded[scope].next(true)
176 this.loadingScopes[scope] = false
177 } catch (err) {
178 console.error('Cannot load plugins by scope %s.', scope, err)
179 }
180 }
181
182 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
183 return this.zone.runOutsideAngular(() => {
184 return runHook(this.hooks, hookName, result, params)
185 })
186 }
187
188 nameToNpmName (name: string, type: PluginType) {
189 const prefix = type === PluginType.PLUGIN
190 ? 'peertube-plugin-'
191 : 'peertube-theme-'
192
193 return prefix + name
194 }
195
196 pluginTypeFromNpmName (npmName: string) {
197 return npmName.startsWith('peertube-plugin-')
198 ? PluginType.PLUGIN
199 : PluginType.THEME
200 }
201
202 getRegisteredVideoFormFields (type: VideoEditType) {
203 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
204 }
205
206 getRegisteredSettingsScript (npmName: string) {
207 return this.settingsScripts[npmName]
208 }
209
210 translateBy (npmName: string, toTranslate: string) {
211 const helpers = this.helpers[npmName]
212 if (!helpers) {
213 console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName)
214 return toTranslate
215 }
216
217 return helpers.translate(toTranslate)
218 }
219
220 private loadPlugin (pluginInfo: PluginInfo) {
221 return this.zone.runOutsideAngular(() => {
222 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
223
224 const helpers = this.buildPeerTubeHelpers(pluginInfo)
225 this.helpers[npmName] = helpers
226
227 return loadPlugin({
228 hooks: this.hooks,
229 formFields: this.formFields,
230 onSettingsScripts: options => this.settingsScripts[npmName] = options,
231 pluginInfo,
232 peertubeHelpersFactory: () => helpers
233 })
234 })
235 }
236
237 private buildScopeStruct () {
238 for (const plugin of this.plugins) {
239 this.addPlugin(plugin)
240 }
241 }
242
243 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
244 const { plugin } = pluginInfo
245 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
246
247 return {
248 getBaseStaticRoute: () => {
249 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
250 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
251 },
252
253 getSettings: () => {
254 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
255
256 return this.authHttp.get<PublicServerSetting>(path)
257 .pipe(
258 map(p => p.publicSettings),
259 catchError(res => this.restExtractor.handleError(res))
260 )
261 .toPromise()
262 },
263
264 getServerConfig: () => {
265 return this.server.getConfig()
266 .pipe(catchError(res => this.restExtractor.handleError(res)))
267 .toPromise()
268 },
269
270 isLoggedIn: () => {
271 return this.authService.isLoggedIn()
272 },
273
274 notifier: {
275 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
276 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
277 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
278 },
279
280 showModal: (input: {
281 title: string,
282 content: string,
283 close?: boolean,
284 cancel?: { value: string, action?: () => void },
285 confirm?: { value: string, action?: () => void }
286 }) => {
287 this.customModal.show(input)
288 },
289
290 markdownRenderer: {
291 textMarkdownToHTML: (textMarkdown: string) => {
292 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
293 },
294
295 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
296 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
297 }
298 },
299
300 translate: (value: string) => {
301 return this.translationsObservable
302 .pipe(map(allTranslations => allTranslations[npmName]))
303 .pipe(map(translations => peertubeTranslate(value, translations)))
304 .toPromise()
305 }
306 }
307 }
308
309 private loadTranslations () {
310 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
311
312 // Default locale, nothing to translate
313 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
314
315 this.translationsObservable = this.authHttp
316 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
317 .pipe(shareReplay())
318 }
319
320 private getPluginPathPrefix (isTheme: boolean) {
321 return isTheme ? '/themes' : '/plugins'
322 }
323 }