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