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),
73 'video-channel': new ReplaySubject<boolean>(1)
76 private readonly peertubeHelpersFactory: PeertubeHelpersFactory
77 private readonly onFormFields: OnFormFields
78 private readonly onSettingsScripts: OnSettingsScripts
79 private readonly onClientRoute: OnClientRoute
81 constructor (options: {
82 peertubeHelpersFactory: PeertubeHelpersFactory
83 onFormFields?: OnFormFields
84 onSettingsScripts?: OnSettingsScripts
85 onClientRoute?: OnClientRoute
87 this.peertubeHelpersFactory = options.peertubeHelpersFactory
88 this.onFormFields = options.onFormFields
89 this.onSettingsScripts = options.onSettingsScripts
90 this.onClientRoute = options.onClientRoute
93 static getPluginPathPrefix (isTheme: boolean) {
94 return isTheme ? '/themes' : '/plugins'
97 static getExternalAuthHref (auth: RegisteredExternalAuthConfig) {
98 return environment.apiUrl + `/plugins/${auth.name}/${auth.version}/auth/${auth.authName}`
102 loadPluginsList (config: HTMLServerConfig) {
103 for (const plugin of config.plugin.registered) {
104 this.addPlugin(plugin)
108 async runHook<T> (hookName: ClientHookName, resultArg?: T | Promise<T>, params?: any) {
109 if (!this.hooks[hookName]) {
110 // eslint-disable-next-line no-return-await
111 return await resultArg
114 const hookType = getHookType(hookName)
116 let result = await resultArg
118 for (const hook of this.hooks[hookName]) {
119 logger.info(`Running hook ${hookName} of plugin ${hook.plugin.name}`)
121 result = await internalRunHook({
122 handler: hook.handler,
127 logger.error(`Cannot run hook ${hookName} of script ${hook.clientScript.script} of plugin ${hook.plugin.name}`, err)
135 ensurePluginsAreLoaded (scope: PluginClientScope) {
136 this.loadPluginsByScope(scope)
138 const obs = this.pluginsLoaded[scope].asObservable()
139 .pipe(first(), shareReplay())
141 return firstValueFrom(obs)
144 async reloadLoadedScopes () {
145 for (const scope of this.loadedScopes) {
146 await this.loadPluginsByScope(scope, true)
150 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
151 const pathPrefix = PluginsManager.getPluginPathPrefix(isTheme)
153 for (const key of Object.keys(plugin.clientScripts)) {
154 const clientScript = plugin.clientScripts[key]
156 for (const scope of clientScript.scopes) {
157 if (!this.scopes[scope]) this.scopes[scope] = []
159 this.scopes[scope].push({
162 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
163 scopes: clientScript.scopes
165 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
169 this.loadedScripts[clientScript.script] = false
174 removePlugin (plugin: ServerConfigPlugin) {
175 for (const key of Object.keys(this.scopes)) {
176 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
180 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
181 if (this.loadingScopes[scope]) return
182 if (!isReload && this.loadedScopes.includes(scope)) return
184 this.loadingScopes[scope] = true
186 debugLogger('Loading scope %s', scope)
189 if (!isReload) this.loadedScopes.push(scope)
191 const toLoad = this.scopes[scope]
192 if (!Array.isArray(toLoad)) {
193 this.loadingScopes[scope] = false
194 this.pluginsLoaded[scope].next(true)
196 debugLogger('Nothing to load for scope %s', scope)
200 const promises: Promise<any>[] = []
201 for (const pluginInfo of toLoad) {
202 const clientScript = pluginInfo.clientScript
204 if (this.loadedScripts[clientScript.script]) continue
206 promises.push(this.loadPlugin(pluginInfo))
208 this.loadedScripts[clientScript.script] = true
211 await Promise.all(promises)
213 this.pluginsLoaded[scope].next(true)
214 this.loadingScopes[scope] = false
216 debugLogger('Scope %s loaded', scope)
218 logger.error(`Cannot load plugins by scope ${scope}`, err)
222 private loadPlugin (pluginInfo: PluginInfo) {
223 const { plugin, clientScript } = pluginInfo
225 const registerHook = (options: RegisterClientHookOptions) => {
226 if (clientHookObject[options.target] !== true) {
227 logger.error(`Unknown hook ${options.target} of plugin ${plugin.name}. Skipping.`)
231 if (!this.hooks[options.target]) this.hooks[options.target] = []
233 this.hooks[options.target].push({
236 target: options.target,
237 handler: options.handler,
238 priority: options.priority || 0
242 const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => {
243 if (!this.onFormFields) {
244 throw new Error('Video field registration is not supported')
247 return this.onFormFields(pluginInfo, commonOptions, videoFormOptions)
250 const registerSettingsScript = (options: RegisterClientSettingsScriptOptions) => {
251 if (!this.onSettingsScripts) {
252 throw new Error('Registering settings script is not supported')
255 return this.onSettingsScripts(pluginInfo, options)
258 const registerClientRoute = (options: RegisterClientRouteOptions) => {
259 if (!this.onClientRoute) {
260 throw new Error('Registering client route is not supported')
263 return this.onClientRoute(options)
266 const peertubeHelpers = this.peertubeHelpersFactory(pluginInfo)
268 logger.info(`Loading script ${clientScript.script} of plugin ${plugin.name}`)
270 const absURL = (environment.apiUrl || window.location.origin) + clientScript.script
271 return dynamicImport(absURL)
272 .then((script: ClientScript) => {
273 return script.register({
276 registerSettingsScript,
281 .then(() => this.sortHooksByPriority())
282 .catch(err => logger.error(`Cannot import or register plugin ${pluginInfo.plugin.name}`, err))
285 private sortHooksByPriority () {
286 for (const hookName of Object.keys(this.hooks)) {
287 this.hooks[hookName].sort((a, b) => {
288 return b.priority - a.priority
298 PeertubeHelpersFactory,
303 // ---------------------------------------------------------------------------
305 async function dynamicImport (url: string) {
307 // eslint-disable-next-line no-new-func
308 return new Function(`return import('${url}')`)()
310 logger.info('Fallback to import polyfill')
312 return new Promise((resolve, reject) => {
313 const vector = '$importModule$' + Math.random().toString(32).slice(2)
314 const script = document.createElement('script')
316 const destructor = () => {
317 delete window[vector]
318 script.onerror = null
321 URL.revokeObjectURL(script.src)
326 script.type = 'module'
328 script.onerror = () => {
329 reject(new Error(`Failed to import: ${url}`))
332 script.onload = () => {
333 resolve(window[vector])
336 const loader = `import * as m from "${url}"; window.${vector} = m;` // export Module
337 const blob = new Blob([ loader ], { type: 'text/javascript' })
338 script.src = URL.createObjectURL(blob)
340 document.head.appendChild(script)