]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/plugin.service.ts
Add unicode emoji to markdown
[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'
bd45d503 12import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
67ed6552
C
13import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
14import {
15 ClientHook,
16 ClientHookName,
17 clientHookObject,
18 ClientScript,
67ed6552
C
19 PluginClientScope,
20 PluginTranslation,
21 PluginType,
22 PublicServerSetting,
23 RegisterClientHookOptions,
24 ServerConfigPlugin
25} from '@shared/models'
26import { environment } from '../../../environments/environment'
27import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
28import { RegisterClientHelpers } from '../../../types/register-client-option.model'
18a6f04c 29
9ae88819 30interface HookStructValue extends RegisterClientHookOptions {
18a6f04c
C
31 plugin: ServerConfigPlugin
32 clientScript: ClientScript
33}
34
f0c5e8b6
C
35type PluginInfo = {
36 plugin: ServerConfigPlugin
37 clientScript: ClientScript
23bdacf8 38 pluginType: PluginType
f0c5e8b6
C
39 isTheme: boolean
40}
41
18a6f04c 42@Injectable()
93cae479 43export class PluginService implements ClientHook {
d75db01f
C
44 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
45 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 46
93cae479
C
47 pluginsBuilt = new ReplaySubject<boolean>(1)
48
49 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
50 common: new ReplaySubject<boolean>(1),
e8f902c0 51 search: new ReplaySubject<boolean>(1),
ba7b7e57 52 'video-watch': new ReplaySubject<boolean>(1),
f375bb3d
C
53 signup: new ReplaySubject<boolean>(1),
54 login: new ReplaySubject<boolean>(1)
93cae479 55 }
18a6f04c 56
d75db01f
C
57 translationsObservable: Observable<PluginTranslation>
58
437e8e06
K
59 customModal: CustomModalComponent
60
18a6f04c 61 private plugins: ServerConfigPlugin[] = []
f0c5e8b6 62 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
18a6f04c 63 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 64 private loadedScopes: PluginClientScope[] = []
c9e3eeed 65 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c
C
66
67 private hooks: { [ name: string ]: HookStructValue[] } = {}
68
69 constructor (
eb8f702c 70 private authService: AuthService,
74c2dece 71 private notifier: Notifier,
8c7725dc 72 private markdownRenderer: MarkdownService,
23bdacf8 73 private server: ServerService,
16d54696 74 private zone: NgZone,
23bdacf8 75 private authHttp: HttpClient,
d75db01f
C
76 private restExtractor: RestExtractor,
77 @Inject(LOCALE_ID) private localeId: string
18a6f04c 78 ) {
d75db01f 79 this.loadTranslations()
18a6f04c
C
80 }
81
82 initializePlugins () {
ba430d75
C
83 this.server.getConfig()
84 .subscribe(config => {
85 this.plugins = config.plugin.registered
18a6f04c
C
86
87 this.buildScopeStruct()
88
93cae479 89 this.pluginsBuilt.next(true)
18a6f04c
C
90 })
91 }
92
437e8e06
K
93 initializeCustomModal (customModal: CustomModalComponent) {
94 this.customModal = customModal
95 }
96
93cae479
C
97 ensurePluginsAreBuilt () {
98 return this.pluginsBuilt.asObservable()
99 .pipe(first(), shareReplay())
100 .toPromise()
101 }
102
103 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
104 this.loadPluginsByScope(scope)
105
93cae479 106 return this.pluginsLoaded[scope].asObservable()
ffb321be 107 .pipe(first(), shareReplay())
18a6f04c
C
108 .toPromise()
109 }
110
b5f919ac 111 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 112 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 113
ffb321be
C
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: {
b5f919ac 123 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 124 scopes: clientScript.scopes
f0c5e8b6 125 },
23bdacf8 126 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 127 isTheme
ffb321be
C
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) {
f0c5e8b6 143 await this.loadPluginsByScope(scope, true)
ffb321be
C
144 }
145 }
146
93cae479 147 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
148 if (this.loadingScopes[scope]) return
149 if (!isReload && this.loadedScopes.includes(scope)) return
150
151 this.loadingScopes[scope] = true
152
18a6f04c 153 try {
93cae479 154 await this.ensurePluginsAreBuilt()
18a6f04c 155
f0c5e8b6 156 if (!isReload) this.loadedScopes.push(scope)
ffb321be 157
18a6f04c 158 const toLoad = this.scopes[ scope ]
e8f902c0 159 if (!Array.isArray(toLoad)) {
c9e3eeed 160 this.loadingScopes[scope] = false
e8f902c0
C
161 this.pluginsLoaded[scope].next(true)
162
163 return
164 }
18a6f04c
C
165
166 const promises: Promise<any>[] = []
f0c5e8b6
C
167 for (const pluginInfo of toLoad) {
168 const clientScript = pluginInfo.clientScript
169
18a6f04c
C
170 if (this.loadedScripts[ clientScript.script ]) continue
171
f0c5e8b6 172 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
173
174 this.loadedScripts[ clientScript.script ] = true
175 }
176
ffb321be 177 await Promise.all(promises)
93cae479
C
178
179 this.pluginsLoaded[scope].next(true)
c9e3eeed 180 this.loadingScopes[scope] = false
18a6f04c
C
181 } catch (err) {
182 console.error('Cannot load plugins by scope %s.', scope, err)
183 }
184 }
185
16d54696
C
186 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
187 return this.zone.runOutsideAngular(async () => {
188 if (!this.hooks[ hookName ]) return result
f0c5e8b6 189
16d54696 190 const hookType = getHookType(hookName)
18a6f04c 191
16d54696
C
192 for (const hook of this.hooks[ hookName ]) {
193 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
93cae479 194
16d54696
C
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 }
18a6f04c 199
16d54696
C
200 return result
201 })
18a6f04c
C
202 }
203
23bdacf8
C
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
f0c5e8b6
C
218 private loadPlugin (pluginInfo: PluginInfo) {
219 const { plugin, clientScript } = pluginInfo
220
9ae88819 221 const registerHook = (options: RegisterClientHookOptions) => {
7663e55a
C
222 if (clientHookObject[options.target] !== true) {
223 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
224 return
225 }
226
18a6f04c
C
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
f0c5e8b6
C
238 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
239
18a6f04c
C
240 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
241
16d54696 242 return this.zone.runOutsideAngular(() => {
0c503f5c 243 return importModule(clientScript.script)
16d54696
C
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 })
18a6f04c
C
248 }
249
250 private buildScopeStruct () {
251 for (const plugin of this.plugins) {
ffb321be 252 this.addPlugin(plugin)
18a6f04c
C
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 }
f0c5e8b6 263
d75db01f 264 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 265 const { plugin } = pluginInfo
d75db01f 266 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
267
268 return {
269 getBaseStaticRoute: () => {
270 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
271 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
272 },
273
274 getSettings: () => {
d75db01f 275 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 276
ba211e73 277 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 278 .pipe(
ba211e73 279 map(p => p.publicSettings),
23bdacf8
C
280 catchError(res => this.restExtractor.handleError(res))
281 )
282 .toPromise()
d75db01f
C
283 },
284
eb8f702c
RK
285 isLoggedIn: () => {
286 return this.authService.isLoggedIn()
287 },
288
f757be65
C
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 },
74c2dece 294
437e8e06
K
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
8c7725dc
K
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
d75db01f
C
315 translate: (value: string) => {
316 return this.translationsObservable
317 .pipe(map(allTranslations => allTranslations[npmName]))
318 .pipe(map(translations => peertubeTranslate(value, translations)))
319 .toPromise()
f0c5e8b6
C
320 }
321 }
322 }
323
d75db01f
C
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
f0c5e8b6
C
335 private getPluginPathPrefix (isTheme: boolean) {
336 return isTheme ? '/themes' : '/plugins'
337 }
18a6f04c 338}