1 import { Observable, of, ReplaySubject } from 'rxjs'
2 import { catchError, first, map, shareReplay } from 'rxjs/operators'
3 import { HttpClient } from '@angular/common/http'
4 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
5 import { AuthService } from '@app/core/auth'
6 import { Notifier } from '@app/core/notification'
7 import { MarkdownService } from '@app/core/renderer'
8 import { RestExtractor } from '@app/core/rest'
9 import { ServerService } from '@app/core/server/server.service'
10 import { getDevLocale, importModule, isOnDevLocale } from '@app/helpers'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
13 import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
23 RegisterClientHookOptions,
25 } from '@shared/models'
26 import { environment } from '../../../environments/environment'
27 import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
28 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
30 interface HookStructValue extends RegisterClientHookOptions {
31 plugin: ServerConfigPlugin
32 clientScript: ClientScript
36 plugin: ServerConfigPlugin
37 clientScript: ClientScript
38 pluginType: PluginType
43 export class PluginService implements ClientHook {
44 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
45 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
47 pluginsBuilt = new ReplaySubject<boolean>(1)
49 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
50 common: new ReplaySubject<boolean>(1),
51 search: new ReplaySubject<boolean>(1),
52 'video-watch': new ReplaySubject<boolean>(1),
53 signup: new ReplaySubject<boolean>(1),
54 login: new ReplaySubject<boolean>(1)
57 translationsObservable: Observable<PluginTranslation>
59 customModal: CustomModalComponent
61 private plugins: ServerConfigPlugin[] = []
62 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
63 private loadedScripts: { [ script: string ]: boolean } = {}
64 private loadedScopes: PluginClientScope[] = []
65 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
67 private hooks: { [ name: string ]: HookStructValue[] } = {}
70 private authService: AuthService,
71 private notifier: Notifier,
72 private markdownRenderer: MarkdownService,
73 private server: ServerService,
75 private authHttp: HttpClient,
76 private restExtractor: RestExtractor,
77 @Inject(LOCALE_ID) private localeId: string
79 this.loadTranslations()
82 initializePlugins () {
83 this.server.getConfig()
84 .subscribe(config => {
85 this.plugins = config.plugin.registered
87 this.buildScopeStruct()
89 this.pluginsBuilt.next(true)
93 initializeCustomModal (customModal: CustomModalComponent) {
94 this.customModal = customModal
97 ensurePluginsAreBuilt () {
98 return this.pluginsBuilt.asObservable()
99 .pipe(first(), shareReplay())
103 ensurePluginsAreLoaded (scope: PluginClientScope) {
104 this.loadPluginsByScope(scope)
106 return this.pluginsLoaded[scope].asObservable()
107 .pipe(first(), shareReplay())
111 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
112 const pathPrefix = this.getPluginPathPrefix(isTheme)
114 for (const key of Object.keys(plugin.clientScripts)) {
115 const clientScript = plugin.clientScripts[key]
117 for (const scope of clientScript.scopes) {
118 if (!this.scopes[scope]) this.scopes[scope] = []
120 this.scopes[scope].push({
123 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
124 scopes: clientScript.scopes
126 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
130 this.loadedScripts[clientScript.script] = false
135 removePlugin (plugin: ServerConfigPlugin) {
136 for (const key of Object.keys(this.scopes)) {
137 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
141 async reloadLoadedScopes () {
142 for (const scope of this.loadedScopes) {
143 await this.loadPluginsByScope(scope, true)
147 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
148 if (this.loadingScopes[scope]) return
149 if (!isReload && this.loadedScopes.includes(scope)) return
151 this.loadingScopes[scope] = true
154 await this.ensurePluginsAreBuilt()
156 if (!isReload) this.loadedScopes.push(scope)
158 const toLoad = this.scopes[ scope ]
159 if (!Array.isArray(toLoad)) {
160 this.loadingScopes[scope] = false
161 this.pluginsLoaded[scope].next(true)
166 const promises: Promise<any>[] = []
167 for (const pluginInfo of toLoad) {
168 const clientScript = pluginInfo.clientScript
170 if (this.loadedScripts[ clientScript.script ]) continue
172 promises.push(this.loadPlugin(pluginInfo))
174 this.loadedScripts[ clientScript.script ] = true
177 await Promise.all(promises)
179 this.pluginsLoaded[scope].next(true)
180 this.loadingScopes[scope] = false
182 console.error('Cannot load plugins by scope %s.', scope, err)
186 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
187 return this.zone.runOutsideAngular(async () => {
188 if (!this.hooks[ hookName ]) return result
190 const hookType = getHookType(hookName)
192 for (const hook of this.hooks[ hookName ]) {
193 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
195 result = await internalRunHook(hook.handler, hookType, result, params, err => {
196 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
204 nameToNpmName (name: string, type: PluginType) {
205 const prefix = type === PluginType.PLUGIN
212 pluginTypeFromNpmName (npmName: string) {
213 return npmName.startsWith('peertube-plugin-')
218 private loadPlugin (pluginInfo: PluginInfo) {
219 const { plugin, clientScript } = pluginInfo
221 const registerHook = (options: RegisterClientHookOptions) => {
222 if (clientHookObject[options.target] !== true) {
223 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
227 if (!this.hooks[options.target]) this.hooks[options.target] = []
229 this.hooks[options.target].push({
232 target: options.target,
233 handler: options.handler,
234 priority: options.priority || 0
238 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
240 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
242 return this.zone.runOutsideAngular(() => {
243 return importModule(clientScript.script)
244 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
245 .then(() => this.sortHooksByPriority())
246 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
250 private buildScopeStruct () {
251 for (const plugin of this.plugins) {
252 this.addPlugin(plugin)
256 private sortHooksByPriority () {
257 for (const hookName of Object.keys(this.hooks)) {
258 this.hooks[hookName].sort((a, b) => {
259 return b.priority - a.priority
264 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
265 const { plugin } = pluginInfo
266 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
269 getBaseStaticRoute: () => {
270 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
271 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
275 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
277 return this.authHttp.get<PublicServerSetting>(path)
279 map(p => p.publicSettings),
280 catchError(res => this.restExtractor.handleError(res))
286 return this.authService.isLoggedIn()
290 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
291 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
292 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
299 cancel?: { value: string, action?: () => void },
300 confirm?: { value: string, action?: () => void }
302 this.customModal.show(input)
306 textMarkdownToHTML: (textMarkdown: string) => {
307 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
310 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
311 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
315 translate: (value: string) => {
316 return this.translationsObservable
317 .pipe(map(allTranslations => allTranslations[npmName]))
318 .pipe(map(translations => peertubeTranslate(value, translations)))
324 private loadTranslations () {
325 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
327 // Default locale, nothing to translate
328 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
330 this.translationsObservable = this.authHttp
331 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
335 private getPluginPathPrefix (isTheme: boolean) {
336 return isTheme ? '/themes' : '/plugins'