1 import { Subject, Subscription } from 'rxjs'
2 import { filter } from 'rxjs/operators'
3 import { Component, EventEmitter, Input, Output, OnDestroy, OnInit, ViewChild } from '@angular/core'
4 import { NavigationEnd, Router } from '@angular/router'
5 import { Notifier, User, PeerTubeSocket } from '@app/core'
6 import { UserNotificationService } from '@app/shared/shared-main'
7 import { NgbPopover } from '@ng-bootstrap/ng-bootstrap'
10 selector: 'my-avatar-notification',
11 templateUrl: './avatar-notification.component.html',
12 styleUrls: [ './avatar-notification.component.scss' ]
14 export class AvatarNotificationComponent implements OnInit, OnDestroy {
15 @ViewChild('popover', { static: true }) popover: NgbPopover
18 @Output() navigate = new EventEmitter<HTMLAnchorElement>()
20 unreadNotifications = 0
23 markAllAsReadSubject = new Subject<boolean>()
25 private notificationSub: Subscription
26 private routeSub: Subscription
29 private userNotificationService: UserNotificationService,
30 private peertubeSocket: PeerTubeSocket,
31 private notifier: Notifier,
32 private router: Router
37 this.userNotificationService.countUnreadNotifications()
40 this.unreadNotifications = Math.min(result, 99) // Limit number to 99
41 this.subscribeToNotifications()
44 err => this.notifier.error(err.message)
47 this.routeSub = this.router.events
48 .pipe(filter(event => event instanceof NavigationEnd))
49 .subscribe(() => this.closePopover())
53 if (this.notificationSub) this.notificationSub.unsubscribe()
54 if (this.routeSub) this.routeSub.unsubscribe()
65 onNotificationLoaded () {
69 onNavigate (link: HTMLAnchorElement) {
70 this.navigate.emit(link)
74 this.markAllAsReadSubject.next(true)
77 private async subscribeToNotifications () {
78 const obs = await this.peertubeSocket.getMyNotificationsSocket()
80 this.notificationSub = obs.subscribe(data => {
81 if (data.type === 'new') return this.unreadNotifications++
82 if (data.type === 'read') return this.unreadNotifications--
83 if (data.type === 'read-all') return this.unreadNotifications = 0