local-video-viewer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { QueryTypes } from 'sequelize'
  2. import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, HasMany, IsUUID, Model, Table } from 'sequelize-typescript'
  3. import { getActivityStreamDuration } from '@server/lib/activitypub/activity'
  4. import { buildGroupByAndBoundaries } from '@server/lib/timeserie'
  5. import { MLocalVideoViewer, MLocalVideoViewerWithWatchSections, MVideo } from '@server/types/models'
  6. import { VideoStatsOverall, VideoStatsRetention, VideoStatsTimeserie, VideoStatsTimeserieMetric, WatchActionObject } from '@shared/models'
  7. import { AttributesOnly } from '@shared/typescript-utils'
  8. import { VideoModel } from '../video/video'
  9. import { LocalVideoViewerWatchSectionModel } from './local-video-viewer-watch-section'
  10. /**
  11. *
  12. * Aggregate viewers of local videos only to display statistics to video owners
  13. * A viewer is a user that watched one or multiple sections of a specific video inside a time window
  14. *
  15. */
  16. @Table({
  17. tableName: 'localVideoViewer',
  18. updatedAt: false,
  19. indexes: [
  20. {
  21. fields: [ 'videoId' ]
  22. },
  23. {
  24. fields: [ 'url' ],
  25. unique: true
  26. }
  27. ]
  28. })
  29. export class LocalVideoViewerModel extends Model<Partial<AttributesOnly<LocalVideoViewerModel>>> {
  30. @CreatedAt
  31. createdAt: Date
  32. @AllowNull(false)
  33. @Column(DataType.DATE)
  34. startDate: Date
  35. @AllowNull(false)
  36. @Column(DataType.DATE)
  37. endDate: Date
  38. @AllowNull(false)
  39. @Column
  40. watchTime: number
  41. @AllowNull(true)
  42. @Column
  43. country: string
  44. @AllowNull(false)
  45. @Default(DataType.UUIDV4)
  46. @IsUUID(4)
  47. @Column(DataType.UUID)
  48. uuid: string
  49. @AllowNull(false)
  50. @Column
  51. url: string
  52. @ForeignKey(() => VideoModel)
  53. @Column
  54. videoId: number
  55. @BelongsTo(() => VideoModel, {
  56. foreignKey: {
  57. allowNull: false
  58. },
  59. onDelete: 'CASCADE'
  60. })
  61. Video: VideoModel
  62. @HasMany(() => LocalVideoViewerWatchSectionModel, {
  63. foreignKey: {
  64. allowNull: false
  65. },
  66. onDelete: 'cascade'
  67. })
  68. WatchSections: LocalVideoViewerWatchSectionModel[]
  69. static loadByUrl (url: string): Promise<MLocalVideoViewer> {
  70. return this.findOne({
  71. where: {
  72. url
  73. }
  74. })
  75. }
  76. static loadFullById (id: number): Promise<MLocalVideoViewerWithWatchSections> {
  77. return this.findOne({
  78. include: [
  79. {
  80. model: VideoModel.unscoped(),
  81. required: true
  82. },
  83. {
  84. model: LocalVideoViewerWatchSectionModel.unscoped(),
  85. required: true
  86. }
  87. ],
  88. where: {
  89. id
  90. }
  91. })
  92. }
  93. static async getOverallStats (options: {
  94. video: MVideo
  95. startDate?: string
  96. endDate?: string
  97. }): Promise<VideoStatsOverall> {
  98. const { video, startDate, endDate } = options
  99. const queryOptions = {
  100. type: QueryTypes.SELECT as QueryTypes.SELECT,
  101. replacements: { videoId: video.id } as any
  102. }
  103. if (startDate) queryOptions.replacements.startDate = startDate
  104. if (endDate) queryOptions.replacements.endDate = endDate
  105. const buildWatchTimePromise = () => {
  106. let watchTimeDateWhere = ''
  107. if (startDate) watchTimeDateWhere += ' AND "localVideoViewer"."startDate" >= :startDate'
  108. if (endDate) watchTimeDateWhere += ' AND "localVideoViewer"."endDate" <= :endDate'
  109. const watchTimeQuery = `SELECT ` +
  110. `COUNT("localVideoViewer"."id") AS "totalViewers", ` +
  111. `SUM("localVideoViewer"."watchTime") AS "totalWatchTime", ` +
  112. `AVG("localVideoViewer"."watchTime") AS "averageWatchTime" ` +
  113. `FROM "localVideoViewer" ` +
  114. `INNER JOIN "video" ON "video"."id" = "localVideoViewer"."videoId" ` +
  115. `WHERE "videoId" = :videoId ${watchTimeDateWhere}`
  116. return LocalVideoViewerModel.sequelize.query<any>(watchTimeQuery, queryOptions)
  117. }
  118. const buildWatchPeakPromise = () => {
  119. let watchPeakDateWhereStart = ''
  120. let watchPeakDateWhereEnd = ''
  121. if (startDate) {
  122. watchPeakDateWhereStart += ' AND "localVideoViewer"."startDate" >= :startDate'
  123. watchPeakDateWhereEnd += ' AND "localVideoViewer"."endDate" >= :startDate'
  124. }
  125. if (endDate) {
  126. watchPeakDateWhereStart += ' AND "localVideoViewer"."startDate" <= :endDate'
  127. watchPeakDateWhereEnd += ' AND "localVideoViewer"."endDate" <= :endDate'
  128. }
  129. // Add viewers that were already here, before our start date
  130. const beforeWatchersQuery = startDate
  131. // eslint-disable-next-line max-len
  132. ? `SELECT COUNT(*) AS "total" FROM "localVideoViewer" WHERE "localVideoViewer"."startDate" < :startDate AND "localVideoViewer"."endDate" >= :startDate`
  133. : `SELECT 0 AS "total"`
  134. const watchPeakQuery = `WITH
  135. "beforeWatchers" AS (${beforeWatchersQuery}),
  136. "watchPeakValues" AS (
  137. SELECT "startDate" AS "dateBreakpoint", 1 AS "inc"
  138. FROM "localVideoViewer"
  139. WHERE "videoId" = :videoId ${watchPeakDateWhereStart}
  140. UNION ALL
  141. SELECT "endDate" AS "dateBreakpoint", -1 AS "inc"
  142. FROM "localVideoViewer"
  143. WHERE "videoId" = :videoId ${watchPeakDateWhereEnd}
  144. )
  145. SELECT "dateBreakpoint", "concurrent"
  146. FROM (
  147. SELECT "dateBreakpoint", SUM(SUM("inc")) OVER (ORDER BY "dateBreakpoint") + (SELECT "total" FROM "beforeWatchers") AS "concurrent"
  148. FROM "watchPeakValues"
  149. GROUP BY "dateBreakpoint"
  150. ) tmp
  151. ORDER BY "concurrent" DESC
  152. FETCH FIRST 1 ROW ONLY`
  153. return LocalVideoViewerModel.sequelize.query<any>(watchPeakQuery, queryOptions)
  154. }
  155. const buildCountriesPromise = () => {
  156. let countryDateWhere = ''
  157. if (startDate) countryDateWhere += ' AND "localVideoViewer"."endDate" >= :startDate'
  158. if (endDate) countryDateWhere += ' AND "localVideoViewer"."startDate" <= :endDate'
  159. const countriesQuery = `SELECT country, COUNT(country) as viewers ` +
  160. `FROM "localVideoViewer" ` +
  161. `WHERE "videoId" = :videoId AND country IS NOT NULL ${countryDateWhere} ` +
  162. `GROUP BY country ` +
  163. `ORDER BY viewers DESC`
  164. return LocalVideoViewerModel.sequelize.query<any>(countriesQuery, queryOptions)
  165. }
  166. const [ rowsWatchTime, rowsWatchPeak, rowsCountries ] = await Promise.all([
  167. buildWatchTimePromise(),
  168. buildWatchPeakPromise(),
  169. buildCountriesPromise()
  170. ])
  171. const viewersPeak = rowsWatchPeak.length !== 0
  172. ? parseInt(rowsWatchPeak[0].concurrent) || 0
  173. : 0
  174. return {
  175. totalWatchTime: rowsWatchTime.length !== 0
  176. ? Math.round(rowsWatchTime[0].totalWatchTime) || 0
  177. : 0,
  178. averageWatchTime: rowsWatchTime.length !== 0
  179. ? Math.round(rowsWatchTime[0].averageWatchTime) || 0
  180. : 0,
  181. totalViewers: rowsWatchTime.length !== 0
  182. ? Math.round(rowsWatchTime[0].totalViewers) || 0
  183. : 0,
  184. viewersPeak,
  185. viewersPeakDate: rowsWatchPeak.length !== 0 && viewersPeak !== 0
  186. ? rowsWatchPeak[0].dateBreakpoint || null
  187. : null,
  188. countries: rowsCountries.map(r => ({
  189. isoCode: r.country,
  190. viewers: r.viewers
  191. }))
  192. }
  193. }
  194. static async getRetentionStats (video: MVideo): Promise<VideoStatsRetention> {
  195. const step = Math.max(Math.round(video.duration / 100), 1)
  196. const query = `WITH "total" AS (SELECT COUNT(*) AS viewers FROM "localVideoViewer" WHERE "videoId" = :videoId) ` +
  197. `SELECT serie AS "second", ` +
  198. `(COUNT("localVideoViewer".id)::float / (SELECT GREATEST("total"."viewers", 1) FROM "total")) AS "retention" ` +
  199. `FROM generate_series(0, ${video.duration}, ${step}) serie ` +
  200. `LEFT JOIN "localVideoViewer" ON "localVideoViewer"."videoId" = :videoId ` +
  201. `AND EXISTS (` +
  202. `SELECT 1 FROM "localVideoViewerWatchSection" ` +
  203. `WHERE "localVideoViewer"."id" = "localVideoViewerWatchSection"."localVideoViewerId" ` +
  204. `AND serie >= "localVideoViewerWatchSection"."watchStart" ` +
  205. `AND serie <= "localVideoViewerWatchSection"."watchEnd"` +
  206. `)` +
  207. `GROUP BY serie ` +
  208. `ORDER BY serie ASC`
  209. const queryOptions = {
  210. type: QueryTypes.SELECT as QueryTypes.SELECT,
  211. replacements: { videoId: video.id }
  212. }
  213. const rows = await LocalVideoViewerModel.sequelize.query<any>(query, queryOptions)
  214. return {
  215. data: rows.map(r => ({
  216. second: r.second,
  217. retentionPercent: parseFloat(r.retention) * 100
  218. }))
  219. }
  220. }
  221. static async getTimeserieStats (options: {
  222. video: MVideo
  223. metric: VideoStatsTimeserieMetric
  224. startDate: string
  225. endDate: string
  226. }): Promise<VideoStatsTimeserie> {
  227. const { video, metric } = options
  228. const { groupInterval, startDate, endDate } = buildGroupByAndBoundaries(options.startDate, options.endDate)
  229. const selectMetrics: { [ id in VideoStatsTimeserieMetric ]: string } = {
  230. viewers: 'COUNT("localVideoViewer"."id")',
  231. aggregateWatchTime: 'SUM("localVideoViewer"."watchTime")'
  232. }
  233. const intervalWhere: { [ id in VideoStatsTimeserieMetric ]: string } = {
  234. // Viewer is still in the interval. Overlap algorithm
  235. viewers: '"localVideoViewer"."startDate" <= "intervals"."endDate" ' +
  236. 'AND "localVideoViewer"."endDate" >= "intervals"."startDate"',
  237. // We do an aggregation, so only sum things once. Arbitrary we use the end date for that purpose
  238. aggregateWatchTime: '"localVideoViewer"."endDate" >= "intervals"."startDate" ' +
  239. 'AND "localVideoViewer"."endDate" <= "intervals"."endDate"'
  240. }
  241. const query = `WITH "intervals" AS (
  242. SELECT
  243. "time" AS "startDate", "time" + :groupInterval::interval as "endDate"
  244. FROM
  245. generate_series(:startDate::timestamptz, :endDate::timestamptz, :groupInterval::interval) serie("time")
  246. )
  247. SELECT "intervals"."startDate" as "date", COALESCE(${selectMetrics[metric]}, 0) AS value
  248. FROM
  249. intervals
  250. LEFT JOIN "localVideoViewer" ON "localVideoViewer"."videoId" = :videoId
  251. AND ${intervalWhere[metric]}
  252. GROUP BY
  253. "intervals"."startDate"
  254. ORDER BY
  255. "intervals"."startDate"`
  256. const queryOptions = {
  257. type: QueryTypes.SELECT as QueryTypes.SELECT,
  258. replacements: {
  259. startDate,
  260. endDate,
  261. groupInterval,
  262. videoId: video.id
  263. }
  264. }
  265. const rows = await LocalVideoViewerModel.sequelize.query<any>(query, queryOptions)
  266. return {
  267. groupInterval,
  268. data: rows.map(r => ({
  269. date: r.date,
  270. value: parseInt(r.value)
  271. }))
  272. }
  273. }
  274. toActivityPubObject (this: MLocalVideoViewerWithWatchSections): WatchActionObject {
  275. const location = this.country
  276. ? {
  277. location: {
  278. addressCountry: this.country
  279. }
  280. }
  281. : {}
  282. return {
  283. id: this.url,
  284. type: 'WatchAction',
  285. duration: getActivityStreamDuration(this.watchTime),
  286. startTime: this.startDate.toISOString(),
  287. endTime: this.endDate.toISOString(),
  288. object: this.Video.url,
  289. uuid: this.uuid,
  290. actionStatus: 'CompletedActionStatus',
  291. watchSections: this.WatchSections.map(w => ({
  292. startTimestamp: w.watchStart,
  293. endTimestamp: w.watchEnd
  294. })),
  295. ...location
  296. }
  297. }
  298. }