1 import * as express from 'express'
2 import { UserRight } from '../../../../shared/models/users'
3 import { getAccountFromWebfinger, getFormattedObjects, getServerAccount, logger, retryTransactionWrapper } from '../../../helpers'
4 import { sequelizeTypescript, SERVER_ACCOUNT_NAME } from '../../../initializers'
5 import { saveAccountAndServerIfNotExist } from '../../../lib/activitypub'
6 import { sendUndoFollow } from '../../../lib/activitypub/send'
7 import { sendFollow } from '../../../lib/index'
13 removeFollowingValidator,
18 } from '../../../middlewares'
19 import { followersSortValidator, followingSortValidator, followValidator } from '../../../middlewares/validators'
20 import { AccountModel } from '../../../models/account/account'
21 import { AccountFollowModel } from '../../../models/account/account-follow'
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 asyncMiddleware(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 AccountFollowModel.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 AccountFollowModel.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: AccountModel, targetAccount: AccountModel, targetAlreadyInDB: boolean) {
115 await sequelizeTypescript.transaction(async t => {
116 if (targetAlreadyInDB === false) {
117 await saveAccountAndServerIfNotExist(targetAccount, t)
120 const [ accountFollow ] = await AccountFollowModel.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: AccountFollowModel = res.locals.follow
150 await sequelizeTypescript.transaction(async t => {
151 if (follow.state === 'accepted') await sendUndoFollow(follow, t)
153 await follow.destroy({ transaction: t })
156 // Destroy the account that will destroy video channels, videos and video files too
157 // This could be long so don't wait this task
158 const following = follow.AccountFollowing
160 .catch(err => logger.error('Cannot destroy account that we do not follow anymore %s.', following.Actor.url, err))
162 return res.status(204).end()
165 async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
166 let loadedFromDB = true
167 let account = await AccountModel.loadByNameAndHost(name, host)
170 const nameWithDomain = name + '@' + host
171 account = await getAccountFromWebfinger(nameWithDomain)
175 return { account, loadedFromDB }