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