unoffical wafrn mirror wafrn.net
atproto social-network activitypub
at angular21 78 lines 2.4 kB view raw
1import { Injectable, inject } from "@angular/core"; 2import { WebSocketSubject, webSocket } from "rxjs/webSocket"; 3import { EnvironmentService } from "./environment.service"; 4import { LoginService } from "./login.service"; 5import { DashboardService } from "./dashboard.service"; 6import { debounce, retry, Subject } from "rxjs"; 7import { MessageService } from "./message.service"; 8import { ParticleService } from "./particle.service"; 9 10@Injectable({ 11 providedIn: "root", 12}) 13export class WebsocketService { 14 private loginService = inject(LoginService); 15 private dashboardService = inject(DashboardService); 16 private particle = inject(ParticleService); 17 18 private socket$!: WebSocketSubject<any>; 19 constructor() { 20 const loginService = this.loginService; 21 22 if (loginService.loggedIn.value) { 23 this.connectSocket(); 24 } 25 } 26 27 connectSocket() { 28 try { 29 const onSocketConnect = new Subject(); 30 const url = 31 EnvironmentService.environment.baseUrl 32 .replace("http://", "ws://") 33 .replace("https://", "wss://") + "/socket/notifications"; 34 this.socket$ = webSocket({ 35 url: url, 36 WebSocketCtor: WebSocket, 37 openObserver: onSocketConnect, 38 protocol: "server", 39 }); 40 this.socket$ 41 .pipe( 42 retry({ 43 delay: 3000, 44 }) 45 ) 46 .subscribe((obs: { message: "update_notifications"; type: string }) => { 47 try { 48 switch (obs.message) { 49 case "update_notifications": { 50 this.dashboardService.scrollEventEmitter.next("scroll"); 51 console.log(obs); 52 if ( 53 obs.type == "LIKE" && 54 localStorage.getItem("enableConfettiRecivingLike") == "true" 55 ) { 56 this.particle.like(); 57 } 58 } 59 } 60 } catch (error) { 61 console.error(error); 62 } 63 }); 64 if (this.socket$) { 65 } 66 onSocketConnect.subscribe((data) => { 67 this.socket$.next({ 68 type: "auth", 69 object: localStorage.getItem("authToken") as string, 70 }); 71 this.dashboardService.scrollEventEmitter.next("scroll"); 72 }); 73 } catch (error) { 74 console.error("error conecting websocket"); 75 console.error(error); 76 } 77 } 78}