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'
9 const lTags = loggerTagsFactory('views')
11 export class VideoViews {
13 async addLocalView (options: {
14 video: MVideoImmutable
18 const { video, ip, watchTime } = options
20 logger.debug('Adding local view to video %s.', video.uuid, { watchTime, ...lTags(video.uuid) })
22 if (!await this.hasEnoughWatchTime(video, watchTime)) return false
24 const viewExists = await Redis.Instance.doesVideoIPViewExist(ip, video.uuid)
25 if (viewExists) return false
27 await Redis.Instance.setIPVideoView(ip, video.uuid)
29 await this.addView(video)
31 await sendView({ byActor: await getServerActor(), video, type: 'view', viewerIdentifier: buildUUID() })
36 async addRemoteView (options: {
39 const { video } = options
41 logger.debug('Adding remote view to video %s.', video.uuid, { ...lTags(video.uuid) })
43 await this.addView(video)
48 // ---------------------------------------------------------------------------
50 private async addView (video: MVideoImmutable) {
51 const promises: Promise<any>[] = []
53 if (video.isOwned()) {
54 promises.push(Redis.Instance.addLocalVideoView(video.id))
57 promises.push(Redis.Instance.addVideoViewStats(video.id))
59 await Promise.all(promises)
62 private async hasEnoughWatchTime (video: MVideoImmutable, watchTime: number) {
63 const { duration, isLive } = await getCachedVideoDuration(video.id)
65 if (isLive || duration >= 30) return watchTime >= 30
67 // Check more than 50% of the video is watched
68 return duration / watchTime < 2