X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=client%2Fsrc%2Fapp%2Fcore%2Fplugins%2Fplugin.service.ts;h=bfd5ba4ccd6629f4c8462e9149a3d4bca84979a7;hb=72f611ca1549d711f8cbf5dd08a3f1562a32fabb;hp=6c567d3ca3733706e0e3f4ef2eef0cdd71667d19;hpb=18a6f04c071f7a0735eb39b8c67fd51a082d1a31;p=github%2FChocobozzz%2FPeerTube.git diff --git a/client/src/app/core/plugins/plugin.service.ts b/client/src/app/core/plugins/plugin.service.ts index 6c567d3ca..bfd5ba4cc 100644 --- a/client/src/app/core/plugins/plugin.service.ts +++ b/client/src/app/core/plugins/plugin.service.ts @@ -1,137 +1,237 @@ -import { Injectable } from '@angular/core' -import { Router } from '@angular/router' -import { ServerConfigPlugin } from '@shared/models' +import { Observable, of } from 'rxjs' +import { catchError, map, shareReplay } from 'rxjs/operators' +import { HttpClient } from '@angular/common/http' +import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core' +import { VideoEditType } from '@app/+videos/+video-edit/shared/video-edit.type' +import { AuthService } from '@app/core/auth' +import { Notifier } from '@app/core/notification' +import { MarkdownService } from '@app/core/renderer' +import { RestExtractor } from '@app/core/rest' import { ServerService } from '@app/core/server/server.service' -import { ClientScript } from '@shared/models/plugins/plugin-package-json.model' -import { PluginScope } from '@shared/models/plugins/plugin-scope.type' +import { getDevLocale, isOnDevLocale } from '@app/helpers' +import { CustomModalComponent } from '@app/modal/custom-modal.component' +import { PluginInfo, PluginsManager } from '@root-helpers/plugins-manager' +import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n' +import { + ClientHook, + ClientHookName, + PluginClientScope, + PluginTranslation, + PluginType, + PublicServerSetting, + RegisterClientFormFieldOptions, + RegisterClientSettingsScript, + RegisterClientVideoFieldOptions, + ServerConfigPlugin +} from '@shared/models' import { environment } from '../../../environments/environment' -import { RegisterHookOptions } from '@shared/models/plugins/register.model' -import { ReplaySubject } from 'rxjs' -import { first } from 'rxjs/operators' +import { RegisterClientHelpers } from '../../../types/register-client-option.model' -interface HookStructValue extends RegisterHookOptions { - plugin: ServerConfigPlugin - clientScript: ClientScript +type FormFields = { + video: { + commonOptions: RegisterClientFormFieldOptions + videoFormOptions: RegisterClientVideoFieldOptions + }[] } @Injectable() -export class PluginService { - pluginsLoaded = new ReplaySubject(1) +export class PluginService implements ClientHook { + private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins' + private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins' - private plugins: ServerConfigPlugin[] = [] - private scopes: { [ scopeName: string ]: { plugin: ServerConfigPlugin, clientScript: ClientScript }[] } = {} - private loadedScripts: { [ script: string ]: boolean } = {} + translationsObservable: Observable - private hooks: { [ name: string ]: HookStructValue[] } = {} + customModal: CustomModalComponent + + private helpers: { [ npmName: string ]: RegisterClientHelpers } = {} + + private formFields: FormFields = { + video: [] + } + private settingsScripts: { [ npmName: string ]: RegisterClientSettingsScript } = {} + + private pluginsManager: PluginsManager constructor ( - private router: Router, - private server: ServerService + private authService: AuthService, + private notifier: Notifier, + private markdownRenderer: MarkdownService, + private server: ServerService, + private zone: NgZone, + private authHttp: HttpClient, + private restExtractor: RestExtractor, + @Inject(LOCALE_ID) private localeId: string ) { + this.loadTranslations() + + this.pluginsManager = new PluginsManager({ + peertubeHelpersFactory: this.buildPeerTubeHelpers.bind(this), + onFormFields: this.onFormFields.bind(this), + onSettingsScripts: this.onSettingsScripts.bind(this) + }) } initializePlugins () { - this.server.configLoaded - .subscribe(() => { - this.plugins = this.server.getConfig().plugins - - this.buildScopeStruct() + this.pluginsManager.loadPluginsList(this.server.getHTMLConfig()) - this.pluginsLoaded.next(true) - }) + this.pluginsManager.ensurePluginsAreLoaded('common') } - ensurePluginsAreLoaded () { - return this.pluginsLoaded.asObservable() - .pipe(first()) - .toPromise() + initializeCustomModal (customModal: CustomModalComponent) { + this.customModal = customModal } - async loadPluginsByScope (scope: PluginScope) { - try { - await this.ensurePluginsAreLoaded() - - const toLoad = this.scopes[ scope ] - if (!Array.isArray(toLoad)) return + runHook (hookName: ClientHookName, result?: T, params?: any): Promise { + return this.zone.runOutsideAngular(() => { + return this.pluginsManager.runHook(hookName, result, params) + }) + } - const promises: Promise[] = [] - for (const { plugin, clientScript } of toLoad) { - if (this.loadedScripts[ clientScript.script ]) continue + ensurePluginsAreLoaded (scope: PluginClientScope) { + return this.pluginsManager.ensurePluginsAreLoaded(scope) + } - promises.push(this.loadPlugin(plugin, clientScript)) + reloadLoadedScopes () { + return this.pluginsManager.reloadLoadedScopes() + } - this.loadedScripts[ clientScript.script ] = true - } + getPluginsManager () { + return this.pluginsManager + } - return Promise.all(promises) - } catch (err) { - console.error('Cannot load plugins by scope %s.', scope, err) - } + addPlugin (plugin: ServerConfigPlugin, isTheme = false) { + return this.pluginsManager.addPlugin(plugin, isTheme) } - async runHook (hookName: string, param?: any) { - let result = param + removePlugin (plugin: ServerConfigPlugin) { + return this.pluginsManager.removePlugin(plugin) + } - const wait = hookName.startsWith('static:') + nameToNpmName (name: string, type: PluginType) { + const prefix = type === PluginType.PLUGIN + ? 'peertube-plugin-' + : 'peertube-theme-' - for (const hook of this.hooks[hookName]) { - try { - if (wait) result = await hook.handler(param) - else result = hook.handler() - } catch (err) { - console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.plugin, hook.clientScript, err) - } - } + return prefix + name + } - return result + getRegisteredVideoFormFields (type: VideoEditType) { + return this.formFields.video.filter(f => f.videoFormOptions.type === type) } - private loadPlugin (plugin: ServerConfigPlugin, clientScript: ClientScript) { - const registerHook = (options: RegisterHookOptions) => { - if (!this.hooks[options.target]) this.hooks[options.target] = [] + getRegisteredSettingsScript (npmName: string) { + return this.settingsScripts[npmName] + } - this.hooks[options.target].push({ - plugin, - clientScript, - target: options.target, - handler: options.handler, - priority: options.priority || 0 - }) + translateBy (npmName: string, toTranslate: string) { + const helpers = this.helpers[npmName] + if (!helpers) { + console.error('Unknown helpers to translate %s from %s.', toTranslate, npmName) + return toTranslate } - console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name) - - const url = environment.apiUrl + `/plugins/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}` - - return import(/* webpackIgnore: true */ url) - .then(script => script.register({ registerHook })) - .then(() => this.sortHooksByPriority()) + return helpers.translate(toTranslate) } - private buildScopeStruct () { - for (const plugin of this.plugins) { - for (const key of Object.keys(plugin.clientScripts)) { - const clientScript = plugin.clientScripts[key] + private onFormFields (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) { + this.formFields.video.push({ + commonOptions, + videoFormOptions + }) + } - for (const scope of clientScript.scopes) { - if (!this.scopes[scope]) this.scopes[scope] = [] + private onSettingsScripts (pluginInfo: PluginInfo, options: RegisterClientSettingsScript) { + const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType) - this.scopes[scope].push({ - plugin, - clientScript - }) + this.settingsScripts[npmName] = options + } - this.loadedScripts[clientScript.script] = false + private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers { + const { plugin } = pluginInfo + const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType) + + return { + getBaseStaticRoute: () => { + const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme) + return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static` + }, + + getBaseRouterRoute: () => { + const pathPrefix = PluginsManager.getPluginPathPrefix(pluginInfo.isTheme) + return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/router` + }, + + getSettings: () => { + const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings' + + return this.authHttp.get(path) + .pipe( + map(p => p.publicSettings), + catchError(res => this.restExtractor.handleError(res)) + ) + .toPromise() + }, + + getServerConfig: () => { + return this.server.getConfig() + .pipe(catchError(res => this.restExtractor.handleError(res))) + .toPromise() + }, + + isLoggedIn: () => { + return this.authService.isLoggedIn() + }, + + getAuthHeader: () => { + if (!this.authService.isLoggedIn()) return undefined + + const value = this.authService.getRequestHeaderValue() + return { 'Authorization': value } + }, + + notifier: { + info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout), + error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout), + success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout) + }, + + showModal: (input: { + title: string, + content: string, + close?: boolean, + cancel?: { value: string, action?: () => void }, + confirm?: { value: string, action?: () => void } + }) => { + this.customModal.show(input) + }, + + markdownRenderer: { + textMarkdownToHTML: (textMarkdown: string) => { + return this.markdownRenderer.textMarkdownToHTML(textMarkdown) + }, + + enhancedMarkdownToHTML: (enhancedMarkdown: string) => { + return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown) } + }, + + translate: (value: string) => { + return this.translationsObservable + .pipe(map(allTranslations => allTranslations[npmName])) + .pipe(map(translations => peertubeTranslate(value, translations))) + .toPromise() } } } - private sortHooksByPriority () { - for (const hookName of Object.keys(this.hooks)) { - this.hooks[hookName].sort((a, b) => { - return b.priority - a.priority - }) - } + private loadTranslations () { + const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId) + + // Default locale, nothing to translate + if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay()) + + this.translationsObservable = this.authHttp + .get(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json') + .pipe(shareReplay()) } }