1 import { logger, loggerTagsFactory } from '@server/helpers/logger'
2 import { sendView } from '@server/lib/activitypub/send/send-view'
3 import { getServerActor } from '@server/models/application/application'
4 import { MVideo } from '@server/types/models'
5 import { buildUUID } from '@shared/extra-utils'
6 import { Redis } from '../../redis'
8 const lTags = loggerTagsFactory('views')
10 export class VideoViews {
12 async addLocalView (options: {
17 const { video, ip, watchTime } = options
19 logger.debug('Adding local view to video %s.', video.uuid, { watchTime, ...lTags(video.uuid) })
21 if (!this.hasEnoughWatchTime(video, watchTime)) return false
23 const viewExists = await Redis.Instance.doesVideoIPViewExist(ip, video.uuid)
24 if (viewExists) return false
26 await Redis.Instance.setIPVideoView(ip, video.uuid)
28 await this.addView(video)
30 await sendView({ byActor: await getServerActor(), video, type: 'view', viewerIdentifier: buildUUID() })
35 async addRemoteView (options: {
38 const { video } = options
40 logger.debug('Adding remote view to video %s.', video.uuid, { ...lTags(video.uuid) })
42 await this.addView(video)
47 // ---------------------------------------------------------------------------
49 private async addView (video: MVideo) {
50 const promises: Promise<any>[] = []
52 if (video.isOwned()) {
53 promises.push(Redis.Instance.addLocalVideoView(video.id))
56 promises.push(Redis.Instance.addVideoViewStats(video.id))
58 await Promise.all(promises)
61 private hasEnoughWatchTime (video: MVideo, watchTime: number) {
62 if (video.isLive || video.duration >= 30) return watchTime >= 30
64 // Check more than 50% of the video is watched
65 return video.duration / watchTime < 2