ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

65 lines
2.5 KiB

  1. import { VIDEO_RATE_TYPES } from '@server/initializers/constants.js'
  2. import { sequelizeTypescript } from '@server/initializers/database.js'
  3. import { AccountVideoRateModel } from '@server/models/account/account-video-rate.js'
  4. import { AccountModel } from '@server/models/account/account.js'
  5. import { getLocalRateUrl, sendVideoRateChange } from './activitypub/video-rates.js'
  6. import { MAccountId, MAccountUrl, MVideoFullLight } from '@server/types/models/index.js'
  7. import { UserVideoRateType } from '@peertube/peertube-models'
  8. export async function userRateVideo (options: {
  9. rateType: UserVideoRateType
  10. account: MAccountUrl & MAccountId
  11. video: MVideoFullLight
  12. }) {
  13. const { account, rateType, video } = options
  14. await sequelizeTypescript.transaction(async t => {
  15. const sequelizeOptions = { transaction: t }
  16. const accountInstance = await AccountModel.load(account.id, t)
  17. const previousRate = await AccountVideoRateModel.load(accountInstance.id, video.id, t)
  18. // Same rate, nothing do to
  19. if (rateType === 'none' && !previousRate || previousRate?.type === rateType) return
  20. let likesToIncrement = 0
  21. let dislikesToIncrement = 0
  22. if (rateType === VIDEO_RATE_TYPES.LIKE) likesToIncrement++
  23. else if (rateType === VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement++
  24. // There was a previous rate, update it
  25. if (previousRate) {
  26. // We will remove the previous rate, so we will need to update the video count attribute
  27. if (previousRate.type === 'like') likesToIncrement--
  28. else if (previousRate.type === 'dislike') dislikesToIncrement--
  29. if (rateType === 'none') { // Destroy previous rate
  30. await previousRate.destroy(sequelizeOptions)
  31. } else { // Update previous rate
  32. previousRate.type = rateType
  33. previousRate.url = getLocalRateUrl(rateType, account.Actor, video)
  34. await previousRate.save(sequelizeOptions)
  35. }
  36. } else if (rateType !== 'none') { // There was not a previous rate, insert a new one if there is a rate
  37. const query = {
  38. accountId: accountInstance.id,
  39. videoId: video.id,
  40. type: rateType,
  41. url: getLocalRateUrl(rateType, account.Actor, video)
  42. }
  43. await AccountVideoRateModel.create(query, sequelizeOptions)
  44. }
  45. const incrementQuery = {
  46. likes: likesToIncrement,
  47. dislikes: dislikesToIncrement
  48. }
  49. await video.increment(incrementQuery, sequelizeOptions)
  50. await sendVideoRateChange(accountInstance, video, likesToIncrement, dislikesToIncrement, t)
  51. })
  52. }