Move to eslint
[oweals/peertube.git] / server / lib / plugins / plugin-index.ts
1 import { doRequest } from '../../helpers/requests'
2 import { CONFIG } from '../../initializers/config'
3 import {
4   PeertubePluginLatestVersionRequest,
5   PeertubePluginLatestVersionResponse
6 } from '../../../shared/models/plugins/peertube-plugin-latest-version.model'
7 import { PeertubePluginIndexList } from '../../../shared/models/plugins/peertube-plugin-index-list.model'
8 import { ResultList } from '../../../shared/models'
9 import { PeerTubePluginIndex } from '../../../shared/models/plugins/peertube-plugin-index.model'
10 import { PluginModel } from '../../models/server/plugin'
11 import { PluginManager } from './plugin-manager'
12 import { logger } from '../../helpers/logger'
13 import { PEERTUBE_VERSION } from '../../initializers/constants'
14
15 async function listAvailablePluginsFromIndex (options: PeertubePluginIndexList) {
16   const { start = 0, count = 20, search, sort = 'npmName', pluginType } = options
17
18   const qs: PeertubePluginIndexList = {
19     start,
20     count,
21     sort,
22     pluginType,
23     search,
24     currentPeerTubeEngine: options.currentPeerTubeEngine || PEERTUBE_VERSION
25   }
26
27   const uri = CONFIG.PLUGINS.INDEX.URL + '/api/v1/plugins'
28
29   try {
30     const { body } = await doRequest({ uri, qs, json: true })
31
32     logger.debug('Got result from PeerTube index.', { body })
33
34     addInstanceInformation(body)
35
36     return body as ResultList<PeerTubePluginIndex>
37   } catch (err) {
38     logger.error('Cannot list available plugins from index %s.', uri, { err })
39     return undefined
40   }
41 }
42
43 function addInstanceInformation (result: ResultList<PeerTubePluginIndex>) {
44   for (const d of result.data) {
45     d.installed = PluginManager.Instance.isRegistered(d.npmName)
46     d.name = PluginModel.normalizePluginName(d.npmName)
47   }
48
49   return result
50 }
51
52 async function getLatestPluginsVersion (npmNames: string[]): Promise<PeertubePluginLatestVersionResponse> {
53   const bodyRequest: PeertubePluginLatestVersionRequest = {
54     npmNames,
55     currentPeerTubeEngine: PEERTUBE_VERSION
56   }
57
58   const uri = CONFIG.PLUGINS.INDEX.URL + '/api/v1/plugins/latest-version'
59
60   const { body } = await doRequest({ uri, body: bodyRequest, json: true, method: 'POST' })
61
62   return body
63 }
64
65 export {
66   listAvailablePluginsFromIndex,
67   getLatestPluginsVersion
68 }