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