1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import { getFormattedObjects } from '../../helpers'
4 import { getOrCreateAccount } from '../../helpers/activitypub'
5 import { getApplicationAccount } from '../../helpers/utils'
6 import { REMOTE_SCHEME } from '../../initializers/constants'
7 import { database as db } from '../../initializers/database'
8 import { asyncMiddleware, paginationValidator, setFollowersSort, setPagination } from '../../middlewares'
9 import { setBodyHostsPort } from '../../middlewares/pods'
10 import { setFollowingSort } from '../../middlewares/sort'
11 import { followValidator } from '../../middlewares/validators/pods'
12 import { followersSortValidator, followingSortValidator } from '../../middlewares/validators/sort'
13 import { sendFollow } from '../../lib/activitypub/send-request'
15 const podsRouter = express.Router()
17 podsRouter.get('/following',
19 followingSortValidator,
22 asyncMiddleware(listFollowing)
25 podsRouter.post('/follow',
28 asyncMiddleware(follow)
31 podsRouter.get('/followers',
33 followersSortValidator,
36 asyncMiddleware(listFollowers)
39 // ---------------------------------------------------------------------------
45 // ---------------------------------------------------------------------------
47 async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
48 const applicationAccount = await getApplicationAccount()
49 const resultList = await db.Account.listFollowingForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort)
51 return res.json(getFormattedObjects(resultList.data, resultList.total))
54 async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) {
55 const applicationAccount = await getApplicationAccount()
56 const resultList = await db.Account.listFollowersForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort)
58 return res.json(getFormattedObjects(resultList.data, resultList.total))
61 async function follow (req: express.Request, res: express.Response, next: express.NextFunction) {
62 const hosts = req.body.hosts as string[]
63 const fromAccount = await getApplicationAccount()
65 const tasks: Bluebird<any>[] = []
66 for (const host of hosts) {
67 const url = REMOTE_SCHEME.HTTP + '://' + host
68 const targetAccount = await getOrCreateAccount(url)
70 // We process each host in a specific transaction
71 // First, we add the follow request in the database
72 // Then we send the follow request to other account
73 const p = db.sequelize.transaction(async t => {
74 return db.AccountFollow.create({
75 accountId: fromAccount.id,
76 targetAccountId: targetAccount.id,
79 .then(() => sendFollow(fromAccount, targetAccount, t))
85 await Promise.all(tasks)
87 return res.status(204).end()