Files
doneit-web/src/app/module/chat/infra/socket/signalR.ts
T

254 lines
6.9 KiB
TypeScript
Raw Normal View History

2024-07-11 10:28:21 +01:00
import * as signalR from '@microsoft/signalr';
import { BehaviorSubject, Observable } from 'rxjs';
import { ok, Result, err } from 'neverthrow';
import { SessionStore } from 'src/app/store/session.service';
import { filter, first } from 'rxjs/operators';
2024-07-17 16:39:18 +01:00
import { v4 as uuidv4 } from 'uuid'
2024-07-18 16:19:30 +01:00
import { UserTypingDTO } from '../../data/dto/typing/typingInputDTO';
import { MessageOutPutDataDTO } from '../../data/dto/message/messageOutputDTO';
2024-07-26 16:54:32 +01:00
var msgObj = {
roomId: "53bc6471-c28e-42d0-aa72-f4e52221f16f",
senderId:312,
message:"message enviada",
messageType:312,
canEdit:true,
oneShot:false,
requestId:"testing"
};
// var deletObj = {
// roomId: "53bc6471-c28e-42d0-aa72-f4e52221f16f",
// senderId:312,
// messageId:"message enviada",
// requestId:"testing"
// };
// var reactObj = {
// roomId: "53bc6471-c28e-42d0-aa72-f4e52221f16f",
// memberId:2,
// messageId:"e7074c10-4f92-458c-adb2-774ec2d42992",
// reaction:"reacted",
// requestId:"testingReaction"
// };
const typingObj = {
roomId: "53bc6471-c28e-42d0-aa72-f4e52221f16f",
userId: 312,
userName:"usertyping",
requestId:"testing"
};
2024-07-11 10:28:21 +01:00
export class SignalRConnection {
private hubConnection: signalR.HubConnection;
2024-07-18 16:19:30 +01:00
private messageSubject: BehaviorSubject<MessageOutPutDataDTO> = new BehaviorSubject<MessageOutPutDataDTO>(null);
private typingSubject: BehaviorSubject<UserTypingDTO> = new BehaviorSubject<UserTypingDTO>(null);
private readAtSubject: BehaviorSubject<string> = new BehaviorSubject<any>(null);
2024-07-11 10:28:21 +01:00
private connectionStateSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
private disconnectSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
private reconnectSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
private sendLaterSubject: BehaviorSubject<Object> = new BehaviorSubject<Object>(false);
private reconnect = true
url: string
constructor({url}) {
this.url = url
}
establishConnection(): Promise<Result<signalR.HubConnection, false>> {
return new Promise((resolve, reject) => {
2024-07-18 16:19:30 +01:00
console.log('try to connect');
2024-07-11 10:28:21 +01:00
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl(this.url)
.build();
this.hubConnection = hubConnection
hubConnection
.start()
.then(() => {
console.log('Connection started');
this.connectionStateSubject.next(true);
this.hubConnection = hubConnection
this.join()
2024-07-18 16:19:30 +01:00
this.addMessageListener()
2024-07-11 10:28:21 +01:00
resolve(ok(hubConnection))
})
.catch(error => {
console.log('Error while starting connection: ' + error);
this.connectionStateSubject.next(false);
reject(err(false))
});
hubConnection.onclose(() => {
console.log('Connection closed');
this.connectionStateSubject.next(false);
this.disconnectSubject.next(true)
if(this.reconnect) {
this.attempReconnect();
}
});
})
}
async attempReconnect() {
const attempConnection = await this.establishConnection()
if(attempConnection.isOk()) {
this.reconnectSubject.next(true)
}
}
public join() {
if(this.connectionStateSubject.value == true) {
2024-07-17 16:39:18 +01:00
2024-07-18 16:19:30 +01:00
console.log('join=================')
2024-07-26 16:54:32 +01:00
this.hubConnection.invoke("Join", 312, SessionStore.user.FullName);
2024-07-17 16:39:18 +01:00
//this.hubConnection.invoke("Join", 105, "UserFirefox");
2024-07-11 10:28:21 +01:00
} else {
this.sendLaterSubject.next({method: 'SendMessage', args:["Join", 312, "Daniel"]})
}
}
public async sendMessage(data: Object & { requestId}):Promise<Result<any, any>> {
return new Promise((resolve, reject) => {
if(this.connectionStateSubject.value == true) {
2024-07-18 16:19:30 +01:00
console.log('sendMessage', data)
2024-07-26 16:54:32 +01:00
this.hubConnection.invoke("SendMessage", msgObj)
2024-07-11 10:28:21 +01:00
this.messageSubject.pipe(
filter((message: any) => data.requestId == message?.requestId),
first()
).subscribe(value => {
resolve(ok(value))
console.log('Received valid value:', value);
});
} else {
this.sendLaterSubject.next({method: 'SendMessage', args: data})
return reject(err(false))
}
})
}
2024-07-25 08:51:04 +01:00
public async typing(data: Object & { roomId, UserName, userId }):Promise<Result<any, any>> {
2024-07-17 16:39:18 +01:00
return new Promise((resolve, reject) => {
const requestId = uuidv4()
if(this.connectionStateSubject.value == true) {
2024-07-25 08:51:04 +01:00
console.log('send typing', data)
2024-07-17 16:39:18 +01:00
try {
2024-07-26 16:54:32 +01:00
this.hubConnection.invoke("Typing", typingObj)
2024-07-17 16:39:18 +01:00
} catch (error) {}
this.typingSubject.pipe(
filter((message: any) => {
return requestId == message?.requestId
}),
first()
).subscribe(value => {
resolve(ok(value));
});
} else {
this.sendLaterSubject.next({method: 'SendMessage', args: data})
return reject(err(false))
}
})
}
2024-07-18 16:19:30 +01:00
public async sendReadAt(data: Object & { roomId, memberId, chatMessageId}):Promise<Result<any, any>> {
return new Promise((resolve, reject) => {
const requestId = uuidv4()
if(this.connectionStateSubject.value == true) {
try {
this.hubConnection.invoke("ReadAt", { roomId: data.roomId, memberId: data.memberId, requestId } as any)
} catch (error) {}
this.readAtSubject.pipe(
filter((message: any) => {
return requestId == message?.requestId
}),
first()
).subscribe(value => {
resolve(ok(value));
});
} else {
this.sendLaterSubject.next({method: 'SendMessage', args: data})
return reject(err(false))
}
})
}
2024-07-11 10:28:21 +01:00
private addMessageListener(): void {
2024-07-18 16:19:30 +01:00
console.log('listening')
this.hubConnection.on('ReceiveMessage', (message: MessageOutPutDataDTO) => {
2024-07-11 10:28:21 +01:00
console.log('ReceiveMessage', message)
this.messageSubject.next(message);
});
2024-07-17 16:39:18 +01:00
2024-07-25 11:27:39 +01:00
this.hubConnection.on('TypingMessage', (_typing: UserTypingDTO) => {
2024-07-18 16:19:30 +01:00
console.log('Typing', _typing)
this.typingSubject.next(_typing);
});
this.hubConnection.on('ReadAt', (_message) => {
console.log('ReadAt', _message)
this.readAtSubject.next(_message);
2024-07-17 16:39:18 +01:00
});
2024-07-18 16:19:30 +01:00
2024-07-11 10:28:21 +01:00
}
2024-07-18 16:19:30 +01:00
public getMessages() {
2024-07-11 10:28:21 +01:00
return this.messageSubject.asObservable()
}
2024-07-18 16:19:30 +01:00
public getTyping() {
2024-07-17 16:39:18 +01:00
return this.typingSubject.asObservable()
}
2024-07-11 10:28:21 +01:00
public getConnectionState(): Observable<boolean> {
return this.connectionStateSubject.asObservable();
}
public getDisconnectTrigger(): Observable<boolean> {
return this.disconnectSubject.asObservable();
}
public getSendLater() {
return this.sendLaterSubject.asObservable();
}
public closeConnection(): void {
this.reconnect = false
if (this.hubConnection) {
this.hubConnection
.stop()
.then(() => {
console.log('Connection closed by user');
this.connectionStateSubject.next(false);
})
.catch(err => console.log('Error while closing connection: ' + err));
}
}
}