]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/plugins/plugin.service.ts
Add commentor name alongside fid for video comments
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
CommitLineData
d75db01f 1import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
18a6f04c 2import { Router } from '@angular/router'
d75db01f 3import { getCompleteLocale, isDefaultLocale, peertubeTranslate, ServerConfigPlugin } from '@shared/models'
18a6f04c
C
4import { ServerService } from '@app/core/server/server.service'
5import { ClientScript } from '@shared/models/plugins/plugin-package-json.model'
bfa1a32b 6import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
18a6f04c 7import { environment } from '../../../environments/environment'
d75db01f 8import { Observable, of, ReplaySubject } from 'rxjs'
23bdacf8 9import { catchError, first, map, shareReplay } from 'rxjs/operators'
93cae479 10import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
7663e55a 11import { ClientHook, ClientHookName, clientHookObject } from '@shared/models/plugins/client-hook.model'
93cae479 12import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
9ae88819 13import { RegisterClientHookOptions } from '@shared/models/plugins/register-client-hook.model'
23bdacf8 14import { HttpClient } from '@angular/common/http'
64ff48cb 15import { AuthService } from '@app/core/auth'
23bdacf8
C
16import { RestExtractor } from '@app/shared/rest'
17import { PluginType } from '@shared/models/plugins/plugin.type'
ba211e73 18import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
d75db01f
C
19import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
20import { RegisterClientHelpers } from '../../../types/register-client-option.model'
21import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
0c503f5c 22import { importModule } from '@app/shared/misc/utils'
18a6f04c 23
9ae88819 24interface HookStructValue extends RegisterClientHookOptions {
18a6f04c
C
25 plugin: ServerConfigPlugin
26 clientScript: ClientScript
27}
28
f0c5e8b6
C
29type PluginInfo = {
30 plugin: ServerConfigPlugin
31 clientScript: ClientScript
23bdacf8 32 pluginType: PluginType
f0c5e8b6
C
33 isTheme: boolean
34}
35
18a6f04c 36@Injectable()
93cae479 37export class PluginService implements ClientHook {
d75db01f
C
38 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
39 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
23bdacf8 40
93cae479
C
41 pluginsBuilt = new ReplaySubject<boolean>(1)
42
43 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
44 common: new ReplaySubject<boolean>(1),
e8f902c0 45 search: new ReplaySubject<boolean>(1),
ba7b7e57
RK
46 'video-watch': new ReplaySubject<boolean>(1),
47 signup: new ReplaySubject<boolean>(1)
93cae479 48 }
18a6f04c 49
d75db01f
C
50 translationsObservable: Observable<PluginTranslation>
51
18a6f04c 52 private plugins: ServerConfigPlugin[] = []
f0c5e8b6 53 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
18a6f04c 54 private loadedScripts: { [ script: string ]: boolean } = {}
93cae479 55 private loadedScopes: PluginClientScope[] = []
c9e3eeed 56 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
18a6f04c
C
57
58 private hooks: { [ name: string ]: HookStructValue[] } = {}
59
60 constructor (
61 private router: Router,
eb8f702c 62 private authService: AuthService,
23bdacf8 63 private server: ServerService,
16d54696 64 private zone: NgZone,
23bdacf8 65 private authHttp: HttpClient,
d75db01f
C
66 private restExtractor: RestExtractor,
67 @Inject(LOCALE_ID) private localeId: string
18a6f04c 68 ) {
d75db01f 69 this.loadTranslations()
18a6f04c
C
70 }
71
72 initializePlugins () {
73 this.server.configLoaded
74 .subscribe(() => {
7cd4d2ba 75 this.plugins = this.server.getConfig().plugin.registered
18a6f04c
C
76
77 this.buildScopeStruct()
78
93cae479 79 this.pluginsBuilt.next(true)
18a6f04c
C
80 })
81 }
82
93cae479
C
83 ensurePluginsAreBuilt () {
84 return this.pluginsBuilt.asObservable()
85 .pipe(first(), shareReplay())
86 .toPromise()
87 }
88
89 ensurePluginsAreLoaded (scope: PluginClientScope) {
c9e3eeed
C
90 this.loadPluginsByScope(scope)
91
93cae479 92 return this.pluginsLoaded[scope].asObservable()
ffb321be 93 .pipe(first(), shareReplay())
18a6f04c
C
94 .toPromise()
95 }
96
b5f919ac 97 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
f0c5e8b6 98 const pathPrefix = this.getPluginPathPrefix(isTheme)
b5f919ac 99
ffb321be
C
100 for (const key of Object.keys(plugin.clientScripts)) {
101 const clientScript = plugin.clientScripts[key]
102
103 for (const scope of clientScript.scopes) {
104 if (!this.scopes[scope]) this.scopes[scope] = []
105
106 this.scopes[scope].push({
107 plugin,
108 clientScript: {
b5f919ac 109 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
ffb321be 110 scopes: clientScript.scopes
f0c5e8b6 111 },
23bdacf8 112 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
f0c5e8b6 113 isTheme
ffb321be
C
114 })
115
116 this.loadedScripts[clientScript.script] = false
117 }
118 }
119 }
120
121 removePlugin (plugin: ServerConfigPlugin) {
122 for (const key of Object.keys(this.scopes)) {
123 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
124 }
125 }
126
127 async reloadLoadedScopes () {
128 for (const scope of this.loadedScopes) {
f0c5e8b6 129 await this.loadPluginsByScope(scope, true)
ffb321be
C
130 }
131 }
132
93cae479 133 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
c9e3eeed
C
134 if (this.loadingScopes[scope]) return
135 if (!isReload && this.loadedScopes.includes(scope)) return
136
137 this.loadingScopes[scope] = true
138
18a6f04c 139 try {
93cae479 140 await this.ensurePluginsAreBuilt()
18a6f04c 141
f0c5e8b6 142 if (!isReload) this.loadedScopes.push(scope)
ffb321be 143
18a6f04c 144 const toLoad = this.scopes[ scope ]
e8f902c0 145 if (!Array.isArray(toLoad)) {
c9e3eeed 146 this.loadingScopes[scope] = false
e8f902c0
C
147 this.pluginsLoaded[scope].next(true)
148
149 return
150 }
18a6f04c
C
151
152 const promises: Promise<any>[] = []
f0c5e8b6
C
153 for (const pluginInfo of toLoad) {
154 const clientScript = pluginInfo.clientScript
155
18a6f04c
C
156 if (this.loadedScripts[ clientScript.script ]) continue
157
f0c5e8b6 158 promises.push(this.loadPlugin(pluginInfo))
18a6f04c
C
159
160 this.loadedScripts[ clientScript.script ] = true
161 }
162
ffb321be 163 await Promise.all(promises)
93cae479
C
164
165 this.pluginsLoaded[scope].next(true)
c9e3eeed 166 this.loadingScopes[scope] = false
18a6f04c
C
167 } catch (err) {
168 console.error('Cannot load plugins by scope %s.', scope, err)
169 }
170 }
171
16d54696
C
172 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
173 return this.zone.runOutsideAngular(async () => {
174 if (!this.hooks[ hookName ]) return result
f0c5e8b6 175
16d54696 176 const hookType = getHookType(hookName)
18a6f04c 177
16d54696
C
178 for (const hook of this.hooks[ hookName ]) {
179 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
93cae479 180
16d54696
C
181 result = await internalRunHook(hook.handler, hookType, result, params, err => {
182 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
183 })
184 }
18a6f04c 185
16d54696
C
186 return result
187 })
18a6f04c
C
188 }
189
23bdacf8
C
190 nameToNpmName (name: string, type: PluginType) {
191 const prefix = type === PluginType.PLUGIN
192 ? 'peertube-plugin-'
193 : 'peertube-theme-'
194
195 return prefix + name
196 }
197
198 pluginTypeFromNpmName (npmName: string) {
199 return npmName.startsWith('peertube-plugin-')
200 ? PluginType.PLUGIN
201 : PluginType.THEME
202 }
203
f0c5e8b6
C
204 private loadPlugin (pluginInfo: PluginInfo) {
205 const { plugin, clientScript } = pluginInfo
206
9ae88819 207 const registerHook = (options: RegisterClientHookOptions) => {
7663e55a
C
208 if (clientHookObject[options.target] !== true) {
209 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
210 return
211 }
212
18a6f04c
C
213 if (!this.hooks[options.target]) this.hooks[options.target] = []
214
215 this.hooks[options.target].push({
216 plugin,
217 clientScript,
218 target: options.target,
219 handler: options.handler,
220 priority: options.priority || 0
221 })
222 }
223
f0c5e8b6
C
224 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
225
18a6f04c
C
226 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
227
16d54696 228 return this.zone.runOutsideAngular(() => {
0c503f5c 229 return importModule(clientScript.script)
16d54696
C
230 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
231 .then(() => this.sortHooksByPriority())
232 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
233 })
18a6f04c
C
234 }
235
236 private buildScopeStruct () {
237 for (const plugin of this.plugins) {
ffb321be 238 this.addPlugin(plugin)
18a6f04c
C
239 }
240 }
241
242 private sortHooksByPriority () {
243 for (const hookName of Object.keys(this.hooks)) {
244 this.hooks[hookName].sort((a, b) => {
245 return b.priority - a.priority
246 })
247 }
248 }
f0c5e8b6 249
d75db01f 250 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
f0c5e8b6 251 const { plugin } = pluginInfo
d75db01f 252 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
f0c5e8b6
C
253
254 return {
255 getBaseStaticRoute: () => {
256 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
257 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
23bdacf8
C
258 },
259
260 getSettings: () => {
d75db01f 261 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
23bdacf8 262
ba211e73 263 return this.authHttp.get<PublicServerSetting>(path)
23bdacf8 264 .pipe(
ba211e73 265 map(p => p.publicSettings),
23bdacf8
C
266 catchError(res => this.restExtractor.handleError(res))
267 )
268 .toPromise()
d75db01f
C
269 },
270
eb8f702c
RK
271 isLoggedIn: () => {
272 return this.authService.isLoggedIn()
273 },
274
d75db01f
C
275 translate: (value: string) => {
276 return this.translationsObservable
277 .pipe(map(allTranslations => allTranslations[npmName]))
278 .pipe(map(translations => peertubeTranslate(value, translations)))
279 .toPromise()
f0c5e8b6
C
280 }
281 }
282 }
283
d75db01f
C
284 private loadTranslations () {
285 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
286
287 // Default locale, nothing to translate
288 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
289
290 this.translationsObservable = this.authHttp
291 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
292 .pipe(shareReplay())
293 }
294
f0c5e8b6
C
295 private getPluginPathPrefix (isTheme: boolean) {
296 return isTheme ? '/themes' : '/plugins'
297 }
18a6f04c 298}