1 import * as Bluebird from 'bluebird'
2 import { Transaction } from 'sequelize'
3 import { doJSONRequest } from '@server/helpers/requests'
4 import { VideoRateType } from '../../../shared/models/videos'
5 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
6 import { logger } from '../../helpers/logger'
7 import { CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
8 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
9 import { MAccountActor, MActorUrl, MVideo, MVideoAccountLight, MVideoId } from '../../types/models'
10 import { getOrCreateActorAndServerAndModel } from './actor'
11 import { sendLike, sendUndoDislike, sendUndoLike } from './send'
12 import { sendDislike } from './send/send-dislike'
13 import { getVideoDislikeActivityPubUrlByLocalActor, getVideoLikeActivityPubUrlByLocalActor } from './url'
15 async function createRates (ratesUrl: string[], video: MVideo, rate: VideoRateType) {
16 await Bluebird.map(ratesUrl, async rateUrl => {
19 const { body } = await doJSONRequest<any>(rateUrl, { activityPub: true })
20 if (!body || !body.actor) throw new Error('Body or body actor is invalid')
22 const actorUrl = getAPId(body.actor)
23 if (checkUrlsSameHost(actorUrl, rateUrl) !== true) {
24 throw new Error(`Rate url ${rateUrl} has not the same host than actor url ${actorUrl}`)
27 if (checkUrlsSameHost(body.id, rateUrl) !== true) {
28 throw new Error(`Rate url ${rateUrl} host is different from the AP object id ${body.id}`)
31 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
35 accountId: actor.Account.id,
40 // Video "likes"/"dislikes" will be updated by the caller
41 await AccountVideoRateModel.upsert(entry)
43 logger.warn('Cannot add rate %s.', rateUrl, { err })
45 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
48 async function sendVideoRateChange (
49 account: MAccountActor,
50 video: MVideoAccountLight,
55 const actor = account.Actor
57 // Keep the order: first we undo and then we create
60 if (likes < 0) await sendUndoLike(actor, video, t)
62 if (dislikes < 0) await sendUndoDislike(actor, video, t)
65 if (likes > 0) await sendLike(actor, video, t)
67 if (dislikes > 0) await sendDislike(actor, video, t)
70 function getLocalRateUrl (rateType: VideoRateType, actor: MActorUrl, video: MVideoId) {
71 return rateType === 'like'
72 ? getVideoLikeActivityPubUrlByLocalActor(actor, video)
73 : getVideoDislikeActivityPubUrlByLocalActor(actor, video)