]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/views/shared/video-views.ts
Support video views/viewers stats in server
[github/Chocobozzz/PeerTube.git] / server / lib / views / shared / video-views.ts
1 import { logger, loggerTagsFactory } from '@server/helpers/logger'
2 import { MVideo } from '@server/types/models'
3 import { Redis } from '../../redis'
4
5 const lTags = loggerTagsFactory('views')
6
7 export class VideoViews {
8
9 async addLocalView (options: {
10 video: MVideo
11 ip: string
12 watchTime: number
13 }) {
14 const { video, ip, watchTime } = options
15
16 logger.debug('Adding local view to video %s.', video.uuid, { watchTime, ...lTags(video.uuid) })
17
18 if (!this.hasEnoughWatchTime(video, watchTime)) return false
19
20 const viewExists = await Redis.Instance.doesVideoIPViewExist(ip, video.uuid)
21 if (viewExists) return false
22
23 await Redis.Instance.setIPVideoView(ip, video.uuid)
24
25 await this.addView(video)
26
27 return true
28 }
29
30 async addRemoteView (options: {
31 video: MVideo
32 }) {
33 const { video } = options
34
35 logger.debug('Adding remote view to video %s.', video.uuid, { ...lTags(video.uuid) })
36
37 await this.addView(video)
38
39 return true
40 }
41
42 private async addView (video: MVideo) {
43 const promises: Promise<any>[] = []
44
45 if (video.isOwned()) {
46 promises.push(Redis.Instance.addLocalVideoView(video.id))
47 }
48
49 promises.push(Redis.Instance.addVideoViewStats(video.id))
50
51 await Promise.all(promises)
52 }
53
54 private hasEnoughWatchTime (video: MVideo, watchTime: number) {
55 if (video.isLive || video.duration >= 30) return watchTime >= 30
56
57 // Check more than 50% of the video is watched
58 return video.duration / watchTime < 2
59 }
60 }