1
0
Fork 0
peertube/server/controllers/api/server/follows.ts

173 lines
5.9 KiB
TypeScript
Raw Normal View History

2017-06-05 19:53:49 +00:00
import * as express from 'express'
import { UserRight } from '../../../../shared/models/users/user-right.enum'
import { getFormattedObjects } from '../../../helpers'
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'
2017-11-20 08:43:39 +00:00
import { asyncMiddleware, paginationValidator, removeFollowingValidator, setFollowersSort, setPagination } from '../../../middlewares'
import { authenticate } from '../../../middlewares/oauth'
2017-11-15 10:00:25 +00:00
import { setBodyHostsPort } from '../../../middlewares/servers'
import { setFollowingSort } from '../../../middlewares/sort'
import { ensureUserHasRight } from '../../../middlewares/user-right'
2017-11-20 08:43:39 +00:00
import { followValidator } from '../../../middlewares/validators/follows'
import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort'
2017-11-20 08:43:39 +00:00
import { AccountFollowInstance } from '../../../models/index'
import { sendFollow } from '../../../lib/index'
import { sendUndoFollow } from '../../../lib/activitypub/send/send-undo'
2017-11-21 12:43:29 +00:00
import { AccountInstance } from '../../../models/account/account-interface'
import { retryTransactionWrapper } from '../../../helpers/database-utils'
import { saveAccountAndServerIfNotExist } from '../../../lib/activitypub/account'
2017-11-22 09:29:55 +00:00
import { addFetchOutboxJob } from '../../../lib/activitypub/fetch'
2017-11-16 16:16:42 +00:00
const serverFollowsRouter = express.Router()
2017-11-16 16:16:42 +00:00
serverFollowsRouter.get('/following',
paginationValidator,
2017-11-13 16:39:41 +00:00
followingSortValidator,
setFollowingSort,
setPagination,
2017-11-13 16:39:41 +00:00
asyncMiddleware(listFollowing)
)
2017-11-17 14:20:42 +00:00
serverFollowsRouter.post('/following',
2017-11-14 08:11:43 +00:00
authenticate,
2017-11-16 16:16:42 +00:00
ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
2017-11-13 17:48:28 +00:00
followValidator,
setBodyHostsPort,
2017-11-21 12:43:29 +00:00
asyncMiddleware(followRetry)
2017-11-13 17:48:28 +00:00
)
2017-11-20 08:43:39 +00:00
serverFollowsRouter.delete('/following/:accountId',
authenticate,
ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW),
removeFollowingValidator,
asyncMiddleware(removeFollow)
)
2017-11-16 16:16:42 +00:00
serverFollowsRouter.get('/followers',
2017-11-13 16:39:41 +00:00
paginationValidator,
followersSortValidator,
setFollowersSort,
setPagination,
asyncMiddleware(listFollowers)
2017-05-15 20:22:03 +00:00
)
// ---------------------------------------------------------------------------
export {
2017-11-16 16:16:42 +00:00
serverFollowsRouter
2017-05-15 20:22:03 +00:00
}
// ---------------------------------------------------------------------------
2017-11-13 16:39:41 +00:00
async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) {
2017-11-16 16:16:42 +00:00
const serverAccount = await getServerAccount()
const resultList = await db.AccountFollow.listFollowingForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
2017-11-13 16:39:41 +00:00
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) {
2017-11-16 16:16:42 +00:00
const serverAccount = await getServerAccount()
const resultList = await db.AccountFollow.listFollowersForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort)
2017-10-25 09:55:06 +00:00
return res.json(getFormattedObjects(resultList.data, resultList.total))
2017-05-15 20:22:03 +00:00
}
2017-11-13 17:48:28 +00:00
2017-11-21 12:43:29 +00:00
async function followRetry (req: express.Request, res: express.Response, next: express.NextFunction) {
2017-11-13 17:48:28 +00:00
const hosts = req.body.hosts as string[]
const fromAccount = await getServerAccount()
2017-11-13 17:48:28 +00:00
2017-11-14 16:31:26 +00:00
const tasks: Promise<any>[] = []
const accountName = SERVER_ACCOUNT_NAME
2017-11-13 17:48:28 +00:00
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
2017-11-14 16:31:26 +00:00
const p = loadLocalOrGetAccountFromWebfinger(accountName, host)
.then(accountResult => {
let targetAccount = accountResult.account
2017-11-21 12:43:29 +00:00
const options = {
arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ],
errorMessage: 'Cannot follow with many retries.'
}
return retryTransactionWrapper(follow, options)
2017-11-13 17:48:28 +00:00
})
2017-11-14 16:31:26 +00:00
.catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err))
2017-11-13 17:48:28 +00:00
tasks.push(p)
}
2017-11-15 15:28:35 +00:00
// Don't make the client wait the tasks
Promise.all(tasks)
2017-11-21 12:43:29 +00:00
.catch(err => logger.error('Error in follow.', err))
2017-11-13 17:48:28 +00:00
return res.status(204).end()
}
2017-11-14 16:31:26 +00:00
2017-11-21 12:43:29 +00:00
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)
}
2017-11-22 09:29:55 +00:00
await addFetchOutboxJob(targetAccount, t)
2017-11-21 12:43:29 +00:00
})
} catch (err) {
// Reset target account
targetAccount.isNewRecord = !targetAlreadyInDB
throw err
}
}
2017-11-20 08:43:39 +00:00
async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) {
2017-11-21 12:43:29 +00:00
const follow: AccountFollowInstance = res.locals.follow
2017-11-20 08:43:39 +00:00
await db.sequelize.transaction(async t => {
2017-11-21 12:43:29 +00:00
await sendUndoFollow(follow, t)
await follow.destroy({ transaction: t })
2017-11-20 08:43:39 +00:00
})
return res.status(204).end()
}
2017-11-14 16:31:26 +00:00
async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) {
let loadedFromDB = true
let account = await db.Account.loadByNameAndHost(name, host)
if (!account) {
const nameWithDomain = name + '@' + host
account = await getAccountFromWebfinger(nameWithDomain)
loadedFromDB = false
}
return { account, loadedFromDB }
}