4 Request Video events (likes, dislikes, views...)
7 const values
= require('lodash/values')
9 const constants
= require('../initializers/constants')
10 const customVideosValidators
= require('../helpers/custom-validators').videos
12 // ---------------------------------------------------------------------------
14 module
.exports = function (sequelize
, DataTypes
) {
15 const RequestVideoEvent
= sequelize
.define('RequestVideoEvent',
18 type: DataTypes
.ENUM(values(constants
.REQUEST_VIDEO_EVENT_TYPES
)),
22 type: DataTypes
.INTEGER
,
25 countValid: function (value
) {
26 const res
= customVideosValidators
.isVideoEventCountValid(value
)
27 if (res
=== false) throw new Error('Video event count is not valid.')
42 listWithLimitAndRandom
,
46 removeByRequestIdsAndPod
51 return RequestVideoEvent
54 // ------------------------------ STATICS ------------------------------
56 function associate (models
) {
57 this.belongsTo(models
.Video
, {
66 function countTotalRequests (callback
) {
68 return this.count(query
).asCallback(callback
)
71 function listWithLimitAndRandom (limitPods
, limitRequestsPerPod
, callback
) {
73 const Pod
= this.sequelize
.models
.Pod
75 // We make a join between videos and authors to find the podId of our video event requests
76 const podJoins
= 'INNER JOIN "Videos" ON "Videos"."authorId" = "Authors"."id" ' +
77 'INNER JOIN "RequestVideoEvents" ON "RequestVideoEvents"."videoId" = "Videos"."id"'
79 Pod
.listRandomPodIdsWithRequest(limitPods
, 'Authors', podJoins
, function (err
, podIds
) {
80 if (err
) return callback(err
)
82 // We don't have friends that have requests
83 if (podIds
.length
=== 0) return callback(null, [])
88 model: self
.sequelize
.models
.Video
,
91 model: self
.sequelize
.models
.Author
,
94 model: self
.sequelize
.models
.Pod
,
108 self
.findAll(query
).asCallback(function (err
, requests
) {
109 if (err
) return callback(err
)
111 const requestsGrouped
= groupAndTruncateRequests(requests
, limitRequestsPerPod
)
112 return callback(err
, requestsGrouped
)
117 function removeByRequestIdsAndPod (ids
, podId
, callback
) {
126 model: this.sequelize
.models
.Video
,
129 model: this.sequelize
.models
.Author
,
139 this.destroy(query
).asCallback(callback
)
142 function removeAll (callback
) {
143 // Delete all requests
144 this.truncate({ cascade: true }).asCallback(callback
)
147 // ---------------------------------------------------------------------------
149 function groupAndTruncateRequests (events
, limitRequestsPerPod
) {
150 const eventsGrouped
= {}
152 events
.forEach(function (event
) {
153 const pod
= event
.Video
.Author
.Pod
155 if (!eventsGrouped
[pod
.id
]) eventsGrouped
[pod
.id
] = []
157 if (eventsGrouped
[pod
.id
].length
< limitRequestsPerPod
) {
158 eventsGrouped
[pod
.id
].push({