]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/plugin.service.ts
Speed up plugins loading
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
CommitLineData
fc21ef5c 1import * as debug from 'debug'
d75db01f 2import { Observable, of, ReplaySubject } from 'rxjs'
23bdacf8 3import { catchError, first, map, shareReplay } from 'rxjs/operators'
23bdacf8 4import { HttpClient } from '@angular/common/http'
67ed6552 5import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
c6c0fa6c 6import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
891bc2ff
C
7import { AuthService } from '@app/core/auth'
8import { Notifier } from '@app/core/notification'
67ed6552
C
9import { MarkdownService } from '@app/core/renderer'
10import { RestExtractor } from '@app/core/rest'
11import { ServerService } from '@app/core/server/server.service'
f9562863 12import { getDevLocale, isOnDevLocale } from '@app/helpers'
437e8e06 13import { CustomModalComponent } from '@app/modal/custom-modal.component'
7294aab0 14import { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
bd45d503 15import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
67ed6552
C
16import {
17 ClientHook,
18 ClientHookName,
67ed6552
C
19 PluginClientScope,
20 PluginTranslation,
21 PluginType,
22 PublicServerSetting,
3c47fa3b 23 RegisterClientSettingsScript,
67ed6552
C
24 ServerConfigPlugin
25} from '@shared/models'
26import { environment } from '../../../environments/environment'
67ed6552 27import { RegisterClientHelpers } from '../../../types/register-client-option.model'
584ac47a
C
28
29const logger = debug('peertube:plugins')
18a6f04c 30
18a6f04c 31@Injectable()
93cae479 32export class PluginService implements ClientHook {
d75db01f
C
33 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
34 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 35
93cae479
C
36 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
37 common: new ReplaySubject<boolean>(1),
0ea9f463 38 'admin-plugin': new ReplaySubject<boolean>(1),
e8f902c0 39 search: new ReplaySubject<boolean>(1),
ba7b7e57 40 'video-watch': new ReplaySubject<boolean>(1),
f375bb3d 41 signup: new ReplaySubject<boolean>(1),
f9562863 42 login: new ReplaySubject<boolean>(1),
7294aab0 43 'video-edit': new ReplaySubject<boolean>(1),
f9562863 44 embed: new ReplaySubject<boolean>(1)
93cae479 45 }
18a6f04c 46
d75db01f
C
47 translationsObservable: Observable<PluginTranslation>
48
437e8e06
K
49 customModal: CustomModalComponent
50
18a6f04c 51 private plugins: ServerConfigPlugin[] = []
c713017f
C
52 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
53
f0c5e8b6 54 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
c713017f 55
18a6f04c 56 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 57 private loadedScopes: PluginClientScope[] = []
c9e3eeed 58 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c 59
f9562863 60 private hooks: Hooks = {}
7294aab0
C
61 private formFields: FormFields = {
62 video: []
63 }
3c47fa3b 64 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
18a6f04c
C
65
66 constructor (
eb8f702c 67 private authService: AuthService,
74c2dece 68 private notifier: Notifier,
8c7725dc 69 private markdownRenderer: MarkdownService,
23bdacf8 70 private server: ServerService,
16d54696 71 private zone: NgZone,
23bdacf8 72 private authHttp: HttpClient,
d75db01f
C
73 private restExtractor: RestExtractor,
74 @Inject(LOCALE_ID) private localeId: string
18a6f04c 75 ) {
d75db01f 76 this.loadTranslations()
18a6f04c
C
77 }
78
79 initializePlugins () {
fc21ef5c
C
80 const config = this.server.getHTMLConfig()
81 this.plugins = config.plugin.registered
18a6f04c 82
fc21ef5c 83 this.buildScopeStruct()
584ac47a 84
fc21ef5c 85 this.ensurePluginsAreLoaded('common')
18a6f04c
C
86 }
87
437e8e06
K
88 initializeCustomModal (customModal: CustomModalComponent) {
89 this.customModal = customModal
90 }
91
93cae479 92 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
93 this.loadPluginsByScope(scope)
94
93cae479 95 return this.pluginsLoaded[scope].asObservable()
ffb321be 96 .pipe(first(), shareReplay())
18a6f04c
C
97 .toPromise()
98 }
99
b5f919ac 100 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 101 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 102
ffb321be
C
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: {
f9562863 112 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 113 scopes: clientScript.scopes
f0c5e8b6 114 },
23bdacf8 115 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 116 isTheme
ffb321be
C
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) {
f0c5e8b6 132 await this.loadPluginsByScope(scope, true)
ffb321be
C
133 }
134 }
135
93cae479 136 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
137 if (this.loadingScopes[scope]) return
138 if (!isReload && this.loadedScopes.includes(scope)) return
139
140 this.loadingScopes[scope] = true
141
584ac47a
C
142 logger('Loading scope %s', scope)
143
18a6f04c 144 try {
f0c5e8b6 145 if (!isReload) this.loadedScopes.push(scope)
ffb321be 146
18a6f04c 147 const toLoad = this.scopes[ scope ]
e8f902c0 148 if (!Array.isArray(toLoad)) {
c9e3eeed 149 this.loadingScopes[scope] = false
e8f902c0
C
150 this.pluginsLoaded[scope].next(true)
151
584ac47a 152 logger('Nothing to load for scope %s', scope)
e8f902c0
C
153 return
154 }
18a6f04c
C
155
156 const promises: Promise<any>[] = []
f0c5e8b6
C
157 for (const pluginInfo of toLoad) {
158 const clientScript = pluginInfo.clientScript
159
18a6f04c
C
160 if (this.loadedScripts[ clientScript.script ]) continue
161
f0c5e8b6 162 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
163
164 this.loadedScripts[ clientScript.script ] = true
165 }
166
ffb321be 167 await Promise.all(promises)
93cae479
C
168
169 this.pluginsLoaded[scope].next(true)
c9e3eeed 170 this.loadingScopes[scope] = false
584ac47a
C
171
172 logger('Scope %s loaded', scope)
18a6f04c
C
173 } catch (err) {
174 console.error('Cannot load plugins by scope %s.', scope, err)
175 }
176 }
177
16d54696 178 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
f9562863
C
179 return this.zone.runOutsideAngular(() => {
180 return runHook(this.hooks, hookName, result, params)
16d54696 181 })
18a6f04c
C
182 }
183
23bdacf8
C
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
c6c0fa6c 198 getRegisteredVideoFormFields (type: VideoEditType) {
7294aab0
C
199 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
200 }
201
3c47fa3b
C
202 getRegisteredSettingsScript (npmName: string) {
203 return this.settingsScripts[npmName]
204 }
205
c713017f
C
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
f0c5e8b6 216 private loadPlugin (pluginInfo: PluginInfo) {
16d54696 217 return this.zone.runOutsideAngular(() => {
c713017f
C
218 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
219
220 const helpers = this.buildPeerTubeHelpers(pluginInfo)
221 this.helpers[npmName] = helpers
222
7294aab0
C
223 return loadPlugin({
224 hooks: this.hooks,
225 formFields: this.formFields,
3c47fa3b 226 onSettingsScripts: options => this.settingsScripts[npmName] = options,
7294aab0 227 pluginInfo,
c713017f 228 peertubeHelpersFactory: () => helpers
7294aab0 229 })
16d54696 230 })
18a6f04c
C
231 }
232
233 private buildScopeStruct () {
234 for (const plugin of this.plugins) {
ffb321be 235 this.addPlugin(plugin)
18a6f04c
C
236 }
237 }
238
d75db01f 239 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 240 const { plugin } = pluginInfo
d75db01f 241 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
242
243 return {
244 getBaseStaticRoute: () => {
245 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
246 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
247 },
248
9777fe9e
JL
249 getBaseRouterRoute: () => {
250 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
251 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
252 },
253
23bdacf8 254 getSettings: () => {
d75db01f 255 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 256
ba211e73 257 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 258 .pipe(
ba211e73 259 map(p => p.publicSettings),
23bdacf8
C
260 catchError(res => this.restExtractor.handleError(res))
261 )
262 .toPromise()
d75db01f
C
263 },
264
faeec106
C
265 getServerConfig: () => {
266 return this.server.getConfig()
267 .pipe(catchError(res => this.restExtractor.handleError(res)))
268 .toPromise()
269 },
270
eb8f702c
RK
271 isLoggedIn: () => {
272 return this.authService.isLoggedIn()
273 },
274
4eca42ff
C
275 getAuthHeader: () => {
276 if (!this.authService.isLoggedIn()) return undefined
277
278 const value = this.authService.getRequestHeaderValue()
279 return { 'Authorization': value }
280 },
281
f757be65
C
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 },
74c2dece 287
437e8e06
K
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
8c7725dc
K
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
d75db01f
C
308 translate: (value: string) => {
309 return this.translationsObservable
310 .pipe(map(allTranslations => allTranslations[npmName]))
311 .pipe(map(translations => peertubeTranslate(value, translations)))
312 .toPromise()
f0c5e8b6
C
313 }
314 }
315 }
316
d75db01f
C
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
f0c5e8b6
C
328 private getPluginPathPrefix (isTheme: boolean) {
329 return isTheme ? '/themes' : '/plugins'
330 }
18a6f04c 331}