878c5c88c581b96947a8ecc0c2dee9b27b83c593
[oweals/peertube.git] / client / src / app / menu / avatar-notification.component.ts
1 import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
2 import { User } from '../shared/users/user.model'
3 import { UserNotificationService } from '@app/shared/users/user-notification.service'
4 import { Subscription } from 'rxjs'
5 import { Notifier, UserNotificationSocket } from '@app/core'
6 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
7 import { NavigationEnd, Router } from '@angular/router'
8 import { filter } from 'rxjs/operators'
9
10 @Component({
11   selector: 'my-avatar-notification',
12   templateUrl: './avatar-notification.component.html',
13   styleUrls: [ './avatar-notification.component.scss' ]
14 })
15 export class AvatarNotificationComponent implements OnInit, OnDestroy {
16   @ViewChild('popover') popover: NgbPopover
17   @Input() user: User
18
19   unreadNotifications = 0
20
21   private notificationSub: Subscription
22   private routeSub: Subscription
23
24   constructor (
25     private userNotificationService: UserNotificationService,
26     private userNotificationSocket: UserNotificationSocket,
27     private notifier: Notifier,
28     private router: Router
29   ) {
30   }
31
32   ngOnInit () {
33     this.userNotificationService.countUnreadNotifications()
34         .subscribe(
35           result => {
36             this.unreadNotifications = Math.min(result, 99) // Limit number to 99
37             this.subscribeToNotifications()
38           },
39
40           err => this.notifier.error(err.message)
41         )
42
43     this.routeSub = this.router.events
44                         .pipe(filter(event => event instanceof NavigationEnd))
45                         .subscribe(() => this.closePopover())
46   }
47
48   ngOnDestroy () {
49     if (this.notificationSub) this.notificationSub.unsubscribe()
50     if (this.routeSub) this.routeSub.unsubscribe()
51   }
52
53   closePopover () {
54     this.popover.close()
55   }
56
57   private async subscribeToNotifications () {
58     const obs = await this.userNotificationSocket.getMyNotificationsSocket()
59
60     this.notificationSub = obs.subscribe(data => {
61       if (data.type === 'new') return this.unreadNotifications++
62       if (data.type === 'read') return this.unreadNotifications--
63       if (data.type === 'read-all') return this.unreadNotifications = 0
64     })
65   }
66
67 }