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