1 import { PersonViewSafe, WebSocketJsonResponse } from "lemmy-js-client";
3 default as ReconnectingWebSocket,
5 } from "reconnecting-websocket";
6 import { Observable } from "rxjs";
7 import { share } from "rxjs/operators";
8 import { wsUri } from "../env";
9 import { isBrowser } from "../utils";
11 export class WebSocketService {
12 private static _instance: WebSocketService;
13 private ws: ReconnectingWebSocket;
14 public wsOptions: WSOptions = {
15 connectionTimeout: 5000,
18 public subject: Observable<any>;
20 public admins: PersonViewSafe[];
21 public banned: PersonViewSafe[];
23 private constructor() {
24 this.ws = new ReconnectingWebSocket(wsUri, [], this.wsOptions);
25 let firstConnect = true;
27 this.subject = new Observable((obs: any) => {
28 this.ws.onmessage = e => {
29 obs.next(JSON.parse(e.data));
31 this.ws.onopen = () => {
32 console.log(`Connected to ${wsUri}`);
35 let res: WebSocketJsonResponse<any> = {
46 window.onunload = () => {
49 // Clears out scroll positions.
50 sessionStorage.clear();
55 public send(data: string) {
59 public closeEventListener(listener: (event: CloseEvent) => void) {
60 this.ws.addEventListener("close", listener);
63 public static get Instance() {
64 return this._instance || (this._instance = new this());