1 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { getCompleteLocale, isDefaultLocale, peertubeTranslate, ServerConfigPlugin } from '@shared/models'
4 import { ServerService } from '@app/core/server/server.service'
5 import { ClientScript } from '@shared/models/plugins/plugin-package-json.model'
6 import { ClientScript as ClientScriptModule } from '../../../types/client-script.model'
7 import { environment } from '../../../environments/environment'
8 import { Observable, of, ReplaySubject } from 'rxjs'
9 import { catchError, first, map, shareReplay } from 'rxjs/operators'
10 import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
11 import { ClientHook, ClientHookName, clientHookObject } from '@shared/models/plugins/client-hook.model'
12 import { PluginClientScope } from '@shared/models/plugins/plugin-client-scope.type'
13 import { RegisterClientHookOptions } from '@shared/models/plugins/register-client-hook.model'
14 import { HttpClient } from '@angular/common/http'
15 import { AuthService } from '@app/core/auth'
16 import { Notifier } from '@app/core/notification'
17 import { RestExtractor } from '@app/shared/rest'
18 import { MarkdownService } from '@app/shared/renderer'
19 import { PluginType } from '@shared/models/plugins/plugin.type'
20 import { PublicServerSetting } from '@shared/models/plugins/public-server.setting'
21 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
22 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
23 import { PluginTranslation } from '@shared/models/plugins/plugin-translation.model'
24 import { importModule } from '@app/shared/misc/utils'
25 import { CustomModalComponent } from '@app/modal/custom-modal.component'
27 interface HookStructValue extends RegisterClientHookOptions {
28 plugin: ServerConfigPlugin
29 clientScript: ClientScript
33 plugin: ServerConfigPlugin
34 clientScript: ClientScript
35 pluginType: PluginType
40 export class PluginService implements ClientHook {
41 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
42 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
44 pluginsBuilt = new ReplaySubject<boolean>(1)
46 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
47 common: new ReplaySubject<boolean>(1),
48 search: new ReplaySubject<boolean>(1),
49 'video-watch': new ReplaySubject<boolean>(1),
50 signup: new ReplaySubject<boolean>(1)
53 translationsObservable: Observable<PluginTranslation>
55 customModal: CustomModalComponent
57 private plugins: ServerConfigPlugin[] = []
58 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
59 private loadedScripts: { [ script: string ]: boolean } = {}
60 private loadedScopes: PluginClientScope[] = []
61 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
63 private hooks: { [ name: string ]: HookStructValue[] } = {}
66 private router: Router,
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 this.server.getConfig()
81 .subscribe(config => {
82 this.plugins = config.plugin.registered
84 this.buildScopeStruct()
86 this.pluginsBuilt.next(true)
90 initializeCustomModal (customModal: CustomModalComponent) {
91 this.customModal = customModal
94 ensurePluginsAreBuilt () {
95 return this.pluginsBuilt.asObservable()
96 .pipe(first(), shareReplay())
100 ensurePluginsAreLoaded (scope: PluginClientScope) {
101 this.loadPluginsByScope(scope)
103 return this.pluginsLoaded[scope].asObservable()
104 .pipe(first(), shareReplay())
108 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
109 const pathPrefix = this.getPluginPathPrefix(isTheme)
111 for (const key of Object.keys(plugin.clientScripts)) {
112 const clientScript = plugin.clientScripts[key]
114 for (const scope of clientScript.scopes) {
115 if (!this.scopes[scope]) this.scopes[scope] = []
117 this.scopes[scope].push({
120 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
121 scopes: clientScript.scopes
123 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
127 this.loadedScripts[clientScript.script] = false
132 removePlugin (plugin: ServerConfigPlugin) {
133 for (const key of Object.keys(this.scopes)) {
134 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
138 async reloadLoadedScopes () {
139 for (const scope of this.loadedScopes) {
140 await this.loadPluginsByScope(scope, true)
144 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
145 if (this.loadingScopes[scope]) return
146 if (!isReload && this.loadedScopes.includes(scope)) return
148 this.loadingScopes[scope] = true
151 await this.ensurePluginsAreBuilt()
153 if (!isReload) this.loadedScopes.push(scope)
155 const toLoad = this.scopes[ scope ]
156 if (!Array.isArray(toLoad)) {
157 this.loadingScopes[scope] = false
158 this.pluginsLoaded[scope].next(true)
163 const promises: Promise<any>[] = []
164 for (const pluginInfo of toLoad) {
165 const clientScript = pluginInfo.clientScript
167 if (this.loadedScripts[ clientScript.script ]) continue
169 promises.push(this.loadPlugin(pluginInfo))
171 this.loadedScripts[ clientScript.script ] = true
174 await Promise.all(promises)
176 this.pluginsLoaded[scope].next(true)
177 this.loadingScopes[scope] = false
179 console.error('Cannot load plugins by scope %s.', scope, err)
183 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
184 return this.zone.runOutsideAngular(async () => {
185 if (!this.hooks[ hookName ]) return result
187 const hookType = getHookType(hookName)
189 for (const hook of this.hooks[ hookName ]) {
190 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
192 result = await internalRunHook(hook.handler, hookType, result, params, err => {
193 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
201 nameToNpmName (name: string, type: PluginType) {
202 const prefix = type === PluginType.PLUGIN
209 pluginTypeFromNpmName (npmName: string) {
210 return npmName.startsWith('peertube-plugin-')
215 private loadPlugin (pluginInfo: PluginInfo) {
216 const { plugin, clientScript } = pluginInfo
218 const registerHook = (options: RegisterClientHookOptions) => {
219 if (clientHookObject[options.target] !== true) {
220 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
224 if (!this.hooks[options.target]) this.hooks[options.target] = []
226 this.hooks[options.target].push({
229 target: options.target,
230 handler: options.handler,
231 priority: options.priority || 0
235 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
237 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
239 return this.zone.runOutsideAngular(() => {
240 return importModule(clientScript.script)
241 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
242 .then(() => this.sortHooksByPriority())
243 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
247 private buildScopeStruct () {
248 for (const plugin of this.plugins) {
249 this.addPlugin(plugin)
253 private sortHooksByPriority () {
254 for (const hookName of Object.keys(this.hooks)) {
255 this.hooks[hookName].sort((a, b) => {
256 return b.priority - a.priority
261 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
262 const { plugin } = pluginInfo
263 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
266 getBaseStaticRoute: () => {
267 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
268 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
272 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
274 return this.authHttp.get<PublicServerSetting>(path)
276 map(p => p.publicSettings),
277 catchError(res => this.restExtractor.handleError(res))
283 return this.authService.isLoggedIn()
287 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
288 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
289 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
296 cancel?: { value: string, action?: () => void },
297 confirm?: { value: string, action?: () => void }
299 this.customModal.show(input)
303 textMarkdownToHTML: (textMarkdown: string) => {
304 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
307 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
308 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
312 translate: (value: string) => {
313 return this.translationsObservable
314 .pipe(map(allTranslations => allTranslations[npmName]))
315 .pipe(map(translations => peertubeTranslate(value, translations)))
321 private loadTranslations () {
322 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
324 // Default locale, nothing to translate
325 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
327 this.translationsObservable = this.authHttp
328 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
332 private getPluginPathPrefix (isTheme: boolean) {
333 return isTheme ? '/themes' : '/plugins'