Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Feat: video download stats (#7437)

Sébastien NOBILIc9855027ec66
diff --git a/client/src/app/+about/about-instance/instance-stat-rules.component.html b/client/src/app/+about/about-instance/instance-stat-rules.component.html
index 0f6605f9bc..9c8f07a41a 100644
--- a/client/src/app/+about/about-instance/instance-stat-rules.component.html
+++ b/client/src/app/+about/about-instance/instance-stat-rules.component.html
@@ -28,6 +28,12 @@
<my-global-icon iconName="eye-open"></my-global-icon>
</div>
+ <div class="stat">
+ <strong>{{ stats().totalLocalVideoDownloads | number }}</strong>
+ <div i18n>downloads</div>
+ <my-global-icon iconName="download"></my-global-icon>
+ </div>
+
<div class="stat">
<strong>{{ stats().totalLocalVideoComments | number }}</strong>
<div i18n>comments</div>
diff --git a/client/src/app/+admin/system/jobs/jobs.component.ts b/client/src/app/+admin/system/jobs/jobs.component.ts
index 15b023f70a..901a58c663 100644
--- a/client/src/app/+admin/system/jobs/jobs.component.ts
+++ b/client/src/app/+admin/system/jobs/jobs.component.ts
@@ -81,7 +81,7 @@ export class JobsComponent implements OnInit {
'video-studio-edition',
'video-transcoding',
'video-transcription',
- 'videos-views-stats'
+ 'videos-stats'
]
jobTypeItems: SelectOptionsItem[] = this.jobTypes.map(i => ({ id: i, label: i }))
diff --git a/client/src/app/+my-library/my-videos/my-videos.component.html b/client/src/app/+my-library/my-videos/my-videos.component.html
index fea7bb19b4..3c139e6ad5 100644
--- a/client/src/app/+my-library/my-videos/my-videos.component.html
+++ b/client/src/app/+my-library/my-videos/my-videos.component.html
@@ -99,6 +99,7 @@
<td>
<a class="pt" [routerLink]="[ '/videos/manage', video.shortUUID, 'stats' ]" i18n-title title="Navigate to the video stats page">
<ng-container i18n>{video.views, plural, =0 {No views} =1 {1 view} other {{{ video.views | myNumberFormatter }} views}}</ng-container>
+
@if (video.isLive) {
<br />
<ng-container i18n>{video.viewers, plural, =0 {No viewers} =1 {1 viewer} other {{{ video.views | myNumberFormatter }} viewers}}</ng-container>
diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
index d938d4ae6f..89a32965b1 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
@@ -120,6 +120,7 @@ type UpdateFromAPIOptions = {
| 'likes'
| 'aspectRatio'
| 'views'
+ | 'downloads'
| 'blacklisted'
| 'blacklistedReason'
| 'thumbnails'
@@ -173,6 +174,7 @@ export class VideoEdit {
state: VideoStateType
isLive: boolean
views: number
+ downloads: number
aspectRatio: number
duration: number
likes: number
@@ -197,6 +199,7 @@ export class VideoEdit {
aspectRatio: number
duration: number
views: number
+ downloads: number
likes: number
blacklisted: boolean
@@ -310,6 +313,7 @@ export class VideoEdit {
this.common.pluginData = {}
this.metadata.views = 0
+ this.metadata.downloads = 0
this.metadata.likes = 0
this.metadata.ownerAccountDisplayName = options.user.account.displayName
@@ -429,6 +433,7 @@ export class VideoEdit {
this.metadata.state = video.state.id
this.metadata.duration = video.duration
this.metadata.views = video.views
+ this.metadata.downloads = video.downloads
this.metadata.likes = video.likes
this.metadata.aspectRatio = video.aspectRatio
this.metadata.blacklisted = video.blacklisted
@@ -1115,6 +1120,7 @@ export class VideoEdit {
isLive: this.metadata.isLive,
aspectRatio: this.metadata.aspectRatio,
views: this.metadata.views,
+ downloads: this.metadata.downloads,
likes: this.metadata.likes,
duration: this.metadata.duration,
blacklisted: this.metadata.blacklisted,
diff --git a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.ts b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.ts
index 9ef1967a46..81f3aa3e2f 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.ts
@@ -131,6 +131,11 @@ export class VideoStatsComponent implements OnInit {
label: $localize`Watch time`,
zoomEnabled: true
},
+ {
+ id: 'downloads',
+ label: $localize`Downloads`,
+ zoomEnabled: true
+ },
{
id: 'countries',
label: $localize`Countries`,
@@ -242,7 +247,7 @@ export class VideoStatsComponent implements OnInit {
}
private isTimeserieGraph (graphId: ActiveGraphId) {
- return graphId === 'aggregateWatchTime' || graphId === 'viewers'
+ return graphId === 'aggregateWatchTime' || graphId === 'viewers' || graphId === 'downloads'
}
private loadOverallStats () {
@@ -334,6 +339,10 @@ export class VideoStatsComponent implements OnInit {
value: this.numberFormatter.transform(this.videoEdit.getVideoAttributes().views),
help: $localize`A view means that someone watched the video for several seconds (10 seconds by default)`
},
+ {
+ label: $localize`Downloads`,
+ value: this.numberFormatter.transform(this.videoEdit.getVideoAttributes().downloads)
+ },
{
label: $localize`Likes`,
value: this.numberFormatter.transform(this.videoEdit.getVideoAttributes().likes)
@@ -399,6 +408,12 @@ export class VideoStatsComponent implements OnInit {
endDate: this.statsEndDate,
metric: 'viewers'
}),
+ downloads: this.statsService.getTimeserieStats({
+ videoId,
+ startDate: this.statsStartDate,
+ endDate: this.statsEndDate,
+ metric: 'downloads'
+ }),
countries: of(this.countries),
@@ -426,6 +441,7 @@ export class VideoStatsComponent implements OnInit {
retention: (rawData: VideoStatsRetention) => this.buildRetentionChartOptions(rawData),
aggregateWatchTime: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
viewers: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
+ downloads: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
countries: (rawData: GeoData) => this.buildGeoChartOptions(rawData),
regions: (rawData: GeoData) => this.buildGeoChartOptions(rawData)
}
diff --git a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.service.ts b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.service.ts
index 58b12d766b..76636075c3 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.service.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.service.ts
@@ -1,8 +1,7 @@
-import { catchError } from 'rxjs'
-import { environment } from 'src/environments/environment'
import { HttpClient, HttpParams } from '@angular/common/http'
import { Injectable, inject } from '@angular/core'
import { RestExtractor } from '@app/core'
+import { VideoService } from '@app/shared/shared-main/video/video.service'
import {
VideoStatsOverall,
VideoStatsRetention,
@@ -10,7 +9,8 @@ import {
VideoStatsTimeserieMetric,
VideoStatsUserAgent
} from '@peertube/peertube-models'
-import { VideoService } from '@app/shared/shared-main/video/video.service'
+import { catchError } from 'rxjs'
+import { environment } from 'src/environments/environment'
@Injectable({
providedIn: 'root'
diff --git a/client/src/app/shared/shared-main/video/video.model.ts b/client/src/app/shared/shared-main/video/video.model.ts
index b7da94fb36..6a7db68c13 100644
--- a/client/src/app/shared/shared-main/video/video.model.ts
+++ b/client/src/app/shared/shared-main/video/video.model.ts
@@ -70,6 +70,8 @@ export class Video implements VideoServerModel {
views: number
viewers: number
+ downloads: number
+
likes: number
dislikes: number
@@ -178,6 +180,7 @@ export class Video implements VideoServerModel {
this.viewers = hash.viewers
this.likes = hash.likes
this.dislikes = hash.dislikes
+ this.downloads = hash.downloads
this.nsfw = hash.nsfw
this.nsfwFlags = hash.nsfwFlags
diff --git a/packages/models/src/activitypub/activity.ts b/packages/models/src/activitypub/activity.ts
index e2a4d964b7..f4e599e47c 100644
--- a/packages/models/src/activitypub/activity.ts
+++ b/packages/models/src/activitypub/activity.ts
@@ -44,6 +44,7 @@ export type Activity =
| ActivityFlag
| ActivityApproveReply
| ActivityRejectReply
+ | ActivityDownload
export type ActivityType =
| 'Create'
@@ -60,6 +61,7 @@ export type ActivityType =
| 'Flag'
| 'ApproveReply'
| 'RejectReply'
+ | 'Download'
export interface ActivityAudience {
to: string[]
@@ -162,3 +164,9 @@ export interface ActivityFlag extends BaseActivity {
startAt?: number
endAt?: number
}
+
+export interface ActivityDownload extends BaseActivity {
+ type: 'Download'
+ actor: string
+ object: APObjectId
+}
diff --git a/packages/models/src/activitypub/context.ts b/packages/models/src/activitypub/context.ts
index e85a1677c3..a3f0e3c217 100644
--- a/packages/models/src/activitypub/context.ts
+++ b/packages/models/src/activitypub/context.ts
@@ -18,3 +18,4 @@ export type ContextType =
| 'ApproveReply'
| 'RejectReply'
| 'PlayerSettings'
+ | 'Download'
diff --git a/packages/models/src/activitypub/objects/video-object.ts b/packages/models/src/activitypub/objects/video-object.ts
index 2534230348..bcd3b33e27 100644
--- a/packages/models/src/activitypub/objects/video-object.ts
+++ b/packages/models/src/activitypub/objects/video-object.ts
@@ -22,6 +22,7 @@ export interface VideoObject {
subtitleLanguage: VideoCaptionObject[]
views: number
+ downloads: number
sensitive: boolean
summary: string
diff --git a/packages/models/src/server/debug.model.ts b/packages/models/src/server/debug.model.ts
index ffab325ef1..7ef5fc0470 100644
--- a/packages/models/src/server/debug.model.ts
+++ b/packages/models/src/server/debug.model.ts
@@ -6,12 +6,12 @@ export interface Debug {
export type SendDebugCommand = {
command:
| 'remove-dandling-resumable-uploads'
- | 'process-video-views-buffer'
+ | 'process-video-stats-buffer'
| 'process-video-viewers'
| 'process-video-channel-sync-latest'
| 'process-update-videos-scheduler'
| 'remove-expired-user-exports'
- | 'process-remove-old-views'
+ | 'process-remove-old-stats'
} | SendDebugTestEmails
export type SendDebugTestEmails = {
diff --git a/packages/models/src/server/job.model.ts b/packages/models/src/server/job.model.ts
index 296753396c..64117fa0e8 100644
--- a/packages/models/src/server/job.model.ts
+++ b/packages/models/src/server/job.model.ts
@@ -29,7 +29,7 @@ export type JobType =
| 'video-redundancy'
| 'video-studio-edition'
| 'video-transcoding'
- | 'videos-views-stats'
+ | 'videos-stats'
| 'generate-video-storyboard'
| 'create-user-export'
| 'import-user-archive'
diff --git a/packages/models/src/server/server-stats.model.ts b/packages/models/src/server/server-stats.model.ts
index 1f02a0d031..f1a6caeebb 100644
--- a/packages/models/src/server/server-stats.model.ts
+++ b/packages/models/src/server/server-stats.model.ts
@@ -15,6 +15,7 @@ export interface ServerStats extends ActivityPubMessagesSuccess, ActivityPubMess
totalLocalVideos: number
totalLocalVideoViews: number
+ totalLocalVideoDownloads: number
totalLocalVideoComments: number
totalLocalVideoFilesSize: number
diff --git a/packages/models/src/videos/stats/video-stats-timeserie-metric.type.ts b/packages/models/src/videos/stats/video-stats-timeserie-metric.type.ts
index fc268d083e..4ef9c03466 100644
--- a/packages/models/src/videos/stats/video-stats-timeserie-metric.type.ts
+++ b/packages/models/src/videos/stats/video-stats-timeserie-metric.type.ts
@@ -1 +1 @@
-export type VideoStatsTimeserieMetric = 'viewers' | 'aggregateWatchTime'
+export type VideoStatsTimeserieMetric = 'viewers' | 'aggregateWatchTime' | 'downloads'
diff --git a/packages/models/src/videos/video.model.ts b/packages/models/src/videos/video.model.ts
index c0242c0601..40e6b65a0b 100644
--- a/packages/models/src/videos/video.model.ts
+++ b/packages/models/src/videos/video.model.ts
@@ -69,6 +69,8 @@ export interface Video extends Partial<VideoAdditionalAttributes> {
views: number
viewers: number
+ downloads: number
+
likes: number
dislikes: number
comments: number
diff --git a/packages/server-commands/src/server/jobs.ts b/packages/server-commands/src/server/jobs.ts
index 3938c92648..0946de2bfe 100644
--- a/packages/server-commands/src/server/jobs.ts
+++ b/packages/server-commands/src/server/jobs.ts
@@ -22,7 +22,7 @@ async function waitJobs (
const states: JobState[] = [ 'waiting', 'active' ]
if (!skipDelayed) states.push('delayed')
- const repeatableJobs: JobType[] = [ 'videos-views-stats', 'activitypub-cleaner' ]
+ const repeatableJobs: JobType[] = [ 'videos-stats', 'activitypub-cleaner' ]
let pendingRequests: boolean
function tasksBuilder () {
diff --git a/packages/tests/src/api/server/jobs.ts b/packages/tests/src/api/server/jobs.ts
index e975fbac70..ac232b0578 100644
--- a/packages/tests/src/api/server/jobs.ts
+++ b/packages/tests/src/api/server/jobs.ts
@@ -54,7 +54,7 @@ describe('Test jobs', function () {
let job = body.data[0]
// Skip repeat jobs
- if (job.type === 'videos-views-stats') job = body.data[1]
+ if (job.type === 'videos-stats') job = body.data[1]
expect(job.state).to.equal('completed')
expect(dateIsValid(job.createdAt as string)).to.be.true
diff --git a/packages/tests/src/api/views/index.ts b/packages/tests/src/api/stats/index.ts
similarity index 86%
rename from packages/tests/src/api/views/index.ts
rename to packages/tests/src/api/stats/index.ts
index edb6c92c44..54fd73ff35 100644
--- a/packages/tests/src/api/views/index.ts
+++ b/packages/tests/src/api/stats/index.ts
@@ -1,3 +1,4 @@
+export * from './video-downloads-counter.js'
export * from './video-views-counter.js'
export * from './video-views-overall-stats.js'
export * from './video-views-retention-stats.js'
diff --git a/packages/tests/src/api/stats/video-downloads-counter.ts b/packages/tests/src/api/stats/video-downloads-counter.ts
new file mode 100644
index 0000000000..bc1538d051
--- /dev/null
+++ b/packages/tests/src/api/stats/video-downloads-counter.ts
@@ -0,0 +1,121 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { wait } from '@peertube/peertube-core-utils'
+import { HttpStatusCode } from '@peertube/peertube-models'
+import {
+ createMultipleServers,
+ doubleFollow,
+ makeRawRequest,
+ PeerTubeServer,
+ setAccessTokensToServers,
+ waitJobs
+} from '@peertube/peertube-server-commands'
+import { expect } from 'chai'
+
+describe('Test video downloads stats', function () {
+ let servers: PeerTubeServer[]
+ let videoId: string
+ let remoteVideoId: string
+
+ async function processStats () {
+ for (const server of servers) {
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
+ }
+
+ await waitJobs(servers)
+ }
+
+ before(async function () {
+ this.timeout(120000)
+
+ servers = await createMultipleServers(2)
+ await setAccessTokensToServers(servers)
+
+ await doubleFollow(servers[0], servers[1])
+
+ await servers[0].config.enableMinimumTranscoding()
+
+ {
+ const { uuid } = await servers[0].videos.quickUpload({ name: 'video' })
+ videoId = uuid
+ }
+
+ {
+ const { uuid } = await servers[1].videos.quickUpload({ name: 'remote video' })
+ remoteVideoId = uuid
+ }
+
+ await waitJobs(servers)
+ })
+
+ it('Should count web video downloads', async function () {
+ const video = await servers[0].videos.get({ id: remoteVideoId })
+ await makeRawRequest({ url: video.files[0].fileDownloadUrl, expectedStatus: HttpStatusCode.OK_200 })
+
+ await processStats()
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: remoteVideoId })
+ expect(video.downloads).to.equal(1)
+ }
+ })
+
+ it('Should count hls downloads', async function () {
+ const video = await servers[0].videos.get({ id: videoId })
+ await makeRawRequest({ url: video.streamingPlaylists[0].files[0].fileDownloadUrl, expectedStatus: HttpStatusCode.OK_200 })
+
+ await processStats()
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: videoId })
+ expect(video.downloads).to.equal(1)
+ }
+ })
+
+ it('Should count generated download', async function () {
+ const video = await servers[0].videos.get({ id: videoId })
+ const videoFileIds = [ video.files[0].id ]
+
+ await servers[0].videos.generateDownload({ videoId, videoFileIds })
+
+ await processStats()
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: videoId })
+ expect(video.downloads).to.equal(2)
+ }
+ })
+
+ it('Should count remote download', async function () {
+ const video = await servers[1].videos.get({ id: videoId })
+ const videoFileIds = [ video.files[0].id ]
+
+ await servers[1].videos.generateDownload({ videoId, videoFileIds })
+ await waitJobs(servers)
+
+ await servers[0].debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
+ await waitJobs(servers)
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: videoId })
+ expect(video.downloads).to.equal(3)
+ }
+ })
+
+ it('Should return time-series for downloads stats', async function () {
+ await wait(6000)
+
+ const now = new Date()
+ const twoHoursAgo = new Date()
+ twoHoursAgo.setHours(twoHoursAgo.getHours() - 4)
+
+ const { data } = await servers[0].videoStats.getTimeserieStats({
+ videoId,
+ metric: 'downloads',
+ startDate: twoHoursAgo,
+ endDate: now
+ })
+
+ expect(data.reduce((sum, point) => sum + point.value, 0)).to.equal(3)
+ })
+})
diff --git a/packages/tests/src/api/views/video-views-counter.ts b/packages/tests/src/api/stats/video-views-counter.ts
similarity index 100%
rename from packages/tests/src/api/views/video-views-counter.ts
rename to packages/tests/src/api/stats/video-views-counter.ts
diff --git a/packages/tests/src/api/views/video-views-overall-stats.ts b/packages/tests/src/api/stats/video-views-overall-stats.ts
similarity index 100%
rename from packages/tests/src/api/views/video-views-overall-stats.ts
rename to packages/tests/src/api/stats/video-views-overall-stats.ts
diff --git a/packages/tests/src/api/views/video-views-retention-stats.ts b/packages/tests/src/api/stats/video-views-retention-stats.ts
similarity index 100%
rename from packages/tests/src/api/views/video-views-retention-stats.ts
rename to packages/tests/src/api/stats/video-views-retention-stats.ts
diff --git a/packages/tests/src/api/views/video-views-timeserie-stats.ts b/packages/tests/src/api/stats/video-views-timeserie-stats.ts
similarity index 100%
rename from packages/tests/src/api/views/video-views-timeserie-stats.ts
rename to packages/tests/src/api/stats/video-views-timeserie-stats.ts
diff --git a/packages/tests/src/api/views/video-views-user-agent-stats.ts b/packages/tests/src/api/stats/video-views-user-agent-stats.ts
similarity index 100%
rename from packages/tests/src/api/views/video-views-user-agent-stats.ts
rename to packages/tests/src/api/stats/video-views-user-agent-stats.ts
diff --git a/packages/tests/src/api/views/videos-views-cleaner.ts b/packages/tests/src/api/stats/videos-views-cleaner.ts
similarity index 98%
rename from packages/tests/src/api/views/videos-views-cleaner.ts
rename to packages/tests/src/api/stats/videos-views-cleaner.ts
index 9d087c775f..556b148aa2 100644
--- a/packages/tests/src/api/views/videos-views-cleaner.ts
+++ b/packages/tests/src/api/stats/videos-views-cleaner.ts
@@ -53,7 +53,7 @@ describe('Test video views cleaner', function () {
await killallServers([ servers[0] ])
await servers[0].run({ views: { videos: { remote: { max_age: '10 days' } } } })
- await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-views' } })
+ await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-stats' } })
for (let i = 0; i < servers.length; i++) {
const total = await sqlCommands[i].countVideoViewsOf(videoIdServer1)
@@ -75,7 +75,7 @@ describe('Test video views cleaner', function () {
await killallServers([ servers[0] ])
await servers[0].run({ views: { videos: { remote: { max_age: '5 seconds' } } } })
- await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-views' } })
+ await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-stats' } })
for (let i = 0; i < servers.length; i++) {
const total = await sqlCommands[i].countVideoViewsOf(videoIdServer1)
@@ -100,7 +100,7 @@ describe('Test video views cleaner', function () {
await killallServers([ servers[0] ])
await servers[0].run({ views: { videos: { local: { max_age: '5 hours' } } } })
- await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-views' } })
+ await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-stats' } })
for (let i = 0; i < servers.length; i++) {
const total = await sqlCommands[i].countVideoViewsOf(videoIdServer1)
@@ -123,7 +123,7 @@ describe('Test video views cleaner', function () {
await killallServers([ servers[0] ])
await servers[0].run({ views: { videos: { local: { max_age: '5 seconds' } } } })
- await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-views' } })
+ await servers[0].debug.sendCommand({ body: { command: 'process-remove-old-stats' } })
{
const totalServer1 = await sqlCommands[0].countVideoViewsOf(videoIdServer1)
diff --git a/packages/tests/src/api/videos/multiple-servers.ts b/packages/tests/src/api/videos/multiple-servers.ts
index 97f8850595..675e3ebdd9 100644
--- a/packages/tests/src/api/videos/multiple-servers.ts
+++ b/packages/tests/src/api/videos/multiple-servers.ts
@@ -514,7 +514,7 @@ describe('Test multiple servers', function () {
await waitJobs(servers)
for (const server of servers) {
- await server.debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
}
await waitJobs(servers)
@@ -550,7 +550,7 @@ describe('Test multiple servers', function () {
await waitJobs(servers)
for (const server of servers) {
- await server.debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
}
await waitJobs(servers)
diff --git a/packages/tests/src/api/videos/single-server.ts b/packages/tests/src/api/videos/single-server.ts
index c152f25518..88c7e9ceb1 100644
--- a/packages/tests/src/api/videos/single-server.ts
+++ b/packages/tests/src/api/videos/single-server.ts
@@ -189,7 +189,7 @@ describe('Test a single server', function () {
await server.views.simulateView({ id: videoId })
await server.views.simulateView({ id: videoId })
- await server.debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
const video = await server.videos.get({ id: videoId })
expect(video.views).to.equal(3)
diff --git a/packages/tests/src/client/jsonld.ts b/packages/tests/src/client/jsonld.ts
index 66b5ef71ff..ed45a17a21 100644
--- a/packages/tests/src/client/jsonld.ts
+++ b/packages/tests/src/client/jsonld.ts
@@ -66,7 +66,7 @@ describe('Test JSONLD HTML tags', function () {
await servers[0].videos.rate({ id: publicVideo.id, rating: 'like' })
await servers[0].views.simulateView({ id: publicVideo.id, xForwardedFor: '0.0.0.1,127.0.0.1' })
await servers[0].views.simulateView({ id: publicVideo.id, xForwardedFor: '0.0.0.2,127.0.0.1' })
- await servers[0].debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await servers[0].debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
}
{
diff --git a/packages/tests/src/shared/sql-command.ts b/packages/tests/src/shared/sql-command.ts
index 49ba8e0de1..b0083b49b4 100644
--- a/packages/tests/src/shared/sql-command.ts
+++ b/packages/tests/src/shared/sql-command.ts
@@ -42,8 +42,8 @@ export class SQLCommand {
}
async countVideoViewsOf (uuid: string) {
- const query = 'SELECT SUM("videoView"."views") AS "total" FROM "videoView" ' +
- `INNER JOIN "video" ON "video"."id" = "videoView"."videoId" WHERE "video"."uuid" = :uuid`
+ const query = 'SELECT SUM("videoStat"."views") AS "total" FROM "videoStat" ' +
+ `INNER JOIN "video" ON "video"."id" = "videoStat"."videoId" WHERE "video"."uuid" = :uuid`
const [ { total } ] = await this.selectQuery<{ total: number }>(query, { uuid })
if (!total) return 0
diff --git a/packages/tests/src/shared/views.ts b/packages/tests/src/shared/views.ts
index ea924d4a35..f22a4fb0b8 100644
--- a/packages/tests/src/shared/views.ts
+++ b/packages/tests/src/shared/views.ts
@@ -16,7 +16,7 @@ async function processViewersStats (servers: PeerTubeServer[]) {
await wait(6000)
for (const server of servers) {
- await server.debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
await server.debug.sendCommand({ body: { command: 'process-video-viewers' } })
}
@@ -25,7 +25,7 @@ async function processViewersStats (servers: PeerTubeServer[]) {
async function processViewsBuffer (servers: PeerTubeServer[]) {
for (const server of servers) {
- await server.debug.sendCommand({ body: { command: 'process-video-views-buffer' } })
+ await server.debug.sendCommand({ body: { command: 'process-video-stats-buffer' } })
}
await waitJobs(servers)
diff --git a/scripts/ci.sh b/scripts/ci.sh
index a98b777ec8..e82b2ea83c 100755
--- a/scripts/ci.sh
+++ b/scripts/ci.sh
@@ -110,9 +110,9 @@ elif [ "$1" = "api-3" ]; then
npm run build:tests
videosFiles=$(findTestFiles ./packages/tests/dist/api/videos)
- viewsFiles=$(findTestFiles ./packages/tests/dist/api/views)
+ statsFiles=$(findTestFiles ./packages/tests/dist/api/stats)
- MOCHA_PARALLEL=true runJSTest "$1" $((3*$speedFactor)) $viewsFiles $videosFiles
+ MOCHA_PARALLEL=true runJSTest "$1" $((3*$speedFactor)) $statsFiles $videosFiles
elif [ "$1" = "api-4" ]; then
npm run build:server
npm run build:tests
diff --git a/server/core/controllers/api/server/debug.ts b/server/core/controllers/api/server/debug.ts
index f843eb597e..5bf20e7894 100644
--- a/server/core/controllers/api/server/debug.ts
+++ b/server/core/controllers/api/server/debug.ts
@@ -15,13 +15,13 @@ import { InboxManager } from '@server/lib/activitypub/inbox-manager.js'
import { Emailer } from '@server/lib/emailer.js'
import { RemoveDanglingResumableUploadsScheduler } from '@server/lib/schedulers/remove-dangling-resumable-uploads-scheduler.js'
import { RemoveExpiredUserExportsScheduler } from '@server/lib/schedulers/remove-expired-user-exports-scheduler.js'
+import { RemoveOldStatsScheduler } from '@server/lib/schedulers/remove-old-stats-scheduler.js'
import { UpdateVideosScheduler } from '@server/lib/schedulers/update-videos-scheduler.js'
import { VideoChannelSyncLatestScheduler } from '@server/lib/schedulers/video-channel-sync-latest-scheduler.js'
-import { VideoViewsBufferScheduler } from '@server/lib/schedulers/video-views-buffer-scheduler.js'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsBufferScheduler } from '@server/lib/schedulers/video-stats-buffer-scheduler.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import express from 'express'
import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../../middlewares/index.js'
-import { RemoveOldViewsScheduler } from '@server/lib/schedulers/remove-old-views-scheduler.js'
const debugRouter = express.Router()
@@ -60,11 +60,11 @@ async function runCommand (req: express.Request, res: express.Response) {
const processors: { [id in SendDebugCommand['command']]: () => Promise<any> } = {
'remove-dandling-resumable-uploads': () => RemoveDanglingResumableUploadsScheduler.Instance.execute(),
'remove-expired-user-exports': () => RemoveExpiredUserExportsScheduler.Instance.execute(),
- 'process-video-views-buffer': () => VideoViewsBufferScheduler.Instance.execute(),
- 'process-video-viewers': () => VideoViewsManager.Instance.processViewerStats(),
+ 'process-video-stats-buffer': () => VideoStatsBufferScheduler.Instance.execute(),
+ 'process-video-viewers': () => VideoStatsManager.Instance.processViewerStats(),
'process-update-videos-scheduler': () => UpdateVideosScheduler.Instance.execute(),
'process-video-channel-sync-latest': () => VideoChannelSyncLatestScheduler.Instance.execute(),
- 'process-remove-old-views': () => RemoveOldViewsScheduler.Instance.execute(),
+ 'process-remove-old-stats': () => RemoveOldStatsScheduler.Instance.execute(),
'test-emails': () => testEmails(req, res)
}
diff --git a/server/core/controllers/api/videos/stats.ts b/server/core/controllers/api/videos/stats.ts
index 03c0de2cca..8ff3448b63 100644
--- a/server/core/controllers/api/videos/stats.ts
+++ b/server/core/controllers/api/videos/stats.ts
@@ -4,7 +4,8 @@ import {
VideoStatsTimeserieQuery,
VideoStatsUserAgentQuery
} from '@peertube/peertube-models'
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
+import { VideoStatModel } from '@server/models/stat/video-stat.js'
import express from 'express'
import {
asyncMiddleware,
@@ -89,15 +90,17 @@ async function getRetentionStats (req: express.Request, res: express.Response) {
async function getTimeseriesStats (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const metric = req.params.metric as VideoStatsTimeserieMetric
-
const query = req.query as VideoStatsTimeserieQuery
- const stats = await LocalVideoViewerModel.getTimeserieStats({
+ const options = {
video,
- metric,
startDate: query.startDate ?? video.createdAt.toISOString(),
endDate: query.endDate ?? new Date().toISOString()
- })
+ }
+
+ const stats = metric === 'downloads'
+ ? await VideoStatModel.getDownloadTimeserieStats(options)
+ : await LocalVideoViewerModel.getTimeserieStats({ ...options, metric })
return res.json(stats)
}
diff --git a/server/core/controllers/api/videos/view.ts b/server/core/controllers/api/videos/view.ts
index a75591ad50..9d395ae2cd 100644
--- a/server/core/controllers/api/videos/view.ts
+++ b/server/core/controllers/api/videos/view.ts
@@ -1,6 +1,6 @@
import { HttpStatusCode, VideoView } from '@peertube/peertube-models'
import { Hooks } from '@server/lib/plugins/hooks.js'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import { MVideoId } from '@server/types/models/index.js'
import express from 'express'
import {
@@ -37,7 +37,7 @@ async function viewVideo (req: express.Request, res: express.Response) {
const body = req.body as VideoView
const ip = req.ip
- const { successView } = await VideoViewsManager.Instance.processLocalView({
+ const { successView } = await VideoStatsManager.Instance.processLocalView({
video,
ip,
currentTime: body.currentTime,
diff --git a/server/core/controllers/download.ts b/server/core/controllers/download.ts
index 25b2498b40..b443ce1827 100644
--- a/server/core/controllers/download.ts
+++ b/server/core/controllers/download.ts
@@ -39,6 +39,7 @@ import {
videosDownloadValidator,
videosGenerateDownloadValidator
} from '../middlewares/index.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
const lTags = loggerTagsFactory('download')
@@ -176,6 +177,9 @@ async function downloadWebVideoFile (req: express.Request, res: express.Response
const downloadFilename = buildDownloadFilename({ video, resolution: videoFile.resolution, extname: videoFile.extname })
+ VideoStatsManager.Instance.processLocalDownload({ video })
+ .catch(err => logger.error(`Cannot process local download stats for video ${video.uuid}`, { err, ...lTags(video.uuid) }))
+
if (videoFile.storage === FileStorage.OBJECT_STORAGE) {
return redirectVideoDownloadToObjectStorage({ res, video, file: videoFile, downloadFilename })
}
@@ -214,6 +218,9 @@ async function downloadHLSVideoFile (req: express.Request, res: express.Response
if (!checkAllowResult(res, allowParameters, allowedResult)) return
+ VideoStatsManager.Instance.processLocalDownload({ video })
+ .catch(err => logger.error(`Cannot process local download stats for video ${video.uuid}`, { err, ...lTags(video.uuid) }))
+
const downloadFilename = buildDownloadFilename({ video, streamingPlaylist, resolution: videoFile.resolution, extname: videoFile.extname })
if (videoFile.storage === FileStorage.OBJECT_STORAGE) {
@@ -287,6 +294,9 @@ async function downloadGeneratedVideoFile (req: express.Request, res: express.Re
res.type(extname)
+ VideoStatsManager.Instance.processLocalDownload({ video })
+ .catch(err => logger.error(`Cannot process local download stats for video ${video.uuid}`, { err, ...lTags(video.uuid) }))
+
try {
await new VideoDownload({ video, videoFiles }).muxToMergeVideoFiles(res)
} catch (err) {
diff --git a/server/core/helpers/activity-pub-utils.ts b/server/core/helpers/activity-pub-utils.ts
index 43ab49a7d1..572ad78eaf 100644
--- a/server/core/helpers/activity-pub-utils.ts
+++ b/server/core/helpers/activity-pub-utils.ts
@@ -140,6 +140,10 @@ const contextStore: { [id in ContextType]: (string | { [id: string]: string })[]
'@type': 'sc:Number',
'@id': 'pt:views'
},
+ downloads: {
+ '@type': 'sc:Number',
+ '@id': 'pt:downloads'
+ },
state: {
'@type': 'sc:Number',
'@id': 'pt:state'
@@ -313,6 +317,13 @@ const contextStore: { [id in ContextType]: (string | { [id: string]: string })[]
},
theme: 'pt:theme'
+ }),
+
+ Download: buildContext({
+ DownloadAction: 'sc:DownloadAction',
+ InteractionCounter: 'sc:InteractionCounter',
+ interactionType: 'sc:interactionType',
+ userInteractionCount: 'sc:userInteractionCount'
})
}
diff --git a/server/core/helpers/custom-validators/activitypub/activity.ts b/server/core/helpers/custom-validators/activitypub/activity.ts
index 4e9365d62c..4d2b7d4fa9 100644
--- a/server/core/helpers/custom-validators/activitypub/activity.ts
+++ b/server/core/helpers/custom-validators/activitypub/activity.ts
@@ -43,7 +43,8 @@ const activityCheckers: { [P in ActivityType]: (activity: Activity) => boolean }
Flag: isFlagActivityValid,
Dislike: isDislikeActivityValid,
ApproveReply: isApproveReplyActivityValid,
- RejectReply: isRejectReplyActivityValid
+ RejectReply: isRejectReplyActivityValid,
+ Download: isDownloadActivityValid
}
export function isActivityValid (activity: any) {
@@ -148,3 +149,9 @@ export function isRejectReplyActivityValid (activity: any) {
isActivityPubUrlValid(activity.object) &&
isActivityPubUrlValid(activity.inReplyTo)
}
+
+export function isDownloadActivityValid (activity: any) {
+ return isBaseActivityValid(activity, 'Download') &&
+ isActivityPubUrlValid(activity.actor) &&
+ isActivityPubUrlValid(activity.object)
+}
diff --git a/server/core/helpers/custom-validators/video-stats.ts b/server/core/helpers/custom-validators/video-stats.ts
index 7bd30c8e22..f25c4b5721 100644
--- a/server/core/helpers/custom-validators/video-stats.ts
+++ b/server/core/helpers/custom-validators/video-stats.ts
@@ -2,7 +2,8 @@ import { VideoStatsTimeserieMetric } from '@peertube/peertube-models'
const validMetrics = new Set<VideoStatsTimeserieMetric>([
'viewers',
- 'aggregateWatchTime'
+ 'aggregateWatchTime',
+ 'downloads'
])
function isValidStatTimeserieMetric (value: VideoStatsTimeserieMetric) {
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index 616701080a..c2a70bbad6 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -60,7 +60,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'
// ---------------------------------------------------------------------------
-export const LAST_MIGRATION_VERSION = 1000
+export const LAST_MIGRATION_VERSION = 1005
// ---------------------------------------------------------------------------
@@ -219,7 +219,7 @@ export const JOB_ATTEMPTS: { [id in JobType]: number } = {
'video-import': 1,
'email': 5,
'actor-keys': 3,
- 'videos-views-stats': 1,
+ 'videos-stats': 1,
'activitypub-refresher': 1,
'video-redundancy': 1,
'video-live-ending': 1,
@@ -248,7 +248,7 @@ export const JOB_CONCURRENCY: { [id in Exclude<JobType, 'video-transcoding' | 'v
'video-file-import': 1,
'email': 5,
'actor-keys': 1,
- 'videos-views-stats': 1,
+ 'videos-stats': 1,
'activitypub-refresher': 1,
'video-redundancy': 1,
'video-live-ending': 10,
@@ -279,7 +279,7 @@ export const JOB_TTL: { [id in JobType]: number } = {
'video-import': CONFIG.IMPORT.VIDEOS.TIMEOUT,
'email': 60000 * 10, // 10 minutes
'actor-keys': 60000 * 20, // 20 minutes
- 'videos-views-stats': undefined, // Unlimited
+ 'videos-stats': undefined, // Unlimited
'activitypub-refresher': 60000 * 10, // 10 minutes
'video-redundancy': 1000 * 3600 * 3, // 3 hours
'video-live-ending': 1000 * 60 * 10, // 10 minutes
@@ -297,7 +297,7 @@ export const JOB_TTL: { [id in JobType]: number } = {
'video-transcription': CONFIG.VIDEO_TRANSCRIPTION.TIMEOUT
}
export const REPEAT_JOBS: { [id in JobType]?: RepeatOptions } = {
- 'videos-views-stats': {
+ 'videos-stats': {
pattern: randomInt(1, 20) + ' * * * *' // Between 1-20 minutes past the hour
},
'activitypub-cleaner': {
@@ -320,7 +320,7 @@ export const JOB_REMOVAL_OPTIONS = {
'activitypub-http-broadcast-parallel': parseDurationToMs('10 minutes'),
'activitypub-http-unicast': parseDurationToMs('1 hour'),
- 'videos-views-stats': parseDurationToMs('3 hours'),
+ 'videos-stats': parseDurationToMs('3 hours'),
'activitypub-refresher': parseDurationToMs('10 hours')
},
@@ -362,11 +362,11 @@ export const SCHEDULER_INTERVALS_MS = {
UPDATE_TOKEN_SESSION: 60000, // 1 minute
YOUTUBE_DL_UPDATE: 60000 * 60 * 24, // 1 day
GEO_IP_UPDATE: 60000 * 60 * 24, // 1 day
- VIDEO_VIEWS_BUFFER_UPDATE: CONFIG.VIEWS.VIDEOS.LOCAL_BUFFER_UPDATE_INTERVAL,
+ VIDEO_STATS_BUFFER_UPDATE: CONFIG.VIEWS.VIDEOS.LOCAL_BUFFER_UPDATE_INTERVAL,
CHECK_PLUGINS: CONFIG.PLUGINS.INDEX.CHECK_LATEST_VERSIONS_INTERVAL,
CHECK_PEERTUBE_VERSION: 60000 * 60 * 24, // 1 day
AUTO_FOLLOW_INDEX_INSTANCES: 60000 * 60 * 24, // 1 day
- REMOVE_OLD_VIEWS: 60000 * 60 * 24, // 1 day
+ REMOVE_OLD_STATS: 60000 * 60 * 24, // 1 day
REMOVE_OLD_HISTORY: 60000 * 60 * 24, // 1 day
REMOVE_EXPIRED_USER_EXPORTS: 1000 * 3600, // 1 hour
UPDATE_INBOX_STATS: 1000 * 60, // 1 minute
@@ -558,6 +558,10 @@ export const VIEW_LIFETIME = {
}
export let VIEWER_SYNC_REDIS = 30000 // Sync viewer into redis
+export const STATS_LIFETIME = {
+ DOWNLOADS: 60000 * 60 // 1 hour
+}
+
export const MAX_LOCAL_VIEWER_WATCH_SECTIONS = 100
export let CONTACT_FORM_LIFETIME = 60000 * 60 // 1 hour
@@ -1275,7 +1279,7 @@ if (process.env.PRODUCTION_CONSTANTS !== 'true') {
SCHEDULER_INTERVALS_MS.CHECK_PEERTUBE_VERSION = 2000
SCHEDULER_INTERVALS_MS.UPDATE_TOKEN_SESSION = 2000
- REPEAT_JOBS['videos-views-stats'] = { every: 5000 }
+ REPEAT_JOBS['videos-stats'] = { every: 5000 }
REPEAT_JOBS['activitypub-cleaner'] = { every: 5000 }
AP_CLEANER.PERIOD = 5000
@@ -1294,7 +1298,7 @@ if (process.env.PRODUCTION_CONSTANTS !== 'true') {
PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME = 5000
- JOB_REMOVAL_OPTIONS.SUCCESS['videos-views-stats'] = 10000
+ JOB_REMOVAL_OPTIONS.SUCCESS['videos-stats'] = 10000
VIEWER_SYNC_REDIS = 1000
}
diff --git a/server/core/initializers/database.ts b/server/core/initializers/database.ts
index 4d1dd29c57..9a96cc5117 100644
--- a/server/core/initializers/database.ts
+++ b/server/core/initializers/database.ts
@@ -30,8 +30,8 @@ import { VideoLiveScheduleModel } from '@server/models/video/video-live-schedule
import { VideoLiveSessionModel } from '@server/models/video/video-live-session.js'
import { VideoPasswordModel } from '@server/models/video/video-password.js'
import { VideoSourceModel } from '@server/models/video/video-source.js'
-import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section.js'
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
+import { LocalVideoViewerWatchSectionModel } from '@server/models/stat/local-video-viewer-watch-section.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
import { WatchedWordsListModel } from '@server/models/watched-words/watched-words-list.js'
import { readFileSync } from 'fs'
import pg from 'pg'
@@ -73,7 +73,7 @@ import { VideoShareModel } from '../models/video/video-share.js'
import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist.js'
import { VideoTagModel } from '../models/video/video-tag.js'
import { VideoModel } from '../models/video/video.js'
-import { VideoViewModel } from '../models/view/video-view.js'
+import { VideoStatModel } from '../models/stat/video-stat.js'
import { CONFIG } from './config.js'
pg.defaults.parseInt8 = true // Avoid BIGINT to be converted to string
@@ -173,7 +173,7 @@ export async function initDatabaseModels (silent: boolean) {
VideoCommentModel,
ScheduleVideoUpdateModel,
VideoImportModel,
- VideoViewModel,
+ VideoStatModel,
VideoRedundancyModel,
UserVideoHistoryModel,
VideoLiveModel,
diff --git a/server/core/initializers/migrations/1005-download-stats.ts b/server/core/initializers/migrations/1005-download-stats.ts
new file mode 100644
index 0000000000..d152b92282
--- /dev/null
+++ b/server/core/initializers/migrations/1005-download-stats.ts
@@ -0,0 +1,36 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ {
+ await utils.queryInterface.addColumn('video', 'downloads', {
+ type: Sequelize.INTEGER,
+ allowNull: false,
+ defaultValue: 0
+ }, { transaction: utils.transaction })
+
+ await utils.queryInterface.renameTable('videoView', 'videoStat', { transaction: utils.transaction })
+
+ await utils.queryInterface.addColumn('videoStat', 'downloads', {
+ type: Sequelize.INTEGER,
+ allowNull: false,
+ defaultValue: 0
+ }, { transaction: utils.transaction })
+ }
+}
+
+async function down (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ await utils.queryInterface.removeColumn('video', 'downloads', { transaction: utils.transaction })
+ await utils.queryInterface.removeColumn('videoStat', 'downloads', { transaction: utils.transaction })
+
+ await utils.queryInterface.renameTable('videoStat', 'videoView', { transaction: utils.transaction })
+}
+
+export { up, down }
diff --git a/server/core/lib/activitypub/local-video-viewer.ts b/server/core/lib/activitypub/local-video-viewer.ts
index 8669054d7e..d030a5e2ab 100644
--- a/server/core/lib/activitypub/local-video-viewer.ts
+++ b/server/core/lib/activitypub/local-video-viewer.ts
@@ -1,6 +1,6 @@
import { Transaction } from 'sequelize'
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
-import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
+import { LocalVideoViewerWatchSectionModel } from '@server/models/stat/local-video-viewer-watch-section.js'
import { MVideo } from '@server/types/models/index.js'
import { WatchActionObject } from '@peertube/peertube-models'
import { getDurationFromActivityStream } from './activity.js'
diff --git a/server/core/lib/activitypub/process/process-download.ts b/server/core/lib/activitypub/process/process-download.ts
new file mode 100644
index 0000000000..a85380ac42
--- /dev/null
+++ b/server/core/lib/activitypub/process/process-download.ts
@@ -0,0 +1,30 @@
+import { ActivityView } from '@peertube/peertube-models'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
+import { APProcessorOptions } from '../../../types/activitypub-processor.model.js'
+import { getOrCreateAPVideo } from '../videos/index.js'
+
+async function processDownloadActivity (options: APProcessorOptions<ActivityView>) {
+ const { activity } = options
+
+ return processCreateDownload(activity)
+}
+
+// ---------------------------------------------------------------------------
+
+export {
+ processDownloadActivity
+}
+
+// ---------------------------------------------------------------------------
+
+async function processCreateDownload (activity: ActivityView) {
+ const videoObject = activity.object
+
+ const { video } = await getOrCreateAPVideo({
+ videoObject,
+ fetchType: 'only-video-and-blacklist',
+ allowRefresh: false
+ })
+
+ await VideoStatsManager.Instance.processRemoteDownload({ video })
+}
diff --git a/server/core/lib/activitypub/process/process-view.ts b/server/core/lib/activitypub/process/process-view.ts
index 6ea508cfe5..c1f61196a4 100644
--- a/server/core/lib/activitypub/process/process-view.ts
+++ b/server/core/lib/activitypub/process/process-view.ts
@@ -1,5 +1,5 @@
import { ActivityView } from '@peertube/peertube-models'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import { APProcessorOptions } from '../../../types/activitypub-processor.model.js'
import { MActorSignature } from '../../../types/models/index.js'
import { forwardVideoRelatedActivity } from '../send/shared/send-utils.js'
@@ -28,7 +28,7 @@ async function processCreateView (activity: ActivityView, byActor: MActorSignatu
allowRefresh: false
})
- await VideoViewsManager.Instance.processRemoteView({
+ await VideoStatsManager.Instance.processRemoteView({
video,
viewerId: activity.id,
diff --git a/server/core/lib/activitypub/process/process.ts b/server/core/lib/activitypub/process/process.ts
index 1db0e6f06b..30d3795a23 100644
--- a/server/core/lib/activitypub/process/process.ts
+++ b/server/core/lib/activitypub/process/process.ts
@@ -19,6 +19,7 @@ import { processReplyApprovalFactory } from './process-reply-approval.js'
import { processUndoActivity } from './process-undo.js'
import { processUpdateActivity } from './process-update.js'
import { processViewActivity } from './process-view.js'
+import { processDownloadActivity } from './process-download.js'
const processActivity: { [ P in ActivityType ]: (options: APProcessorOptions<Activity>) => Promise<any> } = {
Create: processCreateActivity,
@@ -33,6 +34,7 @@ const processActivity: { [ P in ActivityType ]: (options: APProcessorOptions<Act
Dislike: processDislikeActivity,
Flag: processFlagActivity,
View: processViewActivity,
+ Download: processDownloadActivity,
ApproveReply: processReplyApprovalFactory('ApproveReply'),
RejectReply: processReplyApprovalFactory('RejectReply')
}
diff --git a/server/core/lib/activitypub/send/send-download.ts b/server/core/lib/activitypub/send/send-download.ts
new file mode 100644
index 0000000000..0c123f3ddb
--- /dev/null
+++ b/server/core/lib/activitypub/send/send-download.ts
@@ -0,0 +1,63 @@
+import { ActivityAudience, ActivityDownload } from '@peertube/peertube-models'
+import { MActorAudience, MActorLight, MVideoImmutable, MVideoUrl } from '@server/types/models/index.js'
+import { Transaction } from 'sequelize'
+import { logger } from '../../../helpers/logger.js'
+import { audiencify, getPublicAudience } from '../audience.js'
+import { getDownloadsActivityPubUrl } from '../url.js'
+import { sendVideoRelatedActivity } from './shared/send-utils.js'
+
+async function sendDownload (options: {
+ byActor: MActorLight
+ video: MVideoImmutable
+ transaction?: Transaction
+}) {
+ const { byActor, video, transaction } = options
+
+ logger.info('Creating job to send downloads of %s.', video.url)
+
+ const activityBuilder = (audience: ActivityAudience) => {
+ const url = getDownloadsActivityPubUrl(byActor, video)
+
+ return buildDownloadActivity({
+ url,
+ byActor,
+ video,
+ audience
+ })
+ }
+
+ return sendVideoRelatedActivity(activityBuilder, {
+ byActor,
+ video,
+ transaction,
+ contextType: 'Download',
+ parallelizable: true
+ })
+}
+
+// ---------------------------------------------------------------------------
+
+export { sendDownload }
+
+// ---------------------------------------------------------------------------
+
+function buildDownloadActivity (options: {
+ url: string
+ byActor: MActorAudience
+ video: MVideoUrl
+ audience?: ActivityAudience
+}): ActivityDownload {
+ const {
+ url,
+ byActor,
+ video,
+ audience = getPublicAudience(byActor)
+ } = options
+
+ return audiencify({
+ id: url,
+ type: 'Download' as 'Download',
+ actor: byActor.url,
+ object: video.url
+ }, audience)
+}
diff --git a/server/core/lib/activitypub/send/send-view.ts b/server/core/lib/activitypub/send/send-view.ts
index 59659837dc..30ec19662a 100644
--- a/server/core/lib/activitypub/send/send-view.ts
+++ b/server/core/lib/activitypub/send/send-view.ts
@@ -1,5 +1,5 @@
import { ActivityAudience, ActivityView } from '@peertube/peertube-models'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import { MActorAudience, MActorLight, MVideoImmutable, MVideoUrl } from '@server/types/models/index.js'
import { Transaction } from 'sequelize'
import { logger } from '../../../helpers/logger.js'
@@ -58,7 +58,7 @@ function buildViewActivity (options: {
return audiencify({
...base,
- expires: new Date(VideoViewsManager.Instance.buildViewerExpireTime()).toISOString(),
+ expires: new Date(VideoStatsManager.Instance.buildViewerExpireTime()).toISOString(),
result: {
interactionType: 'WatchAction',
diff --git a/server/core/lib/activitypub/url.ts b/server/core/lib/activitypub/url.ts
index 76de2b4e4d..5ca54a9b1f 100644
--- a/server/core/lib/activitypub/url.ts
+++ b/server/core/lib/activitypub/url.ts
@@ -1,3 +1,4 @@
+import { buildSUUID } from '@peertube/peertube-node-utils'
import { REMOTE_SCHEME, WEBSERVER } from '../../initializers/constants.js'
import {
MAbuseFull,
@@ -129,6 +130,10 @@ export function getLocalApproveReplyActivityPubUrl (video: MVideoUUID, comment:
return getLocalVideoCommentActivityPubUrl(video, comment) + '/approve-reply'
}
+export function getDownloadsActivityPubUrl (byActor: MActorUrl, video: MVideoId) {
+ return byActor.url + '/downloads/videos/' + video.id + '/' + buildSUUID()
+}
+
// ---------------------------------------------------------------------------
// Try to fetch target URL
diff --git a/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts b/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
index b6059897cf..fff8442a58 100644
--- a/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
+++ b/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
@@ -312,6 +312,7 @@ export function getVideoAttributesFromObject (videoChannel: MChannelId, videoObj
updatedAt: new Date(videoObject.updated),
views: videoObject.views,
+ downloads: videoObject.downloads || 0,
remote: true,
privacy
}
diff --git a/server/core/lib/activitypub/videos/updater.ts b/server/core/lib/activitypub/videos/updater.ts
index 97284e05f0..aa2f300f0c 100644
--- a/server/core/lib/activitypub/videos/updater.ts
+++ b/server/core/lib/activitypub/videos/updater.ts
@@ -142,6 +142,7 @@ export class APVideoUpdater extends APVideoAbstractBuilder {
this.video.privacy = videoData.privacy
this.video.channelId = videoData.channelId
this.video.views = videoData.views
+ this.video.downloads = videoData.downloads
this.video.isLive = videoData.isLive
this.video.aspectRatio = videoData.aspectRatio
this.video.embedPrivacyPolicy = videoData.embedPrivacyPolicy
diff --git a/server/core/lib/job-queue/handlers/video-stats.ts b/server/core/lib/job-queue/handlers/video-stats.ts
new file mode 100644
index 0000000000..916d091944
--- /dev/null
+++ b/server/core/lib/job-queue/handlers/video-stats.ts
@@ -0,0 +1,66 @@
+import { isTestOrDevInstance } from '@peertube/peertube-node-utils'
+import { VideoStatModel } from '@server/models/stat/video-stat.js'
+import { logger } from '../../../helpers/logger.js'
+import { VideoModel } from '../../../models/video/video.js'
+import { Redis } from '../../redis.js'
+
+/**
+ * Add number of stats grabbed in a time-range to the database, so we can calculate stats timeseries
+ */
+
+export async function processVideosStats () {
+ const lastHour = new Date()
+
+ // In test mode, we run this function multiple times per hour, so we don't want the values of the previous hour
+ if (!isTestOrDevInstance()) lastHour.setHours(lastHour.getHours() - 1)
+
+ const hour = lastHour.getHours()
+ const startDate = lastHour.setMinutes(0, 0, 0)
+ const endDate = lastHour.setMinutes(59, 59, 999)
+
+ const videoIds = await Redis.Instance.listVideosForStats(hour)
+ if (videoIds.length === 0) return
+
+ logger.info(`Processing videos stats in job for hour ${hour}`)
+
+ for (const videoId of videoIds) {
+ try {
+ const views = await Redis.Instance.getVideoStats('views', videoId, hour)
+ const downloads = await Redis.Instance.getVideoStats('downloads', videoId, hour)
+
+ await Redis.Instance.deleteVideoStats(videoId, hour)
+
+ if (!views && !downloads) continue
+
+ logger.debug(
+ `Adding ${views} views and ${downloads} downloads to video ${videoId} stats in hour ${hour}.`,
+ views,
+ downloads,
+ videoId,
+ hour
+ )
+
+ try {
+ const video = await VideoModel.load(videoId)
+ if (!video) {
+ logger.debug(`Video ${videoId} does not exist anymore, skipping videos stats.`)
+ continue
+ }
+
+ await VideoStatModel.create({
+ startDate: new Date(startDate),
+ endDate: new Date(endDate),
+
+ views,
+ downloads,
+
+ videoId
+ })
+ } catch (err) {
+ logger.error('Cannot create video stats for video %d in hour %d.', videoId, hour, { err })
+ }
+ } catch (err) {
+ logger.error('Cannot update video stats of video %d in hour %d.', videoId, hour, { err })
+ }
+ }
+}
diff --git a/server/core/lib/job-queue/handlers/video-views-stats.ts b/server/core/lib/job-queue/handlers/video-views-stats.ts
deleted file mode 100644
index 479b47ed08..0000000000
--- a/server/core/lib/job-queue/handlers/video-views-stats.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { isTestOrDevInstance } from '@peertube/peertube-node-utils'
-import { VideoViewModel } from '@server/models/view/video-view.js'
-import { logger } from '../../../helpers/logger.js'
-import { VideoModel } from '../../../models/video/video.js'
-import { Redis } from '../../redis.js'
-
-async function processVideosViewsStats () {
- const lastHour = new Date()
-
- // In test mode, we run this function multiple times per hour, so we don't want the values of the previous hour
- if (!isTestOrDevInstance()) lastHour.setHours(lastHour.getHours() - 1)
-
- const hour = lastHour.getHours()
- const startDate = lastHour.setMinutes(0, 0, 0)
- const endDate = lastHour.setMinutes(59, 59, 999)
-
- const videoIds = await Redis.Instance.listVideosViewedForStats(hour)
- if (videoIds.length === 0) return
-
- logger.info('Processing videos views stats in job for hour %d.', hour)
-
- for (const videoId of videoIds) {
- try {
- const views = await Redis.Instance.getVideoViewsStats(videoId, hour)
- await Redis.Instance.deleteVideoViewsStats(videoId, hour)
-
- if (views) {
- logger.debug('Adding %d views to video %d stats in hour %d.', views, videoId, hour)
-
- try {
- const video = await VideoModel.load(videoId)
- if (!video) {
- logger.debug('Video %d does not exist anymore, skipping videos view stats.', videoId)
- continue
- }
-
- await VideoViewModel.create({
- startDate: new Date(startDate),
- endDate: new Date(endDate),
- views,
- videoId
- })
- } catch (err) {
- logger.error('Cannot create video views stats for video %d in hour %d.', videoId, hour, { err })
- }
- }
- } catch (err) {
- logger.error('Cannot update video views stats of video %d in hour %d.', videoId, hour, { err })
- }
- }
-}
-
-// ---------------------------------------------------------------------------
-
-export {
- processVideosViewsStats
-}
diff --git a/server/core/lib/job-queue/job-queue.ts b/server/core/lib/job-queue/job-queue.ts
index 6ac3753a73..98beae3e4d 100644
--- a/server/core/lib/job-queue/job-queue.ts
+++ b/server/core/lib/job-queue/job-queue.ts
@@ -74,7 +74,7 @@ import { processVideoLiveEnding } from './handlers/video-live-ending.js'
import { processVideoStudioEdition } from './handlers/video-studio-edition.js'
import { processVideoTranscoding } from './handlers/video-transcoding.js'
import { processVideoTranscription } from './handlers/video-transcription.js'
-import { processVideosViewsStats } from './handlers/video-views-stats.js'
+import { processVideosStats } from './handlers/video-stats.js'
export type CreateJobArgument =
| { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload }
@@ -89,7 +89,7 @@ export type CreateJobArgument =
| { type: 'transcoding-job-builder', payload: TranscodingJobBuilderPayload }
| { type: 'video-import', payload: VideoImportPayload }
| { type: 'activitypub-refresher', payload: RefreshPayload }
- | { type: 'videos-views-stats', payload: {} }
+ | { type: 'videos-stats', payload: {} }
| { type: 'video-live-ending', payload: VideoLiveEndingPayload }
| { type: 'actor-keys', payload: ActorKeysPayload }
| { type: 'video-redundancy', payload: VideoRedundancyPayload }
@@ -136,7 +136,7 @@ const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
'video-redundancy': processVideoRedundancy,
'video-studio-edition': processVideoStudioEdition,
'video-transcoding': processVideoTranscoding,
- 'videos-views-stats': processVideosViewsStats,
+ 'videos-stats': processVideosStats,
'generate-video-storyboard': processGenerateStoryboard,
'create-user-export': processCreateUserExport,
'import-user-archive': processImportUserArchive,
@@ -173,7 +173,7 @@ const jobTypes: JobType[] = [
'video-redundancy',
'video-studio-edition',
'video-transcription',
- 'videos-views-stats',
+ 'videos-stats',
'create-user-export',
'import-user-archive',
'video-transcoding'
@@ -520,10 +520,10 @@ class JobQueue {
// ---------------------------------------------------------------------------
private addRepeatableJobs () {
- this.queues['videos-views-stats'].add('job', {}, {
- repeat: REPEAT_JOBS['videos-views-stats'],
+ this.queues['videos-stats'].add('job', {}, {
+ repeat: REPEAT_JOBS['videos-stats'],
- ...this.buildJobRemovalOptions('videos-views-stats')
+ ...this.buildJobRemovalOptions('videos-stats')
}).catch(err => logger.error('Cannot add repeatable job.', { err }))
if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
diff --git a/server/core/lib/opentelemetry/metric-helpers/stats-observers-builder.ts b/server/core/lib/opentelemetry/metric-helpers/stats-observers-builder.ts
index 5817b6ef3b..ed411e94fa 100644
--- a/server/core/lib/opentelemetry/metric-helpers/stats-observers-builder.ts
+++ b/server/core/lib/opentelemetry/metric-helpers/stats-observers-builder.ts
@@ -81,6 +81,14 @@ export class StatsObserversBuilder {
observableResult.observe(stats.totalLocalVideoViews, { viewOrigin: 'local' })
})
+ this.meter.createObservableGauge('peertube_video_downloads_total', {
+ description: 'Total video downloads made on the instance'
+ }).addCallback(async observableResult => {
+ const stats = await this.getInstanceStats()
+
+ observableResult.observe(stats.totalLocalVideoDownloads, { viewOrigin: 'local' })
+ })
+
this.meter.createObservableGauge('peertube_video_bytes_total', {
description: 'Total bytes of videos'
}).addCallback(async observableResult => {
diff --git a/server/core/lib/opentelemetry/metric-helpers/viewers-observers-builder.ts b/server/core/lib/opentelemetry/metric-helpers/viewers-observers-builder.ts
index a1e1c74963..1d06f277bb 100644
--- a/server/core/lib/opentelemetry/metric-helpers/viewers-observers-builder.ts
+++ b/server/core/lib/opentelemetry/metric-helpers/viewers-observers-builder.ts
@@ -1,11 +1,9 @@
import { Meter } from '@opentelemetry/api'
-import { VideoScope, ViewerScope } from '@server/lib/views/shared/index.js'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoScope, ViewerScope } from '@server/lib/stats/shared/index.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
export class ViewersObserversBuilder {
-
constructor (private readonly meter: Meter) {
-
}
buildObservers () {
@@ -14,7 +12,7 @@ export class ViewersObserversBuilder {
}).addCallback(observableResult => {
for (const viewerScope of [ 'local', 'remote' ] as ViewerScope[]) {
for (const videoScope of [ 'local', 'remote' ] as VideoScope[]) {
- const result = VideoViewsManager.Instance.getTotalViewers({ viewerScope, videoScope })
+ const result = VideoStatsManager.Instance.getTotalViewers({ viewerScope, videoScope })
observableResult.observe(result, { viewerOrigin: viewerScope, videoOrigin: videoScope })
}
diff --git a/server/core/lib/redis.ts b/server/core/lib/redis.ts
index 4be4a19bc3..f6609b0ec8 100644
--- a/server/core/lib/redis.ts
+++ b/server/core/lib/redis.ts
@@ -20,6 +20,8 @@ import {
const lTags = loggerTagsFactory('redis')
+type StatKind = 'views' | 'downloads'
+
class Redis {
private static instance: Redis
private initialized = false
@@ -234,10 +236,10 @@ class Redis {
return this.exists(this.generateSessionIdViewKey(sessionId, videoUUID))
}
- /* ************ Video views stats ************ */
+ /* ************ Video stats ************ */
- addVideoViewStats (videoId: number) {
- const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
+ addVideoStat (kind: StatKind, videoId: number) {
+ const { videoKey, setKey } = this.generateVideoStatsKeys({ kind, videoId })
return Promise.all([
this.addToSet(setKey, videoId.toString()),
@@ -245,40 +247,39 @@ class Redis {
])
}
- async getVideoViewsStats (videoId: number, hour: number) {
- const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
+ async getVideoStats (kind: StatKind, videoId: number, hour: number) {
+ const { videoKey } = this.generateVideoStatsKeys({ kind, videoId, hour })
const valueString = await this.getValue(videoKey)
const valueInt = parseInt(valueString, 10)
- if (isNaN(valueInt)) {
- logger.error(`Cannot get videos views stats of video ${videoId} in hour ${hour}: views number is NaN (${valueString}).`, lTags())
- return undefined
- }
+ if (isNaN(valueInt)) return undefined
return valueInt
}
- async listVideosViewedForStats (hour: number) {
- const { setKey } = this.generateVideoViewStatsKeys({ hour })
+ async listVideosForStats (hour: number) {
+ const { setKey } = this.generateVideoStatsKeys({ hour })
const stringIds = await this.getSet(setKey)
return stringIds.map(s => parseInt(s, 10))
}
- deleteVideoViewsStats (videoId: number, hour: number) {
- const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
+ async deleteVideoStats (videoId: number, hour: number) {
+ for (const kind of ([ 'views', 'downloads' ] as StatKind[])) {
+ const { setKey, videoKey } = this.generateVideoStatsKeys({ kind, videoId, hour })
- return Promise.all([
- this.deleteFromSet(setKey, videoId.toString()),
- this.deleteKey(videoKey)
- ])
+ await Promise.all([
+ this.deleteFromSet(setKey, videoId.toString()),
+ this.deleteKey(videoKey)
+ ])
+ }
}
- /* ************ Local video views buffer ************ */
+ /* ************ Local video stats buffer ************ */
- addLocalVideoView (videoId: number) {
- const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
+ addLocalVideoStat (kind: StatKind, videoId: number) {
+ const { videoKey, setKey } = this.generateLocalVideoStatKeys(kind, videoId)
return Promise.all([
this.addToSet(setKey, videoId.toString()),
@@ -286,34 +287,33 @@ class Redis {
])
}
- async getLocalVideoViews (videoId: number) {
- const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
+ async getLocalVideoStats (kind: StatKind, videoId: number) {
+ const { videoKey } = this.generateLocalVideoStatKeys(kind, videoId)
const valueString = await this.getValue(videoKey)
const valueInt = parseInt(valueString, 10)
- if (isNaN(valueInt)) {
- logger.error(`Cannot get videos views of video ${videoId}: views number is NaN (${valueString}).`, lTags())
- return undefined
- }
+ if (isNaN(valueInt)) return undefined
return valueInt
}
- async listLocalVideosViewed () {
- const { setKey } = this.generateLocalVideoViewsKeys()
+ async listLocalVideosWithStats () {
+ const { setKey } = this.generateLocalVideoStatKeys()
const stringIds = await this.getSet(setKey)
return stringIds.map(s => parseInt(s, 10))
}
- deleteLocalVideoViews (videoId: number) {
- const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
+ async deleteLocalVideoStats (videoId: number) {
+ for (const kind of ([ 'views', 'downloads' ] as StatKind[])) {
+ const { setKey, videoKey } = this.generateLocalVideoStatKeys(kind, videoId)
- return Promise.all([
- this.deleteFromSet(setKey, videoId.toString()),
- this.deleteKey(videoKey)
- ])
+ await Promise.all([
+ this.deleteFromSet(setKey, videoId.toString()),
+ this.deleteKey(videoKey)
+ ])
+ }
}
/* ************ Video viewers stats ************ */
@@ -355,6 +355,46 @@ class Redis {
])
}
+ /* ************ Generic stats ************ */
+
+ getStats (options: {
+ key?: string
+ // Or
+ scope?: string
+ ip?: string
+ videoId?: number
+ }) {
+ if (options.key) return this.getObject(options.key)
+
+ const { key } = this.generateKeysForStats(options.scope, options.ip, options.videoId)
+
+ return this.getObject(key)
+ }
+
+ setStats (scope: string, sessionId: string, videoId: number, object: any) {
+ const { setKey, key } = this.generateKeysForStats(scope, sessionId, videoId)
+
+ return Promise.all([
+ this.addToSet(setKey, key),
+ this.setObject(key, object)
+ ])
+ }
+
+ getStatsKeys (scope: string) {
+ const { setKey } = this.generateKeysForStats(scope)
+
+ return this.getSet(setKey)
+ }
+
+ deleteStatsKey (scope: string, key: string) {
+ const { setKey } = this.generateKeysForStats(scope)
+
+ return Promise.all([
+ this.deleteFromSet(setKey, key),
+ this.deleteKey(key)
+ ])
+ }
+
/* ************ Resumable uploads final responses ************ */
setUploadSession (uploadId: string) {
@@ -382,10 +422,15 @@ class Redis {
/* ************ Keys generation ************ */
- private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
- private generateLocalVideoViewsKeys (): { setKey: string }
- private generateLocalVideoViewsKeys (videoId?: number) {
- return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
+ private generateLocalVideoStatKeys (type: StatKind, videoId: number): { setKey: string, videoKey: string }
+ private generateLocalVideoStatKeys (): { setKey: string }
+ private generateLocalVideoStatKeys (type?: StatKind, videoId?: number) {
+ const setKey = `local-video-stats-buffer`
+ if (!type || !videoId) return { setKey }
+
+ const videoKey = `local-video-${type}-buffer-${videoId}`
+
+ return { setKey, videoKey }
}
generateLocalVideoViewerKeys (sessionId: string, videoId: number): { setKey: string, viewerKey: string }
@@ -400,12 +445,30 @@ class Redis {
}
}
- private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
+ private generateVideoStatsKeys (options: { hour: number }): { setKey: string }
+ private generateVideoStatsKeys (options: { videoId: number, hour?: number, kind: StatKind }): { setKey: string, videoKey: string }
+ private generateVideoStatsKeys (options: { kind?: StatKind, videoId?: number, hour?: number }) {
const hour = exists(options.hour)
? options.hour
: new Date().getHours()
- return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
+ if (!options.kind || !options.videoId) {
+ return { setKey: `videos-stats-h${hour}` }
+ }
+
+ return { setKey: `videos-stats-h${hour}`, videoKey: `video-${options.kind}-${options.videoId}-h${hour}` }
+ }
+
+ generateKeysForStats (scope: string, sessionId: string, videoId: number): { setKey: string, key: string }
+ generateKeysForStats (scole: string): { setKey: string }
+ generateKeysForStats (scope: string, sessionId?: string, videoId?: number) {
+ return {
+ setKey: `${scope}-stats-keys`,
+
+ key: sessionId && videoId
+ ? `${scope}-stats-${sessionId}-${videoId}`
+ : undefined
+ }
}
private generateResetPasswordKey (userId: number) {
diff --git a/server/core/lib/schedulers/remove-old-views-scheduler.ts b/server/core/lib/schedulers/remove-old-stats-scheduler.ts
similarity index 73%
rename from server/core/lib/schedulers/remove-old-views-scheduler.ts
rename to server/core/lib/schedulers/remove-old-stats-scheduler.ts
index 3c5a9329c8..bef17211e6 100644
--- a/server/core/lib/schedulers/remove-old-views-scheduler.ts
+++ b/server/core/lib/schedulers/remove-old-stats-scheduler.ts
@@ -1,5 +1,5 @@
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
-import { VideoViewModel } from '@server/models/view/video-view.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
+import { VideoStatModel } from '@server/models/stat/video-stat.js'
import { logger, loggerTagsFactory } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants.js'
@@ -7,10 +7,10 @@ import { AbstractScheduler } from './abstract-scheduler.js'
const lTags = loggerTagsFactory('schedulers')
-export class RemoveOldViewsScheduler extends AbstractScheduler {
+export class RemoveOldStatsScheduler extends AbstractScheduler {
private static instance: AbstractScheduler
- protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.REMOVE_OLD_VIEWS
+ protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.REMOVE_OLD_STATS
private constructor () {
super({ randomRunOnEnable: true })
@@ -24,23 +24,23 @@ export class RemoveOldViewsScheduler extends AbstractScheduler {
private removeRemoteViews () {
if (CONFIG.VIEWS.VIDEOS.REMOTE.MAX_AGE <= 0) return
- logger.info('Removing old views from remote videos.', lTags())
+ logger.info('Removing old stats from remote videos.', lTags())
const now = new Date()
const beforeDate = new Date(now.getTime() - CONFIG.VIEWS.VIDEOS.REMOTE.MAX_AGE).toISOString()
- return VideoViewModel.removeOldRemoteViews(beforeDate)
+ return VideoStatModel.removeOldRemoteStats(beforeDate)
}
private async removeLocalViews () {
if (CONFIG.VIEWS.VIDEOS.LOCAL.MAX_AGE <= 0) return
- logger.info('Removing old views from local videos.', lTags())
+ logger.info('Removing old stats from local videos.', lTags())
const now = new Date()
const beforeDate = new Date(now.getTime() - CONFIG.VIEWS.VIDEOS.LOCAL.MAX_AGE).toISOString()
- await VideoViewModel.removeOldLocalViews(beforeDate)
+ await VideoStatModel.removeOldLocalStats(beforeDate)
await LocalVideoViewerModel.removeOldViews(beforeDate)
}
diff --git a/server/core/lib/schedulers/video-stats-buffer-scheduler.ts b/server/core/lib/schedulers/video-stats-buffer-scheduler.ts
new file mode 100644
index 0000000000..d4235115cf
--- /dev/null
+++ b/server/core/lib/schedulers/video-stats-buffer-scheduler.ts
@@ -0,0 +1,68 @@
+import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
+import { VideoModel } from '@server/models/video/video.js'
+import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants.js'
+import { federateVideoIfNeeded } from '../activitypub/videos/index.js'
+import { Redis } from '../redis.js'
+import { AbstractScheduler } from './abstract-scheduler.js'
+
+const lTags = loggerTagsFactory('schedulers', 'stats')
+
+/**
+ * Increment video counters in the database with the pending values stored in Redis, and send video updates if needed
+ */
+
+export class VideoStatsBufferScheduler extends AbstractScheduler {
+ private static instance: AbstractScheduler
+
+ protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.VIDEO_STATS_BUFFER_UPDATE
+
+ private constructor () {
+ super({ randomRunOnEnable: false })
+ }
+
+ protected async internalExecute () {
+ logger.debug(`Running video stats buffer scheduler`, lTags())
+
+ const videoIds = await Redis.Instance.listLocalVideosWithStats()
+ if (videoIds.length === 0) return
+
+ for (const videoId of videoIds) {
+ try {
+ const views = await Redis.Instance.getLocalVideoStats('views', videoId)
+ const downloads = await Redis.Instance.getLocalVideoStats('downloads', videoId)
+
+ await Redis.Instance.deleteLocalVideoStats(videoId)
+
+ if (!views && !downloads) continue
+
+ const video = await VideoModel.loadFull(videoId)
+ if (!video) {
+ logger.debug(`Video ${videoId} does not exist anymore, skipping videos stats addition.`, lTags())
+ continue
+ }
+
+ logger.info(`Processing local video ${video.uuid} stats buffer.`, lTags(video.uuid))
+
+ // If this is a remote video, the origin instance will send us an update
+ if (views) {
+ video.views += views
+ await VideoModel.incrementStats('views', videoId, views)
+ }
+
+ if (downloads) {
+ video.downloads += downloads
+ await VideoModel.incrementStats('downloads', videoId, downloads)
+ }
+
+ // Send video update
+ await federateVideoIfNeeded(video, false)
+ } catch (err) {
+ logger.error(`Cannot process local video stats buffer of video ${videoId}.`, { err, ...lTags() })
+ }
+ }
+ }
+
+ static get Instance () {
+ return this.instance || (this.instance = new this())
+ }
+}
diff --git a/server/core/lib/schedulers/video-views-buffer-scheduler.ts b/server/core/lib/schedulers/video-views-buffer-scheduler.ts
deleted file mode 100644
index 4d1c7f0053..0000000000
--- a/server/core/lib/schedulers/video-views-buffer-scheduler.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
-import { VideoModel } from '@server/models/video/video.js'
-import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants.js'
-import { federateVideoIfNeeded } from '../activitypub/videos/index.js'
-import { Redis } from '../redis.js'
-import { AbstractScheduler } from './abstract-scheduler.js'
-
-const lTags = loggerTagsFactory('schedulers', 'views')
-
-export class VideoViewsBufferScheduler extends AbstractScheduler {
- private static instance: AbstractScheduler
-
- protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.VIDEO_VIEWS_BUFFER_UPDATE
-
- private constructor () {
- super({ randomRunOnEnable: false })
- }
-
- protected async internalExecute () {
- logger.debug('Running video views buffer scheduler', lTags())
-
- const videoIds = await Redis.Instance.listLocalVideosViewed()
- if (videoIds.length === 0) return
-
- for (const videoId of videoIds) {
- try {
- const views = await Redis.Instance.getLocalVideoViews(videoId)
- await Redis.Instance.deleteLocalVideoViews(videoId)
-
- const video = await VideoModel.loadFull(videoId)
- if (!video) {
- logger.debug('Video %d does not exist anymore, skipping videos view addition.', videoId, lTags())
- continue
- }
-
- logger.info('Processing local video %s views buffer.', video.uuid, lTags(video.uuid))
-
- // If this is a remote video, the origin instance will send us an update
- await VideoModel.incrementViews(videoId, views)
-
- // Send video update
- video.views += views
- await federateVideoIfNeeded(video, false)
- } catch (err) {
- logger.error('Cannot process local video views buffer of video %d.', videoId, { err, ...lTags() })
- }
- }
- }
-
- static get Instance () {
- return this.instance || (this.instance = new this())
- }
-}
diff --git a/server/core/lib/stat-manager.ts b/server/core/lib/stat-manager.ts
index 202502ef45..4989298fbc 100644
--- a/server/core/lib/stat-manager.ts
+++ b/server/core/lib/stat-manager.ts
@@ -47,7 +47,7 @@ class StatsManager {
}
async getStats () {
- const { totalLocalVideos, totalLocalVideoViews, totalVideos } = await VideoModel.getStats()
+ const { totalLocalVideos, totalLocalVideoViews, totalLocalVideoDownloads, totalVideos } = await VideoModel.getStats()
const { totalLocalVideoComments, totalVideoComments } = await VideoCommentModel.getStats()
const {
totalUsers,
@@ -85,6 +85,7 @@ class StatsManager {
totalLocalVideos,
totalLocalVideoViews,
+ totalLocalVideoDownloads,
totalLocalVideoComments,
totalLocalVideoFilesSize,
@@ -148,6 +149,7 @@ class StatsManager {
Dislike: 0,
Flag: 0,
View: 0,
+ Download: 0,
ApproveReply: 0,
RejectReply: 0
}
@@ -172,6 +174,7 @@ class StatsManager {
totalActivityPubDislikeMessagesSuccesses: this.inboxMessages.successesPerType.Dislike,
totalActivityPubFlagMessagesSuccesses: this.inboxMessages.successesPerType.Flag,
totalActivityPubViewMessagesSuccesses: this.inboxMessages.successesPerType.View,
+ totalActivityPubDownloadMessagesSuccesses: this.inboxMessages.successesPerType.Download,
totalActivityPubApproveReplyMessagesSuccesses: this.inboxMessages.successesPerType.ApproveReply,
totalActivityPubRejectReplyMessagesSuccesses: this.inboxMessages.successesPerType.RejectReply,
@@ -187,6 +190,7 @@ class StatsManager {
totalActivityPubDislikeMessagesErrors: this.inboxMessages.errorsPerType.Dislike,
totalActivityPubFlagMessagesErrors: this.inboxMessages.errorsPerType.Flag,
totalActivityPubViewMessagesErrors: this.inboxMessages.errorsPerType.View,
+ totalActivityPubDownloadMessagesErrors: this.inboxMessages.errorsPerType.Download,
totalActivityPubApproveReplyMessagesErrors: this.inboxMessages.errorsPerType.ApproveReply,
totalActivityPubRejectReplyMessagesErrors: this.inboxMessages.errorsPerType.RejectReply,
diff --git a/server/core/lib/views/shared/index.ts b/server/core/lib/stats/shared/index.ts
similarity index 71%
rename from server/core/lib/views/shared/index.ts
rename to server/core/lib/stats/shared/index.ts
index e311fb22fc..4e2dcb1b17 100644
--- a/server/core/lib/views/shared/index.ts
+++ b/server/core/lib/stats/shared/index.ts
@@ -1,3 +1,3 @@
export * from './video-viewer-counters.js'
export * from './video-viewer-stats.js'
-export * from './video-views.js'
+export * from './video-stats.js'
diff --git a/server/core/lib/views/shared/video-views.ts b/server/core/lib/stats/shared/video-stats.ts
similarity index 65%
rename from server/core/lib/views/shared/video-views.ts
rename to server/core/lib/stats/shared/video-stats.ts
index b8a0a2c549..d561ed5ad5 100644
--- a/server/core/lib/views/shared/video-views.ts
+++ b/server/core/lib/stats/shared/video-stats.ts
@@ -1,22 +1,27 @@
import { buildUUID } from '@peertube/peertube-node-utils'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
+import { CONFIG } from '@server/initializers/config.js'
import { VIEW_LIFETIME } from '@server/initializers/constants.js'
+import { sendDownload } from '@server/lib/activitypub/send/send-download.js'
import { sendView } from '@server/lib/activitypub/send/send-view.js'
import { getCachedVideoDuration } from '@server/lib/video.js'
import { getServerActor } from '@server/models/application/application.js'
import { MVideo, MVideoImmutable } from '@server/types/models/index.js'
import { LRUCache } from 'lru-cache'
import { Redis } from '../../redis.js'
-import { CONFIG } from '@server/initializers/config.js'
const lTags = loggerTagsFactory('views')
-export class VideoViews {
+export class VideoStats {
private readonly viewsCache = new LRUCache<string, boolean>({
max: 10_000,
ttl: VIEW_LIFETIME.VIEW
})
+ // ---------------------------------------------------------------------------
+ // Views
+ // ---------------------------------------------------------------------------
+
async addLocalView (options: {
video: MVideoImmutable
sessionId: string
@@ -58,10 +63,10 @@ export class VideoViews {
const promises: Promise<any>[] = []
if (video.isLocal()) {
- promises.push(Redis.Instance.addLocalVideoView(video.id))
+ promises.push(Redis.Instance.addLocalVideoStat('views', video.id))
}
- promises.push(Redis.Instance.addVideoViewStats(video.id))
+ promises.push(Redis.Instance.addVideoStat('views', video.id))
await Promise.all(promises)
}
@@ -90,4 +95,48 @@ export class VideoViews {
return Redis.Instance.setSessionIdVideoView(sessionId, videoUUID)
}
+
+ // ---------------------------------------------------------------------------
+ // Download
+ // ---------------------------------------------------------------------------
+
+ async addLocalDownload (options: {
+ video: MVideoImmutable
+ }) {
+ const { video } = options
+
+ logger.debug('Adding local download to video %s.', video.uuid, { ...lTags(video.uuid) })
+
+ await this.addDownload(video)
+
+ await sendDownload({ byActor: await getServerActor(), video })
+
+ return true
+ }
+
+ async addRemoteDownload (options: {
+ video: MVideoImmutable
+ }) {
+ const { video } = options
+
+ logger.debug('Adding remote download to video %s.', video.uuid, { ...lTags(video.uuid) })
+
+ await this.addDownload(video)
+
+ return true
+ }
+
+ // ---------------------------------------------------------------------------
+
+ private async addDownload (video: MVideoImmutable) {
+ const promises: Promise<any>[] = []
+
+ if (video.isLocal()) {
+ promises.push(Redis.Instance.addLocalVideoStat('downloads', video.id))
+ }
+
+ promises.push(Redis.Instance.addVideoStat('downloads', video.id))
+
+ await Promise.all(promises)
+ }
}
diff --git a/server/core/lib/views/shared/video-viewer-counters.ts b/server/core/lib/stats/shared/video-viewer-counters.ts
similarity index 100%
rename from server/core/lib/views/shared/video-viewer-counters.ts
rename to server/core/lib/stats/shared/video-viewer-counters.ts
diff --git a/server/core/lib/views/shared/video-viewer-stats.ts b/server/core/lib/stats/shared/video-viewer-stats.ts
similarity index 98%
rename from server/core/lib/views/shared/video-viewer-stats.ts
rename to server/core/lib/stats/shared/video-viewer-stats.ts
index 4fb6d1bd48..6e9b423fde 100644
--- a/server/core/lib/views/shared/video-viewer-stats.ts
+++ b/server/core/lib/stats/shared/video-viewer-stats.ts
@@ -7,9 +7,9 @@ import { sequelizeTypescript } from '@server/initializers/database.js'
import { sendCreateWatchAction } from '@server/lib/activitypub/send/index.js'
import { getLocalVideoViewerActivityPubUrl } from '@server/lib/activitypub/url.js'
import { Redis } from '@server/lib/redis.js'
+import { LocalVideoViewerWatchSectionModel } from '@server/models/stat/local-video-viewer-watch-section.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
import { VideoModel } from '@server/models/video/video.js'
-import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section.js'
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
import { MVideo, MVideoImmutable } from '@server/types/models/index.js'
import { Transaction } from 'sequelize'
@@ -35,7 +35,6 @@ type LocalViewerStats = {
videoId: number
}
-
export class VideoViewerStats {
private processingViewersStats = false
private processingRedisWrites = false
diff --git a/server/core/lib/views/video-views-manager.ts b/server/core/lib/stats/video-stats-manager.ts
similarity index 77%
rename from server/core/lib/views/video-views-manager.ts
rename to server/core/lib/stats/video-stats-manager.ts
index 8d70efc195..1f4a442045 100644
--- a/server/core/lib/views/video-views-manager.ts
+++ b/server/core/lib/stats/video-stats-manager.ts
@@ -3,7 +3,7 @@ import { sha256 } from '@peertube/peertube-node-utils'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import { MVideo, MVideoImmutable } from '@server/types/models/index.js'
-import { VideoScope, VideoViewerCounters, VideoViewerStats, VideoViews, ViewerScope } from './shared/index.js'
+import { VideoScope, VideoStats, VideoViewerCounters, VideoViewerStats, ViewerScope } from './shared/index.js'
/**
* If processing a local view:
@@ -22,14 +22,14 @@ import { VideoScope, VideoViewerCounters, VideoViewerStats, VideoViews, ViewerSc
* Viewers statistics are sent to origin instance using the `WatchAction` ActivityPub object
*/
-const lTags = loggerTagsFactory('views')
+const lTags = loggerTagsFactory('stats')
-export class VideoViewsManager {
- private static instance: VideoViewsManager
+export class VideoStatsManager {
+ private static instance: VideoStatsManager
private videoViewerStats: VideoViewerStats
private videoViewerCounters: VideoViewerCounters
- private videoViews: VideoViews
+ private videoStats: VideoStats
private constructor () {
}
@@ -37,7 +37,7 @@ export class VideoViewsManager {
init () {
this.videoViewerStats = new VideoViewerStats()
this.videoViewerCounters = new VideoViewerCounters()
- this.videoViews = new VideoViews()
+ this.videoStats = new VideoStats()
}
async processLocalView (options: {
@@ -66,7 +66,7 @@ export class VideoViewsManager {
// Do it after added local viewer to fetch updated information
const watchTime = await this.videoViewerStats.getWatchTime(video.id, sessionId)
- const successView = await this.videoViews.addLocalView({ video, watchTime, sessionId })
+ const successView = await this.videoStats.addLocalView({ video, watchTime, sessionId })
return { successView, successViewer }
}
@@ -93,9 +93,33 @@ export class VideoViewsManager {
}
// Just a view
- await this.videoViews.addRemoteView({ video })
+ await this.videoStats.addRemoteView({ video })
}
+ // ---------------------------------------------------------------------------
+
+ async processLocalDownload (options: {
+ video: MVideoImmutable
+ }) {
+ const { video } = options
+
+ logger.debug('Processing local download for %s.', video.url, lTags())
+
+ await this.videoStats.addLocalDownload({ video })
+ }
+
+ async processRemoteDownload (options: {
+ video: MVideoImmutable
+ }) {
+ const { video } = options
+
+ logger.debug('Processing remote download for %s.', video.url, lTags())
+
+ await this.videoStats.addRemoteDownload({ video })
+ }
+
+ // ---------------------------------------------------------------------------
+
getTotalViewersOf (video: MVideo) {
return this.videoViewerCounters.getTotalViewersOf(video)
}
diff --git a/server/core/lib/video-download.ts b/server/core/lib/video-download.ts
index c0ca4a698b..bccd71866e 100644
--- a/server/core/lib/video-download.ts
+++ b/server/core/lib/video-download.ts
@@ -5,6 +5,7 @@ import { logger } from '@server/helpers/logger.js'
import { buildRequestError, doRequestAndSaveToFile, generateRequestStream } from '@server/helpers/requests.js'
import { REQUEST_TIMEOUTS } from '@server/initializers/constants.js'
import { isWebVideoFile, MVideoFile, MVideoThumbnail } from '@server/types/models/index.js'
+import { createReadStream } from 'fs'
import { remove } from 'fs-extra/esm'
import { Readable, Writable } from 'stream'
import { pipeline } from 'stream/promises'
@@ -16,7 +17,6 @@ import {
makeWebVideoFileAvailable
} from './object-storage/videos.js'
import { VideoPathManager } from './video-path-manager.js'
-import { createReadStream } from 'fs'
export class VideoDownload {
static totalDownloads = 0
diff --git a/server/core/middlewares/validators/videos/video-view.ts b/server/core/middlewares/validators/videos/video-view.ts
index b669754191..8f4b70d142 100644
--- a/server/core/middlewares/validators/videos/video-view.ts
+++ b/server/core/middlewares/validators/videos/video-view.ts
@@ -6,7 +6,7 @@ import {
toVideoViewUADeviceOrNull
} from '@server/helpers/custom-validators/video-view.js'
import { getCachedVideoDuration } from '@server/lib/video.js'
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
import express from 'express'
import { body, param } from 'express-validator'
import { isIdValid, toIntOrNull } from '../../../helpers/custom-validators/misc.js'
diff --git a/server/core/models/shared/sort.ts b/server/core/models/shared/sort.ts
index b46ccb88a1..6dee76c2ec 100644
--- a/server/core/models/shared/sort.ts
+++ b/server/core/models/shared/sort.ts
@@ -49,7 +49,7 @@ export function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC'
if (field.toLowerCase() === 'trending') { // Sort by aggregation
return [
- [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
+ [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoStats.views')), '0'), direction ],
[ Sequelize.col('VideoModel.views'), direction ],
diff --git a/server/core/models/view/local-video-viewer-watch-section.ts b/server/core/models/stat/local-video-viewer-watch-section.ts
similarity index 100%
rename from server/core/models/view/local-video-viewer-watch-section.ts
rename to server/core/models/stat/local-video-viewer-watch-section.ts
diff --git a/server/core/models/view/local-video-viewer.ts b/server/core/models/stat/local-video-viewer.ts
similarity index 97%
rename from server/core/models/view/local-video-viewer.ts
rename to server/core/models/stat/local-video-viewer.ts
index 160d2cd09a..6f8a751455 100644
--- a/server/core/models/view/local-video-viewer.ts
+++ b/server/core/models/stat/local-video-viewer.ts
@@ -319,7 +319,7 @@ export class LocalVideoViewerModel extends SequelizeModel<LocalVideoViewerModel>
static async getTimeserieStats (options: {
video: MVideo
- metric: VideoStatsTimeserieMetric
+ metric: Extract<VideoStatsTimeserieMetric, 'viewers' | 'aggregateWatchTime'>
startDate: string
endDate: string
}): Promise<VideoStatsTimeserie> {
@@ -327,12 +327,12 @@ export class LocalVideoViewerModel extends SequelizeModel<LocalVideoViewerModel>
const { groupInterval, startDate, endDate } = buildGroupByAndBoundaries(options.startDate, options.endDate)
- const selectMetrics: { [id in VideoStatsTimeserieMetric]: string } = {
+ const selectMetrics: { [id in Extract<VideoStatsTimeserieMetric, 'viewers' | 'aggregateWatchTime'>]: string } = {
viewers: 'COUNT("localVideoViewer"."id")',
aggregateWatchTime: 'SUM("localVideoViewer"."watchTime")'
}
- const intervalWhere: { [id in VideoStatsTimeserieMetric]: string } = {
+ const intervalWhere: { [id in Extract<VideoStatsTimeserieMetric, 'viewers' | 'aggregateWatchTime'>]: string } = {
// Viewer is still in the interval. Overlap algorithm
viewers: '"localVideoViewer"."startDate" <= "intervals"."endDate" ' +
'AND "localVideoViewer"."endDate" >= "intervals"."startDate"',
diff --git a/server/core/models/stat/video-stat.ts b/server/core/models/stat/video-stat.ts
new file mode 100644
index 0000000000..546cd01860
--- /dev/null
+++ b/server/core/models/stat/video-stat.ts
@@ -0,0 +1,148 @@
+import { VideoStatsTimeserie } from '@peertube/peertube-models'
+import { MAX_SQL_DELETE_ITEMS } from '@server/initializers/constants.js'
+import { buildGroupByAndBoundaries } from '@server/lib/timeserie.js'
+import { MVideo } from '@server/types/models/index.js'
+import { literal, Op, QueryTypes } from 'sequelize'
+import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Table } from 'sequelize-typescript'
+import { safeBulkDestroy, SequelizeModel } from '../shared/index.js'
+import { VideoModel } from '../video/video.js'
+
+/**
+ * Aggregate stats of all videos federated with our instance
+ * Mainly used by the trending/hot algorithms
+ */
+
+@Table({
+ tableName: 'videoStat',
+ updatedAt: false,
+ indexes: [ {
+ fields: [ 'videoId' ]
+ }, {
+ fields: [ 'startDate' ]
+ } ]
+})
+export class VideoStatModel extends SequelizeModel<VideoStatModel> {
+ @CreatedAt
+ declare createdAt: Date
+
+ @AllowNull(false)
+ @Column(DataType.DATE)
+ declare startDate: Date
+
+ @AllowNull(false)
+ @Column(DataType.DATE)
+ declare endDate: Date
+
+ @AllowNull(false)
+ @Default(0)
+ @Column
+ declare views: number
+
+ @AllowNull(false)
+ @Default(0)
+ @Column
+ declare downloads: number
+
+ @ForeignKey(() => VideoModel)
+ @Column
+ declare videoId: number
+
+ @BelongsTo(() => VideoModel, {
+ foreignKey: {
+ allowNull: false
+ },
+ onDelete: 'CASCADE'
+ })
+ declare Video: Awaited<VideoModel>
+
+ static removeOldRemoteStats (beforeDate: string) {
+ return safeBulkDestroy(() => {
+ return VideoStatModel.destroy({
+ where: {
+ startDate: {
+ [Op.lt]: beforeDate
+ },
+ videoId: {
+ [Op.in]: literal(
+ '(SELECT "id" FROM "video" WHERE "remote" IS TRUE)'
+ )
+ }
+ },
+ limit: MAX_SQL_DELETE_ITEMS
+ })
+ })
+ }
+
+ static removeOldLocalStats (beforeDate: string) {
+ return safeBulkDestroy(() => {
+ return VideoStatModel.destroy({
+ where: {
+ startDate: {
+ [Op.lt]: beforeDate
+ },
+ videoId: {
+ [Op.in]: literal(
+ '(SELECT "id" FROM "video" WHERE "remote" IS FALSE)'
+ )
+ }
+ },
+ limit: MAX_SQL_DELETE_ITEMS
+ })
+ })
+ }
+
+ static async getDownloadTimeserieStats (options: {
+ video: MVideo
+ startDate: string
+ endDate: string
+ }): Promise<VideoStatsTimeserie> {
+ const { video } = options
+
+ const { groupInterval, startDate, endDate } = buildGroupByAndBoundaries(
+ options.startDate,
+ options.endDate
+ )
+
+ const query = `WITH "intervals" AS (
+ SELECT
+ "time" AS "startDate", "time" + :groupInterval::interval as "endDate"
+ FROM
+ generate_series(:startDate::timestamptz, :endDate::timestamptz, :groupInterval::interval) serie("time")
+ )
+ SELECT
+ "intervals"."startDate" AS date, COALESCE("videoStat"."downloads", 0) AS value
+ FROM
+ "intervals"
+ LEFT JOIN "videoStat" ON "videoStat"."videoId" = :videoId
+ AND
+ "videoStat"."startDate" <= "intervals"."endDate"
+ AND
+ "videoStat"."startDate" >= "intervals"."startDate"
+ ORDER BY
+ "intervals"."startDate"
+ `
+
+ const queryOptions = {
+ type: QueryTypes.SELECT as QueryTypes.SELECT,
+ replacements: {
+ startDate,
+ endDate,
+ groupInterval,
+ videoId: video.id
+ }
+ }
+
+ const rows = await VideoStatModel.sequelize.query<any>(
+ query,
+ queryOptions
+ )
+
+ return {
+ groupInterval,
+ data: rows.map(r => ({
+ date: r.date,
+ value: parseInt(r.value)
+ }))
+ }
+ }
+}
diff --git a/server/core/models/video/formatter/video-activity-pub-format.ts b/server/core/models/video/formatter/video-activity-pub-format.ts
index 0709695c54..680bbff302 100644
--- a/server/core/models/video/formatter/video-activity-pub-format.ts
+++ b/server/core/models/video/formatter/video-activity-pub-format.ts
@@ -74,6 +74,7 @@ export function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
licence,
language,
views: video.views,
+ downloads: video.downloads,
sensitive: video.nsfw,
summary: video.nsfwSummary,
diff --git a/server/core/models/video/formatter/video-api-format.ts b/server/core/models/video/formatter/video-api-format.ts
index 86efbd4a1f..e3c0671471 100644
--- a/server/core/models/video/formatter/video-api-format.ts
+++ b/server/core/models/video/formatter/video-api-format.ts
@@ -12,7 +12,7 @@ import { uuidToShort } from '@peertube/peertube-node-utils'
import { tracer } from '@server/lib/opentelemetry/tracing.js'
import { getHLSResolutionPlaylistFilename } from '@server/lib/paths.js'
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls.js'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import { generateMagnetUri } from '@server/lib/webtorrent.js'
import { isArray } from '../../../helpers/custom-validators/misc.js'
import {
@@ -111,7 +111,9 @@ export function videoModelToFormattedJSON (video: MVideoFormattable, options: Vi
aspectRatio: video.aspectRatio,
views: video.views,
- viewers: VideoViewsManager.Instance.getTotalViewersOf(video),
+ viewers: VideoStatsManager.Instance.getTotalViewersOf(video),
+
+ downloads: video.downloads,
likes: video.likes,
dislikes: video.dislikes,
diff --git a/server/core/models/video/sql/channel/video-channel-list-query-builder.ts b/server/core/models/video/sql/channel/video-channel-list-query-builder.ts
index 53b022a5bc..622c77ace6 100644
--- a/server/core/models/video/sql/channel/video-channel-list-query-builder.ts
+++ b/server/core/models/video/sql/channel/video-channel-list-query-builder.ts
@@ -231,12 +231,12 @@ export class VideoChannelListQueryBuilder extends AbstractListQuery {
`SELECT generate_series(date_trunc('day', now()) - '${this.options.statsDaysPrior} day'::interval, ` +
`date_trunc('day', now()), '1 day'::interval) AS day ` +
') ' +
- 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
+ 'SELECT days.day AS day, COALESCE(SUM("videoStat".views), 0) AS views ' +
'FROM days ' +
'LEFT JOIN (' +
- '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
+ '"videoStat" INNER JOIN "video" ON "videoStat"."videoId" = "video"."id" ' +
'AND "video"."channelId" = "VideoChannelModel"."id"' +
- `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
+ `) ON date_trunc('day', "videoStat"."startDate") = date_trunc('day', days.day) ` +
'GROUP BY day ORDER BY day ' +
') t' +
') AS "viewsPerDay"'
diff --git a/server/core/models/video/sql/video/shared/video-table-attributes.ts b/server/core/models/video/sql/video/shared/video-table-attributes.ts
index fbeade411c..a04de8ee57 100644
--- a/server/core/models/video/sql/video/shared/video-table-attributes.ts
+++ b/server/core/models/video/sql/video/shared/video-table-attributes.ts
@@ -291,6 +291,7 @@ export class VideoTableAttributes {
'support',
'duration',
'views',
+ 'downloads',
'likes',
'dislikes',
'remote',
diff --git a/server/core/models/video/sql/video/videos-id-list-query-builder.ts b/server/core/models/video/sql/video/videos-id-list-query-builder.ts
index 3da5be68a8..88fd82a41a 100644
--- a/server/core/models/video/sql/video/videos-id-list-query-builder.ts
+++ b/server/core/models/video/sql/video/videos-id-list-query-builder.ts
@@ -808,10 +808,10 @@ export class VideosIdListQueryBuilder extends AbstractRunQuery {
private groupForTrending (trendingDays: number) {
const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
- this.joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
+ this.joins.push('LEFT JOIN "videoStat" ON "video"."id" = "videoStat"."videoId" AND "videoStat"."startDate" >= :viewsGteDate')
this.replacements.viewsGteDate = viewsGteDate
- this.attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "score"')
+ this.attributes.push('COALESCE(SUM("videoStat"."views"), 0) AS "score"')
this.group = 'GROUP BY "video"."id"'
}
diff --git a/server/core/models/video/video.ts b/server/core/models/video/video.ts
index 70b36f6e3a..b74e5a973a 100644
--- a/server/core/models/video/video.ts
+++ b/server/core/models/video/video.ts
@@ -137,7 +137,7 @@ import {
} from '../shared/index.js'
import { UserVideoHistoryModel } from '../user/user-video-history.js'
import { UserModel } from '../user/user.js'
-import { VideoViewModel } from '../view/video-view.js'
+import { VideoStatModel } from '../stat/video-stat.js'
import { videoModelToActivityPubObject } from './formatter/video-activity-pub-format.js'
import {
VideoFormattingJSONOptions,
@@ -512,6 +512,13 @@ export class VideoModel extends SequelizeModel<VideoModel> {
@Column
declare views: number
+ @AllowNull(false)
+ @Default(0)
+ @IsInt
+ @Min(0)
+ @Column
+ declare downloads: number
+
@AllowNull(false)
@Default(0)
@IsInt
@@ -704,14 +711,14 @@ export class VideoModel extends SequelizeModel<VideoModel> {
})
declare VideoComments: Awaited<VideoCommentModel>[]
- @HasMany(() => VideoViewModel, {
+ @HasMany(() => VideoStatModel, {
foreignKey: {
name: 'videoId',
allowNull: false
},
onDelete: 'cascade'
})
- declare VideoViews: Awaited<VideoViewModel>[]
+ declare VideoStats: Awaited<VideoStatModel>[]
@HasMany(() => UserVideoHistoryModel, {
foreignKey: {
@@ -1465,8 +1472,15 @@ export class VideoModel extends SequelizeModel<VideoModel> {
}
})
- // Sequelize could return null...
+ let totalLocalVideoDownloads = await VideoModel.sum('downloads', {
+ where: {
+ remote: false
+ }
+ })
+
+ // Sequelize can return null
if (!totalLocalVideoViews) totalLocalVideoViews = 0
+ if (!totalLocalVideoDownloads) totalLocalVideoDownloads = 0
const baseOptions = {
start: 0,
@@ -1490,6 +1504,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {
return {
totalLocalVideos,
totalLocalVideoViews,
+ totalLocalVideoDownloads,
totalVideos
}
}
@@ -1503,9 +1518,9 @@ export class VideoModel extends SequelizeModel<VideoModel> {
})
}
- static incrementViews (id: number, views: number) {
- return VideoModel.increment('views', {
- by: views,
+ static incrementStats (column: 'views' | 'downloads', id: number, by: number) {
+ return VideoModel.increment(column, {
+ by,
where: {
id
}
@@ -1654,7 +1669,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {
return {
attributes: [],
subQuery: false,
- model: VideoViewModel,
+ model: VideoStatModel,
required: false,
where: {
startDate: {
diff --git a/server/core/models/view/video-view.ts b/server/core/models/view/video-view.ts
deleted file mode 100644
index cad6326c52..0000000000
--- a/server/core/models/view/video-view.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { MAX_SQL_DELETE_ITEMS } from '@server/initializers/constants.js'
-import { literal, Op } from 'sequelize'
-import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table } from 'sequelize-typescript'
-import { safeBulkDestroy, SequelizeModel } from '../shared/index.js'
-import { VideoModel } from '../video/video.js'
-
-/**
- * Aggregate views of all videos federated with our instance
- * Mainly used by the trending/hot algorithms
- */
-
-@Table({
- tableName: 'videoView',
- updatedAt: false,
- indexes: [
- {
- fields: [ 'videoId' ]
- },
- {
- fields: [ 'startDate' ]
- }
- ]
-})
-export class VideoViewModel extends SequelizeModel<VideoViewModel> {
- @CreatedAt
- declare createdAt: Date
-
- @AllowNull(false)
- @Column(DataType.DATE)
- declare startDate: Date
-
- @AllowNull(false)
- @Column(DataType.DATE)
- declare endDate: Date
-
- @AllowNull(false)
- @Column
- declare views: number
-
- @ForeignKey(() => VideoModel)
- @Column
- declare videoId: number
-
- @BelongsTo(() => VideoModel, {
- foreignKey: {
- allowNull: false
- },
- onDelete: 'CASCADE'
- })
- declare Video: Awaited<VideoModel>
-
- static removeOldRemoteViews (beforeDate: string) {
- return safeBulkDestroy(() => {
- return VideoViewModel.destroy({
- where: {
- startDate: {
- [Op.lt]: beforeDate
- },
- videoId: {
- [Op.in]: literal('(SELECT "id" FROM "video" WHERE "remote" IS TRUE)')
- }
- },
- limit: MAX_SQL_DELETE_ITEMS
- })
- })
- }
-
- static removeOldLocalViews (beforeDate: string) {
- return safeBulkDestroy(() => {
- return VideoViewModel.destroy({
- where: {
- startDate: {
- [Op.lt]: beforeDate
- },
- videoId: {
- [Op.in]: literal('(SELECT "id" FROM "video" WHERE "remote" IS FALSE)')
- }
- },
- limit: MAX_SQL_DELETE_ITEMS
- })
- })
- }
-}
diff --git a/server/core/types/models/video/local-video-viewer-watch-section.ts b/server/core/types/models/video/local-video-viewer-watch-section.ts
index c621dd1cc4..769d013cc6 100644
--- a/server/core/types/models/video/local-video-viewer-watch-section.ts
+++ b/server/core/types/models/video/local-video-viewer-watch-section.ts
@@ -1,4 +1,4 @@
-import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section.js'
+import { LocalVideoViewerWatchSectionModel } from '@server/models/stat/local-video-viewer-watch-section.js'
// ############################################################################
diff --git a/server/core/types/models/video/local-video-viewer.ts b/server/core/types/models/video/local-video-viewer.ts
index cfc4ca675a..3e60dbe2fa 100644
--- a/server/core/types/models/video/local-video-viewer.ts
+++ b/server/core/types/models/video/local-video-viewer.ts
@@ -1,4 +1,4 @@
-import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
+import { LocalVideoViewerModel } from '@server/models/stat/local-video-viewer.js'
import { PickWith } from '@peertube/peertube-typescript-utils'
import { MLocalVideoViewerWatchSection } from './local-video-viewer-watch-section.js'
import { MVideo } from './video.js'
diff --git a/server/core/types/models/video/video.ts b/server/core/types/models/video/video.ts
index 2365e16e92..2670636785 100644
--- a/server/core/types/models/video/video.ts
+++ b/server/core/types/models/video/video.ts
@@ -46,6 +46,7 @@ export type MVideo = Omit<
| 'AccountVideoRates'
| 'VideoComments'
| 'VideoViews'
+ | 'VideoDownloads'
| 'UserVideoHistories'
| 'ScheduleVideoUpdate'
| 'VideoBlacklist'
diff --git a/server/server.ts b/server/server.ts
index a625c3d74c..1d2738d048 100644
--- a/server/server.ts
+++ b/server/server.ts
@@ -126,14 +126,14 @@ import { advertiseDoNotTrack } from './core/middlewares/dnt.js'
import { apiFailMiddleware } from './core/middlewares/error.js'
import { Redis } from './core/lib/redis.js'
import { ActorFollowScheduler } from './core/lib/schedulers/actor-follow-scheduler.js'
-import { RemoveOldViewsScheduler } from './core/lib/schedulers/remove-old-views-scheduler.js'
+import { RemoveOldStatsScheduler } from './core/lib/schedulers/remove-old-stats-scheduler.js'
import { UpdateVideosScheduler } from './core/lib/schedulers/update-videos-scheduler.js'
import { YoutubeDlUpdateScheduler } from './core/lib/schedulers/youtube-dl-update-scheduler.js'
import { VideosRedundancyScheduler } from './core/lib/schedulers/videos-redundancy-scheduler.js'
import { RemoveOldHistoryScheduler } from './core/lib/schedulers/remove-old-history-scheduler.js'
import { AutoFollowIndexInstances } from './core/lib/schedulers/auto-follow-index-instances.js'
import { RemoveDanglingResumableUploadsScheduler } from './core/lib/schedulers/remove-dangling-resumable-uploads-scheduler.js'
-import { VideoViewsBufferScheduler } from './core/lib/schedulers/video-views-buffer-scheduler.js'
+import { VideoStatsBufferScheduler } from './core/lib/schedulers/video-stats-buffer-scheduler.js'
import { GeoIPUpdateScheduler } from './core/lib/schedulers/geo-ip-update-scheduler.js'
import { RunnerJobWatchDogScheduler } from './core/lib/schedulers/runner-job-watch-dog-scheduler.js'
import { isHTTPSignatureDigestValid } from './core/helpers/peertube-crypto.js'
@@ -146,7 +146,7 @@ import { PluginManager } from './core/lib/plugins/plugin-manager.js'
import { LiveManager } from './core/lib/live/index.js'
import { HttpStatusCode } from '@peertube/peertube-models'
import { ServerConfigManager } from '@server/lib/server-config-manager.js'
-import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'
import { isTestOrDevInstance } from '@peertube/peertube-node-utils'
import { OpenTelemetryMetrics } from '@server/lib/opentelemetry/metrics.js'
import { ApplicationModel } from '@server/models/application/application.js'
@@ -318,13 +318,13 @@ async function startApplication () {
YoutubeDlUpdateScheduler.Instance.enable()
VideosRedundancyScheduler.Instance.enable()
RemoveOldHistoryScheduler.Instance.enable()
- RemoveOldViewsScheduler.Instance.enable()
+ RemoveOldStatsScheduler.Instance.enable()
PluginsCheckScheduler.Instance.enable()
PeerTubeVersionCheckScheduler.Instance.enable()
AutoFollowIndexInstances.Instance.enable()
RemoveDanglingResumableUploadsScheduler.Instance.enable()
VideoChannelSyncLatestScheduler.Instance.enable()
- VideoViewsBufferScheduler.Instance.enable()
+ VideoStatsBufferScheduler.Instance.enable()
GeoIPUpdateScheduler.Instance.enable()
RunnerJobWatchDogScheduler.Instance.enable()
RemoveExpiredUserExportsScheduler.Instance.enable()
@@ -337,7 +337,7 @@ async function startApplication () {
PluginManager.Instance.registerWebSocketRouter()
PeerTubeSocket.Instance.init(server)
- VideoViewsManager.Instance.init()
+ VideoStatsManager.Instance.init()
updateStreamingPlaylistsInfohashesIfNeeded()
.catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yaml
index e4d7c1359c..9c04fd0f01 100644
--- a/support/doc/api/openapi.yaml
+++ b/support/doc/api/openapi.yaml
@@ -8664,7 +8664,7 @@ components:
- video-transcoding
- video-file-import
- video-import
- - videos-views-stats
+ - videos-stats
- activitypub-refresher
- video-redundancy
- video-live-ending
@@ -10683,6 +10683,9 @@ components:
totalLocalVideoViews:
type: number
description: Total video views made on the instance
+ totalLocalVideoDownloads:
+ type: number
+ description: Total video downloads made on the instance
totalLocalVideoComments:
type: number
description: Total comments made by local users
@@ -11130,7 +11133,7 @@ components:
- video-transcoding
- email
- video-import
- - videos-views-stats
+ - videos-stats
- activitypub-refresher
- video-redundancy
- video-channel-import