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'
10 import { RequestVideoEventType } from '../../../shared'
12 export type RequestVideoEventSchedulerOptions = {
13 type: RequestVideoEventType
16 transaction?: Sequelize.Transaction
19 class RequestVideoEventScheduler extends AbstractRequestScheduler {
23 // We limit the size of the requests
24 this.limitPods = REQUESTS_VIDEO_EVENT_LIMIT_PODS
25 this.limitPerPod = REQUESTS_VIDEO_EVENT_LIMIT_PER_POD
27 this.description = 'video event requests'
31 return db.RequestVideoEvent
34 getRequestToPodModel () {
35 return db.RequestVideoEvent
38 buildRequestObjects (eventsToProcess: { [ toPodId: number ]: any }[]) {
39 const requestsToMakeGrouped = {}
44 video1: { views: 4, likes: 5 },
49 const eventsPerVideoPerPod = {}
51 // We group video events per video and per pod
52 // We add the counts of the same event types
53 Object.keys(eventsToProcess).forEach(toPodId => {
54 eventsToProcess[toPodId].forEach(eventToProcess => {
55 if (!eventsPerVideoPerPod[toPodId]) eventsPerVideoPerPod[toPodId] = {}
57 if (!requestsToMakeGrouped[toPodId]) {
58 requestsToMakeGrouped[toPodId] = {
59 toPod: eventToProcess.pod,
60 endpoint: REQUEST_VIDEO_EVENT_ENDPOINT,
61 ids: [], // request ids, to delete them from the DB in the future
62 datas: [] // requests data
65 requestsToMakeGrouped[toPodId].ids.push(eventToProcess.id)
67 const eventsPerVideo = eventsPerVideoPerPod[toPodId]
68 const remoteId = eventToProcess.video.remoteId
69 if (!eventsPerVideo[remoteId]) eventsPerVideo[remoteId] = {}
71 const events = eventsPerVideo[remoteId]
72 if (!events[eventToProcess.type]) events[eventToProcess.type] = 0
74 events[eventToProcess.type] += eventToProcess.count
78 // Now we build our requests array per pod
79 Object.keys(eventsPerVideoPerPod).forEach(toPodId => {
80 const eventsForPod = eventsPerVideoPerPod[toPodId]
82 Object.keys(eventsForPod).forEach(remoteId => {
83 const eventsForVideo = eventsForPod[remoteId]
85 Object.keys(eventsForVideo).forEach(eventType => {
86 requestsToMakeGrouped[toPodId].datas.push({
90 count: eventsForVideo[eventType]
97 return requestsToMakeGrouped
100 createRequest ({ type, videoId, count, transaction }: RequestVideoEventSchedulerOptions, callback: (err: Error) => void) {
101 if (count === undefined) count = 1
103 const dbRequestOptions: Sequelize.CreateOptions = {}
104 if (transaction) dbRequestOptions.transaction = transaction
106 const createQuery = {
112 return db.RequestVideoEvent.create(createQuery, dbRequestOptions).asCallback(callback)
116 // ---------------------------------------------------------------------------
119 RequestVideoEventScheduler