aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/root-helpers/plugins.ts
blob: 011721761682ee2a388c87a15ed74903967adcd8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { getHookType, internalRunHook } from '@shared/core-utils/plugins/hooks'
import { ClientHookName, ClientScript, RegisterClientHookOptions, ServerConfigPlugin, PluginType, clientHookObject } from '../../../shared/models'
import { RegisterClientHelpers } from 'src/types/register-client-option.model'
import { ClientScript as ClientScriptModule } from '../types/client-script.model'
import { importModule } from './utils'

interface HookStructValue extends RegisterClientHookOptions {
  plugin: ServerConfigPlugin
  clientScript: ClientScript
}

type Hooks = { [ name: string ]: HookStructValue[] }

type PluginInfo = {
  plugin: ServerConfigPlugin
  clientScript: ClientScript
  pluginType: PluginType
  isTheme: boolean
}

async function runHook<T> (hooks: Hooks, hookName: ClientHookName, result?: T, params?: any) {
  if (!hooks[hookName]) return result

  const hookType = getHookType(hookName)

  for (const hook of hooks[hookName]) {
    console.log('Running hook %s of plugin %s.', hookName, hook.plugin.name)

    result = await internalRunHook(hook.handler, hookType, result, params, err => {
      console.error('Cannot run hook %s of script %s of plugin %s.', hookName, hook.clientScript.script, hook.plugin.name, err)
    })
  }

  return result
}

function loadPlugin (hooks: Hooks, pluginInfo: PluginInfo, peertubeHelpersFactory: (pluginInfo: PluginInfo) => RegisterClientHelpers) {
  const { plugin, clientScript } = pluginInfo

  const registerHook = (options: RegisterClientHookOptions) => {
    if (clientHookObject[options.target] !== true) {
      console.error('Unknown hook %s of plugin %s. Skipping.', options.target, plugin.name)
      return
    }

    if (!hooks[options.target]) hooks[options.target] = []

    hooks[options.target].push({
      plugin,
      clientScript,
      target: options.target,
      handler: options.handler,
      priority: options.priority || 0
    })
  }

  const peertubeHelpers = peertubeHelpersFactory(pluginInfo)

  console.log('Loading script %s of plugin %s.', clientScript.script, plugin.name)

  return importModule(clientScript.script)
    .then((script: ClientScriptModule) => script.register({ registerHook, peertubeHelpers }))
    .then(() => sortHooksByPriority(hooks))
    .catch(err => console.error('Cannot import or register plugin %s.', pluginInfo.plugin.name, err))
}

export {
  HookStructValue,
  Hooks,
  PluginInfo,
  loadPlugin,
  runHook
}

function sortHooksByPriority (hooks: Hooks) {
  for (const hookName of Object.keys(hooks)) {
    hooks[hookName].sort((a, b) => {
      return b.priority - a.priority
    })
  }
}