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 { RestExtractor } from '@app/shared/rest'
16 import { PluginType } from '@shared/models/plugins/plugin.type'
17 import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
18 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
19 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
20 import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
22 interface HookStructValue extends RegisterClientHookOptions {
23 plugin: ServerConfigPlugin
24 clientScript: ClientScript
28 plugin: ServerConfigPlugin
29 clientScript: ClientScript
30 pluginType: PluginType
35 export class PluginService implements ClientHook {
36 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
37 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
39 pluginsBuilt = new ReplaySubject<boolean>(1)
41 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
42 common: new ReplaySubject<boolean>(1),
43 search: new ReplaySubject<boolean>(1),
44 'video-watch': new ReplaySubject<boolean>(1)
47 translationsObservable: Observable<PluginTranslation>
49 private plugins: ServerConfigPlugin[] = []
50 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
51 private loadedScripts: { [ script: string ]: boolean } = {}
52 private loadedScopes: PluginClientScope[] = []
53 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
55 private hooks: { [ name: string ]: HookStructValue[] } = {}
58 private router: Router,
59 private server: ServerService,
61 private authHttp: HttpClient,
62 private restExtractor: RestExtractor,
63 @Inject(LOCALE_ID) private localeId: string
65 this.loadTranslations()
68 initializePlugins () {
69 this.server.configLoaded
71 this.plugins = this.server.getConfig().plugin.registered
73 this.buildScopeStruct()
75 this.pluginsBuilt.next(true)
79 ensurePluginsAreBuilt () {
80 return this.pluginsBuilt.asObservable()
81 .pipe(first(), shareReplay())
85 ensurePluginsAreLoaded (scope: PluginClientScope) {
86 this.loadPluginsByScope(scope)
88 return this.pluginsLoaded[scope].asObservable()
89 .pipe(first(), shareReplay())
93 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
94 const pathPrefix = this.getPluginPathPrefix(isTheme)
96 for (const key of Object.keys(plugin.clientScripts)) {
97 const clientScript = plugin.clientScripts[key]
99 for (const scope of clientScript.scopes) {
100 if (!this.scopes[scope]) this.scopes[scope] = []
102 this.scopes[scope].push({
105 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
106 scopes: clientScript.scopes
108 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
112 this.loadedScripts[clientScript.script] = false
117 removePlugin (plugin: ServerConfigPlugin) {
118 for (const key of Object.keys(this.scopes)) {
119 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
123 async reloadLoadedScopes () {
124 for (const scope of this.loadedScopes) {
125 await this.loadPluginsByScope(scope, true)
129 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
130 if (this.loadingScopes[scope]) return
131 if (!isReload && this.loadedScopes.includes(scope)) return
133 this.loadingScopes[scope] = true
136 await this.ensurePluginsAreBuilt()
138 if (!isReload) this.loadedScopes.push(scope)
140 const toLoad = this.scopes[ scope ]
141 if (!Array.isArray(toLoad)) {
142 this.loadingScopes[scope] = false
143 this.pluginsLoaded[scope].next(true)
148 const promises: Promise<any>[] = []
149 for (const pluginInfo of toLoad) {
150 const clientScript = pluginInfo.clientScript
152 if (this.loadedScripts[ clientScript.script ]) continue
154 promises.push(this.loadPlugin(pluginInfo))
156 this.loadedScripts[ clientScript.script ] = true
159 await Promise.all(promises)
161 this.pluginsLoaded[scope].next(true)
162 this.loadingScopes[scope] = false
164 console.error('Cannot load plugins by scope %s.', scope, err)
168 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
169 return this.zone.runOutsideAngular(async () => {
170 if (!this.hooks[ hookName ]) return result
172 const hookType = getHookType(hookName)
174 for (const hook of this.hooks[ hookName ]) {
175 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
177 result = await internalRunHook(hook.handler, hookType, result, params, err => {
178 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
186 nameToNpmName (name: string, type: PluginType) {
187 const prefix = type === PluginType.PLUGIN
194 pluginTypeFromNpmName (npmName: string) {
195 return npmName.startsWith('peertube-plugin-')
200 private loadPlugin (pluginInfo: PluginInfo) {
201 const { plugin, clientScript } = pluginInfo
203 const registerHook = (options: RegisterClientHookOptions) => {
204 if (clientHookObject[options.target] !== true) {
205 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
209 if (!this.hooks[options.target]) this.hooks[options.target] = []
211 this.hooks[options.target].push({
214 target: options.target,
215 handler: options.handler,
216 priority: options.priority || 0
220 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
222 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
224 return this.zone.runOutsideAngular(() => {
225 return import(/* webpackIgnore: true */ clientScript.script)
226 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
227 .then(() => this.sortHooksByPriority())
228 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
232 private buildScopeStruct () {
233 for (const plugin of this.plugins) {
234 this.addPlugin(plugin)
238 private sortHooksByPriority () {
239 for (const hookName of Object.keys(this.hooks)) {
240 this.hooks[hookName].sort((a, b) => {
241 return b.priority - a.priority
246 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
247 const { plugin } = pluginInfo
248 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
251 getBaseStaticRoute: () => {
252 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
253 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
257 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
259 return this.authHttp.get<PublicServerSetting>(path)
261 map(p => p.publicSettings),
262 catchError(res => this.restExtractor.handleError(res))
267 translate: (value: string) => {
268 return this.translationsObservable
269 .pipe(map(allTranslations => allTranslations[npmName]))
270 .pipe(map(translations => peertubeTranslate(value, translations)))
276 private loadTranslations () {
277 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
279 // Default locale, nothing to translate
280 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
282 this.translationsObservable = this.authHttp
283 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
287 private getPluginPathPrefix (isTheme: boolean) {
288 return isTheme ? '/themes' : '/plugins'