video-rates.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Transaction } from 'sequelize'
  2. import { AccountModel } from '../../models/account/account'
  3. import { VideoModel } from '../../models/video/video'
  4. import { sendCreateDislike, 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'
  11. async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
  12. let rateCounts = 0
  13. await Bluebird.map(actorUrls, async actorUrl => {
  14. try {
  15. const actor = await getOrCreateActorAndServerAndModel(actorUrl)
  16. const [ , created ] = await AccountVideoRateModel
  17. .findOrCreate({
  18. where: {
  19. videoId: video.id,
  20. accountId: actor.Account.id
  21. },
  22. defaults: {
  23. videoId: video.id,
  24. accountId: actor.Account.id,
  25. type: rate
  26. }
  27. })
  28. if (created) rateCounts += 1
  29. } catch (err) {
  30. logger.warn('Cannot add rate %s for actor %s.', rate, actorUrl, { err })
  31. }
  32. }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
  33. logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
  34. // This is "likes" and "dislikes"
  35. if (rateCounts !== 0) await video.increment(rate + 's', { by: rateCounts })
  36. return
  37. }
  38. async function sendVideoRateChange (account: AccountModel,
  39. video: VideoModel,
  40. likes: number,
  41. dislikes: number,
  42. t: Transaction) {
  43. const actor = account.Actor
  44. // Keep the order: first we undo and then we create
  45. // Undo Like
  46. if (likes < 0) await sendUndoLike(actor, video, t)
  47. // Undo Dislike
  48. if (dislikes < 0) await sendUndoDislike(actor, video, t)
  49. // Like
  50. if (likes > 0) await sendLike(actor, video, t)
  51. // Dislike
  52. if (dislikes > 0) await sendCreateDislike(actor, video, t)
  53. }
  54. export {
  55. createRates,
  56. sendVideoRateChange
  57. }