import * as express from 'express'
import { UserRight } from '../../../../shared/models/users/user-right.enum'
import { getFormattedObjects } from '../../../helpers'
+import { retryTransactionWrapper } from '../../../helpers/database-utils'
import { logger } from '../../../helpers/logger'
import { getServerAccount } from '../../../helpers/utils'
import { getAccountFromWebfinger } from '../../../helpers/webfinger'
import { SERVER_ACCOUNT_NAME } from '../../../initializers/constants'
import { database as db } from '../../../initializers/database'
-import { sendFollow } from '../../../lib/activitypub/send-request'
-import { asyncMiddleware, paginationValidator, setFollowersSort, setPagination } from '../../../middlewares'
+import { saveAccountAndServerIfNotExist } from '../../../lib/activitypub/account'
+import { sendUndoFollow } from '../../../lib/activitypub/send/send-undo'
+import { sendFollow } from '../../../lib/index'
+import { asyncMiddleware, paginationValidator, removeFollowingValidator, setFollowersSort, setPagination } from '../../../middlewares'
import { authenticate } from '../../../middlewares/oauth'
import { setBodyHostsPort } from '../../../middlewares/servers'
import { setFollowingSort } from '../../../middlewares/sort'
import { ensureUserHasRight } from '../../../middlewares/user-right'
-import { followValidator } from '../../../middlewares/validators/servers'
+import { followValidator } from '../../../middlewares/validators/follows'
import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort'
+import { AccountInstance } from '../../../models/account/account-interface'
+import { AccountFollowInstance } from '../../../models/index'
const serverFollowsRouter = express.Router()
ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
followValidator,
setBodyHostsPort,
- asyncMiddleware(follow)
+ asyncMiddleware(followRetry)
+)
+
+serverFollowsRouter.delete('/following/:accountId',
+ authenticate,
+ ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
+ removeFollowingValidator,
+ asyncMiddleware(removeFollow)
)
serverFollowsRouter.get('/followers',
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
-async function follow (req: express.Request, res: express.Response, next: express.NextFunction) {
+async function followRetry (req: express.Request, res: express.Response, next: express.NextFunction) {
const hosts = req.body.hosts as string[]
const fromAccount = await getServerAccount()
.then(accountResult => {
let targetAccount = accountResult.account
- return db.sequelize.transaction(async t => {
- if (accountResult.loadedFromDB === false) {
- targetAccount = await targetAccount.save({ transaction: t })
- }
-
- const [ accountFollow ] = await db.AccountFollow.findOrCreate({
- where: {
- accountId: fromAccount.id,
- targetAccountId: targetAccount.id
- },
- defaults: {
- state: 'pending',
- accountId: fromAccount.id,
- targetAccountId: targetAccount.id
- },
- transaction: t
- })
-
- // Send a notification to remote server
- if (accountFollow.state === 'pending') {
- await sendFollow(fromAccount, targetAccount, t)
- }
- })
+ const options = {
+ arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ],
+ errorMessage: 'Cannot follow with many retries.'
+ }
+
+ return retryTransactionWrapper(follow, options)
})
.catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
// Don't make the client wait the tasks
Promise.all(tasks)
- .catch(err => {
- logger.error('Error in follow.', err)
+ .catch(err => logger.error('Error in follow.', err))
+
+ return res.status(204).end()
+}
+
+async function follow (fromAccount: AccountInstance, targetAccount: AccountInstance, targetAlreadyInDB: boolean) {
+ try {
+ await db.sequelize.transaction(async t => {
+ if (targetAlreadyInDB === false) {
+ await saveAccountAndServerIfNotExist(targetAccount, t)
+ }
+
+ const [ accountFollow ] = await db.AccountFollow.findOrCreate({
+ where: {
+ accountId: fromAccount.id,
+ targetAccountId: targetAccount.id
+ },
+ defaults: {
+ state: 'pending',
+ accountId: fromAccount.id,
+ targetAccountId: targetAccount.id
+ },
+ transaction: t
+ })
+ accountFollow.AccountFollowing = targetAccount
+ accountFollow.AccountFollower = fromAccount
+
+ // Send a notification to remote server
+ if (accountFollow.state === 'pending') {
+ await sendFollow(accountFollow, t)
+ }
})
+ } catch (err) {
+ // Reset target account
+ targetAccount.isNewRecord = !targetAlreadyInDB
+ throw err
+ }
+}
+
+async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
+ const follow: AccountFollowInstance = res.locals.follow
+
+ await db.sequelize.transaction(async t => {
+ await sendUndoFollow(follow, t)
+ await follow.destroy({ transaction: t })
+ })
return res.status(204).end()
}