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