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