PeerTube/server/lib/activitypub/process/process-follow.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-12-12 17:53:50 +01:00
import { ActivityFollow } from '../../../../shared/models/activitypub'
import { logger, retryTransactionWrapper } from '../../../helpers'
import { sequelizeTypescript } from '../../../initializers'
import { AccountModel } from '../../../models/account/account'
import { AccountFollowModel } from '../../../models/account/account-follow'
2017-11-21 13:43:29 +01:00
import { getOrCreateAccountAndServer } from '../account'
2017-12-12 17:53:50 +01:00
import { sendAccept } from '../send'
2017-11-13 17:39:41 +01:00
async function processFollowActivity (activity: ActivityFollow) {
const activityObject = activity.object
2017-11-21 13:43:29 +01:00
const account = await getOrCreateAccountAndServer(activity.actor)
2017-11-13 17:39:41 +01:00
return processFollow(account, activityObject)
}
// ---------------------------------------------------------------------------
export {
processFollowActivity
}
// ---------------------------------------------------------------------------
2017-12-12 17:53:50 +01:00
function processFollow (account: AccountModel, targetAccountURL: string) {
2017-11-13 18:48:28 +01:00
const options = {
arguments: [ account, targetAccountURL ],
errorMessage: 'Cannot follow with many retries.'
}
2017-11-13 17:39:41 +01:00
2017-11-13 18:48:28 +01:00
return retryTransactionWrapper(follow, options)
}
2017-12-12 17:53:50 +01:00
async function follow (account: AccountModel, targetAccountURL: string) {
await sequelizeTypescript.transaction(async t => {
const targetAccount = await AccountModel.loadByUrl(targetAccountURL, t)
2017-11-13 18:48:28 +01:00
2017-11-20 09:43:39 +01:00
if (!targetAccount) throw new Error('Unknown account')
2017-11-13 18:48:28 +01:00
if (targetAccount.isOwned() === false) throw new Error('This is not a local account.')
2017-11-13 17:39:41 +01:00
2017-12-12 17:53:50 +01:00
const [ accountFollow ] = await AccountFollowModel.findOrCreate({
2017-11-14 17:31:26 +01:00
where: {
accountId: account.id,
targetAccountId: targetAccount.id
},
defaults: {
accountId: account.id,
targetAccountId: targetAccount.id,
state: 'accepted'
},
2017-11-13 18:48:28 +01:00
transaction: t
2017-11-14 17:31:26 +01:00
})
2017-11-22 16:25:03 +01:00
if (accountFollow.state !== 'accepted') {
accountFollow.state = 'accepted'
await accountFollow.save({ transaction: t })
}
2017-11-20 09:43:39 +01:00
accountFollow.AccountFollower = account
accountFollow.AccountFollowing = targetAccount
2017-11-13 18:48:28 +01:00
// Target sends to account he accepted the follow request
2017-11-20 09:43:39 +01:00
return sendAccept(accountFollow, t)
2017-11-13 17:39:41 +01:00
})
2017-11-13 18:48:28 +01:00
logger.info('Account uuid %s is followed by account %s.', account.url, targetAccountURL)
2017-11-13 17:39:41 +01:00
}