]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+stats/video/video-stats.component.ts
Add help to understand what is a view
[github/Chocobozzz/PeerTube.git] / client / src / app / +stats / video / video-stats.component.ts
1 import { ChartConfiguration, ChartData, PluginOptionsByType, Scale, TooltipItem } from 'chart.js'
2 import zoomPlugin from 'chartjs-plugin-zoom'
3 import { Observable, of } from 'rxjs'
4 import { SelectOptionsItem } from 'src/types'
5 import { Component, OnInit } from '@angular/core'
6 import { ActivatedRoute } from '@angular/router'
7 import { Notifier, PeerTubeRouterService } from '@app/core'
8 import { NumberFormatterPipe, VideoDetails } from '@app/shared/shared-main'
9 import { LiveVideoService } from '@app/shared/shared-video-live'
10 import { secondsToTime } from '@shared/core-utils'
11 import { HttpStatusCode } from '@shared/models/http'
12 import {
13 LiveVideoSession,
14 VideoStatsOverall,
15 VideoStatsRetention,
16 VideoStatsTimeserie,
17 VideoStatsTimeserieMetric
18 } from '@shared/models/videos'
19 import { VideoStatsService } from './video-stats.service'
20
21 type ActiveGraphId = VideoStatsTimeserieMetric | 'retention' | 'countries'
22
23 type CountryData = { name: string, viewers: number }[]
24
25 type ChartIngestData = VideoStatsTimeserie | VideoStatsRetention | CountryData
26 type ChartBuilderResult = {
27 type: 'line' | 'bar'
28 plugins: Partial<PluginOptionsByType<'line' | 'bar'>>
29 data: ChartData<'line' | 'bar'>
30 displayLegend: boolean
31 }
32
33 type Card = { label: string, value: string | number, moreInfo?: string, help?: string }
34
35 @Component({
36 templateUrl: './video-stats.component.html',
37 styleUrls: [ './video-stats.component.scss' ],
38 providers: [ NumberFormatterPipe ]
39 })
40 export class VideoStatsComponent implements OnInit {
41 // Cannot handle date filters
42 globalStatsCards: Card[] = []
43 // Can handle date filters
44 overallStatCards: Card[] = []
45
46 chartOptions: { [ id in ActiveGraphId ]?: ChartConfiguration<'line' | 'bar'> } = {}
47 chartHeight = '300px'
48 chartWidth: string = null
49
50 availableCharts: { id: string, label: string, zoomEnabled: boolean }[] = []
51 activeGraphId: ActiveGraphId = 'viewers'
52
53 video: VideoDetails
54
55 countries: CountryData = []
56
57 chartPlugins = [ zoomPlugin ]
58
59 currentDateFilter = 'all'
60 dateFilters: SelectOptionsItem[] = [
61 {
62 id: 'all',
63 label: $localize`Since the video publication`
64 }
65 ]
66
67 private statsStartDate: Date
68 private statsEndDate: Date
69
70 private chartIngestData: { [ id in ActiveGraphId ]?: ChartIngestData } = {}
71
72 constructor (
73 private route: ActivatedRoute,
74 private notifier: Notifier,
75 private statsService: VideoStatsService,
76 private peertubeRouter: PeerTubeRouterService,
77 private numberFormatter: NumberFormatterPipe,
78 private liveService: LiveVideoService
79 ) {}
80
81 ngOnInit () {
82 this.video = this.route.snapshot.data.video
83
84 this.availableCharts = [
85 {
86 id: 'viewers',
87 label: $localize`Viewers`,
88 zoomEnabled: true
89 },
90 {
91 id: 'aggregateWatchTime',
92 label: $localize`Watch time`,
93 zoomEnabled: true
94 },
95 {
96 id: 'countries',
97 label: $localize`Countries`,
98 zoomEnabled: false
99 }
100 ]
101
102 if (!this.video.isLive) {
103 this.availableCharts.push({
104 id: 'retention',
105 label: $localize`Retention`,
106 zoomEnabled: false
107 })
108 }
109
110 const snapshotQuery = this.route.snapshot.queryParams
111 if (snapshotQuery.startDate || snapshotQuery.endDate) {
112 this.addAndSelectCustomDateFilter()
113 }
114
115 this.route.queryParams.subscribe(params => {
116 this.statsStartDate = params.startDate
117 ? new Date(params.startDate)
118 : undefined
119
120 this.statsEndDate = params.endDate
121 ? new Date(params.endDate)
122 : undefined
123
124 this.loadChart()
125 this.loadOverallStats()
126 })
127
128 this.loadDateFilters()
129 }
130
131 hasCountries () {
132 return this.countries.length !== 0
133 }
134
135 onChartChange (newActive: ActiveGraphId) {
136 this.activeGraphId = newActive
137
138 this.loadChart()
139 }
140
141 resetZoom () {
142 this.peertubeRouter.silentNavigate([], {})
143 this.removeAndResetCustomDateFilter()
144 }
145
146 hasZoom () {
147 return !!this.statsStartDate && this.isTimeserieGraph(this.activeGraphId)
148 }
149
150 getViewersStatsTitle () {
151 if (this.statsStartDate && this.statsEndDate) {
152 return $localize`Viewers stats between ${this.statsStartDate.toLocaleString()} and ${this.statsEndDate.toLocaleString()}`
153 }
154
155 return $localize`Viewers stats`
156 }
157
158 onDateFilterChange () {
159 if (this.currentDateFilter === 'all') {
160 return this.resetZoom()
161 }
162
163 const idParts = this.currentDateFilter.split('|')
164 if (idParts.length === 2) {
165 return this.peertubeRouter.silentNavigate([], { startDate: idParts[0], endDate: idParts[1] })
166 }
167 }
168
169 private isTimeserieGraph (graphId: ActiveGraphId) {
170 return graphId === 'aggregateWatchTime' || graphId === 'viewers'
171 }
172
173 private loadOverallStats () {
174 this.statsService.getOverallStats({ videoId: this.video.uuid, startDate: this.statsStartDate, endDate: this.statsEndDate })
175 .subscribe({
176 next: res => {
177 this.countries = res.countries.slice(0, 10).map(c => ({
178 name: this.countryCodeToName(c.isoCode),
179 viewers: c.viewers
180 }))
181
182 this.buildOverallStatCard(res)
183 },
184
185 error: err => this.notifier.error(err.message)
186 })
187 }
188
189 private loadDateFilters () {
190 if (this.video.isLive) return this.loadLiveDateFilters()
191
192 return this.loadVODDateFilters()
193 }
194
195 private loadLiveDateFilters () {
196 this.liveService.listSessions(this.video.id)
197 .subscribe({
198 next: ({ data }) => {
199 const newFilters = data.map(session => this.buildLiveFilter(session))
200
201 this.dateFilters = this.dateFilters.concat(newFilters)
202 },
203
204 error: err => this.notifier.error(err.message)
205 })
206 }
207
208 private loadVODDateFilters () {
209 this.liveService.findLiveSessionFromVOD(this.video.id)
210 .subscribe({
211 next: session => {
212 this.dateFilters = this.dateFilters.concat([ this.buildLiveFilter(session) ])
213 },
214
215 error: err => {
216 if (err.status === HttpStatusCode.NOT_FOUND_404) return
217
218 this.notifier.error(err.message)
219 }
220 })
221 }
222
223 private buildLiveFilter (session: LiveVideoSession) {
224 return {
225 id: session.startDate + '|' + session.endDate,
226 label: $localize`Of live of ${new Date(session.startDate).toLocaleString()}`
227 }
228 }
229
230 private addAndSelectCustomDateFilter () {
231 const exists = this.dateFilters.some(d => d.id === 'custom')
232
233 if (!exists) {
234 this.dateFilters = this.dateFilters.concat([
235 {
236 id: 'custom',
237 label: $localize`Custom dates`
238 }
239 ])
240 }
241
242 this.currentDateFilter = 'custom'
243 }
244
245 private removeAndResetCustomDateFilter () {
246 this.dateFilters = this.dateFilters.filter(d => d.id !== 'custom')
247
248 this.currentDateFilter = 'all'
249 }
250
251 private buildOverallStatCard (overallStats: VideoStatsOverall) {
252 this.globalStatsCards = [
253 {
254 label: $localize`Views`,
255 value: this.numberFormatter.transform(this.video.views),
256 help: $localize`A view means that someone watched the video for at least 30 seconds`
257 },
258 {
259 label: $localize`Likes`,
260 value: this.numberFormatter.transform(this.video.likes)
261 }
262 ]
263
264 this.overallStatCards = [
265 {
266 label: $localize`Average watch time`,
267 value: secondsToTime(overallStats.averageWatchTime)
268 },
269 {
270 label: $localize`Total watch time`,
271 value: secondsToTime(overallStats.totalWatchTime)
272 },
273 {
274 label: $localize`Peak viewers`,
275 value: this.numberFormatter.transform(overallStats.viewersPeak),
276 moreInfo: overallStats.viewersPeak !== 0
277 ? $localize`at ${new Date(overallStats.viewersPeakDate).toLocaleString()}`
278 : undefined
279 }
280 ]
281
282 if (overallStats.countries.length !== 0) {
283 this.overallStatCards.push({
284 label: $localize`Countries`,
285 value: this.numberFormatter.transform(overallStats.countries.length)
286 })
287 }
288 }
289
290 private loadChart () {
291 const obsBuilders: { [ id in ActiveGraphId ]: Observable<ChartIngestData> } = {
292 retention: this.statsService.getRetentionStats(this.video.uuid),
293
294 aggregateWatchTime: this.statsService.getTimeserieStats({
295 videoId: this.video.uuid,
296 startDate: this.statsStartDate,
297 endDate: this.statsEndDate,
298 metric: 'aggregateWatchTime'
299 }),
300 viewers: this.statsService.getTimeserieStats({
301 videoId: this.video.uuid,
302 startDate: this.statsStartDate,
303 endDate: this.statsEndDate,
304 metric: 'viewers'
305 }),
306
307 countries: of(this.countries)
308 }
309
310 obsBuilders[this.activeGraphId].subscribe({
311 next: res => {
312 this.chartIngestData[this.activeGraphId] = res
313
314 this.chartOptions[this.activeGraphId] = this.buildChartOptions(this.activeGraphId)
315 },
316
317 error: err => this.notifier.error(err.message)
318 })
319 }
320
321 private buildChartOptions (graphId: ActiveGraphId): ChartConfiguration<'line' | 'bar'> {
322 const dataBuilders: {
323 [ id in ActiveGraphId ]: (rawData: ChartIngestData) => ChartBuilderResult
324 } = {
325 retention: (rawData: VideoStatsRetention) => this.buildRetentionChartOptions(rawData),
326 aggregateWatchTime: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
327 viewers: (rawData: VideoStatsTimeserie) => this.buildTimeserieChartOptions(rawData),
328 countries: (rawData: CountryData) => this.buildCountryChartOptions(rawData)
329 }
330
331 const { type, data, displayLegend, plugins } = dataBuilders[graphId](this.chartIngestData[graphId])
332
333 const self = this
334
335 return {
336 type,
337 data,
338
339 options: {
340 responsive: true,
341
342 scales: {
343 x: {
344 ticks: {
345 callback: function (value) {
346 return self.formatXTick({
347 graphId,
348 value,
349 data: self.chartIngestData[graphId] as VideoStatsTimeserie,
350 scale: this
351 })
352 }
353 }
354 },
355
356 y: {
357 beginAtZero: true,
358
359 max: this.activeGraphId === 'retention'
360 ? 100
361 : undefined,
362
363 ticks: {
364 callback: value => this.formatYTick({ graphId, value })
365 }
366 }
367 },
368
369 plugins: {
370 legend: {
371 display: displayLegend
372 },
373 tooltip: {
374 callbacks: {
375 title: items => this.formatTooltipTitle({ graphId, items }),
376 label: value => this.formatYTick({ graphId, value: value.raw as number | string })
377 }
378 },
379
380 ...plugins
381 }
382 }
383 }
384 }
385
386 private buildRetentionChartOptions (rawData: VideoStatsRetention): ChartBuilderResult {
387 const labels: string[] = []
388 const data: number[] = []
389
390 for (const d of rawData.data) {
391 labels.push(secondsToTime(d.second))
392 data.push(d.retentionPercent)
393 }
394
395 return {
396 type: 'line' as 'line',
397
398 displayLegend: false,
399
400 plugins: {
401 ...this.buildDisabledZoomPlugin()
402 },
403
404 data: {
405 labels,
406 datasets: [
407 {
408 data,
409 borderColor: this.buildChartColor()
410 }
411 ]
412 }
413 }
414 }
415
416 private buildTimeserieChartOptions (rawData: VideoStatsTimeserie): ChartBuilderResult {
417 const labels: string[] = []
418 const data: number[] = []
419
420 for (const d of rawData.data) {
421 labels.push(d.date)
422 data.push(d.value)
423 }
424
425 return {
426 type: 'line' as 'line',
427
428 displayLegend: false,
429
430 plugins: {
431 zoom: {
432 zoom: {
433 wheel: {
434 enabled: false
435 },
436 drag: {
437 enabled: true
438 },
439 pinch: {
440 enabled: true
441 },
442 mode: 'x',
443 onZoomComplete: ({ chart }) => {
444 const { min, max } = chart.scales.x
445
446 const startDate = rawData.data[min].date
447 const endDate = this.buildZoomEndDate(rawData.groupInterval, rawData.data[max].date)
448
449 this.peertubeRouter.silentNavigate([], { startDate, endDate })
450 this.addAndSelectCustomDateFilter()
451 }
452 }
453 }
454 },
455
456 data: {
457 labels,
458 datasets: [
459 {
460 data,
461 borderColor: this.buildChartColor()
462 }
463 ]
464 }
465 }
466 }
467
468 private buildCountryChartOptions (rawData: CountryData): ChartBuilderResult {
469 const labels: string[] = []
470 const data: number[] = []
471
472 for (const d of rawData) {
473 labels.push(d.name)
474 data.push(d.viewers)
475 }
476
477 return {
478 type: 'bar' as 'bar',
479
480 displayLegend: true,
481
482 plugins: {
483 ...this.buildDisabledZoomPlugin()
484 },
485
486 data: {
487 labels,
488 datasets: [
489 {
490 label: $localize`Viewers`,
491 backgroundColor: this.buildChartColor(),
492 maxBarThickness: 20,
493 data
494 }
495 ]
496 }
497 }
498 }
499
500 private buildChartColor () {
501 return getComputedStyle(document.body).getPropertyValue('--mainColorLighter')
502 }
503
504 private formatXTick (options: {
505 graphId: ActiveGraphId
506 value: number | string
507 data: VideoStatsTimeserie
508 scale: Scale
509 }) {
510 const { graphId, value, data, scale } = options
511
512 const label = scale.getLabelForValue(value as number)
513
514 if (!this.isTimeserieGraph(graphId)) {
515 return label
516 }
517
518 const date = new Date(label)
519
520 if (data.groupInterval.match(/ month?$/)) {
521 return date.toLocaleDateString([], { month: 'numeric' })
522 }
523
524 if (data.groupInterval.match(/ days?$/)) {
525 return date.toLocaleDateString([], { month: 'numeric', day: 'numeric' })
526 }
527
528 if (data.groupInterval.match(/ hours?$/)) {
529 return date.toLocaleTimeString([], { month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' })
530 }
531
532 return date.toLocaleTimeString([], { hour: 'numeric', minute: 'numeric' })
533 }
534
535 private formatYTick (options: {
536 graphId: ActiveGraphId
537 value: number | string
538 }) {
539 const { graphId, value } = options
540
541 if (graphId === 'retention') return value + ' %'
542 if (graphId === 'aggregateWatchTime') return secondsToTime(+value)
543
544 return value.toLocaleString()
545 }
546
547 private formatTooltipTitle (options: {
548 graphId: ActiveGraphId
549 items: TooltipItem<any>[]
550 }) {
551 const { graphId, items } = options
552 const item = items[0]
553
554 if (this.isTimeserieGraph(graphId)) return new Date(item.label).toLocaleString()
555
556 return item.label
557 }
558
559 private countryCodeToName (code: string) {
560 const intl: any = Intl
561 if (!intl.DisplayNames) return code
562
563 const regionNames = new intl.DisplayNames([], { type: 'region' })
564
565 return regionNames.of(code)
566 }
567
568 private buildDisabledZoomPlugin () {
569 return {
570 zoom: {
571 zoom: {
572 wheel: {
573 enabled: false
574 },
575 drag: {
576 enabled: false
577 },
578 pinch: {
579 enabled: false
580 }
581 }
582 }
583 }
584 }
585
586 private buildZoomEndDate (groupInterval: string, last: string) {
587 const date = new Date(last)
588
589 // Remove parts of the date we don't need
590 if (groupInterval.endsWith(' day') || groupInterval.endsWith(' days')) {
591 date.setHours(23, 59, 59)
592 } else if (groupInterval.endsWith(' hour') || groupInterval.endsWith(' hours')) {
593 date.setMinutes(59, 59)
594 } else {
595 date.setSeconds(59)
596 }
597
598 return date.toISOString()
599 }
600 }