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