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, [])
91 model: self
.sequelize
.models
.Video
,
94 model: self
.sequelize
.models
.Author
,
97 model: self
.sequelize
.models
.Pod
,
111 self
.findAll(query
).asCallback(function (err
, requests
) {
112 if (err
) return callback(err
)
114 const requestsGrouped
= groupAndTruncateRequests(requests
, limitRequestsPerPod
)
115 return callback(err
, requestsGrouped
)
120 function removeByRequestIdsAndPod (ids
, podId
, callback
) {
129 model: this.sequelize
.models
.Video
,
132 model: this.sequelize
.models
.Author
,
142 this.destroy(query
).asCallback(callback
)
145 function removeAll (callback
) {
146 // Delete all requests
147 this.truncate({ cascade: true }).asCallback(callback
)
150 // ---------------------------------------------------------------------------
152 function groupAndTruncateRequests (events
, limitRequestsPerPod
) {
153 const eventsGrouped
= {}
155 events
.forEach(function (event
) {
156 const pod
= event
.Video
.Author
.Pod
158 if (!eventsGrouped
[pod
.id
]) eventsGrouped
[pod
.id
] = []
160 if (eventsGrouped
[pod
.id
].length
< limitRequestsPerPod
) {
161 eventsGrouped
[pod
.id
].push({