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