ChurchAngular/src/app/services/signal-r.service.ts
Chris Chen 2ef9968920 WIP
2025-11-12 18:22:33 -08:00

117 lines
3.6 KiB
TypeScript

import { HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router, UrlSerializer } from '@angular/router';
import * as signalR from "@microsoft/signalr"
import { Subject } from 'rxjs';
import { environment } from '../../environments/environment';
import { UuidUtils } from '../utilities/uuid-utils';
import { AuthService } from './auth.service';
import { LoginUserService } from './login-user.service';
const SIGNAL_R_URL = (id: string = null) => { return `${environment.apiUrl}/${id}` }
@Injectable({
providedIn: 'root'
})
export class SignalRService {
ReceivedSignalRMessageSubject = new Subject<SignalRMessage>();
signalRMessageConnSubject = new Subject<any>();
private hubConnection: signalR.HubConnection
constructor(
private loginUserService: LoginUserService,
private router: Router,
private serializer: UrlSerializer
) { }
public startWhoIsSpyConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(SIGNAL_R_URL('WhoIsSpyHub'))
.withAutomaticReconnect()
.build();
this.hubConnection
.start()
.then(() => console.log('WhoIsSpyHub Connection started:' + this.hubConnection.connectionId))
.catch(err => console.log('Error while starting connection: ' + err))
this.hubConnection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user}: ${message}`;
document.getElementById("messageList").appendChild(li);
});
}
public startSignalRConnection(gameRoomId: string = '') {
if (!this.loginUserService.sessionTabId) {
this.loginUserService.sessionTabId = UuidUtils.generate();
}
const tree = this.router.createUrlTree([], {
queryParams: {
userId: this.loginUserService.userAccess.memberId,
userName: this.loginUserService.userAccess.firstName,
tabId: this.loginUserService.sessionTabId,
roomId: gameRoomId
}
});
const params = new HttpParams()
.set('userId', this.loginUserService.userAccess.memberId)
.set('userName', this.loginUserService.userAccess.firstName)
.set('tabId', this.loginUserService.sessionTabId)
.set('roomId', gameRoomId);
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${SIGNAL_R_URL('GameRoomHub')}?${params.toString()}`)
.withAutomaticReconnect()
.build();
let me = this
this.hubConnection
.start()
.then(() => {
me.setSignalRConnectionId(this.hubConnection.connectionId);
})
.catch(err => console.log('Error while starting connection: ' + err))
this.hubConnection.on("ReceivedMessage", (jsonString) => {
this.BroadcastAPIMessageReceive(JSON.parse(jsonString));
});
}
public setSignalRConnectionId(connectionId: string) {
this.loginUserService.userAccess.signalRSessionId = connectionId;
this.loginUserService.signalRInitialized.next(connectionId);
console.log('GameRoomHub start connection: ' + this.hubConnection.connectionId)
}
BroadcastAPIMessageReceive(msg: SignalRMessage) {
let jsonContent = null;
if (msg.jsonValue) {
try {
msg.jsonValue = JSON.parse(msg.jsonValue);
} catch (e) {
}
}
this.ReceivedSignalRMessageSubject.next(msg);
}
}
export interface SignalRMessage {
from: SignalRSession;
receiver: SignalRSession;
actionType: string;
actionName: string;
parameters: { [key: string]: string; };
jsonValue: string;
}
export interface SignalRSession {
sessionId: string;
name: string;
isGroup: boolean;
}