]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
Add client hook/register typings
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
1 import { Injectable } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { 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 { ReplaySubject } from 'rxjs'
9 import { first, 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
15 interface HookStructValue extends RegisterClientHookOptions {
16 plugin: ServerConfigPlugin
17 clientScript: ClientScript
18 }
19
20 type PluginInfo = {
21 plugin: ServerConfigPlugin
22 clientScript: ClientScript
23 isTheme: boolean
24 }
25
26 @Injectable()
27 export class PluginService implements ClientHook {
28 pluginsBuilt = new ReplaySubject<boolean>(1)
29
30 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
31 common: new ReplaySubject<boolean>(1),
32 search: new ReplaySubject<boolean>(1),
33 'video-watch': new ReplaySubject<boolean>(1)
34 }
35
36 private plugins: ServerConfigPlugin[] = []
37 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
38 private loadedScripts: { [ script: string ]: boolean } = {}
39 private loadedScopes: PluginClientScope[] = []
40 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
41
42 private hooks: { [ name: string ]: HookStructValue[] } = {}
43
44 constructor (
45 private router: Router,
46 private server: ServerService
47 ) {
48 }
49
50 initializePlugins () {
51 this.server.configLoaded
52 .subscribe(() => {
53 this.plugins = this.server.getConfig().plugin.registered
54
55 this.buildScopeStruct()
56
57 this.pluginsBuilt.next(true)
58 })
59 }
60
61 ensurePluginsAreBuilt () {
62 return this.pluginsBuilt.asObservable()
63 .pipe(first(), shareReplay())
64 .toPromise()
65 }
66
67 ensurePluginsAreLoaded (scope: PluginClientScope) {
68 this.loadPluginsByScope(scope)
69
70 return this.pluginsLoaded[scope].asObservable()
71 .pipe(first(), shareReplay())
72 .toPromise()
73 }
74
75 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
76 const pathPrefix = this.getPluginPathPrefix(isTheme)
77
78 for (const key of Object.keys(plugin.clientScripts)) {
79 const clientScript = plugin.clientScripts[key]
80
81 for (const scope of clientScript.scopes) {
82 if (!this.scopes[scope]) this.scopes[scope] = []
83
84 this.scopes[scope].push({
85 plugin,
86 clientScript: {
87 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
88 scopes: clientScript.scopes
89 },
90 isTheme
91 })
92
93 this.loadedScripts[clientScript.script] = false
94 }
95 }
96 }
97
98 removePlugin (plugin: ServerConfigPlugin) {
99 for (const key of Object.keys(this.scopes)) {
100 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
101 }
102 }
103
104 async reloadLoadedScopes () {
105 for (const scope of this.loadedScopes) {
106 await this.loadPluginsByScope(scope, true)
107 }
108 }
109
110 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
111 if (this.loadingScopes[scope]) return
112 if (!isReload && this.loadedScopes.includes(scope)) return
113
114 this.loadingScopes[scope] = true
115
116 try {
117 await this.ensurePluginsAreBuilt()
118
119 if (!isReload) this.loadedScopes.push(scope)
120
121 const toLoad = this.scopes[ scope ]
122 if (!Array.isArray(toLoad)) {
123 this.loadingScopes[scope] = false
124 this.pluginsLoaded[scope].next(true)
125
126 return
127 }
128
129 const promises: Promise<any>[] = []
130 for (const pluginInfo of toLoad) {
131 const clientScript = pluginInfo.clientScript
132
133 if (this.loadedScripts[ clientScript.script ]) continue
134
135 promises.push(this.loadPlugin(pluginInfo))
136
137 this.loadedScripts[ clientScript.script ] = true
138 }
139
140 await Promise.all(promises)
141
142 this.pluginsLoaded[scope].next(true)
143 this.loadingScopes[scope] = false
144 } catch (err) {
145 console.error('Cannot load plugins by scope %s.', scope, err)
146 }
147 }
148
149 async runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
150 if (!this.hooks[hookName]) return Promise.resolve(result)
151
152 const hookType = getHookType(hookName)
153
154 for (const hook of this.hooks[hookName]) {
155 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
156
157 result = await internalRunHook(hook.handler, hookType, result, params, err => {
158 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
159 })
160 }
161
162 return result
163 }
164
165 private loadPlugin (pluginInfo: PluginInfo) {
166 const { plugin, clientScript } = pluginInfo
167
168 const registerHook = (options: RegisterClientHookOptions) => {
169 if (clientHookObject[options.target] !== true) {
170 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
171 return
172 }
173
174 if (!this.hooks[options.target]) this.hooks[options.target] = []
175
176 this.hooks[options.target].push({
177 plugin,
178 clientScript,
179 target: options.target,
180 handler: options.handler,
181 priority: options.priority || 0
182 })
183 }
184
185 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
186
187 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
188
189 return import(/* webpackIgnore: true */ clientScript.script)
190 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
191 .then(() => this.sortHooksByPriority())
192 }
193
194 private buildScopeStruct () {
195 for (const plugin of this.plugins) {
196 this.addPlugin(plugin)
197 }
198 }
199
200 private sortHooksByPriority () {
201 for (const hookName of Object.keys(this.hooks)) {
202 this.hooks[hookName].sort((a, b) => {
203 return b.priority - a.priority
204 })
205 }
206 }
207
208 private buildPeerTubeHelpers (pluginInfo: PluginInfo) {
209 const { plugin } = pluginInfo
210
211 return {
212 getBaseStaticRoute: () => {
213 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
214 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
215 }
216 }
217 }
218
219 private getPluginPathPrefix (isTheme: boolean) {
220 return isTheme ? '/themes' : '/plugins'
221 }
222 }