]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/menu/avatar-notification.component.ts
Reorganize client shared modules
[github/Chocobozzz/PeerTube.git] / client / src / app / menu / avatar-notification.component.ts
1 import { Subject, Subscription } from 'rxjs'
2 import { filter } from 'rxjs/operators'
3 import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'
4 import { NavigationEnd, Router } from '@angular/router'
5 import { Notifier, User, UserNotificationSocket } from '@app/core'
6 import { UserNotificationService } from '@app/shared/shared-main'
7 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
8
9 @Component({
10 selector: 'my-avatar-notification',
11 templateUrl: './avatar-notification.component.html',
12 styleUrls: [ './avatar-notification.component.scss' ]
13 })
14 export class AvatarNotificationComponent implements OnInit, OnDestroy {
15 @ViewChild('popover', { static: true }) popover: NgbPopover
16
17 @Input() user: User
18
19 unreadNotifications = 0
20 loaded = false
21
22 markAllAsReadSubject = new Subject<boolean>()
23
24 private notificationSub: Subscription
25 private routeSub: Subscription
26
27 constructor (
28 private userNotificationService: UserNotificationService,
29 private userNotificationSocket: UserNotificationSocket,
30 private notifier: Notifier,
31 private router: Router
32 ) {
33 }
34
35 ngOnInit () {
36 this.userNotificationService.countUnreadNotifications()
37 .subscribe(
38 result => {
39 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
40 this.subscribeToNotifications()
41 },
42
43 err => this.notifier.error(err.message)
44 )
45
46 this.routeSub = this.router.events
47 .pipe(filter(event => event instanceof NavigationEnd))
48 .subscribe(() => this.closePopover())
49 }
50
51 ngOnDestroy () {
52 if (this.notificationSub) this.notificationSub.unsubscribe()
53 if (this.routeSub) this.routeSub.unsubscribe()
54 }
55
56 closePopover () {
57 this.popover.close()
58 }
59
60 onPopoverHidden () {
61 this.loaded = false
62 }
63
64 onNotificationLoaded () {
65 this.loaded = true
66 }
67
68 markAllAsRead () {
69 this.markAllAsReadSubject.next(true)
70 }
71
72 private async subscribeToNotifications () {
73 const obs = await this.userNotificationSocket.getMyNotificationsSocket()
74
75 this.notificationSub = obs.subscribe(data => {
76 if (data.type === 'new') return this.unreadNotifications++
77 if (data.type === 'read') return this.unreadNotifications--
78 if (data.type === 'read-all') return this.unreadNotifications = 0
79 })
80 }
81
82 }