1 import { RegisterClientHelpers } from 'src/types/register-client-option.model'
2 import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
3 import { RegisterClientFormFieldOptions, RegisterClientVideoFieldOptions } from '@shared/models/plugins/register-client-form-field.model'
9 RegisterClientHookOptions,
11 } from '../../../shared/models'
12 import { ClientScript as ClientScriptModule } from '../types/client-script.model'
13 import { importModule } from './utils'
15 interface HookStructValue extends RegisterClientHookOptions {
16 plugin: ServerConfigPlugin
17 clientScript: ClientScript
20 type Hooks = { [ name: string ]: HookStructValue[] }
23 plugin: ServerConfigPlugin
24 clientScript: ClientScript
25 pluginType: PluginType
31 commonOptions: RegisterClientFormFieldOptions
32 videoFormOptions: RegisterClientVideoFieldOptions
36 async function runHook<T> (hooks: Hooks, hookName: ClientHookName, result?: T, params?: any) {
37 if (!hooks[hookName]) return result
39 const hookType = getHookType(hookName)
41 for (const hook of hooks[hookName]) {
42 console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)
44 result = await internalRunHook(hook.handler, hookType, result, params, err => {
45 console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
52 function loadPlugin (options: {
54 pluginInfo: PluginInfo
55 peertubeHelpersFactory: (pluginInfo: PluginInfo) => RegisterClientHelpers
56 formFields?: FormFields
58 const { hooks, pluginInfo, peertubeHelpersFactory, formFields } = options
59 const { plugin, clientScript } = pluginInfo
61 const registerHook = (options: RegisterClientHookOptions) => {
62 if (clientHookObject[options.target] !== true) {
63 console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
67 if (!hooks[options.target]) hooks[options.target] = []
69 hooks[options.target].push({
72 target: options.target,
73 handler: options.handler,
74 priority: options.priority || 0
78 const registerVideoField = (commonOptions: RegisterClientFormFieldOptions, videoFormOptions: RegisterClientVideoFieldOptions) => {
80 throw new Error('Video field registration is not supported')
83 formFields.video.push({
89 const peertubeHelpers = peertubeHelpersFactory(pluginInfo)
91 console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)
93 return importModule(clientScript.script)
94 .then((script: ClientScriptModule) => script.register({ registerHook, registerVideoField, peertubeHelpers }))
95 .then(() => sortHooksByPriority(hooks))
96 .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
108 function sortHooksByPriority (hooks: Hooks) {
109 for (const hookName of Object.keys(hooks)) {
110 hooks[hookName].sort((a, b) => {
111 return b.priority - a.priority