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