]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/plugin.service.ts
Merge branch 'signup-hooks' into 'develop'
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
CommitLineData
d75db01f 1import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
18a6f04c 2import { Router } from '@angular/router'
d75db01f 3import { getCompleteLocale, isDefaultLocale, peertubeTranslate, ServerConfigPlugin } from '@shared/models'
18a6f04c
C
4import { ServerService } from '@app/core/server/server.service'
5import { ClientScript } from '@shared/models/plugins/plugin-package-json.model'
bfa1a32b 6import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
18a6f04c 7import { environment } from '../../../environments/environment'
d75db01f 8import { Observable, of, ReplaySubject } from 'rxjs'
23bdacf8 9import { catchError, first, map, shareReplay } from 'rxjs/operators'
93cae479 10import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
7663e55a 11import { ClientHook, ClientHookName, clientHookObject } from '@shared/models/plugins/client-hook.model'
93cae479 12import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
9ae88819 13import { RegisterClientHookOptions } from '@shared/models/plugins/register-client-hook.model'
23bdacf8
C
14import { HttpClient } from '@angular/common/http'
15import { RestExtractor } from '@app/shared/rest'
16import { PluginType } from '@shared/models/plugins/plugin.type'
ba211e73 17import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
d75db01f
C
18import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
19import { RegisterClientHelpers } from '../../../types/register-client-option.model'
20import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
0c503f5c 21import { importModule } from '@app/shared/misc/utils'
18a6f04c 22
9ae88819 23interface HookStructValue extends RegisterClientHookOptions {
18a6f04c
C
24 plugin: ServerConfigPlugin
25 clientScript: ClientScript
26}
27
f0c5e8b6
C
28type PluginInfo = {
29 plugin: ServerConfigPlugin
30 clientScript: ClientScript
23bdacf8 31 pluginType: PluginType
f0c5e8b6
C
32 isTheme: boolean
33}
34
18a6f04c 35@Injectable()
93cae479 36export class PluginService implements ClientHook {
d75db01f
C
37 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
38 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 39
93cae479
C
40 pluginsBuilt = new ReplaySubject<boolean>(1)
41
42 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
43 common: new ReplaySubject<boolean>(1),
e8f902c0 44 search: new ReplaySubject<boolean>(1),
ba7b7e57
RK
45 'video-watch': new ReplaySubject<boolean>(1),
46 signup: new ReplaySubject<boolean>(1)
93cae479 47 }
18a6f04c 48
d75db01f
C
49 translationsObservable: Observable<PluginTranslation>
50
18a6f04c 51 private plugins: ServerConfigPlugin[] = []
f0c5e8b6 52 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
18a6f04c 53 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 54 private loadedScopes: PluginClientScope[] = []
c9e3eeed 55 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c
C
56
57 private hooks: { [ name: string ]: HookStructValue[] } = {}
58
59 constructor (
60 private router: Router,
23bdacf8 61 private server: ServerService,
16d54696 62 private zone: NgZone,
23bdacf8 63 private authHttp: HttpClient,
d75db01f
C
64 private restExtractor: RestExtractor,
65 @Inject(LOCALE_ID) private localeId: string
18a6f04c 66 ) {
d75db01f 67 this.loadTranslations()
18a6f04c
C
68 }
69
70 initializePlugins () {
71 this.server.configLoaded
72 .subscribe(() => {
7cd4d2ba 73 this.plugins = this.server.getConfig().plugin.registered
18a6f04c
C
74
75 this.buildScopeStruct()
76
93cae479 77 this.pluginsBuilt.next(true)
18a6f04c
C
78 })
79 }
80
93cae479
C
81 ensurePluginsAreBuilt () {
82 return this.pluginsBuilt.asObservable()
83 .pipe(first(), shareReplay())
84 .toPromise()
85 }
86
87 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
88 this.loadPluginsByScope(scope)
89
93cae479 90 return this.pluginsLoaded[scope].asObservable()
ffb321be 91 .pipe(first(), shareReplay())
18a6f04c
C
92 .toPromise()
93 }
94
b5f919ac 95 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 96 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 97
ffb321be
C
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: {
b5f919ac 107 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 108 scopes: clientScript.scopes
f0c5e8b6 109 },
23bdacf8 110 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 111 isTheme
ffb321be
C
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) {
f0c5e8b6 127 await this.loadPluginsByScope(scope, true)
ffb321be
C
128 }
129 }
130
93cae479 131 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
132 if (this.loadingScopes[scope]) return
133 if (!isReload && this.loadedScopes.includes(scope)) return
134
135 this.loadingScopes[scope] = true
136
18a6f04c 137 try {
93cae479 138 await this.ensurePluginsAreBuilt()
18a6f04c 139
f0c5e8b6 140 if (!isReload) this.loadedScopes.push(scope)
ffb321be 141
18a6f04c 142 const toLoad = this.scopes[ scope ]
e8f902c0 143 if (!Array.isArray(toLoad)) {
c9e3eeed 144 this.loadingScopes[scope] = false
e8f902c0
C
145 this.pluginsLoaded[scope].next(true)
146
147 return
148 }
18a6f04c
C
149
150 const promises: Promise<any>[] = []
f0c5e8b6
C
151 for (const pluginInfo of toLoad) {
152 const clientScript = pluginInfo.clientScript
153
18a6f04c
C
154 if (this.loadedScripts[ clientScript.script ]) continue
155
f0c5e8b6 156 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
157
158 this.loadedScripts[ clientScript.script ] = true
159 }
160
ffb321be 161 await Promise.all(promises)
93cae479
C
162
163 this.pluginsLoaded[scope].next(true)
c9e3eeed 164 this.loadingScopes[scope] = false
18a6f04c
C
165 } catch (err) {
166 console.error('Cannot load plugins by scope %s.', scope, err)
167 }
168 }
169
16d54696
C
170 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
171 return this.zone.runOutsideAngular(async () => {
172 if (!this.hooks[ hookName ]) return result
f0c5e8b6 173
16d54696 174 const hookType = getHookType(hookName)
18a6f04c 175
16d54696
C
176 for (const hook of this.hooks[ hookName ]) {
177 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
93cae479 178
16d54696
C
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 }
18a6f04c 183
16d54696
C
184 return result
185 })
18a6f04c
C
186 }
187
23bdacf8
C
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
f0c5e8b6
C
202 private loadPlugin (pluginInfo: PluginInfo) {
203 const { plugin, clientScript } = pluginInfo
204
9ae88819 205 const registerHook = (options: RegisterClientHookOptions) => {
7663e55a
C
206 if (clientHookObject[options.target] !== true) {
207 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
208 return
209 }
210
18a6f04c
C
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
f0c5e8b6
C
222 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
223
18a6f04c
C
224 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
225
16d54696 226 return this.zone.runOutsideAngular(() => {
0c503f5c 227 return importModule(clientScript.script)
16d54696
C
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 })
18a6f04c
C
232 }
233
234 private buildScopeStruct () {
235 for (const plugin of this.plugins) {
ffb321be 236 this.addPlugin(plugin)
18a6f04c
C
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 }
f0c5e8b6 247
d75db01f 248 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 249 const { plugin } = pluginInfo
d75db01f 250 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
251
252 return {
253 getBaseStaticRoute: () => {
254 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
255 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
256 },
257
258 getSettings: () => {
d75db01f 259 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 260
ba211e73 261 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 262 .pipe(
ba211e73 263 map(p => p.publicSettings),
23bdacf8
C
264 catchError(res => this.restExtractor.handleError(res))
265 )
266 .toPromise()
d75db01f
C
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()
f0c5e8b6
C
274 }
275 }
276 }
277
d75db01f
C
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
f0c5e8b6
C
289 private getPluginPathPrefix (isTheme: boolean) {
290 return isTheme ? '/themes' : '/plugins'
291 }
18a6f04c 292}