err.text -> err
[oweals/peertube.git] / client / src / app / +admin / request-schedulers / request-schedulers-stats / request-schedulers-stats.component.ts
1 import { Component, OnInit, OnDestroy } from '@angular/core'
2
3 import { NotificationsService } from 'angular2-notifications'
4
5 import { RequestSchedulersService, RequestSchedulerStatsAttributes } from '../shared'
6 import { RequestSchedulerStats } from '../../../../../../shared'
7
8 @Component({
9   selector: 'my-request-schedulers-stats',
10   templateUrl: './request-schedulers-stats.component.html',
11   styleUrls: [ './request-schedulers-stats.component.scss' ]
12 })
13 export class RequestSchedulersStatsComponent implements OnInit, OnDestroy {
14   statsTitles = {
15     requestScheduler: 'Basic request scheduler',
16     requestVideoEventScheduler: 'Video events request scheduler',
17     requestVideoQaduScheduler: 'Quick and dirty video updates request scheduler'
18   }
19
20   stats: RequestSchedulerStats
21
22   private intervals: { [ id: string ]: number } = {
23     requestScheduler: null,
24     requestVideoEventScheduler: null,
25     requestVideoQaduScheduler: null
26   }
27
28   private timeouts: { [ id: string ]: number } = {
29     requestScheduler: null,
30     requestVideoEventScheduler: null,
31     requestVideoQaduScheduler: null
32   }
33
34   constructor (
35     private notificationsService: NotificationsService,
36     private requestService: RequestSchedulersService
37   ) { }
38
39   ngOnInit () {
40     this.getStats()
41     this.runIntervals()
42   }
43
44   ngOnDestroy () {
45     Object.keys(this.stats).forEach(requestSchedulerName => {
46       if (this.intervals[requestSchedulerName] !== null) {
47         window.clearInterval(this.intervals[requestSchedulerName])
48       }
49
50       if (this.timeouts[requestSchedulerName] !== null) {
51         window.clearTimeout(this.timeouts[requestSchedulerName])
52       }
53     })
54   }
55
56   getStats () {
57     this.requestService.getStats().subscribe(
58       stats => this.stats = stats,
59
60       err => this.notificationsService.error('Error', err)
61     )
62   }
63
64   private runIntervals () {
65     Object.keys(this.intervals).forEach(requestSchedulerName => {
66       this.intervals[requestSchedulerName] = window.setInterval(() => {
67         const stats: RequestSchedulerStatsAttributes = this.stats[requestSchedulerName]
68
69         stats.remainingMilliSeconds -= 1000
70
71         if (stats.remainingMilliSeconds <= 0) {
72           this.timeouts[requestSchedulerName] = window.setTimeout(() => this.getStats(), stats.remainingMilliSeconds + 100)
73         }
74       }, 1000)
75     })
76   }
77 }