1 /* eslint-disable @typescript-eslint/no-implied-eval */
2 import * as debug from 'debug'
3 import { firstValueFrom, ReplaySubject } from 'rxjs'
4 import { first, shareReplay } from 'rxjs/operators'
5 import { RegisterClientHelpers } from 'src/types/register-client-option.model'
6 import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
14 RegisterClientFormFieldOptions,
15 RegisterClientHookOptions,
16 RegisterClientRouteOptions,
17 RegisterClientSettingsScriptOptions,
18 RegisterClientVideoFieldOptions,
19 RegisteredExternalAuthConfig,
21 } from '@shared/models'
22 import { environment } from '../environments/environment'
23 import { ClientScript } from '../types'
24 import { logger } from './logger'
26 interface HookStructValue extends RegisterClientHookOptions {
27 plugin: ServerConfigPlugin
28 clientScript: ClientScriptJSON
31 type Hooks = { [ name: string ]: HookStructValue[] }
34 plugin: ServerConfigPlugin
35 clientScript: ClientScriptJSON
36 pluginType: PluginType
40 type PeertubeHelpersFactory = (pluginInfo: PluginInfo) => RegisterClientHelpers
43 pluginInfo: PluginInfo,
44 options: RegisterClientFormFieldOptions,
45 videoFormOptions: RegisterClientVideoFieldOptions
48 type OnSettingsScripts = (pluginInfo: PluginInfo, options: RegisterClientSettingsScriptOptions) => void
50 type OnClientRoute = (options: RegisterClientRouteOptions) => void
52 const debugLogger = debug('peertube:plugins')
54 class PluginsManager {
55 private hooks: Hooks = {}
57 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
59 private loadedScripts: { [ script: string ]: boolean } = {}
60 private loadedScopes: PluginClientScope[] = []
61 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
63 private pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
64 common: new ReplaySubject<boolean>(1),
65 'admin-plugin': new ReplaySubject<boolean>(1),
66 search: new ReplaySubject<boolean>(1),
67 'video-watch': new ReplaySubject<boolean>(1),
68 signup: new ReplaySubject<boolean>(1),
69 login: new ReplaySubject<boolean>(1),
70 'video-edit': new ReplaySubject<boolean>(1),
71 embed: new ReplaySubject<boolean>(1),
72 'my-library': new ReplaySubject<boolean>(1)
75 private readonly peertubeHelpersFactory: PeertubeHelpersFactory
76 private readonly onFormFields: OnFormFields
77 private readonly onSettingsScripts: OnSettingsScripts
78 private readonly onClientRoute: OnClientRoute
80 constructor (options: {
81 peertubeHelpersFactory: PeertubeHelpersFactory
82 onFormFields?: OnFormFields
83 onSettingsScripts?: OnSettingsScripts
84 onClientRoute?: OnClientRoute
86 this.peertubeHelpersFactory = options.peertubeHelpersFactory
87 this.onFormFields = options.onFormFields
88 this.onSettingsScripts = options.onSettingsScripts
89 this.onClientRoute = options.onClientRoute
92 static getPluginPathPrefix (isTheme: boolean) {
93 return isTheme ? '/themes' : '/plugins'
96 static getExternalAuthHref (auth: RegisteredExternalAuthConfig) {
97 return environment.apiUrl + `/plugins/${auth.name}/${auth.version}/auth/${auth.authName}`
101 loadPluginsList (config: HTMLServerConfig) {
102 for (const plugin of config.plugin.registered) {
103 this.addPlugin(plugin)
107 async runHook<T> (hookName: ClientHookName, result?: T, params?: any) {
108 if (!this.hooks[hookName]) return result
110 const hookType = getHookType(hookName)
112 for (const hook of this.hooks[hookName]) {
113 logger.info(`Running hook ${hookName} of plugin ${hook.plugin.name}`)
115 result = await internalRunHook(hook.handler, hookType, result, params, err => {
116 logger.error(`Cannot run hook ${hookName} of script ${hook.clientScript.script} of plugin ${hook.plugin.name}`, err)
123 ensurePluginsAreLoaded (scope: PluginClientScope) {
124 this.loadPluginsByScope(scope)
126 const obs = this.pluginsLoaded[scope].asObservable()
127 .pipe(first(), shareReplay())
129 return firstValueFrom(obs)
132 async reloadLoadedScopes () {
133 for (const scope of this.loadedScopes) {
134 await this.loadPluginsByScope(scope, true)
138 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
139 const pathPrefix = PluginsManager.getPluginPathPrefix(isTheme)
141 for (const key of Object.keys(plugin.clientScripts)) {
142 const clientScript = plugin.clientScripts[key]
144 for (const scope of clientScript.scopes) {
145 if (!this.scopes[scope]) this.scopes[scope] = []
147 this.scopes[scope].push({
150 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
151 scopes: clientScript.scopes
153 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
157 this.loadedScripts[clientScript.script] = false
162 removePlugin (plugin: ServerConfigPlugin) {
163 for (const key of Object.keys(this.scopes)) {
164 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
168 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
169 if (this.loadingScopes[scope]) return
170 if (!isReload && this.loadedScopes.includes(scope)) return
172 this.loadingScopes[scope] = true
174 debugLogger('Loading scope %s', scope)
177 if (!isReload) this.loadedScopes.push(scope)
179 const toLoad = this.scopes[scope]
180 if (!Array.isArray(toLoad)) {
181 this.loadingScopes[scope] = false
182 this.pluginsLoaded[scope].next(true)
184 debugLogger('Nothing to load for scope %s', scope)
188 const promises: Promise<any>[] = []
189 for (const pluginInfo of toLoad) {
190 const clientScript = pluginInfo.clientScript
192 if (this.loadedScripts[clientScript.script]) continue
194 promises.push(this.loadPlugin(pluginInfo))
196 this.loadedScripts[clientScript.script] = true
199 await Promise.all(promises)
201 this.pluginsLoaded[scope].next(true)
202 this.loadingScopes[scope] = false
204 debugLogger('Scope %s loaded', scope)
206 logger.error(`Cannot load plugins by scope ${scope}`, err)
210 private loadPlugin (pluginInfo: PluginInfo) {
211 const { plugin, clientScript } = pluginInfo
213 const registerHook = (options: RegisterClientHookOptions) => {
214 if (clientHookObject[options.target] !== true) {
215 logger.error(`Unknown hook ${options.target} of plugin ${plugin.name}. Skipping.`)
219 if (!this.hooks[options.target]) this.hooks[options.target] = []
221 this.hooks[options.target].push({
224 target: options.target,
225 handler: options.handler,
226 priority: options.priority || 0
230 const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => {
231 if (!this.onFormFields) {
232 throw new Error('Video field registration is not supported')
235 return this.onFormFields(pluginInfo, commonOptions, videoFormOptions)
238 const registerSettingsScript = (options: RegisterClientSettingsScriptOptions) => {
239 if (!this.onSettingsScripts) {
240 throw new Error('Registering settings script is not supported')
243 return this.onSettingsScripts(pluginInfo, options)
246 const registerClientRoute = (options: RegisterClientRouteOptions) => {
247 if (!this.onClientRoute) {
248 throw new Error('Registering client route is not supported')
251 return this.onClientRoute(options)
254 const peertubeHelpers = this.peertubeHelpersFactory(pluginInfo)
256 logger.info(`Loading script ${clientScript.script} of plugin ${plugin.name}`)
258 const absURL = (environment.apiUrl || window.location.origin) + clientScript.script
259 return dynamicImport(absURL)
260 .then((script: ClientScript) => {
261 return script.register({
264 registerSettingsScript,
269 .then(() => this.sortHooksByPriority())
270 .catch(err => logger.error(`Cannot import or register plugin ${pluginInfo.plugin.name}`, err))
273 private sortHooksByPriority () {
274 for (const hookName of Object.keys(this.hooks)) {
275 this.hooks[hookName].sort((a, b) => {
276 return b.priority - a.priority
286 PeertubeHelpersFactory,
291 // ---------------------------------------------------------------------------
293 async function dynamicImport (url: string) {
295 // eslint-disable-next-line no-new-func
296 return new Function(`return import('${url}')`)()
298 logger.info('Fallback to import polyfill')
300 return new Promise((resolve, reject) => {
301 const vector = '$importModule$' + Math.random().toString(32).slice(2)
302 const script = document.createElement('script')
304 const destructor = () => {
305 delete window[vector]
306 script.onerror = null
309 URL.revokeObjectURL(script.src)
314 script.type = 'module'
316 script.onerror = () => {
317 reject(new Error(`Failed to import: ${url}`))
320 script.onload = () => {
321 resolve(window[vector])
324 const loader = `import * as m from "${url}"; window.${vector} = m;` // export Module
325 const blob = new Blob([ loader ], { type: 'text/javascript' })
326 script.src = URL.createObjectURL(blob)
328 document.head.appendChild(script)