]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/activitypub/process/process-like.ts
Fix like/dislike federation
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / process / process-like.ts
index be86665e91ed700ed27fd36d491b5a065c5d4564..bba54a19b1e8de893b2efb960909afc75c166915 100644 (file)
@@ -5,8 +5,8 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat
 import { ActorModel } from '../../../models/activitypub/actor'
 import { forwardVideoRelatedActivity } from '../send/utils'
 import { getOrCreateVideoAndAccountAndChannel } from '../videos'
-import { immutableAssign } from '../../../../shared/utils'
-import { getVideoDislikeActivityPubUrl, getVideoLikeActivityPubUrl } from '../url'
+import { getVideoLikeActivityPubUrl } from '../url'
+import { getAPId } from '../../../helpers/activitypub'
 
 async function processLikeActivity (activity: ActivityLike, byActor: ActorModel) {
   return retryTransactionWrapper(processLikeVideo, byActor, activity)
@@ -21,7 +21,7 @@ export {
 // ---------------------------------------------------------------------------
 
 async function processLikeVideo (byActor: ActorModel, activity: ActivityLike) {
-  const videoUrl = activity.object
+  const videoUrl = getAPId(activity.object)
 
   const byAccount = byActor.Account
   if (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)
@@ -29,19 +29,26 @@ async function processLikeVideo (byActor: ActorModel, activity: ActivityLike) {
   const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: videoUrl })
 
   return sequelizeTypescript.transaction(async t => {
-    const rate = {
-      type: 'like' as 'like',
-      videoId: video.id,
-      accountId: byAccount.id
+    const url = getVideoLikeActivityPubUrl(byActor, video)
+
+    const existingRate = await AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, url)
+    if (existingRate && existingRate.type === 'like') return
+
+    if (existingRate && existingRate.type === 'dislike') {
+      await video.decrement('dislikes', { transaction: t })
     }
-    const [ , created ] = await AccountVideoRateModel.findOrCreate({
-      where: rate,
-      defaults: immutableAssign(rate, { url: getVideoLikeActivityPubUrl(byActor, video) }),
-      transaction: t
-    })
-    if (created === true) await video.increment('likes', { transaction: t })
-
-    if (video.isOwned() && created === true) {
+
+    await video.increment('likes', { transaction: t })
+
+    const rate = existingRate || new AccountVideoRateModel()
+    rate.type = 'like'
+    rate.videoId = video.id
+    rate.accountId = byAccount.id
+    rate.url = url
+
+    await rate.save({ transaction: t })
+
+    if (video.isOwned()) {
       // Don't resend the activity to the sender
       const exceptions = [ byActor ]