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