1 import { Transaction } from 'sequelize'
2 import { AccountModel } from '../../models/account/account'
3 import { VideoModel } from '../../models/video/video'
4 import { sendLike, sendUndoDislike, sendUndoLike } from './send'
5 import { VideoRateType } from '../../../shared/models/videos'
6 import * as Bluebird from 'bluebird'
7 import { getOrCreateActorAndServerAndModel } from './actor'
8 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
9 import { logger } from '../../helpers/logger'
10 import { CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
11 import { doRequest } from '../../helpers/requests'
12 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
13 import { ActorModel } from '../../models/activitypub/actor'
14 import { getVideoDislikeActivityPubUrl, getVideoLikeActivityPubUrl } from './url'
15 import { sendDislike } from './send/send-dislike'
17 async function createRates (ratesUrl: string[], video: VideoModel, rate: VideoRateType) {
20 await Bluebird.map(ratesUrl, async rateUrl => {
23 const { body } = await doRequest({
28 if (!body || !body.actor) throw new Error('Body or body actor is invalid')
30 const actorUrl = getAPId(body.actor)
31 if (checkUrlsSameHost(actorUrl, rateUrl) !== true) {
32 throw new Error(`Rate url ${rateUrl} has not the same host than actor url ${actorUrl}`)
35 if (checkUrlsSameHost(body.id, rateUrl) !== true) {
36 throw new Error(`Rate url ${rateUrl} host is different from the AP object id ${body.id}`)
39 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
43 accountId: actor.Account.id,
48 const created = await AccountVideoRateModel.upsert(entry)
50 if (created) rateCounts += 1
52 logger.warn('Cannot add rate %s.', rateUrl, { err })
54 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
56 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
58 // This is "likes" and "dislikes"
59 if (rateCounts !== 0) {
60 const field = rate === 'like' ? 'likes' : 'dislikes'
61 await video.increment(field, { by: rateCounts })
67 async function sendVideoRateChange (account: AccountModel,
72 const actor = account.Actor
74 // Keep the order: first we undo and then we create
77 if (likes < 0) await sendUndoLike(actor, video, t)
79 if (dislikes < 0) await sendUndoDislike(actor, video, t)
82 if (likes > 0) await sendLike(actor, video, t)
84 if (dislikes > 0) await sendDislike(actor, video, t)
87 function getRateUrl (rateType: VideoRateType, actor: ActorModel, video: VideoModel) {
88 return rateType === 'like' ? getVideoLikeActivityPubUrl(actor, video) : getVideoDislikeActivityPubUrl(actor, video)