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 { getOrCreateAPActor } from './actors'
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 => {
18 await createRate(rateUrl, video, rate)
20 logger.warn('Cannot add rate %s.', rateUrl, { err })
22 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
25 async function sendVideoRateChange (
26 account: MAccountActor,
27 video: MVideoAccountLight,
32 const actor = account.Actor
34 // Keep the order: first we undo and then we create
37 if (likes < 0) await sendUndoLike(actor, video, t)
39 if (dislikes < 0) await sendUndoDislike(actor, video, t)
42 if (likes > 0) await sendLike(actor, video, t)
44 if (dislikes > 0) await sendDislike(actor, video, t)
47 function getLocalRateUrl (rateType: VideoRateType, actor: MActorUrl, video: MVideoId) {
48 return rateType === 'like'
49 ? getVideoLikeActivityPubUrlByLocalActor(actor, video)
50 : getVideoDislikeActivityPubUrlByLocalActor(actor, video)
53 // ---------------------------------------------------------------------------
61 // ---------------------------------------------------------------------------
63 async function createRate (rateUrl: string, video: MVideo, rate: VideoRateType) {
65 const { body } = await doJSONRequest<any>(rateUrl, { activityPub: true })
66 if (!body || !body.actor) throw new Error('Body or body actor is invalid')
68 const actorUrl = getAPId(body.actor)
69 if (checkUrlsSameHost(actorUrl, rateUrl) !== true) {
70 throw new Error(`Rate url ${rateUrl} has not the same host than actor url ${actorUrl}`)
73 if (checkUrlsSameHost(body.id, rateUrl) !== true) {
74 throw new Error(`Rate url ${rateUrl} host is different from the AP object id ${body.id}`)
77 const actor = await getOrCreateAPActor(actorUrl)
81 accountId: actor.Account.id,
86 // Video "likes"/"dislikes" will be updated by the caller
87 await AccountVideoRateModel.upsert(entry)