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 { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
6 import { AuthService } from '@app/core/auth'
7 import { Notifier } from '@app/core/notification'
8 import { MarkdownService } from '@app/core/renderer'
9 import { RestExtractor } from '@app/core/rest'
10 import { ServerService } from '@app/core/server/server.service'
11 import { getDevLocale, isOnDevLocale } from '@app/helpers'
12 import { CustomModalComponent } from '@app/modal/custom-modal.component'
13 import { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
14 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
23 } from '@shared/models'
24 import { environment } from '../../../environments/environment'
25 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
28 export class PluginService implements ClientHook {
29 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
30 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
32 pluginsBuilt = new ReplaySubject<boolean>(1)
34 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
35 common: new ReplaySubject<boolean>(1),
36 search: new ReplaySubject<boolean>(1),
37 'video-watch': new ReplaySubject<boolean>(1),
38 signup: new ReplaySubject<boolean>(1),
39 login: new ReplaySubject<boolean>(1),
40 'video-edit': new ReplaySubject<boolean>(1),
41 embed: new ReplaySubject<boolean>(1)
44 translationsObservable: Observable<PluginTranslation>
46 customModal: CustomModalComponent
48 private plugins: ServerConfigPlugin[] = []
49 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
50 private loadedScripts: { [ script: string ]: boolean } = {}
51 private loadedScopes: PluginClientScope[] = []
52 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
54 private hooks: Hooks = {}
55 private formFields: FormFields = {
60 private authService: AuthService,
61 private notifier: Notifier,
62 private markdownRenderer: MarkdownService,
63 private server: ServerService,
65 private authHttp: HttpClient,
66 private restExtractor: RestExtractor,
67 @Inject(LOCALE_ID) private localeId: string
69 this.loadTranslations()
72 initializePlugins () {
73 this.server.getConfig()
74 .subscribe(config => {
75 this.plugins = config.plugin.registered
77 this.buildScopeStruct()
79 this.pluginsBuilt.next(true)
83 initializeCustomModal (customModal: CustomModalComponent) {
84 this.customModal = customModal
87 ensurePluginsAreBuilt () {
88 return this.pluginsBuilt.asObservable()
89 .pipe(first(), shareReplay())
93 ensurePluginsAreLoaded (scope: PluginClientScope) {
94 this.loadPluginsByScope(scope)
96 return this.pluginsLoaded[scope].asObservable()
97 .pipe(first(), shareReplay())
101 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
102 const pathPrefix = this.getPluginPathPrefix(isTheme)
104 for (const key of Object.keys(plugin.clientScripts)) {
105 const clientScript = plugin.clientScripts[key]
107 for (const scope of clientScript.scopes) {
108 if (!this.scopes[scope]) this.scopes[scope] = []
110 this.scopes[scope].push({
113 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
114 scopes: clientScript.scopes
116 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
120 this.loadedScripts[clientScript.script] = false
125 removePlugin (plugin: ServerConfigPlugin) {
126 for (const key of Object.keys(this.scopes)) {
127 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
131 async reloadLoadedScopes () {
132 for (const scope of this.loadedScopes) {
133 await this.loadPluginsByScope(scope, true)
137 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
138 if (this.loadingScopes[scope]) return
139 if (!isReload && this.loadedScopes.includes(scope)) return
141 this.loadingScopes[scope] = true
144 await this.ensurePluginsAreBuilt()
146 if (!isReload) this.loadedScopes.push(scope)
148 const toLoad = this.scopes[ scope ]
149 if (!Array.isArray(toLoad)) {
150 this.loadingScopes[scope] = false
151 this.pluginsLoaded[scope].next(true)
156 const promises: Promise<any>[] = []
157 for (const pluginInfo of toLoad) {
158 const clientScript = pluginInfo.clientScript
160 if (this.loadedScripts[ clientScript.script ]) continue
162 promises.push(this.loadPlugin(pluginInfo))
164 this.loadedScripts[ clientScript.script ] = true
167 await Promise.all(promises)
169 this.pluginsLoaded[scope].next(true)
170 this.loadingScopes[scope] = false
172 console.error('Cannot load plugins by scope %s.', scope, err)
176 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
177 return this.zone.runOutsideAngular(() => {
178 return runHook(this.hooks, hookName, result, params)
182 nameToNpmName (name: string, type: PluginType) {
183 const prefix = type === PluginType.PLUGIN
190 pluginTypeFromNpmName (npmName: string) {
191 return npmName.startsWith('peertube-plugin-')
196 getRegisteredVideoFormFields (type: VideoEditType) {
197 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
200 private loadPlugin (pluginInfo: PluginInfo) {
201 return this.zone.runOutsideAngular(() => {
204 formFields: this.formFields,
206 peertubeHelpersFactory: pluginInfo => this.buildPeerTubeHelpers(pluginInfo)
211 private buildScopeStruct () {
212 for (const plugin of this.plugins) {
213 this.addPlugin(plugin)
217 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
218 const { plugin } = pluginInfo
219 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
222 getBaseStaticRoute: () => {
223 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
224 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
228 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
230 return this.authHttp.get<PublicServerSetting>(path)
232 map(p => p.publicSettings),
233 catchError(res => this.restExtractor.handleError(res))
239 return this.authService.isLoggedIn()
243 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
244 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
245 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
252 cancel?: { value: string, action?: () => void },
253 confirm?: { value: string, action?: () => void }
255 this.customModal.show(input)
259 textMarkdownToHTML: (textMarkdown: string) => {
260 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
263 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
264 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
268 translate: (value: string) => {
269 return this.translationsObservable
270 .pipe(map(allTranslations => allTranslations[npmName]))
271 .pipe(map(translations => peertubeTranslate(value, translations)))
277 private loadTranslations () {
278 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
280 // Default locale, nothing to translate
281 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
283 this.translationsObservable = this.authHttp
284 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
288 private getPluginPathPrefix (isTheme: boolean) {
289 return isTheme ? '/themes' : '/plugins'