-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 express from 'express'
+import { getServerActor } from '@server/models/application/application'
+import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
+import { UserRight } from '../../../../shared/models/users'
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 { 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/follows'
-import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort'
-import { AccountInstance } from '../../../models/account/account-interface'
-import { AccountFollowInstance } from '../../../models/index'
+import { getFormattedObjects } from '../../../helpers/utils'
+import { SERVER_ACTOR_NAME } from '../../../initializers/constants'
+import { sequelizeTypescript } from '../../../initializers/database'
+import { autoFollowBackIfNeeded } from '../../../lib/activitypub/follow'
+import { sendAccept, sendReject, sendUndoFollow } from '../../../lib/activitypub/send'
+import { JobQueue } from '../../../lib/job-queue'
+import { removeRedundanciesOfServer } from '../../../lib/redundancy'
+import {
+ asyncMiddleware,
+ authenticate,
+ ensureUserHasRight,
+ paginationValidator,
+ setBodyHostsPort,
+ setDefaultPagination,
+ setDefaultSort
+} from '../../../middlewares'
+import {
+ acceptOrRejectFollowerValidator,
+ instanceFollowersSortValidator,
+ instanceFollowingSortValidator,
+ followValidator,
+ getFollowerValidator,
+ listFollowsValidator,
+ removeFollowingValidator
+} from '../../../middlewares/validators'
+import { ActorFollowModel } from '../../../models/actor/actor-follow'
+import { ServerFollowCreate } from '@shared/models'
const serverFollowsRouter = express.Router()
-
serverFollowsRouter.get('/following',
+ listFollowsValidator,
paginationValidator,
- followingSortValidator,
- setFollowingSort,
- setPagination,
+ instanceFollowingSortValidator,
+ setDefaultSort,
+ setDefaultPagination,
asyncMiddleware(listFollowing)
)
ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
followValidator,
setBodyHostsPort,
- asyncMiddleware(followRetry)
+ asyncMiddleware(addFollow)
)
-serverFollowsRouter.delete('/following/:accountId',
+serverFollowsRouter.delete('/following/:hostOrHandle',
authenticate,
ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
- removeFollowingValidator,
- asyncMiddleware(removeFollow)
+ asyncMiddleware(removeFollowingValidator),
+ asyncMiddleware(removeFollowing)
)
serverFollowsRouter.get('/followers',
+ listFollowsValidator,
paginationValidator,
- followersSortValidator,
- setFollowersSort,
- setPagination,
+ instanceFollowersSortValidator,
+ setDefaultSort,
+ setDefaultPagination,
asyncMiddleware(listFollowers)
)
+serverFollowsRouter.delete('/followers/:nameWithHost',
+ authenticate,
+ ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
+ asyncMiddleware(getFollowerValidator),
+ asyncMiddleware(removeOrRejectFollower)
+)
+
+serverFollowsRouter.post('/followers/:nameWithHost/reject',
+ authenticate,
+ ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
+ asyncMiddleware(getFollowerValidator),
+ acceptOrRejectFollowerValidator,
+ asyncMiddleware(removeOrRejectFollower)
+)
+
+serverFollowsRouter.post('/followers/:nameWithHost/accept',
+ authenticate,
+ ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
+ asyncMiddleware(getFollowerValidator),
+ acceptOrRejectFollowerValidator,
+ asyncMiddleware(acceptFollower)
+)
+
// ---------------------------------------------------------------------------
export {
// ---------------------------------------------------------------------------
-async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
- const serverAccount = await getServerAccount()
- const resultList = await db.AccountFollow.listFollowingForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
+async function listFollowing (req: express.Request, res: express.Response) {
+ const serverActor = await getServerActor()
+ const resultList = await ActorFollowModel.listInstanceFollowingForApi({
+ followerId: serverActor.id,
+ start: req.query.start,
+ count: req.query.count,
+ sort: req.query.sort,
+ search: req.query.search,
+ actorType: req.query.actorType,
+ state: req.query.state
+ })
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
-async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) {
- const serverAccount = await getServerAccount()
- const resultList = await db.AccountFollow.listFollowersForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
+async function listFollowers (req: express.Request, res: express.Response) {
+ const serverActor = await getServerActor()
+ const resultList = await ActorFollowModel.listFollowersForApi({
+ actorIds: [ serverActor.id ],
+ start: req.query.start,
+ count: req.query.count,
+ sort: req.query.sort,
+ search: req.query.search,
+ actorType: req.query.actorType,
+ state: req.query.state
+ })
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
-async function followRetry (req: express.Request, res: express.Response, next: express.NextFunction) {
- const hosts = req.body.hosts as string[]
- const fromAccount = await getServerAccount()
-
- const tasks: Promise<any>[] = []
- const accountName = SERVER_ACCOUNT_NAME
+async function addFollow (req: express.Request, res: express.Response) {
+ const { hosts, handles } = req.body as ServerFollowCreate
+ const follower = await getServerActor()
for (const host of hosts) {
+ const payload = {
+ host,
+ name: SERVER_ACTOR_NAME,
+ followerActorId: follower.id
+ }
- // We process each host in a specific transaction
- // First, we add the follow request in the database
- // Then we send the follow request to other account
- const p = loadLocalOrGetAccountFromWebfinger(accountName, host)
- .then(accountResult => {
- let targetAccount = accountResult.account
+ JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
+ }
- const options = {
- arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ],
- errorMessage: 'Cannot follow with many retries.'
- }
+ for (const handle of handles) {
+ const [ name, host ] = handle.split('@')
- return retryTransactionWrapper(follow, options)
- })
- .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
+ const payload = {
+ host,
+ name,
+ followerActorId: follower.id
+ }
- tasks.push(p)
+ JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
}
- // Don't make the client wait the tasks
- Promise.all(tasks)
- .catch(err => logger.error('Error in follow.', err))
-
- return res.status(204).end()
+ return res.status(HttpStatusCode.NO_CONTENT_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 removeFollowing (req: express.Request, res: express.Response) {
+ const follow = res.locals.follow
-async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
- const follow: AccountFollowInstance = res.locals.follow
+ await sequelizeTypescript.transaction(async t => {
+ if (follow.state === 'accepted') sendUndoFollow(follow, t)
- await db.sequelize.transaction(async t => {
- if (follow.state === 'accepted') await sendUndoFollow(follow, t)
+ // Disable redundancy on unfollowed instances
+ const server = follow.ActorFollowing.Server
+ server.redundancyAllowed = false
+ await server.save({ transaction: t })
+
+ // Async, could be long
+ removeRedundanciesOfServer(server.id)
+ .catch(err => logger.error('Cannot remove redundancy of %s.', server.host, err))
await follow.destroy({ transaction: t })
})
- // Destroy the account that will destroy video channels, videos and video files too
- // This could be long so don't wait this task
- const following = follow.AccountFollowing
- following.destroy()
- .catch(err => logger.error('Cannot destroy account that we do not follow anymore %s.', following.url, err))
+ return res.status(HttpStatusCode.NO_CONTENT_204).end()
+}
+
+async function removeOrRejectFollower (req: express.Request, res: express.Response) {
+ const follow = res.locals.follow
+
+ await sendReject(follow.url, follow.ActorFollower, follow.ActorFollowing)
- return res.status(204).end()
+ await follow.destroy()
+
+ return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
-async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
- let loadedFromDB = true
- let account = await db.Account.loadByNameAndHost(name, host)
+async function acceptFollower (req: express.Request, res: express.Response) {
+ const follow = res.locals.follow
- if (!account) {
- const nameWithDomain = name + '@' + host
- account = await getAccountFromWebfinger(nameWithDomain)
- loadedFromDB = false
- }
+ sendAccept(follow)
+
+ follow.state = 'accepted'
+ await follow.save()
+
+ await autoFollowBackIfNeeded(follow)
- return { account, loadedFromDB }
+ return res.status(HttpStatusCode.NO_CONTENT_204).end()
}