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