]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/controllers/api/server/follows.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / server / follows.ts
index 497edb8eb0e9b5ffeb26b343b0bd24ff651c5f0b..c69de21fbfd3b33dbfe238180aca6a258668847a 100644 (file)
@@ -1,32 +1,40 @@
 import * as express from 'express'
 import { UserRight } from '../../../../shared/models/users'
-import { getAccountFromWebfinger, getFormattedObjects, getServerAccount, logger, retryTransactionWrapper } from '../../../helpers'
-import { sequelizeTypescript, SERVER_ACCOUNT_NAME } from '../../../initializers'
-import { saveAccountAndServerIfNotExist } from '../../../lib/activitypub'
-import { sendUndoFollow } from '../../../lib/activitypub/send'
-import { sendFollow } from '../../../lib/index'
+import { logger } from '../../../helpers/logger'
+import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
+import { SERVER_ACTOR_NAME } from '../../../initializers/constants'
+import { sendAccept, sendReject, sendUndoFollow } from '../../../lib/activitypub/send'
 import {
   asyncMiddleware,
   authenticate,
   ensureUserHasRight,
   paginationValidator,
-  removeFollowingValidator,
   setBodyHostsPort,
-  setFollowersSort,
-  setFollowingSort,
-  setPagination
+  setDefaultPagination,
+  setDefaultSort
 } from '../../../middlewares'
-import { followersSortValidator, followingSortValidator, followValidator } from '../../../middlewares/validators'
-import { AccountModel } from '../../../models/account/account'
-import { AccountFollowModel } from '../../../models/account/account-follow'
+import {
+  acceptOrRejectFollowerValidator,
+  followersSortValidator,
+  followingSortValidator,
+  followValidator,
+  getFollowerValidator,
+  removeFollowingValidator,
+  listFollowsValidator
+} from '../../../middlewares/validators'
+import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
+import { JobQueue } from '../../../lib/job-queue'
+import { removeRedundanciesOfServer } from '../../../lib/redundancy'
+import { sequelizeTypescript } from '../../../initializers/database'
+import { autoFollowBackIfNeeded } from '../../../lib/activitypub/follow'
 
 const serverFollowsRouter = express.Router()
-
 serverFollowsRouter.get('/following',
+  listFollowsValidator,
   paginationValidator,
   followingSortValidator,
-  setFollowingSort,
-  setPagination,
+  setDefaultSort,
+  setDefaultPagination,
   asyncMiddleware(listFollowing)
 )
 
@@ -35,24 +43,48 @@ serverFollowsRouter.post('/following',
   ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
   followValidator,
   setBodyHostsPort,
-  asyncMiddleware(followRetry)
+  asyncMiddleware(followInstance)
 )
 
-serverFollowsRouter.delete('/following/:accountId',
+serverFollowsRouter.delete('/following/:host',
   authenticate,
   ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
   asyncMiddleware(removeFollowingValidator),
-  asyncMiddleware(removeFollow)
+  asyncMiddleware(removeFollowing)
 )
 
 serverFollowsRouter.get('/followers',
+  listFollowsValidator,
   paginationValidator,
   followersSortValidator,
-  setFollowersSort,
-  setPagination,
+  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 {
@@ -61,116 +93,94 @@ export {
 
 // ---------------------------------------------------------------------------
 
-async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
-  const serverAccount = await getServerAccount()
-  const resultList = await AccountFollowModel.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.listFollowingForApi({
+    id: 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 AccountFollowModel.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({
+    actorId: 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) {
+async function followInstance (req: express.Request, res: express.Response) {
   const hosts = req.body.hosts as string[]
-  const fromAccount = await getServerAccount()
-
-  const tasks: Promise<any>[] = []
-  const accountName = SERVER_ACCOUNT_NAME
+  const follower = await getServerActor()
 
   for (const host of hosts) {
-
-    // 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
-
-        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))
-
-    tasks.push(p)
+    const payload = {
+      host,
+      name: SERVER_ACTOR_NAME,
+      followerActorId: follower.id
+    }
+
+    JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
+      .catch(err => logger.error('Cannot create follow job for %s.', host, err))
   }
 
-  // Don't make the client wait the tasks
-  Promise.all(tasks)
-    .catch(err => logger.error('Error in follow.', err))
-
   return res.status(204).end()
 }
 
-async function follow (fromAccount: AccountModel, targetAccount: AccountModel, targetAlreadyInDB: boolean) {
-  try {
-    await sequelizeTypescript.transaction(async t => {
-      if (targetAlreadyInDB === false) {
-        await saveAccountAndServerIfNotExist(targetAccount, t)
-      }
-
-      const [ accountFollow ] = await AccountFollowModel.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: AccountFollowModel = res.locals.follow
+async function removeFollowing (req: express.Request, res: express.Response) {
+  const follow = res.locals.follow
 
   await sequelizeTypescript.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.Actor.url, err))
+  return res.status(204).end()
+}
+
+async function removeOrRejectFollower (req: express.Request, res: express.Response) {
+  const follow = res.locals.follow
+
+  await sendReject(follow.ActorFollower, follow.ActorFollowing)
+
+  await follow.destroy()
 
   return res.status(204).end()
 }
 
-async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
-  let loadedFromDB = true
-  let account = await AccountModel.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
-  }
+  await sendAccept(follow)
+
+  follow.state = 'accepted'
+  await follow.save()
 
-  return { account, loadedFromDB }
+  await autoFollowBackIfNeeded(follow)
+
+  return res.status(204).end()
 }