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'
22 RegisterClientSettingsScript,
24 } from '@shared/models'
25 import { environment } from '../../../environments/environment'
26 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
29 export class PluginService implements ClientHook {
30 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
31 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
33 pluginsBuilt = new ReplaySubject<boolean>(1)
35 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
36 common: new ReplaySubject<boolean>(1),
37 'admin-plugin': new ReplaySubject<boolean>(1),
38 search: new ReplaySubject<boolean>(1),
39 'video-watch': new ReplaySubject<boolean>(1),
40 signup: new ReplaySubject<boolean>(1),
41 login: new ReplaySubject<boolean>(1),
42 'video-edit': new ReplaySubject<boolean>(1),
43 embed: new ReplaySubject<boolean>(1)
46 translationsObservable: Observable<PluginTranslation>
48 customModal: CustomModalComponent
50 private plugins: ServerConfigPlugin[] = []
51 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
53 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
55 private loadedScripts: { [ script: string ]: boolean } = {}
56 private loadedScopes: PluginClientScope[] = []
57 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
59 private hooks: Hooks = {}
60 private formFields: FormFields = {
63 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
66 private authService: AuthService,
67 private notifier: Notifier,
68 private markdownRenderer: MarkdownService,
69 private server: ServerService,
71 private authHttp: HttpClient,
72 private restExtractor: RestExtractor,
73 @Inject(LOCALE_ID) private localeId: string
75 this.loadTranslations()
78 initializePlugins () {
79 this.server.getConfig()
80 .subscribe(config => {
81 this.plugins = config.plugin.registered
83 this.buildScopeStruct()
85 this.pluginsBuilt.next(true)
89 initializeCustomModal (customModal: CustomModalComponent) {
90 this.customModal = customModal
93 ensurePluginsAreBuilt () {
94 return this.pluginsBuilt.asObservable()
95 .pipe(first(), shareReplay())
99 ensurePluginsAreLoaded (scope: PluginClientScope) {
100 this.loadPluginsByScope(scope)
102 return this.pluginsLoaded[scope].asObservable()
103 .pipe(first(), shareReplay())
107 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
108 const pathPrefix = this.getPluginPathPrefix(isTheme)
110 for (const key of Object.keys(plugin.clientScripts)) {
111 const clientScript = plugin.clientScripts[key]
113 for (const scope of clientScript.scopes) {
114 if (!this.scopes[scope]) this.scopes[scope] = []
116 this.scopes[scope].push({
119 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
120 scopes: clientScript.scopes
122 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
126 this.loadedScripts[clientScript.script] = false
131 removePlugin (plugin: ServerConfigPlugin) {
132 for (const key of Object.keys(this.scopes)) {
133 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
137 async reloadLoadedScopes () {
138 for (const scope of this.loadedScopes) {
139 await this.loadPluginsByScope(scope, true)
143 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
144 if (this.loadingScopes[scope]) return
145 if (!isReload && this.loadedScopes.includes(scope)) return
147 this.loadingScopes[scope] = true
150 await this.ensurePluginsAreBuilt()
152 if (!isReload) this.loadedScopes.push(scope)
154 const toLoad = this.scopes[ scope ]
155 if (!Array.isArray(toLoad)) {
156 this.loadingScopes[scope] = false
157 this.pluginsLoaded[scope].next(true)
162 const promises: Promise<any>[] = []
163 for (const pluginInfo of toLoad) {
164 const clientScript = pluginInfo.clientScript
166 if (this.loadedScripts[ clientScript.script ]) continue
168 promises.push(this.loadPlugin(pluginInfo))
170 this.loadedScripts[ clientScript.script ] = true
173 await Promise.all(promises)
175 this.pluginsLoaded[scope].next(true)
176 this.loadingScopes[scope] = false
178 console.error('Cannot load plugins by scope %s.', scope, err)
182 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
183 return this.zone.runOutsideAngular(() => {
184 return runHook(this.hooks, hookName, result, params)
188 nameToNpmName (name: string, type: PluginType) {
189 const prefix = type === PluginType.PLUGIN
196 pluginTypeFromNpmName (npmName: string) {
197 return npmName.startsWith('peertube-plugin-')
202 getRegisteredVideoFormFields (type: VideoEditType) {
203 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
206 getRegisteredSettingsScript (npmName: string) {
207 return this.settingsScripts[npmName]
210 translateBy (npmName: string, toTranslate: string) {
211 const helpers = this.helpers[npmName]
213 console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName)
217 return helpers.translate(toTranslate)
220 private loadPlugin (pluginInfo: PluginInfo) {
221 return this.zone.runOutsideAngular(() => {
222 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
224 const helpers = this.buildPeerTubeHelpers(pluginInfo)
225 this.helpers[npmName] = helpers
229 formFields: this.formFields,
230 onSettingsScripts: options => this.settingsScripts[npmName] = options,
232 peertubeHelpersFactory: () => helpers
237 private buildScopeStruct () {
238 for (const plugin of this.plugins) {
239 this.addPlugin(plugin)
243 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
244 const { plugin } = pluginInfo
245 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
248 getBaseStaticRoute: () => {
249 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
250 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
254 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
256 return this.authHttp.get<PublicServerSetting>(path)
258 map(p => p.publicSettings),
259 catchError(res => this.restExtractor.handleError(res))
264 getServerConfig: () => {
265 return this.server.getConfig()
266 .pipe(catchError(res => this.restExtractor.handleError(res)))
271 return this.authService.isLoggedIn()
275 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
276 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
277 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
284 cancel?: { value: string, action?: () => void },
285 confirm?: { value: string, action?: () => void }
287 this.customModal.show(input)
291 textMarkdownToHTML: (textMarkdown: string) => {
292 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
295 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
296 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
300 translate: (value: string) => {
301 return this.translationsObservable
302 .pipe(map(allTranslations => allTranslations[npmName]))
303 .pipe(map(translations => peertubeTranslate(value, translations)))
309 private loadTranslations () {
310 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
312 // Default locale, nothing to translate
313 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
315 this.translationsObservable = this.authHttp
316 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
320 private getPluginPathPrefix (isTheme: boolean) {
321 return isTheme ? '/themes' : '/plugins'