1 import * as Sequelize from 'sequelize'
3 import { database as db } from '../../initializers/database'
4 import { AbstractRequestScheduler } from './abstract-request-scheduler'
6 REQUESTS_VIDEO_EVENT_LIMIT_PODS,
7 REQUESTS_VIDEO_EVENT_LIMIT_PER_POD,
8 REQUEST_VIDEO_EVENT_ENDPOINT
9 } from '../../initializers'
11 export type RequestVideoEventSchedulerOptions = {
15 transaction?: Sequelize.Transaction
18 class RequestVideoEventScheduler extends AbstractRequestScheduler {
22 // We limit the size of the requests
23 this.limitPods = REQUESTS_VIDEO_EVENT_LIMIT_PODS
24 this.limitPerPod = REQUESTS_VIDEO_EVENT_LIMIT_PER_POD
26 this.description = 'video event requests'
30 return db.RequestVideoEvent
33 getRequestToPodModel () {
34 return db.RequestVideoEvent
37 buildRequestObjects (eventsToProcess: { [ toPodId: number ]: any }[]) {
38 const requestsToMakeGrouped = {}
43 video1: { views: 4, likes: 5 },
48 const eventsPerVideoPerPod = {}
50 // We group video events per video and per pod
51 // We add the counts of the same event types
52 Object.keys(eventsToProcess).forEach(toPodId => {
53 eventsToProcess[toPodId].forEach(eventToProcess => {
54 if (!eventsPerVideoPerPod[toPodId]) eventsPerVideoPerPod[toPodId] = {}
56 if (!requestsToMakeGrouped[toPodId]) {
57 requestsToMakeGrouped[toPodId] = {
58 toPod: eventToProcess.pod,
59 endpoint: REQUEST_VIDEO_EVENT_ENDPOINT,
60 ids: [], // request ids, to delete them from the DB in the future
61 datas: [] // requests data
64 requestsToMakeGrouped[toPodId].ids.push(eventToProcess.id)
66 const eventsPerVideo = eventsPerVideoPerPod[toPodId]
67 const remoteId = eventToProcess.video.remoteId
68 if (!eventsPerVideo[remoteId]) eventsPerVideo[remoteId] = {}
70 const events = eventsPerVideo[remoteId]
71 if (!events[eventToProcess.type]) events[eventToProcess.type] = 0
73 events[eventToProcess.type] += eventToProcess.count
77 // Now we build our requests array per pod
78 Object.keys(eventsPerVideoPerPod).forEach(toPodId => {
79 const eventsForPod = eventsPerVideoPerPod[toPodId]
81 Object.keys(eventsForPod).forEach(remoteId => {
82 const eventsForVideo = eventsForPod[remoteId]
84 Object.keys(eventsForVideo).forEach(eventType => {
85 requestsToMakeGrouped[toPodId].datas.push({
89 count: eventsForVideo[eventType]
96 return requestsToMakeGrouped
99 createRequest ({ type, videoId, count, transaction }: RequestVideoEventSchedulerOptions, callback: (err: Error) => void) {
100 if (count === undefined) count = 1
102 const dbRequestOptions: Sequelize.CreateOptions = {}
103 if (transaction) dbRequestOptions.transaction = transaction
105 const createQuery = {
111 return db.RequestVideoEvent.create(createQuery, dbRequestOptions).asCallback(callback)
115 // ---------------------------------------------------------------------------
118 RequestVideoEventScheduler