1 import { ActivityCreate, ActivityDislike } from '../../../../shared'
2 import { DislikeObject } from '../../../../shared/models/activitypub/objects'
3 import { retryTransactionWrapper } from '../../../helpers/database-utils'
4 import { sequelizeTypescript } from '../../../initializers/database'
5 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
6 import { APProcessorOptions } from '../../../types/activitypub-processor.model'
7 import { MActorSignature } from '../../../types/models'
8 import { forwardVideoRelatedActivity } from '../send/utils'
9 import { getOrCreateVideoAndAccountAndChannel } from '../videos'
11 async function processDislikeActivity (options: APProcessorOptions<ActivityCreate | ActivityDislike>) {
12 const { activity, byActor } = options
13 return retryTransactionWrapper(processDislike, activity, byActor)
16 // ---------------------------------------------------------------------------
19 processDislikeActivity
22 // ---------------------------------------------------------------------------
24 async function processDislike (activity: ActivityCreate | ActivityDislike, byActor: MActorSignature) {
25 const dislikeObject = activity.type === 'Dislike'
27 : (activity.object as DislikeObject).object
29 const byAccount = byActor.Account
31 if (!byAccount) throw new Error('Cannot create dislike with the non account actor ' + byActor.url)
33 const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: dislikeObject })
35 return sequelizeTypescript.transaction(async t => {
36 const existingRate = await AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, activity.id, t)
37 if (existingRate && existingRate.type === 'dislike') return
39 await video.increment('dislikes', { transaction: t })
41 if (existingRate && existingRate.type === 'like') {
42 await video.decrement('likes', { transaction: t })
45 const rate = existingRate || new AccountVideoRateModel()
47 rate.videoId = video.id
48 rate.accountId = byAccount.id
49 rate.url = activity.id
51 await rate.save({ transaction: t })
53 if (video.isOwned()) {
54 // Don't resend the activity to the sender
55 const exceptions = [ byActor ]
57 await forwardVideoRelatedActivity(activity, t, exceptions, video)