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, isOnDevLocale } from '@app/helpers'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
13 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
22 } from '@shared/models'
23 import { environment } from '../../../environments/environment'
24 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
27 export class PluginService implements ClientHook {
28 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
29 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
31 pluginsBuilt = new ReplaySubject<boolean>(1)
33 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
34 common: new ReplaySubject<boolean>(1),
35 search: new ReplaySubject<boolean>(1),
36 'video-watch': new ReplaySubject<boolean>(1),
37 signup: new ReplaySubject<boolean>(1),
38 login: new ReplaySubject<boolean>(1),
39 embed: new ReplaySubject<boolean>(1)
42 translationsObservable: Observable<PluginTranslation>
44 customModal: CustomModalComponent
46 private plugins: ServerConfigPlugin[] = []
47 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
48 private loadedScripts: { [ script: string ]: boolean } = {}
49 private loadedScopes: PluginClientScope[] = []
50 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
52 private hooks: Hooks = {}
55 private authService: AuthService,
56 private notifier: Notifier,
57 private markdownRenderer: MarkdownService,
58 private server: ServerService,
60 private authHttp: HttpClient,
61 private restExtractor: RestExtractor,
62 @Inject(LOCALE_ID) private localeId: string
64 this.loadTranslations()
67 initializePlugins () {
68 this.server.getConfig()
69 .subscribe(config => {
70 this.plugins = config.plugin.registered
72 this.buildScopeStruct()
74 this.pluginsBuilt.next(true)
78 initializeCustomModal (customModal: CustomModalComponent) {
79 this.customModal = customModal
82 ensurePluginsAreBuilt () {
83 return this.pluginsBuilt.asObservable()
84 .pipe(first(), shareReplay())
88 ensurePluginsAreLoaded (scope: PluginClientScope) {
89 this.loadPluginsByScope(scope)
91 return this.pluginsLoaded[scope].asObservable()
92 .pipe(first(), shareReplay())
96 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
97 const pathPrefix = this.getPluginPathPrefix(isTheme)
99 for (const key of Object.keys(plugin.clientScripts)) {
100 const clientScript = plugin.clientScripts[key]
102 for (const scope of clientScript.scopes) {
103 if (!this.scopes[scope]) this.scopes[scope] = []
105 this.scopes[scope].push({
108 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
109 scopes: clientScript.scopes
111 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
115 this.loadedScripts[clientScript.script] = false
120 removePlugin (plugin: ServerConfigPlugin) {
121 for (const key of Object.keys(this.scopes)) {
122 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
126 async reloadLoadedScopes () {
127 for (const scope of this.loadedScopes) {
128 await this.loadPluginsByScope(scope, true)
132 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
133 if (this.loadingScopes[scope]) return
134 if (!isReload && this.loadedScopes.includes(scope)) return
136 this.loadingScopes[scope] = true
139 await this.ensurePluginsAreBuilt()
141 if (!isReload) this.loadedScopes.push(scope)
143 const toLoad = this.scopes[ scope ]
144 if (!Array.isArray(toLoad)) {
145 this.loadingScopes[scope] = false
146 this.pluginsLoaded[scope].next(true)
151 const promises: Promise<any>[] = []
152 for (const pluginInfo of toLoad) {
153 const clientScript = pluginInfo.clientScript
155 if (this.loadedScripts[ clientScript.script ]) continue
157 promises.push(this.loadPlugin(pluginInfo))
159 this.loadedScripts[ clientScript.script ] = true
162 await Promise.all(promises)
164 this.pluginsLoaded[scope].next(true)
165 this.loadingScopes[scope] = false
167 console.error('Cannot load plugins by scope %s.', scope, err)
171 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
172 return this.zone.runOutsideAngular(() => {
173 return runHook(this.hooks, hookName, result, params)
177 nameToNpmName (name: string, type: PluginType) {
178 const prefix = type === PluginType.PLUGIN
185 pluginTypeFromNpmName (npmName: string) {
186 return npmName.startsWith('peertube-plugin-')
191 private loadPlugin (pluginInfo: PluginInfo) {
192 return this.zone.runOutsideAngular(() => {
193 return loadPlugin(this.hooks, pluginInfo, pluginInfo => this.buildPeerTubeHelpers(pluginInfo))
197 private buildScopeStruct () {
198 for (const plugin of this.plugins) {
199 this.addPlugin(plugin)
203 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
204 const { plugin } = pluginInfo
205 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
208 getBaseStaticRoute: () => {
209 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
210 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
214 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
216 return this.authHttp.get<PublicServerSetting>(path)
218 map(p => p.publicSettings),
219 catchError(res => this.restExtractor.handleError(res))
225 return this.authService.isLoggedIn()
229 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
230 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
231 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
238 cancel?: { value: string, action?: () => void },
239 confirm?: { value: string, action?: () => void }
241 this.customModal.show(input)
245 textMarkdownToHTML: (textMarkdown: string) => {
246 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
249 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
250 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
254 translate: (value: string) => {
255 return this.translationsObservable
256 .pipe(map(allTranslations => allTranslations[npmName]))
257 .pipe(map(translations => peertubeTranslate(value, translations)))
263 private loadTranslations () {
264 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
266 // Default locale, nothing to translate
267 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
269 this.translationsObservable = this.authHttp
270 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
274 private getPluginPathPrefix (isTheme: boolean) {
275 return isTheme ? '/themes' : '/plugins'