1 import { Injectable } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { 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 { 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 { PeerTubePlugin } from '@shared/models/plugins/peertube-plugin.model'
15 import { HttpClient } from '@angular/common/http'
16 import { RestExtractor } from '@app/shared/rest'
17 import { PluginType } from '@shared/models/plugins/plugin.type'
19 interface HookStructValue extends RegisterClientHookOptions {
20 plugin: ServerConfigPlugin
21 clientScript: ClientScript
25 plugin: ServerConfigPlugin
26 clientScript: ClientScript
27 pluginType: PluginType
32 export class PluginService implements ClientHook {
33 private static BASE_PLUGIN_URL = environment.apiUrl + '/api/v1/plugins'
35 pluginsBuilt = new ReplaySubject<boolean>(1)
37 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
38 common: new ReplaySubject<boolean>(1),
39 search: new ReplaySubject<boolean>(1),
40 'video-watch': new ReplaySubject<boolean>(1)
43 private plugins: ServerConfigPlugin[] = []
44 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
45 private loadedScripts: { [ script: string ]: boolean } = {}
46 private loadedScopes: PluginClientScope[] = []
47 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
49 private hooks: { [ name: string ]: HookStructValue[] } = {}
52 private router: Router,
53 private server: ServerService,
54 private authHttp: HttpClient,
55 private restExtractor: RestExtractor
59 initializePlugins () {
60 this.server.configLoaded
62 this.plugins = this.server.getConfig().plugin.registered
64 this.buildScopeStruct()
66 this.pluginsBuilt.next(true)
70 ensurePluginsAreBuilt () {
71 return this.pluginsBuilt.asObservable()
72 .pipe(first(), shareReplay())
76 ensurePluginsAreLoaded (scope: PluginClientScope) {
77 this.loadPluginsByScope(scope)
79 return this.pluginsLoaded[scope].asObservable()
80 .pipe(first(), shareReplay())
84 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
85 const pathPrefix = this.getPluginPathPrefix(isTheme)
87 for (const key of Object.keys(plugin.clientScripts)) {
88 const clientScript = plugin.clientScripts[key]
90 for (const scope of clientScript.scopes) {
91 if (!this.scopes[scope]) this.scopes[scope] = []
93 this.scopes[scope].push({
96 script: environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
97 scopes: clientScript.scopes
99 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
103 this.loadedScripts[clientScript.script] = false
108 removePlugin (plugin: ServerConfigPlugin) {
109 for (const key of Object.keys(this.scopes)) {
110 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
114 async reloadLoadedScopes () {
115 for (const scope of this.loadedScopes) {
116 await this.loadPluginsByScope(scope, true)
120 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
121 if (this.loadingScopes[scope]) return
122 if (!isReload && this.loadedScopes.includes(scope)) return
124 this.loadingScopes[scope] = true
127 await this.ensurePluginsAreBuilt()
129 if (!isReload) this.loadedScopes.push(scope)
131 const toLoad = this.scopes[ scope ]
132 if (!Array.isArray(toLoad)) {
133 this.loadingScopes[scope] = false
134 this.pluginsLoaded[scope].next(true)
139 const promises: Promise<any>[] = []
140 for (const pluginInfo of toLoad) {
141 const clientScript = pluginInfo.clientScript
143 if (this.loadedScripts[ clientScript.script ]) continue
145 promises.push(this.loadPlugin(pluginInfo))
147 this.loadedScripts[ clientScript.script ] = true
150 await Promise.all(promises)
152 this.pluginsLoaded[scope].next(true)
153 this.loadingScopes[scope] = false
155 console.error('Cannot load plugins by scope %s.', scope, err)
159 async runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
160 if (!this.hooks[hookName]) return Promise.resolve(result)
162 const hookType = getHookType(hookName)
164 for (const hook of this.hooks[hookName]) {
165 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
167 result = await internalRunHook(hook.handler, hookType, result, params, err => {
168 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
175 nameToNpmName (name: string, type: PluginType) {
176 const prefix = type === PluginType.PLUGIN
183 pluginTypeFromNpmName (npmName: string) {
184 return npmName.startsWith('peertube-plugin-')
189 private loadPlugin (pluginInfo: PluginInfo) {
190 const { plugin, clientScript } = pluginInfo
192 const registerHook = (options: RegisterClientHookOptions) => {
193 if (clientHookObject[options.target] !== true) {
194 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
198 if (!this.hooks[options.target]) this.hooks[options.target] = []
200 this.hooks[options.target].push({
203 target: options.target,
204 handler: options.handler,
205 priority: options.priority || 0
209 const peertubeHelpers = this.buildPeerTubeHelpers(pluginInfo)
211 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
213 return import(/* webpackIgnore: true */ clientScript.script)
214 .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
215 .then(() => this.sortHooksByPriority())
216 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
219 private buildScopeStruct () {
220 for (const plugin of this.plugins) {
221 this.addPlugin(plugin)
225 private sortHooksByPriority () {
226 for (const hookName of Object.keys(this.hooks)) {
227 this.hooks[hookName].sort((a, b) => {
228 return b.priority - a.priority
233 private buildPeerTubeHelpers (pluginInfo: PluginInfo) {
234 const { plugin } = pluginInfo
237 getBaseStaticRoute: () => {
238 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
239 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
243 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
244 const path = PluginService.BASE_PLUGIN_URL + '/' + npmName
246 return this.authHttp.get<PeerTubePlugin>(path)
248 map(p => p.settings),
249 catchError(res => this.restExtractor.handleError(res))
256 private getPluginPathPrefix (isTheme: boolean) {
257 return isTheme ? '/themes' : '/plugins'