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