1 import * as debug from 'debug'
2 import { Observable, of, ReplaySubject } from 'rxjs'
3 import { catchError, first, map, shareReplay } from 'rxjs/operators'
4 import { HttpClient } from '@angular/common/http'
5 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
6 import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type'
7 import { AuthService } from '@app/core/auth'
8 import { Notifier } from '@app/core/notification'
9 import { MarkdownService } from '@app/core/renderer'
10 import { RestExtractor } from '@app/core/rest'
11 import { ServerService } from '@app/core/server/server.service'
12 import { getDevLocale, isOnDevLocale } from '@app/helpers'
13 import { CustomModalComponent } from '@app/modal/custom-modal.component'
14 import { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
15 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
23 RegisterClientSettingsScript,
25 } from '@shared/models'
26 import { environment } from '../../../environments/environment'
27 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
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 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
37 common: new ReplaySubject<boolean>(1),
38 'admin-plugin': new ReplaySubject<boolean>(1),
39 search: new ReplaySubject<boolean>(1),
40 'video-watch': new ReplaySubject<boolean>(1),
41 signup: new ReplaySubject<boolean>(1),
42 login: new ReplaySubject<boolean>(1),
43 'video-edit': new ReplaySubject<boolean>(1),
44 embed: new ReplaySubject<boolean>(1)
47 translationsObservable: Observable<PluginTranslation>
49 customModal: CustomModalComponent
51 private plugins: ServerConfigPlugin[] = []
52 private helpers: { [ npmName: string ]: RegisterClientHelpers } = {}
54 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
56 private loadedScripts: { [ script: string ]: boolean } = {}
57 private loadedScopes: PluginClientScope[] = []
58 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
60 private hooks: Hooks = {}
61 private formFields: FormFields = {
64 private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {}
67 private authService: AuthService,
68 private notifier: Notifier,
69 private markdownRenderer: MarkdownService,
70 private server: ServerService,
72 private authHttp: HttpClient,
73 private restExtractor: RestExtractor,
74 @Inject(LOCALE_ID) private localeId: string
76 this.loadTranslations()
79 initializePlugins () {
80 const config = this.server.getHTMLConfig()
81 this.plugins = config.plugin.registered
83 this.buildScopeStruct()
85 this.ensurePluginsAreLoaded('common')
88 initializeCustomModal (customModal: CustomModalComponent) {
89 this.customModal = customModal
92 ensurePluginsAreLoaded (scope: PluginClientScope) {
93 this.loadPluginsByScope(scope)
95 return this.pluginsLoaded[scope].asObservable()
96 .pipe(first(), shareReplay())
100 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
101 const pathPrefix = this.getPluginPathPrefix(isTheme)
103 for (const key of Object.keys(plugin.clientScripts)) {
104 const clientScript = plugin.clientScripts[key]
106 for (const scope of clientScript.scopes) {
107 if (!this.scopes[scope]) this.scopes[scope] = []
109 this.scopes[scope].push({
112 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
113 scopes: clientScript.scopes
115 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
119 this.loadedScripts[clientScript.script] = false
124 removePlugin (plugin: ServerConfigPlugin) {
125 for (const key of Object.keys(this.scopes)) {
126 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
130 async reloadLoadedScopes () {
131 for (const scope of this.loadedScopes) {
132 await this.loadPluginsByScope(scope, true)
136 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
137 if (this.loadingScopes[scope]) return
138 if (!isReload && this.loadedScopes.includes(scope)) return
140 this.loadingScopes[scope] = true
142 logger('Loading scope %s', scope)
145 if (!isReload) this.loadedScopes.push(scope)
147 const toLoad = this.scopes[ scope ]
148 if (!Array.isArray(toLoad)) {
149 this.loadingScopes[scope] = false
150 this.pluginsLoaded[scope].next(true)
152 logger('Nothing to load for scope %s', scope)
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 logger('Scope %s loaded', scope)
174 console.error('Cannot load plugins by scope %s.', scope, err)
178 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
179 return this.zone.runOutsideAngular(() => {
180 return runHook(this.hooks, hookName, result, params)
184 nameToNpmName (name: string, type: PluginType) {
185 const prefix = type === PluginType.PLUGIN
192 pluginTypeFromNpmName (npmName: string) {
193 return npmName.startsWith('peertube-plugin-')
198 getRegisteredVideoFormFields (type: VideoEditType) {
199 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
202 getRegisteredSettingsScript (npmName: string) {
203 return this.settingsScripts[npmName]
206 translateBy (npmName: string, toTranslate: string) {
207 const helpers = this.helpers[npmName]
209 console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName)
213 return helpers.translate(toTranslate)
216 private loadPlugin (pluginInfo: PluginInfo) {
217 return this.zone.runOutsideAngular(() => {
218 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
220 const helpers = this.buildPeerTubeHelpers(pluginInfo)
221 this.helpers[npmName] = helpers
225 formFields: this.formFields,
226 onSettingsScripts: options => this.settingsScripts[npmName] = options,
228 peertubeHelpersFactory: () => helpers
233 private buildScopeStruct () {
234 for (const plugin of this.plugins) {
235 this.addPlugin(plugin)
239 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
240 const { plugin } = pluginInfo
241 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
244 getBaseStaticRoute: () => {
245 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
246 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
249 getBaseRouterRoute: () => {
250 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
251 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router`
255 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
257 return this.authHttp.get<PublicServerSetting>(path)
259 map(p => p.publicSettings),
260 catchError(res => this.restExtractor.handleError(res))
265 getServerConfig: () => {
266 return this.server.getConfig()
267 .pipe(catchError(res => this.restExtractor.handleError(res)))
272 return this.authService.isLoggedIn()
275 getAuthHeader: () => {
276 if (!this.authService.isLoggedIn()) return undefined
278 const value = this.authService.getRequestHeaderValue()
279 return { 'Authorization': value }
283 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
284 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
285 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
292 cancel?: { value: string, action?: () => void },
293 confirm?: { value: string, action?: () => void }
295 this.customModal.show(input)
299 textMarkdownToHTML: (textMarkdown: string) => {
300 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
303 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
304 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
308 translate: (value: string) => {
309 return this.translationsObservable
310 .pipe(map(allTranslations => allTranslations[npmName]))
311 .pipe(map(translations => peertubeTranslate(value, translations)))
317 private loadTranslations () {
318 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
320 // Default locale, nothing to translate
321 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
323 this.translationsObservable = this.authHttp
324 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
328 private getPluginPathPrefix (isTheme: boolean) {
329 return isTheme ? '/themes' : '/plugins'