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