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'
27 import * as debug from 'debug'
29 const logger = debug('peertube:plugins')
32 export class PluginService implements ClientHook {
33 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
34 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
36 pluginsBuilt = new ReplaySubject<boolean>(1)
38 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
39 common: new ReplaySubject<boolean>(1),
40 'admin-plugin': new ReplaySubject<boolean>(1),
41 search: new ReplaySubject<boolean>(1),
42 'video-watch': new ReplaySubject<boolean>(1),
43 signup: new ReplaySubject<boolean>(1),
44 login: new ReplaySubject<boolean>(1),
45 'video-edit': new ReplaySubject<boolean>(1),
46 embed: new ReplaySubject<boolean>(1)
49 translationsObservable: Observable<PluginTranslation>
51 customModal: CustomModalComponent
53 private plugins: ServerConfigPlugin[] = []
54 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
56 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
58 private loadedScripts: { [ script: string ]: boolean } = {}
59 private loadedScopes: PluginClientScope[] = []
60 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
62 private hooks: Hooks = {}
63 private formFields: FormFields = {
66 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
69 private authService: AuthService,
70 private notifier: Notifier,
71 private markdownRenderer: MarkdownService,
72 private server: ServerService,
74 private authHttp: HttpClient,
75 private restExtractor: RestExtractor,
76 @Inject(LOCALE_ID) private localeId: string
78 this.loadTranslations()
81 initializePlugins () {
82 logger('Building plugin configuration')
84 this.server.getConfig()
85 .subscribe(config => {
86 this.plugins = config.plugin.registered
88 this.buildScopeStruct()
90 this.pluginsBuilt.next(true)
92 logger('Plugin configuration built')
96 initializeCustomModal (customModal: CustomModalComponent) {
97 this.customModal = customModal
100 ensurePluginsAreBuilt () {
101 return this.pluginsBuilt.asObservable()
102 .pipe(first(), shareReplay())
106 ensurePluginsAreLoaded (scope: PluginClientScope) {
107 this.loadPluginsByScope(scope)
109 return this.pluginsLoaded[scope].asObservable()
110 .pipe(first(), shareReplay())
114 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
115 const pathPrefix = this.getPluginPathPrefix(isTheme)
117 for (const key of Object.keys(plugin.clientScripts)) {
118 const clientScript = plugin.clientScripts[key]
120 for (const scope of clientScript.scopes) {
121 if (!this.scopes[scope]) this.scopes[scope] = []
123 this.scopes[scope].push({
126 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
127 scopes: clientScript.scopes
129 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
133 this.loadedScripts[clientScript.script] = false
138 removePlugin (plugin: ServerConfigPlugin) {
139 for (const key of Object.keys(this.scopes)) {
140 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
144 async reloadLoadedScopes () {
145 for (const scope of this.loadedScopes) {
146 await this.loadPluginsByScope(scope, true)
150 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
151 if (this.loadingScopes[scope]) return
152 if (!isReload && this.loadedScopes.includes(scope)) return
154 this.loadingScopes[scope] = true
156 logger('Loading scope %s', scope)
159 await this.ensurePluginsAreBuilt()
161 if (!isReload) this.loadedScopes.push(scope)
163 const toLoad = this.scopes[ scope ]
164 if (!Array.isArray(toLoad)) {
165 this.loadingScopes[scope] = false
166 this.pluginsLoaded[scope].next(true)
168 logger('Nothing to load for scope %s', scope)
172 const promises: Promise<any>[] = []
173 for (const pluginInfo of toLoad) {
174 const clientScript = pluginInfo.clientScript
176 if (this.loadedScripts[ clientScript.script ]) continue
178 promises.push(this.loadPlugin(pluginInfo))
180 this.loadedScripts[ clientScript.script ] = true
183 await Promise.all(promises)
185 this.pluginsLoaded[scope].next(true)
186 this.loadingScopes[scope] = false
188 logger('Scope %s loaded', scope)
190 console.error('Cannot load plugins by scope %s.', scope, err)
194 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
195 return this.zone.runOutsideAngular(() => {
196 return runHook(this.hooks, hookName, result, params)
200 nameToNpmName (name: string, type: PluginType) {
201 const prefix = type === PluginType.PLUGIN
208 pluginTypeFromNpmName (npmName: string) {
209 return npmName.startsWith('peertube-plugin-')
214 getRegisteredVideoFormFields (type: VideoEditType) {
215 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
218 getRegisteredSettingsScript (npmName: string) {
219 return this.settingsScripts[npmName]
222 translateBy (npmName: string, toTranslate: string) {
223 const helpers = this.helpers[npmName]
225 console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName)
229 return helpers.translate(toTranslate)
232 private loadPlugin (pluginInfo: PluginInfo) {
233 return this.zone.runOutsideAngular(() => {
234 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
236 const helpers = this.buildPeerTubeHelpers(pluginInfo)
237 this.helpers[npmName] = helpers
241 formFields: this.formFields,
242 onSettingsScripts: options => this.settingsScripts[npmName] = options,
244 peertubeHelpersFactory: () => helpers
249 private buildScopeStruct () {
250 for (const plugin of this.plugins) {
251 this.addPlugin(plugin)
255 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
256 const { plugin } = pluginInfo
257 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
260 getBaseStaticRoute: () => {
261 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
262 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
265 getBaseRouterRoute: () => {
266 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
267 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
271 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
273 return this.authHttp.get<PublicServerSetting>(path)
275 map(p => p.publicSettings),
276 catchError(res => this.restExtractor.handleError(res))
281 getServerConfig: () => {
282 return this.server.getConfig()
283 .pipe(catchError(res => this.restExtractor.handleError(res)))
288 return this.authService.isLoggedIn()
291 getAuthHeader: () => {
292 if (!this.authService.isLoggedIn()) return undefined
294 const value = this.authService.getRequestHeaderValue()
295 return { 'Authorization': value }
299 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
300 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
301 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
308 cancel?: { value: string, action?: () => void },
309 confirm?: { value: string, action?: () => void }
311 this.customModal.show(input)
315 textMarkdownToHTML: (textMarkdown: string) => {
316 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
319 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
320 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
324 translate: (value: string) => {
325 return this.translationsObservable
326 .pipe(map(allTranslations => allTranslations[npmName]))
327 .pipe(map(translations => peertubeTranslate(value, translations)))
333 private loadTranslations () {
334 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
336 // Default locale, nothing to translate
337 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
339 this.translationsObservable = this.authHttp
340 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
344 private getPluginPathPrefix (isTheme: boolean) {
345 return isTheme ? '/themes' : '/plugins'