Add user notification animation
[oweals/peertube.git] / client / src / app / core / notification / user-notification-socket.service.ts
1 import { Injectable } from '@angular/core'
2 import { environment } from '../../../environments/environment'
3 import { UserNotification as UserNotificationServer } from '../../../../../shared'
4 import { Subject } from 'rxjs'
5 import { AuthService } from '../auth'
6
7 export type NotificationEvent = 'new' | 'read' | 'read-all'
8
9 @Injectable()
10 export class UserNotificationSocket {
11   private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>()
12
13   private socket: SocketIOClient.Socket
14
15   constructor (
16     private auth: AuthService
17   ) {}
18
19   dispatch (type: NotificationEvent, notification?: UserNotificationServer) {
20     this.notificationSubject.next({ type, notification })
21   }
22
23   async getMyNotificationsSocket () {
24     await this.initSocket()
25
26     return this.notificationSubject.asObservable()
27   }
28
29   private async initSocket () {
30     if (this.socket) return
31
32     // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function
33     const io: typeof import ('socket.io-client') = (await import('socket.io-client') as any).default
34
35     this.socket = io(environment.apiUrl + '/user-notifications', {
36       query: { accessToken: this.auth.getAccessToken() }
37     })
38
39     this.socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))
40   }
41 }