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