]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/plugin.service.ts
Use random port for mock servers in tests
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
CommitLineData
d75db01f 1import { Observable, of, ReplaySubject } from 'rxjs'
23bdacf8 2import { catchError, first, map, shareReplay } from 'rxjs/operators'
23bdacf8 3import { HttpClient } from '@angular/common/http'
67ed6552 4import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
c6c0fa6c 5import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
891bc2ff
C
6import { AuthService } from '@app/core/auth'
7import { Notifier } from '@app/core/notification'
67ed6552
C
8import { MarkdownService } from '@app/core/renderer'
9import { RestExtractor } from '@app/core/rest'
10import { ServerService } from '@app/core/server/server.service'
f9562863 11import { getDevLocale, isOnDevLocale } from '@app/helpers'
437e8e06 12import { CustomModalComponent } from '@app/modal/custom-modal.component'
7294aab0 13import { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
bd45d503 14import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
67ed6552
C
15import {
16 ClientHook,
17 ClientHookName,
67ed6552
C
18 PluginClientScope,
19 PluginTranslation,
20 PluginType,
21 PublicServerSetting,
3c47fa3b 22 RegisterClientSettingsScript,
67ed6552
C
23 ServerConfigPlugin
24} from '@shared/models'
25import { environment } from '../../../environments/environment'
67ed6552 26import { RegisterClientHelpers } from '../../../types/register-client-option.model'
18a6f04c 27
18a6f04c 28@Injectable()
93cae479 29export class PluginService implements ClientHook {
d75db01f
C
30 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
31 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 32
93cae479
C
33 pluginsBuilt = new ReplaySubject<boolean>(1)
34
35 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
36 common: new ReplaySubject<boolean>(1),
0ea9f463 37 'admin-plugin': new ReplaySubject<boolean>(1),
e8f902c0 38 search: new ReplaySubject<boolean>(1),
ba7b7e57 39 'video-watch': new ReplaySubject<boolean>(1),
f375bb3d 40 signup: new ReplaySubject<boolean>(1),
f9562863 41 login: new ReplaySubject<boolean>(1),
7294aab0 42 'video-edit': new ReplaySubject<boolean>(1),
f9562863 43 embed: new ReplaySubject<boolean>(1)
93cae479 44 }
18a6f04c 45
d75db01f
C
46 translationsObservable: Observable<PluginTranslation>
47
437e8e06
K
48 customModal: CustomModalComponent
49
18a6f04c 50 private plugins: ServerConfigPlugin[] = []
c713017f
C
51 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
52
f0c5e8b6 53 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
c713017f 54
18a6f04c 55 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 56 private loadedScopes: PluginClientScope[] = []
c9e3eeed 57 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c 58
f9562863 59 private hooks: Hooks = {}
7294aab0
C
60 private formFields: FormFields = {
61 video: []
62 }
3c47fa3b 63 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
18a6f04c
C
64
65 constructor (
eb8f702c 66 private authService: AuthService,
74c2dece 67 private notifier: Notifier,
8c7725dc 68 private markdownRenderer: MarkdownService,
23bdacf8 69 private server: ServerService,
16d54696 70 private zone: NgZone,
23bdacf8 71 private authHttp: HttpClient,
d75db01f
C
72 private restExtractor: RestExtractor,
73 @Inject(LOCALE_ID) private localeId: string
18a6f04c 74 ) {
d75db01f 75 this.loadTranslations()
18a6f04c
C
76 }
77
78 initializePlugins () {
ba430d75
C
79 this.server.getConfig()
80 .subscribe(config => {
81 this.plugins = config.plugin.registered
18a6f04c
C
82
83 this.buildScopeStruct()
84
93cae479 85 this.pluginsBuilt.next(true)
18a6f04c
C
86 })
87 }
88
437e8e06
K
89 initializeCustomModal (customModal: CustomModalComponent) {
90 this.customModal = customModal
91 }
92
93cae479
C
93 ensurePluginsAreBuilt () {
94 return this.pluginsBuilt.asObservable()
95 .pipe(first(), shareReplay())
96 .toPromise()
97 }
98
99 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
100 this.loadPluginsByScope(scope)
101
93cae479 102 return this.pluginsLoaded[scope].asObservable()
ffb321be 103 .pipe(first(), shareReplay())
18a6f04c
C
104 .toPromise()
105 }
106
b5f919ac 107 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 108 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 109
ffb321be
C
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: {
f9562863 119 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 120 scopes: clientScript.scopes
f0c5e8b6 121 },
23bdacf8 122 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 123 isTheme
ffb321be
C
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) {
f0c5e8b6 139 await this.loadPluginsByScope(scope, true)
ffb321be
C
140 }
141 }
142
93cae479 143 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
144 if (this.loadingScopes[scope]) return
145 if (!isReload && this.loadedScopes.includes(scope)) return
146
147 this.loadingScopes[scope] = true
148
18a6f04c 149 try {
93cae479 150 await this.ensurePluginsAreBuilt()
18a6f04c 151
f0c5e8b6 152 if (!isReload) this.loadedScopes.push(scope)
ffb321be 153
18a6f04c 154 const toLoad = this.scopes[ scope ]
e8f902c0 155 if (!Array.isArray(toLoad)) {
c9e3eeed 156 this.loadingScopes[scope] = false
e8f902c0
C
157 this.pluginsLoaded[scope].next(true)
158
159 return
160 }
18a6f04c
C
161
162 const promises: Promise<any>[] = []
f0c5e8b6
C
163 for (const pluginInfo of toLoad) {
164 const clientScript = pluginInfo.clientScript
165
18a6f04c
C
166 if (this.loadedScripts[ clientScript.script ]) continue
167
f0c5e8b6 168 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
169
170 this.loadedScripts[ clientScript.script ] = true
171 }
172
ffb321be 173 await Promise.all(promises)
93cae479
C
174
175 this.pluginsLoaded[scope].next(true)
c9e3eeed 176 this.loadingScopes[scope] = false
18a6f04c
C
177 } catch (err) {
178 console.error('Cannot load plugins by scope %s.', scope, err)
179 }
180 }
181
16d54696 182 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
f9562863
C
183 return this.zone.runOutsideAngular(() => {
184 return runHook(this.hooks, hookName, result, params)
16d54696 185 })
18a6f04c
C
186 }
187
23bdacf8
C
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
c6c0fa6c 202 getRegisteredVideoFormFields (type: VideoEditType) {
7294aab0
C
203 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
204 }
205
3c47fa3b
C
206 getRegisteredSettingsScript (npmName: string) {
207 return this.settingsScripts[npmName]
208 }
209
c713017f
C
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
f0c5e8b6 220 private loadPlugin (pluginInfo: PluginInfo) {
16d54696 221 return this.zone.runOutsideAngular(() => {
c713017f
C
222 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
223
224 const helpers = this.buildPeerTubeHelpers(pluginInfo)
225 this.helpers[npmName] = helpers
226
7294aab0
C
227 return loadPlugin({
228 hooks: this.hooks,
229 formFields: this.formFields,
3c47fa3b 230 onSettingsScripts: options => this.settingsScripts[npmName] = options,
7294aab0 231 pluginInfo,
c713017f 232 peertubeHelpersFactory: () => helpers
7294aab0 233 })
16d54696 234 })
18a6f04c
C
235 }
236
237 private buildScopeStruct () {
238 for (const plugin of this.plugins) {
ffb321be 239 this.addPlugin(plugin)
18a6f04c
C
240 }
241 }
242
d75db01f 243 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 244 const { plugin } = pluginInfo
d75db01f 245 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
246
247 return {
248 getBaseStaticRoute: () => {
249 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
250 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
251 },
252
253 getSettings: () => {
d75db01f 254 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 255
ba211e73 256 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 257 .pipe(
ba211e73 258 map(p => p.publicSettings),
23bdacf8
C
259 catchError(res => this.restExtractor.handleError(res))
260 )
261 .toPromise()
d75db01f
C
262 },
263
faeec106
C
264 getServerConfig: () => {
265 return this.server.getConfig()
266 .pipe(catchError(res => this.restExtractor.handleError(res)))
267 .toPromise()
268 },
269
eb8f702c
RK
270 isLoggedIn: () => {
271 return this.authService.isLoggedIn()
272 },
273
4eca42ff
C
274 getAuthHeader: () => {
275 if (!this.authService.isLoggedIn()) return undefined
276
277 const value = this.authService.getRequestHeaderValue()
278 return { 'Authorization': value }
279 },
280
f757be65
C
281 notifier: {
282 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
283 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
284 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
285 },
74c2dece 286
437e8e06
K
287 showModal: (input: {
288 title: string,
289 content: string,
290 close?: boolean,
291 cancel?: { value: string, action?: () => void },
292 confirm?: { value: string, action?: () => void }
293 }) => {
294 this.customModal.show(input)
295 },
296
8c7725dc
K
297 markdownRenderer: {
298 textMarkdownToHTML: (textMarkdown: string) => {
299 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
300 },
301
302 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
303 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
304 }
305 },
306
d75db01f
C
307 translate: (value: string) => {
308 return this.translationsObservable
309 .pipe(map(allTranslations => allTranslations[npmName]))
310 .pipe(map(translations => peertubeTranslate(value, translations)))
311 .toPromise()
f0c5e8b6
C
312 }
313 }
314 }
315
d75db01f
C
316 private loadTranslations () {
317 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
318
319 // Default locale, nothing to translate
320 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
321
322 this.translationsObservable = this.authHttp
323 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
324 .pipe(shareReplay())
325 }
326
f0c5e8b6
C
327 private getPluginPathPrefix (isTheme: boolean) {
328 return isTheme ? '/themes' : '/plugins'
329 }
18a6f04c 330}