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