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