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