]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
CommitLineData
d75db01f 1import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
18a6f04c 2import { Router } from '@angular/router'
d75db01f 3import { getCompleteLocale, isDefaultLocale, peertubeTranslate, ServerConfigPlugin } from '@shared/models'
18a6f04c
C
4import { ServerService } from '@app/core/server/server.service'
5import { ClientScript } from '@shared/models/plugins/plugin-package-json.model'
bfa1a32b 6import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
18a6f04c 7import { environment } from '../../../environments/environment'
d75db01f 8import { Observable, of, ReplaySubject } from 'rxjs'
23bdacf8 9import { catchError, first, map, shareReplay } from 'rxjs/operators'
93cae479 10import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
7663e55a 11import { ClientHook, ClientHookName, clientHookObject } from '@shared/models/plugins/client-hook.model'
93cae479 12import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
9ae88819 13import { RegisterClientHookOptions } from '@shared/models/plugins/register-client-hook.model'
23bdacf8 14import { HttpClient } from '@angular/common/http'
891bc2ff
C
15import { AuthService } from '@app/core/auth'
16import { Notifier } from '@app/core/notification'
23bdacf8 17import { RestExtractor } from '@app/shared/rest'
8c7725dc 18import { MarkdownService } from '@app/shared/renderer'
23bdacf8 19import { PluginType } from '@shared/models/plugins/plugin.type'
ba211e73 20import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
d75db01f
C
21import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
22import { RegisterClientHelpers } from '../../../types/register-client-option.model'
23import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
0c503f5c 24import { importModule } from '@app/shared/misc/utils'
437e8e06 25import { CustomModalComponent } from '@app/modal/custom-modal.component'
18a6f04c 26
9ae88819 27interface HookStructValue extends RegisterClientHookOptions {
18a6f04c
C
28 plugin: ServerConfigPlugin
29 clientScript: ClientScript
30}
31
f0c5e8b6
C
32type PluginInfo = {
33 plugin: ServerConfigPlugin
34 clientScript: ClientScript
23bdacf8 35 pluginType: PluginType
f0c5e8b6
C
36 isTheme: boolean
37}
38
18a6f04c 39@Injectable()
93cae479 40export class PluginService implements ClientHook {
d75db01f
C
41 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
42 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 43
93cae479
C
44 pluginsBuilt = new ReplaySubject<boolean>(1)
45
46 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
47 common: new ReplaySubject<boolean>(1),
e8f902c0 48 search: new ReplaySubject<boolean>(1),
ba7b7e57
RK
49 'video-watch': new ReplaySubject<boolean>(1),
50 signup: new ReplaySubject<boolean>(1)
93cae479 51 }
18a6f04c 52
d75db01f
C
53 translationsObservable: Observable<PluginTranslation>
54
437e8e06
K
55 customModal: CustomModalComponent
56
18a6f04c 57 private plugins: ServerConfigPlugin[] = []
f0c5e8b6 58 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
18a6f04c 59 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 60 private loadedScopes: PluginClientScope[] = []
c9e3eeed 61 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c
C
62
63 private hooks: { [ name: string ]: HookStructValue[] } = {}
64
65 constructor (
66 private router: Router,
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 () {
ba430d75
C
80 this.server.getConfig()
81 .subscribe(config => {
82 this.plugins = config.plugin.registered
18a6f04c
C
83
84 this.buildScopeStruct()
85
93cae479 86 this.pluginsBuilt.next(true)
18a6f04c
C
87 })
88 }
89
437e8e06
K
90 initializeCustomModal (customModal: CustomModalComponent) {
91 this.customModal = customModal
92 }
93
93cae479
C
94 ensurePluginsAreBuilt () {
95 return this.pluginsBuilt.asObservable()
96 .pipe(first(), shareReplay())
97 .toPromise()
98 }
99
100 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
101 this.loadPluginsByScope(scope)
102
93cae479 103 return this.pluginsLoaded[scope].asObservable()
ffb321be 104 .pipe(first(), shareReplay())
18a6f04c
C
105 .toPromise()
106 }
107
b5f919ac 108 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 109 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 110
ffb321be
C
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: {
b5f919ac 120 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 121 scopes: clientScript.scopes
f0c5e8b6 122 },
23bdacf8 123 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 124 isTheme
ffb321be
C
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) {
f0c5e8b6 140 await this.loadPluginsByScope(scope, true)
ffb321be
C
141 }
142 }
143
93cae479 144 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
145 if (this.loadingScopes[scope]) return
146 if (!isReload && this.loadedScopes.includes(scope)) return
147
148 this.loadingScopes[scope] = true
149
18a6f04c 150 try {
93cae479 151 await this.ensurePluginsAreBuilt()
18a6f04c 152
f0c5e8b6 153 if (!isReload) this.loadedScopes.push(scope)
ffb321be 154
18a6f04c 155 const toLoad = this.scopes[ scope ]
e8f902c0 156 if (!Array.isArray(toLoad)) {
c9e3eeed 157 this.loadingScopes[scope] = false
e8f902c0
C
158 this.pluginsLoaded[scope].next(true)
159
160 return
161 }
18a6f04c
C
162
163 const promises: Promise<any>[] = []
f0c5e8b6
C
164 for (const pluginInfo of toLoad) {
165 const clientScript = pluginInfo.clientScript
166
18a6f04c
C
167 if (this.loadedScripts[ clientScript.script ]) continue
168
f0c5e8b6 169 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
170
171 this.loadedScripts[ clientScript.script ] = true
172 }
173
ffb321be 174 await Promise.all(promises)
93cae479
C
175
176 this.pluginsLoaded[scope].next(true)
c9e3eeed 177 this.loadingScopes[scope] = false
18a6f04c
C
178 } catch (err) {
179 console.error('Cannot load plugins by scope %s.', scope, err)
180 }
181 }
182
16d54696
C
183 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
184 return this.zone.runOutsideAngular(async () => {
185 if (!this.hooks[ hookName ]) return result
f0c5e8b6 186
16d54696 187 const hookType = getHookType(hookName)
18a6f04c 188
16d54696
C
189 for (const hook of this.hooks[ hookName ]) {
190 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
93cae479 191
16d54696
C
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 }
18a6f04c 196
16d54696
C
197 return result
198 })
18a6f04c
C
199 }
200
23bdacf8
C
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
f0c5e8b6
C
215 private loadPlugin (pluginInfo: PluginInfo) {
216 const { plugin, clientScript } = pluginInfo
217
9ae88819 218 const registerHook = (options: RegisterClientHookOptions) => {
7663e55a
C
219 if (clientHookObject[options.target] !== true) {
220 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
221 return
222 }
223
18a6f04c
C
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
f0c5e8b6
C
235 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
236
18a6f04c
C
237 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
238
16d54696 239 return this.zone.runOutsideAngular(() => {
0c503f5c 240 return importModule(clientScript.script)
16d54696
C
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 })
18a6f04c
C
245 }
246
247 private buildScopeStruct () {
248 for (const plugin of this.plugins) {
ffb321be 249 this.addPlugin(plugin)
18a6f04c
C
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 }
f0c5e8b6 260
d75db01f 261 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 262 const { plugin } = pluginInfo
d75db01f 263 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
264
265 return {
266 getBaseStaticRoute: () => {
267 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
268 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
269 },
270
271 getSettings: () => {
d75db01f 272 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 273
ba211e73 274 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 275 .pipe(
ba211e73 276 map(p => p.publicSettings),
23bdacf8
C
277 catchError(res => this.restExtractor.handleError(res))
278 )
279 .toPromise()
d75db01f
C
280 },
281
eb8f702c
RK
282 isLoggedIn: () => {
283 return this.authService.isLoggedIn()
284 },
285
f757be65
C
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 },
74c2dece 291
437e8e06
K
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
8c7725dc
K
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
d75db01f
C
312 translate: (value: string) => {
313 return this.translationsObservable
314 .pipe(map(allTranslations => allTranslations[npmName]))
315 .pipe(map(translations => peertubeTranslate(value, translations)))
316 .toPromise()
f0c5e8b6
C
317 }
318 }
319 }
320
d75db01f
C
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
f0c5e8b6
C
332 private getPluginPathPrefix (isTheme: boolean) {
333 return isTheme ? '/themes' : '/plugins'
334 }
18a6f04c 335}