]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/hooks.service.ts
Merge branch 'master' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / hooks.service.ts
CommitLineData
f375bb3d
C
1import { from, Observable } from 'rxjs'
2import { mergeMap, switchMap } from 'rxjs/operators'
93cae479
C
3import { Injectable } from '@angular/core'
4import { PluginService } from '@app/core/plugins/plugin.service'
5import { ClientActionHookName, ClientFilterHookName } from '@shared/models/plugins/client-hook.model'
93cae479
C
6import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
7
8type RawFunction<U, T> = (params: U) => T
9type ObservableFunction<U, T> = RawFunction<U, Observable<T>>
10
11@Injectable()
12export class HooksService {
f375bb3d 13 constructor (private pluginService: PluginService) { }
93cae479 14
93cae479
C
15 wrapObsFun
16 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
0912f1b4 17 (fun: ObservableFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
93cae479
C
18 return from(this.pluginService.ensurePluginsAreLoaded(scope))
19 .pipe(
0912f1b4 20 mergeMap(() => this.wrapObjectWithoutScopeLoad(params, hookParamName)),
93cae479
C
21 switchMap(params => fun(params)),
22 mergeMap(result => this.pluginService.runHook(hookResultName, result, params))
23 )
24 }
25
c2023a9f
C
26 async wrapFun
27 <P, R, H1 extends ClientFilterHookName, H2 extends ClientFilterHookName>
0912f1b4 28 (fun: RawFunction<P, R>, params: P, scope: PluginClientScope, hookParamName: H1, hookResultName: H2) {
c2023a9f
C
29 await this.pluginService.ensurePluginsAreLoaded(scope)
30
0912f1b4 31 const newParams = await this.wrapObjectWithoutScopeLoad(params, hookParamName)
c2023a9f 32 const result = fun(newParams)
93cae479 33
c2023a9f 34 return this.pluginService.runHook(hookResultName, result, params)
93cae479
C
35 }
36
c9e3eeed
C
37 runAction<T, U extends ClientActionHookName> (hookName: U, scope: PluginClientScope, params?: T) {
38 this.pluginService.ensurePluginsAreLoaded(scope)
23bdacf8 39 .then(() => this.pluginService.runHook(hookName, undefined, params))
c9e3eeed 40 .catch((err: any) => console.error('Fatal hook error.', { err }))
93cae479 41 }
c2023a9f 42
0912f1b4
C
43 async wrapObject<T, U extends ClientFilterHookName> (result: T, scope: PluginClientScope, hookName: U) {
44 await this.pluginService.ensurePluginsAreLoaded(scope)
45
46 return this.wrapObjectWithoutScopeLoad(result, hookName)
47 }
48
49 private wrapObjectWithoutScopeLoad<T, U extends ClientFilterHookName> (result: T, hookName: U) {
c2023a9f
C
50 return this.pluginService.runHook(hookName, result)
51 }
93cae479 52}