1 import { Transaction } from 'sequelize'
2 import { sendLike, sendUndoDislike, sendUndoLike } from './send'
3 import { VideoRateType } from '../../../shared/models/videos'
4 import * as Bluebird from 'bluebird'
5 import { getOrCreateActorAndServerAndModel } from './actor'
6 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
7 import { logger } from '../../helpers/logger'
8 import { CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
9 import { doRequest } from '../../helpers/requests'
10 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
11 import { getVideoDislikeActivityPubUrl, getVideoLikeActivityPubUrl } from './url'
12 import { sendDislike } from './send/send-dislike'
13 import { MAccountActor, MActorUrl, MVideo, MVideoAccountLight, MVideoId } from '../../typings/models'
15 async function createRates (ratesUrl: string[], video: MVideo, rate: VideoRateType) {
18 await Bluebird.map(ratesUrl, async rateUrl => {
21 const { body } = await doRequest<any>({
26 if (!body || !body.actor) throw new Error('Body or body actor is invalid')
28 const actorUrl = getAPId(body.actor)
29 if (checkUrlsSameHost(actorUrl, rateUrl) !== true) {
30 throw new Error(`Rate url ${rateUrl} has not the same host than actor url ${actorUrl}`)
33 if (checkUrlsSameHost(body.id, rateUrl) !== true) {
34 throw new Error(`Rate url ${rateUrl} host is different from the AP object id ${body.id}`)
37 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
41 accountId: actor.Account.id,
46 const created = await AccountVideoRateModel.upsert(entry)
48 if (created) rateCounts += 1
50 logger.warn('Cannot add rate %s.', rateUrl, { err })
52 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
54 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
56 // This is "likes" and "dislikes"
57 if (rateCounts !== 0) {
58 const field = rate === 'like' ? 'likes' : 'dislikes'
59 await video.increment(field, { by: rateCounts })
63 async function sendVideoRateChange (
64 account: MAccountActor,
65 video: MVideoAccountLight,
70 const actor = account.Actor
72 // Keep the order: first we undo and then we create
75 if (likes < 0) await sendUndoLike(actor, video, t)
77 if (dislikes < 0) await sendUndoDislike(actor, video, t)
80 if (likes > 0) await sendLike(actor, video, t)
82 if (dislikes > 0) await sendDislike(actor, video, t)
85 function getRateUrl (rateType: VideoRateType, actor: MActorUrl, video: MVideoId) {
86 return rateType === 'like'
87 ? getVideoLikeActivityPubUrl(actor, video)
88 : getVideoDislikeActivityPubUrl(actor, video)