2022-03-24 13:36:47 +01:00
|
|
|
import { logger, loggerTagsFactory } from '@server/helpers/logger'
|
2022-04-06 08:50:43 +02:00
|
|
|
import { sendView } from '@server/lib/activitypub/send/send-view'
|
2022-06-17 14:34:37 +02:00
|
|
|
import { getCachedVideoDuration } from '@server/lib/video'
|
2022-04-06 08:50:43 +02:00
|
|
|
import { getServerActor } from '@server/models/application/application'
|
2022-06-17 14:34:37 +02:00
|
|
|
import { MVideo, MVideoImmutable } from '@server/types/models'
|
2022-04-06 08:50:43 +02:00
|
|
|
import { buildUUID } from '@shared/extra-utils'
|
2022-03-24 13:36:47 +01:00
|
|
|
import { Redis } from '../../redis'
|
|
|
|
|
|
|
|
const lTags = loggerTagsFactory('views')
|
|
|
|
|
|
|
|
export class VideoViews {
|
|
|
|
|
|
|
|
async addLocalView (options: {
|
2022-06-17 14:34:37 +02:00
|
|
|
video: MVideoImmutable
|
2022-03-24 13:36:47 +01:00
|
|
|
ip: string
|
|
|
|
watchTime: number
|
|
|
|
}) {
|
|
|
|
const { video, ip, watchTime } = options
|
|
|
|
|
|
|
|
logger.debug('Adding local view to video %s.', video.uuid, { watchTime, ...lTags(video.uuid) })
|
|
|
|
|
2022-06-17 14:34:37 +02:00
|
|
|
if (!await this.hasEnoughWatchTime(video, watchTime)) return false
|
2022-03-24 13:36:47 +01:00
|
|
|
|
|
|
|
const viewExists = await Redis.Instance.doesVideoIPViewExist(ip, video.uuid)
|
|
|
|
if (viewExists) return false
|
|
|
|
|
|
|
|
await Redis.Instance.setIPVideoView(ip, video.uuid)
|
|
|
|
|
|
|
|
await this.addView(video)
|
|
|
|
|
2022-04-06 08:50:43 +02:00
|
|
|
await sendView({ byActor: await getServerActor(), video, type: 'view', viewerIdentifier: buildUUID() })
|
|
|
|
|
2022-03-24 13:36:47 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
async addRemoteView (options: {
|
|
|
|
video: MVideo
|
|
|
|
}) {
|
|
|
|
const { video } = options
|
|
|
|
|
|
|
|
logger.debug('Adding remote view to video %s.', video.uuid, { ...lTags(video.uuid) })
|
|
|
|
|
|
|
|
await this.addView(video)
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-04-06 08:50:43 +02:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2022-06-17 14:34:37 +02:00
|
|
|
private async addView (video: MVideoImmutable) {
|
2022-03-24 13:36:47 +01:00
|
|
|
const promises: Promise<any>[] = []
|
|
|
|
|
|
|
|
if (video.isOwned()) {
|
|
|
|
promises.push(Redis.Instance.addLocalVideoView(video.id))
|
|
|
|
}
|
|
|
|
|
|
|
|
promises.push(Redis.Instance.addVideoViewStats(video.id))
|
|
|
|
|
|
|
|
await Promise.all(promises)
|
|
|
|
}
|
|
|
|
|
2022-06-17 14:34:37 +02:00
|
|
|
private async hasEnoughWatchTime (video: MVideoImmutable, watchTime: number) {
|
|
|
|
const { duration, isLive } = await getCachedVideoDuration(video.id)
|
|
|
|
|
|
|
|
if (isLive || duration >= 30) return watchTime >= 30
|
2022-03-24 13:36:47 +01:00
|
|
|
|
|
|
|
// Check more than 50% of the video is watched
|
2022-06-17 14:34:37 +02:00
|
|
|
return duration / watchTime < 2
|
2022-03-24 13:36:47 +01:00
|
|
|
}
|
|
|
|
}
|