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

60 lines
1.9 KiB
TypeScript
Raw Normal View History

2017-12-12 17:53:50 +01:00
import { ActivityLike } from '../../../../shared/models/activitypub'
import { retryTransactionWrapper } from '../../../helpers'
import { sequelizeTypescript } from '../../../initializers'
import { AccountModel } from '../../../models/account/account'
import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
import { VideoModel } from '../../../models/video/video'
2017-11-23 14:19:55 +01:00
import { getOrCreateAccountAndServer } from '../account'
import { forwardActivity } from '../send/misc'
2017-11-23 14:19:55 +01:00
async function processLikeActivity (activity: ActivityLike) {
const account = await getOrCreateAccountAndServer(activity.actor)
return processLikeVideo(account, activity)
2017-11-23 14:19:55 +01:00
}
// ---------------------------------------------------------------------------
export {
processLikeActivity
}
// ---------------------------------------------------------------------------
2017-12-12 17:53:50 +01:00
async function processLikeVideo (byAccount: AccountModel, activity: ActivityLike) {
2017-11-23 14:19:55 +01:00
const options = {
arguments: [ byAccount, activity ],
2017-11-23 14:19:55 +01:00
errorMessage: 'Cannot like the video with many retries.'
}
return retryTransactionWrapper(createVideoLike, options)
}
2017-12-12 17:53:50 +01:00
function createVideoLike (byAccount: AccountModel, activity: ActivityLike) {
const videoUrl = activity.object
2017-12-12 17:53:50 +01:00
return sequelizeTypescript.transaction(async t => {
const video = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
2017-11-23 14:19:55 +01:00
if (!video) throw new Error('Unknown video ' + videoUrl)
const rate = {
type: 'like' as 'like',
videoId: video.id,
accountId: byAccount.id
}
2017-12-12 17:53:50 +01:00
const [ , created ] = await AccountVideoRateModel.findOrCreate({
2017-11-23 14:19:55 +01:00
where: rate,
defaults: rate,
transaction: t
2017-11-23 14:19:55 +01:00
})
2017-11-30 13:51:53 +01:00
if (created === true) await video.increment('likes', { transaction: t })
2017-11-23 14:19:55 +01:00
if (video.isOwned() && created === true) {
// Don't resend the activity to the sender
const exceptions = [ byAccount ]
await forwardActivity(activity, t, exceptions)
}
2017-11-23 14:19:55 +01:00
})
}