From ce548a10db3822c415b30ea0edb59e02a460734a Mon Sep 17 00:00:00 2001
From: Chocobozzz <florian.bigard@gmail.com>
Date: Mon, 13 Nov 2017 18:48:28 +0100
Subject: Send follow/accept

---
 server/controllers/api/pods.ts | 41 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)

(limited to 'server/controllers/api')

diff --git a/server/controllers/api/pods.ts b/server/controllers/api/pods.ts
index aa07b17f6..f662f1c03 100644
--- a/server/controllers/api/pods.ts
+++ b/server/controllers/api/pods.ts
@@ -1,10 +1,16 @@
+import * as Bluebird from 'bluebird'
 import * as express from 'express'
 import { getFormattedObjects } from '../../helpers'
+import { getOrCreateAccount } from '../../helpers/activitypub'
 import { getApplicationAccount } from '../../helpers/utils'
+import { REMOTE_SCHEME } from '../../initializers/constants'
 import { database as db } from '../../initializers/database'
 import { asyncMiddleware, paginationValidator, setFollowersSort, setPagination } from '../../middlewares'
+import { setBodyHostsPort } from '../../middlewares/pods'
 import { setFollowingSort } from '../../middlewares/sort'
+import { followValidator } from '../../middlewares/validators/pods'
 import { followersSortValidator, followingSortValidator } from '../../middlewares/validators/sort'
+import { sendFollow } from '../../lib/activitypub/send-request'
 
 const podsRouter = express.Router()
 
@@ -16,6 +22,12 @@ podsRouter.get('/following',
   asyncMiddleware(listFollowing)
 )
 
+podsRouter.post('/follow',
+  followValidator,
+  setBodyHostsPort,
+  asyncMiddleware(follow)
+)
+
 podsRouter.get('/followers',
   paginationValidator,
   followersSortValidator,
@@ -45,3 +57,32 @@ async function listFollowers (req: express.Request, res: express.Response, next:
 
   return res.json(getFormattedObjects(resultList.data, resultList.total))
 }
+
+async function follow (req: express.Request, res: express.Response, next: express.NextFunction) {
+  const hosts = req.body.hosts as string[]
+  const fromAccount = await getApplicationAccount()
+
+  const tasks: Bluebird<any>[] = []
+  for (const host of hosts) {
+    const url = REMOTE_SCHEME.HTTP + '://' + host
+    const targetAccount = await getOrCreateAccount(url)
+
+    // 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 = db.sequelize.transaction(async t => {
+      return db.AccountFollow.create({
+        accountId: fromAccount.id,
+        targetAccountId: targetAccount.id,
+        state: 'pending'
+      })
+      .then(() => sendFollow(fromAccount, targetAccount, t))
+    })
+
+    tasks.push(p)
+  }
+
+  await Promise.all(tasks)
+
+  return res.status(204).end()
+}
-- 
cgit v1.2.3