]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/view/local-video-viewer.ts
Add total viewers overall stat
[github/Chocobozzz/PeerTube.git] / server / models / view / local-video-viewer.ts
index 2305c72624434f2b0607d0c6e7ff69a0358cb2f1..12350861b9de48b9a20664aa52351d2b28cd28e6 100644 (file)
@@ -125,6 +125,7 @@ export class LocalVideoViewerModel extends Model<Partial<AttributesOnly<LocalVid
     }
 
     const watchTimeQuery = `SELECT ` +
+      `COUNT("localVideoViewer"."id") AS "totalViewers", ` +
       `SUM("localVideoViewer"."watchTime") AS "totalWatchTime", ` +
       `AVG("localVideoViewer"."watchTime") AS "averageWatchTime" ` +
       `FROM "localVideoViewer" ` +
@@ -177,6 +178,10 @@ export class LocalVideoViewerModel extends Model<Partial<AttributesOnly<LocalVid
         ? Math.round(rowsWatchTime[0].averageWatchTime) || 0
         : 0,
 
+      totalViewers: rowsWatchTime.length !== 0
+        ? Math.round(rowsWatchTime[0].totalViewers) || 0
+        : 0,
+
       viewersPeak,
       viewersPeakDate: rowsWatchPeak.length !== 0 && viewersPeak !== 0
         ? rowsWatchPeak[0].dateBreakpoint || null
@@ -236,6 +241,16 @@ export class LocalVideoViewerModel extends Model<Partial<AttributesOnly<LocalVid
       aggregateWatchTime: 'SUM("localVideoViewer"."watchTime")'
     }
 
+    const intervalWhere: { [ id in VideoStatsTimeserieMetric ]: string } = {
+      // Viewer is still in the interval. Overlap algorithm
+      viewers: '"localVideoViewer"."startDate" <= "intervals"."endDate" ' +
+        'AND "localVideoViewer"."endDate" >= "intervals"."startDate"',
+
+      // We do an aggregation, so only sum things once. Arbitrary we use the end date for that purpose
+      aggregateWatchTime: '"localVideoViewer"."endDate" >= "intervals"."startDate" ' +
+        'AND "localVideoViewer"."endDate" <= "intervals"."endDate"'
+    }
+
     const query = `WITH "intervals" AS (
       SELECT
         "time" AS "startDate", "time" + :groupInterval::interval as "endDate"
@@ -246,7 +261,7 @@ export class LocalVideoViewerModel extends Model<Partial<AttributesOnly<LocalVid
     FROM
       intervals
       LEFT JOIN "localVideoViewer" ON "localVideoViewer"."videoId" = :videoId
-        AND "localVideoViewer"."startDate" >= "intervals"."startDate" AND "localVideoViewer"."startDate" <= "intervals"."endDate"
+        AND ${intervalWhere[metric]}
     GROUP BY
       "intervals"."startDate"
     ORDER BY