Add tests and fix bugs for video privacy
[oweals/peertube.git] / server / controllers / api / pods.ts
1 import * as express from 'express'
2
3 import { database as db } from '../../initializers/database'
4 import { logger, getFormattedObjects } from '../../helpers'
5 import {
6   makeFriends,
7   quitFriends,
8   removeFriend
9 } from '../../lib'
10 import {
11   authenticate,
12   ensureUserHasRight,
13   makeFriendsValidator,
14   setBodyHostsPort,
15   podRemoveValidator,
16   paginationValidator,
17   setPagination,
18   setPodsSort,
19   podsSortValidator,
20   asyncMiddleware
21 } from '../../middlewares'
22 import { PodInstance } from '../../models'
23 import { UserRight } from '../../../shared'
24
25 const podsRouter = express.Router()
26
27 podsRouter.get('/',
28   paginationValidator,
29   podsSortValidator,
30   setPodsSort,
31   setPagination,
32   asyncMiddleware(listPods)
33 )
34 podsRouter.post('/make-friends',
35   authenticate,
36   ensureUserHasRight(UserRight.MANAGE_PODS),
37   makeFriendsValidator,
38   setBodyHostsPort,
39   asyncMiddleware(makeFriendsController)
40 )
41 podsRouter.get('/quit-friends',
42   authenticate,
43   ensureUserHasRight(UserRight.MANAGE_PODS),
44   asyncMiddleware(quitFriendsController)
45 )
46 podsRouter.delete('/:id',
47   authenticate,
48   ensureUserHasRight(UserRight.MANAGE_PODS),
49   podRemoveValidator,
50   asyncMiddleware(removeFriendController)
51 )
52
53 // ---------------------------------------------------------------------------
54
55 export {
56   podsRouter
57 }
58
59 // ---------------------------------------------------------------------------
60
61 async function listPods (req: express.Request, res: express.Response, next: express.NextFunction) {
62   const resultList = await db.Pod.listForApi(req.query.start, req.query.count, req.query.sort)
63
64   return res.json(getFormattedObjects(resultList.data, resultList.total))
65 }
66
67 async function makeFriendsController (req: express.Request, res: express.Response, next: express.NextFunction) {
68   const hosts = req.body.hosts as string[]
69
70   // Don't wait the process that could be long
71   makeFriends(hosts)
72     .then(() => logger.info('Made friends!'))
73     .catch(err => logger.error('Could not make friends.', err))
74
75   return res.type('json').status(204).end()
76 }
77
78 async function quitFriendsController (req: express.Request, res: express.Response, next: express.NextFunction) {
79   await quitFriends()
80
81   return res.type('json').status(204).end()
82 }
83
84 async function removeFriendController (req: express.Request, res: express.Response, next: express.NextFunction) {
85   const pod = res.locals.pod as PodInstance
86
87   await removeFriend(pod)
88
89   return res.type('json').status(204).end()
90 }