aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/views/video-views-manager.ts
blob: e07af1ca940f39cca68a6fb4b0e43a204cd26886 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { logger, loggerTagsFactory } from '@server/helpers/logger'
import { MVideo } from '@server/types/models'
import { VideoViewEvent } from '@shared/models'
import { VideoViewers, VideoViews } from './shared'

const lTags = loggerTagsFactory('views')

export class VideoViewsManager {

  private static instance: VideoViewsManager

  private videoViewers: VideoViewers
  private videoViews: VideoViews

  private constructor () {
  }

  init () {
    this.videoViewers = new VideoViewers()
    this.videoViews = new VideoViews()
  }

  async processLocalView (options: {
    video: MVideo
    currentTime: number
    ip: string | null
    viewEvent?: VideoViewEvent
  }) {
    const { video, ip, viewEvent, currentTime } = options

    logger.debug('Processing local view for %s and ip %s.', video.url, ip, lTags())

    const successViewer = await this.videoViewers.addLocalViewer({ video, ip, viewEvent, currentTime })

    // Do it after added local viewer to fetch updated information
    const watchTime = await this.videoViewers.getWatchTime(video.id, ip)

    const successView = await this.videoViews.addLocalView({ video, watchTime, ip })

    return { successView, successViewer }
  }

  async processRemoteView (options: {
    video: MVideo
    viewerExpires?: Date
  }) {
    const { video, viewerExpires } = options

    logger.debug('Processing remote view for %s.', video.url, { viewerExpires, ...lTags() })

    if (viewerExpires) await this.videoViewers.addRemoteViewer({ video, viewerExpires })
    else await this.videoViews.addRemoteView({ video })
  }

  getViewers (video: MVideo) {
    return this.videoViewers.getViewers(video)
  }

  buildViewerExpireTime () {
    return this.videoViewers.buildViewerExpireTime()
  }

  processViewers () {
    return this.videoViewers.processViewerStats()
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}