]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/server/follows.ts
Fix margin issue when seeking video
[github/Chocobozzz/PeerTube.git] / server / controllers / api / server / follows.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
51548b31
C
2import { UserRight } from '../../../../shared/models/users/user-right.enum'
3import { getFormattedObjects } from '../../../helpers'
4import { logger } from '../../../helpers/logger'
efc32059 5import { getServerAccount } from '../../../helpers/utils'
51548b31
C
6import { getAccountFromWebfinger } from '../../../helpers/webfinger'
7import { SERVER_ACCOUNT_NAME } from '../../../initializers/constants'
8import { database as db } from '../../../initializers/database'
54141398 9import { asyncMiddleware, paginationValidator, removeFollowingValidator, setFollowersSort, setPagination } from '../../../middlewares'
51548b31 10import { authenticate } from '../../../middlewares/oauth'
60862425 11import { setBodyHostsPort } from '../../../middlewares/servers'
51548b31
C
12import { setFollowingSort } from '../../../middlewares/sort'
13import { ensureUserHasRight } from '../../../middlewares/user-right'
54141398 14import { followValidator } from '../../../middlewares/validators/follows'
51548b31 15import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort'
54141398
C
16import { AccountFollowInstance } from '../../../models/index'
17import { sendFollow } from '../../../lib/index'
18import { sendUndoFollow } from '../../../lib/activitypub/send/send-undo'
51548b31 19
4610bc5b 20const serverFollowsRouter = express.Router()
51548b31 21
4610bc5b 22serverFollowsRouter.get('/following',
8a02bd04 23 paginationValidator,
7a7724e6
C
24 followingSortValidator,
25 setFollowingSort,
8a02bd04 26 setPagination,
7a7724e6
C
27 asyncMiddleware(listFollowing)
28)
29
9a27cdc2 30serverFollowsRouter.post('/following',
8e696487 31 authenticate,
4610bc5b 32 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
ce548a10
C
33 followValidator,
34 setBodyHostsPort,
35 asyncMiddleware(follow)
36)
37
54141398
C
38serverFollowsRouter.delete('/following/:accountId',
39 authenticate,
40 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
41 removeFollowingValidator,
42 asyncMiddleware(removeFollow)
43)
44
4610bc5b 45serverFollowsRouter.get('/followers',
7a7724e6
C
46 paginationValidator,
47 followersSortValidator,
48 setFollowersSort,
49 setPagination,
50 asyncMiddleware(listFollowers)
65fcc311 51)
65fcc311
C
52
53// ---------------------------------------------------------------------------
54
55export {
4610bc5b 56 serverFollowsRouter
65fcc311
C
57}
58
59// ---------------------------------------------------------------------------
60
7a7724e6 61async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
4610bc5b
C
62 const serverAccount = await getServerAccount()
63 const resultList = await db.AccountFollow.listFollowingForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
7a7724e6
C
64
65 return res.json(getFormattedObjects(resultList.data, resultList.total))
66}
67
68async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) {
4610bc5b
C
69 const serverAccount = await getServerAccount()
70 const resultList = await db.AccountFollow.listFollowersForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
eb080476
C
71
72 return res.json(getFormattedObjects(resultList.data, resultList.total))
65fcc311 73}
ce548a10
C
74
75async function follow (req: express.Request, res: express.Response, next: express.NextFunction) {
76 const hosts = req.body.hosts as string[]
efc32059 77 const fromAccount = await getServerAccount()
ce548a10 78
350e31d6
C
79 const tasks: Promise<any>[] = []
80 const accountName = SERVER_ACCOUNT_NAME
81
ce548a10 82 for (const host of hosts) {
ce548a10
C
83
84 // We process each host in a specific transaction
85 // First, we add the follow request in the database
86 // Then we send the follow request to other account
350e31d6
C
87 const p = loadLocalOrGetAccountFromWebfinger(accountName, host)
88 .then(accountResult => {
89 let targetAccount = accountResult.account
90
91 return db.sequelize.transaction(async t => {
92 if (accountResult.loadedFromDB === false) {
93 targetAccount = await targetAccount.save({ transaction: t })
94 }
95
96 const [ accountFollow ] = await db.AccountFollow.findOrCreate({
97 where: {
98 accountId: fromAccount.id,
99 targetAccountId: targetAccount.id
100 },
101 defaults: {
102 state: 'pending',
103 accountId: fromAccount.id,
104 targetAccountId: targetAccount.id
105 },
106 transaction: t
107 })
54141398
C
108 accountFollow.AccountFollowing = targetAccount
109 accountFollow.AccountFollower = fromAccount
350e31d6
C
110
111 // Send a notification to remote server
112 if (accountFollow.state === 'pending') {
54141398 113 await sendFollow(accountFollow, t)
350e31d6
C
114 }
115 })
ce548a10 116 })
350e31d6 117 .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
ce548a10
C
118
119 tasks.push(p)
120 }
121
8e10cf1a
C
122 // Don't make the client wait the tasks
123 Promise.all(tasks)
124 .catch(err => {
125 logger.error('Error in follow.', err)
126 })
ce548a10
C
127
128 return res.status(204).end()
129}
350e31d6 130
54141398
C
131async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
132 const following: AccountFollowInstance = res.locals.following
133
134 await db.sequelize.transaction(async t => {
135 await sendUndoFollow(following, t)
136 await following.destroy({ transaction: t })
137 })
138
139 return res.status(204).end()
140}
141
350e31d6
C
142async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
143 let loadedFromDB = true
144 let account = await db.Account.loadByNameAndHost(name, host)
145
146 if (!account) {
147 const nameWithDomain = name + '@' + host
148 account = await getAccountFromWebfinger(nameWithDomain)
149 loadedFromDB = false
150 }
151
152 return { account, loadedFromDB }
153}