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

58 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-11-23 14:19:55 +01:00
import { ActivityLike } from '../../../../shared/models/activitypub/activity'
import { retryTransactionWrapper } from '../../../helpers/database-utils'
2017-11-23 14:19:55 +01:00
import { database as db } from '../../../initializers'
import { AccountInstance } from '../../../models/account/account-interface'
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
}
// ---------------------------------------------------------------------------
async function processLikeVideo (byAccount: AccountInstance, 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)
}
function createVideoLike (byAccount: AccountInstance, activity: ActivityLike) {
const videoUrl = activity.object
2017-11-23 14:19:55 +01:00
return db.sequelize.transaction(async t => {
const video = await db.Video.loadByUrlAndPopulateAccount(videoUrl)
if (!video) throw new Error('Unknown video ' + videoUrl)
const rate = {
type: 'like' as 'like',
videoId: video.id,
accountId: byAccount.id
}
const [ , created ] = await db.AccountVideoRate.findOrCreate({
where: rate,
defaults: rate,
transaction: t
2017-11-23 14:19:55 +01:00
})
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
})
}