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'
24 const serverFollowsRouter = express.Router()
26 serverFollowsRouter.get('/following',
28 followingSortValidator,
31 asyncMiddleware(listFollowing)
34 serverFollowsRouter.post('/following',
36 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
39 asyncMiddleware(followRetry)
42 serverFollowsRouter.delete('/following/:accountId',
44 ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
45 removeFollowingValidator,
46 asyncMiddleware(removeFollow)
49 serverFollowsRouter.get('/followers',
51 followersSortValidator,
54 asyncMiddleware(listFollowers)
57 // ---------------------------------------------------------------------------
63 // ---------------------------------------------------------------------------
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)
69 return res.json(getFormattedObjects(resultList.data, resultList.total))
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)
76 return res.json(getFormattedObjects(resultList.data, resultList.total))
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()
83 const tasks: Promise<any>[] = []
84 const accountName = SERVER_ACCOUNT_NAME
86 for (const host of hosts) {
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
96 arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ],
97 errorMessage: 'Cannot follow with many retries.'
100 return retryTransactionWrapper(follow, options)
102 .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
107 // Don't make the client wait the tasks
109 .catch(err => logger.error('Error in follow.', err))
111 return res.status(204).end()
114 async function follow (fromAccount: AccountInstance, targetAccount: AccountInstance, targetAlreadyInDB: boolean) {
116 await db.sequelize.transaction(async t => {
117 if (targetAlreadyInDB === false) {
118 await saveAccountAndServerIfNotExist(targetAccount, t)
121 const [ accountFollow ] = await db.AccountFollow.findOrCreate({
123 accountId: fromAccount.id,
124 targetAccountId: targetAccount.id
128 accountId: fromAccount.id,
129 targetAccountId: targetAccount.id
133 accountFollow.AccountFollowing = targetAccount
134 accountFollow.AccountFollower = fromAccount
136 // Send a notification to remote server
137 if (accountFollow.state === 'pending') {
138 await sendFollow(accountFollow, t)
141 await addFetchOutboxJob(targetAccount, t)
144 // Reset target account
145 targetAccount.isNewRecord = !targetAlreadyInDB
150 async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
151 const follow: AccountFollowInstance = res.locals.follow
153 await db.sequelize.transaction(async t => {
154 await sendUndoFollow(follow, t)
155 await follow.destroy({ transaction: t })
158 return res.status(204).end()
161 async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
162 let loadedFromDB = true
163 let account = await db.Account.loadByNameAndHost(name, host)
166 const nameWithDomain = name + '@' + host
167 account = await getAccountFromWebfinger(nameWithDomain)
171 return { account, loadedFromDB }