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'
23 const serverFollowsRouter = express.Router()
25 serverFollowsRouter.get('/following',
27 followingSortValidator,
30 asyncMiddleware(listFollowing)
33 serverFollowsRouter.post('/following',
35 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
38 asyncMiddleware(followRetry)
41 serverFollowsRouter.delete('/following/:accountId',
43 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
44 removeFollowingValidator,
45 asyncMiddleware(removeFollow)
48 serverFollowsRouter.get('/followers',
50 followersSortValidator,
53 asyncMiddleware(listFollowers)
56 // ---------------------------------------------------------------------------
62 // ---------------------------------------------------------------------------
64 async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
65 const serverAccount = await getServerAccount()
66 const resultList = await db.AccountFollow.listFollowingForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
68 return res.json(getFormattedObjects(resultList.data, resultList.total))
71 async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) {
72 const serverAccount = await getServerAccount()
73 const resultList = await db.AccountFollow.listFollowersForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
75 return res.json(getFormattedObjects(resultList.data, resultList.total))
78 async function followRetry (req: express.Request, res: express.Response, next: express.NextFunction) {
79 const hosts = req.body.hosts as string[]
80 const fromAccount = await getServerAccount()
82 const tasks: Promise<any>[] = []
83 const accountName = SERVER_ACCOUNT_NAME
85 for (const host of hosts) {
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
90 const p = loadLocalOrGetAccountFromWebfinger(accountName, host)
91 .then(accountResult => {
92 let targetAccount = accountResult.account
95 arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ],
96 errorMessage: 'Cannot follow with many retries.'
99 return retryTransactionWrapper(follow, options)
101 .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
106 // Don't make the client wait the tasks
108 .catch(err => logger.error('Error in follow.', err))
110 return res.status(204).end()
113 async function follow (fromAccount: AccountInstance, targetAccount: AccountInstance, targetAlreadyInDB: boolean) {
115 await db.sequelize.transaction(async t => {
116 if (targetAlreadyInDB === false) {
117 await saveAccountAndServerIfNotExist(targetAccount, t)
120 const [ accountFollow ] = await db.AccountFollow.findOrCreate({
122 accountId: fromAccount.id,
123 targetAccountId: targetAccount.id
127 accountId: fromAccount.id,
128 targetAccountId: targetAccount.id
132 accountFollow.AccountFollowing = targetAccount
133 accountFollow.AccountFollower = fromAccount
135 // Send a notification to remote server
136 if (accountFollow.state === 'pending') {
137 await sendFollow(accountFollow, t)
141 // Reset target account
142 targetAccount.isNewRecord = !targetAlreadyInDB
147 async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
148 const follow: AccountFollowInstance = res.locals.follow
150 await db.sequelize.transaction(async t => {
151 await sendUndoFollow(follow, t)
152 await follow.destroy({ transaction: t })
155 return res.status(204).end()
158 async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
159 let loadedFromDB = true
160 let account = await db.Account.loadByNameAndHost(name, host)
163 const nameWithDomain = name + '@' + host
164 account = await getAccountFromWebfinger(nameWithDomain)
168 return { account, loadedFromDB }