1 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { getCompleteLocale, isDefaultLocale, peertubeTranslate, 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 { Observable, of, 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 { HttpClient } from '@angular/common/http'
15 import { AuthService, Notifier } from '@app/core'
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 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
20 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
21 import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
22 import { importModule } from '@app/shared/misc/utils'
24 interface HookStructValue extends RegisterClientHookOptions {
25 plugin: ServerConfigPlugin
26 clientScript: ClientScript
30 plugin: ServerConfigPlugin
31 clientScript: ClientScript
32 pluginType: PluginType
37 export class PluginService implements ClientHook {
38 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
39 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
41 pluginsBuilt = new ReplaySubject<boolean>(1)
43 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
44 common: new ReplaySubject<boolean>(1),
45 search: new ReplaySubject<boolean>(1),
46 'video-watch': new ReplaySubject<boolean>(1),
47 signup: new ReplaySubject<boolean>(1)
50 translationsObservable: Observable<PluginTranslation>
52 private plugins: ServerConfigPlugin[] = []
53 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
54 private loadedScripts: { [ script: string ]: boolean } = {}
55 private loadedScopes: PluginClientScope[] = []
56 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
58 private hooks: { [ name: string ]: HookStructValue[] } = {}
61 private router: Router,
62 private authService: AuthService,
63 private notifier: Notifier,
64 private server: ServerService,
66 private authHttp: HttpClient,
67 private restExtractor: RestExtractor,
68 @Inject(LOCALE_ID) private localeId: string
70 this.loadTranslations()
73 initializePlugins () {
74 this.server.getConfig()
75 .subscribe(config => {
76 this.plugins = config.plugin.registered
78 this.buildScopeStruct()
80 this.pluginsBuilt.next(true)
84 ensurePluginsAreBuilt () {
85 return this.pluginsBuilt.asObservable()
86 .pipe(first(), shareReplay())
90 ensurePluginsAreLoaded (scope: PluginClientScope) {
91 this.loadPluginsByScope(scope)
93 return this.pluginsLoaded[scope].asObservable()
94 .pipe(first(), shareReplay())
98 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
99 const pathPrefix = this.getPluginPathPrefix(isTheme)
101 for (const key of Object.keys(plugin.clientScripts)) {
102 const clientScript = plugin.clientScripts[key]
104 for (const scope of clientScript.scopes) {
105 if (!this.scopes[scope]) this.scopes[scope] = []
107 this.scopes[scope].push({
110 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
111 scopes: clientScript.scopes
113 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
117 this.loadedScripts[clientScript.script] = false
122 removePlugin (plugin: ServerConfigPlugin) {
123 for (const key of Object.keys(this.scopes)) {
124 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
128 async reloadLoadedScopes () {
129 for (const scope of this.loadedScopes) {
130 await this.loadPluginsByScope(scope, true)
134 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
135 if (this.loadingScopes[scope]) return
136 if (!isReload && this.loadedScopes.includes(scope)) return
138 this.loadingScopes[scope] = true
141 await this.ensurePluginsAreBuilt()
143 if (!isReload) this.loadedScopes.push(scope)
145 const toLoad = this.scopes[ scope ]
146 if (!Array.isArray(toLoad)) {
147 this.loadingScopes[scope] = false
148 this.pluginsLoaded[scope].next(true)
153 const promises: Promise<any>[] = []
154 for (const pluginInfo of toLoad) {
155 const clientScript = pluginInfo.clientScript
157 if (this.loadedScripts[ clientScript.script ]) continue
159 promises.push(this.loadPlugin(pluginInfo))
161 this.loadedScripts[ clientScript.script ] = true
164 await Promise.all(promises)
166 this.pluginsLoaded[scope].next(true)
167 this.loadingScopes[scope] = false
169 console.error('Cannot load plugins by scope %s.', scope, err)
173 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
174 return this.zone.runOutsideAngular(async () => {
175 if (!this.hooks[ hookName ]) return result
177 const hookType = getHookType(hookName)
179 for (const hook of this.hooks[ hookName ]) {
180 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
182 result = await internalRunHook(hook.handler, hookType, result, params, err => {
183 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
191 nameToNpmName (name: string, type: PluginType) {
192 const prefix = type === PluginType.PLUGIN
199 pluginTypeFromNpmName (npmName: string) {
200 return npmName.startsWith('peertube-plugin-')
205 private loadPlugin (pluginInfo: PluginInfo) {
206 const { plugin, clientScript } = pluginInfo
208 const registerHook = (options: RegisterClientHookOptions) => {
209 if (clientHookObject[options.target] !== true) {
210 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
214 if (!this.hooks[options.target]) this.hooks[options.target] = []
216 this.hooks[options.target].push({
219 target: options.target,
220 handler: options.handler,
221 priority: options.priority || 0
225 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
227 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
229 return this.zone.runOutsideAngular(() => {
230 return importModule(clientScript.script)
231 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
232 .then(() => this.sortHooksByPriority())
233 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
237 private buildScopeStruct () {
238 for (const plugin of this.plugins) {
239 this.addPlugin(plugin)
243 private sortHooksByPriority () {
244 for (const hookName of Object.keys(this.hooks)) {
245 this.hooks[hookName].sort((a, b) => {
246 return b.priority - a.priority
251 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
252 const { plugin } = pluginInfo
253 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
256 getBaseStaticRoute: () => {
257 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
258 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
262 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
264 return this.authHttp.get<PublicServerSetting>(path)
266 map(p => p.publicSettings),
267 catchError(res => this.restExtractor.handleError(res))
273 return this.authService.isLoggedIn()
276 notifier: this.notifier,
278 translate: (value: string) => {
279 return this.translationsObservable
280 .pipe(map(allTranslations => allTranslations[npmName]))
281 .pipe(map(translations => peertubeTranslate(value, translations)))
287 private loadTranslations () {
288 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
290 // Default locale, nothing to translate
291 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
293 this.translationsObservable = this.authHttp
294 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
298 private getPluginPathPrefix (isTheme: boolean) {
299 return isTheme ? '/themes' : '/plugins'