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'
21 import { importModule } from '@app/shared/misc/utils'
23 interface HookStructValue extends RegisterClientHookOptions {
24 plugin: ServerConfigPlugin
25 clientScript: ClientScript
29 plugin: ServerConfigPlugin
30 clientScript: ClientScript
31 pluginType: PluginType
36 export class PluginService implements ClientHook {
37 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
38 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
40 pluginsBuilt = new ReplaySubject<boolean>(1)
42 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
43 common: new ReplaySubject<boolean>(1),
44 search: new ReplaySubject<boolean>(1),
45 'video-watch': new ReplaySubject<boolean>(1),
46 signup: new ReplaySubject<boolean>(1)
49 translationsObservable: Observable<PluginTranslation>
51 private plugins: ServerConfigPlugin[] = []
52 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
53 private loadedScripts: { [ script: string ]: boolean } = {}
54 private loadedScopes: PluginClientScope[] = []
55 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
57 private hooks: { [ name: string ]: HookStructValue[] } = {}
60 private router: Router,
61 private server: ServerService,
63 private authHttp: HttpClient,
64 private restExtractor: RestExtractor,
65 @Inject(LOCALE_ID) private localeId: string
67 this.loadTranslations()
70 initializePlugins () {
71 this.server.configLoaded
73 this.plugins = this.server.getConfig().plugin.registered
75 this.buildScopeStruct()
77 this.pluginsBuilt.next(true)
81 ensurePluginsAreBuilt () {
82 return this.pluginsBuilt.asObservable()
83 .pipe(first(), shareReplay())
87 ensurePluginsAreLoaded (scope: PluginClientScope) {
88 this.loadPluginsByScope(scope)
90 return this.pluginsLoaded[scope].asObservable()
91 .pipe(first(), shareReplay())
95 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
96 const pathPrefix = this.getPluginPathPrefix(isTheme)
98 for (const key of Object.keys(plugin.clientScripts)) {
99 const clientScript = plugin.clientScripts[key]
101 for (const scope of clientScript.scopes) {
102 if (!this.scopes[scope]) this.scopes[scope] = []
104 this.scopes[scope].push({
107 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
108 scopes: clientScript.scopes
110 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
114 this.loadedScripts[clientScript.script] = false
119 removePlugin (plugin: ServerConfigPlugin) {
120 for (const key of Object.keys(this.scopes)) {
121 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
125 async reloadLoadedScopes () {
126 for (const scope of this.loadedScopes) {
127 await this.loadPluginsByScope(scope, true)
131 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
132 if (this.loadingScopes[scope]) return
133 if (!isReload && this.loadedScopes.includes(scope)) return
135 this.loadingScopes[scope] = true
138 await this.ensurePluginsAreBuilt()
140 if (!isReload) this.loadedScopes.push(scope)
142 const toLoad = this.scopes[ scope ]
143 if (!Array.isArray(toLoad)) {
144 this.loadingScopes[scope] = false
145 this.pluginsLoaded[scope].next(true)
150 const promises: Promise<any>[] = []
151 for (const pluginInfo of toLoad) {
152 const clientScript = pluginInfo.clientScript
154 if (this.loadedScripts[ clientScript.script ]) continue
156 promises.push(this.loadPlugin(pluginInfo))
158 this.loadedScripts[ clientScript.script ] = true
161 await Promise.all(promises)
163 this.pluginsLoaded[scope].next(true)
164 this.loadingScopes[scope] = false
166 console.error('Cannot load plugins by scope %s.', scope, err)
170 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
171 return this.zone.runOutsideAngular(async () => {
172 if (!this.hooks[ hookName ]) return result
174 const hookType = getHookType(hookName)
176 for (const hook of this.hooks[ hookName ]) {
177 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
179 result = await internalRunHook(hook.handler, hookType, result, params, err => {
180 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
188 nameToNpmName (name: string, type: PluginType) {
189 const prefix = type === PluginType.PLUGIN
196 pluginTypeFromNpmName (npmName: string) {
197 return npmName.startsWith('peertube-plugin-')
202 private loadPlugin (pluginInfo: PluginInfo) {
203 const { plugin, clientScript } = pluginInfo
205 const registerHook = (options: RegisterClientHookOptions) => {
206 if (clientHookObject[options.target] !== true) {
207 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
211 if (!this.hooks[options.target]) this.hooks[options.target] = []
213 this.hooks[options.target].push({
216 target: options.target,
217 handler: options.handler,
218 priority: options.priority || 0
222 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
224 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
226 return this.zone.runOutsideAngular(() => {
227 return importModule(clientScript.script)
228 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
229 .then(() => this.sortHooksByPriority())
230 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
234 private buildScopeStruct () {
235 for (const plugin of this.plugins) {
236 this.addPlugin(plugin)
240 private sortHooksByPriority () {
241 for (const hookName of Object.keys(this.hooks)) {
242 this.hooks[hookName].sort((a, b) => {
243 return b.priority - a.priority
248 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
249 const { plugin } = pluginInfo
250 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
253 getBaseStaticRoute: () => {
254 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
255 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
259 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
261 return this.authHttp.get<PublicServerSetting>(path)
263 map(p => p.publicSettings),
264 catchError(res => this.restExtractor.handleError(res))
269 translate: (value: string) => {
270 return this.translationsObservable
271 .pipe(map(allTranslations => allTranslations[npmName]))
272 .pipe(map(translations => peertubeTranslate(value, translations)))
278 private loadTranslations () {
279 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
281 // Default locale, nothing to translate
282 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
284 this.translationsObservable = this.authHttp
285 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
289 private getPluginPathPrefix (isTheme: boolean) {
290 return isTheme ? '/themes' : '/plugins'