validate user permision on chat

This commit is contained in:
Peter Maquiran
2024-08-23 11:10:52 +01:00
parent 92b2b33e46
commit c9b50620fe
20 changed files with 253 additions and 99 deletions
+7 -7
View File
@@ -4,7 +4,8 @@ import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.serv
import { skip, switchMap } from 'rxjs/operators';
import { SessionStore } from 'src/app/store/session.service';
import { Subject, timer } from 'rxjs';
import { UserTypingLocalRepository } from './data/repository/user-typing-local-data-source.service';
import { UserTypingLocalRepository } from './data/repository/typing/user-typing-local-data-source.service';
import { UserTypingRemoteRepositoryService } from './data/repository/typing/user-typing-live-data-source.service';
import { RoomService } from 'src/app/module/chat/domain/service/room.service'
@NgModule({
imports: [],
@@ -22,6 +23,7 @@ export class ChatModule {
private ChatServiceService: ChatServiceService,
private signalR: SignalRService,
private localDataSource: UserTypingLocalRepository,
private UserTypingRemoteRepositoryService: UserTypingRemoteRepositoryService,
private RoomService: RoomService
) {
@@ -31,8 +33,7 @@ export class ChatModule {
}
async listenToTyping() {
this.signalR.getTyping().subscribe(async (e) => {
if(e?.roomId) {
this.UserTypingRemoteRepositoryService.listenToTyping().subscribe(async(e) => {
// this.memoryDataSource.dispatch(removeUserTyping({data: {...e} as any}))
// this.memoryDataSource.dispatch(addUserTyping({data: {...e} as any}))
@@ -52,9 +53,8 @@ export class ChatModule {
} else {
this.typingCallback[id].next()
}
}
})
}
async syncMessage() {
@@ -62,14 +62,14 @@ export class ChatModule {
connection.pipe(
skip(1) // Skip the first value
).subscribe((value)=> {
).subscribe((value: boolean)=> {
if(value) {
// on reconnect
this.ChatServiceService.chatSync();
}
});
connection.subscribe((value) => {
connection.subscribe((value: boolean) => {
if(value) {
// on connect
// this.ChatServiceService.sendLocalMessages()
@@ -3,7 +3,7 @@ import { z } from "zod"
export const UserTypingDTOSchema = z.object({
requestId: z.string(),
roomId: z.string(),
userId: z.string(),
userId: z.number(),
userName: z.string()
})
export type UserTypingDTO = z.infer<typeof UserTypingDTOSchema>
@@ -3,11 +3,27 @@ import { SignalRService } from '../../../infra/socket/signal-r.service';
import { filter, map } from 'rxjs/operators';
import { z } from 'zod';
import { SocketMessage } from '../../../infra/socket/signalR';
import { RoomInputDTO } from '../../dto/room/roomInputDTO';
import { RoomOutPutDTO } from '../../dto/room/roomOutputDTO';
import { v4 as uuidv4 } from 'uuid'
const listenToDeleteRoomInputSchema = z.object({
roomId: z.string()
})
export const RoomSocketOutPutDTOSchema = z.object({
id: z.string(),
roomName: z.string(),
createdBy: z.any().nullable(),
createdAt: z.string(),
expirationDate: z.string().nullable(),
roomType: z.any()
});
export type RoomSocketOutPutDTO = z.infer<typeof RoomSocketOutPutDTOSchema>
export type ListenToDeleteRoomInput = z.infer<typeof listenToDeleteRoomInputSchema>
@Injectable({
@@ -19,6 +35,19 @@ export class RoomSocketRepositoryService {
private socket: SignalRService
) { }
async CreateGroup(data: RoomInputDTO) {
const result = await this.socket.sendData<RoomSocketOutPutDTO>({
method: 'CreateGroup',
data: {
...data,
requestId: uuidv4()
} as any,
})
return result;
}
listenToCreateRoom() {
return this.socket.getData().pipe(
filter((data) => data?.method == 'UserAddGroup')
@@ -0,0 +1,38 @@
import { Injectable } from '@angular/core';
import { SignalRService } from '../../../infra/socket/signal-r.service';
import { SessionStore } from 'src/app/store/session.service';
import { filter, map } from 'rxjs/operators';
import { SocketMessage } from '../../../infra/socket/signalR';
import { UserTypingDTO } from '../../dto/typing/typingInputDTO';
@Injectable({
providedIn: 'root'
})
export class UserTypingRemoteRepositoryService {
constructor(
private socket: SignalRService
) { }
sendTyping(roomId: string) {
return this.socket.sendData({
method: 'Typing',
data: {
roomId,
UserName:SessionStore.user.FullName,
userId:SessionStore.user.UserId,
requestId: '',
},
})
}
listenToTyping() {
return this.socket.getData().pipe(
filter((e) : e is SocketMessage<UserTypingDTO>=> e?.method == 'TypingMessage'
),
map((e)=> e.data)
)
}
}
@@ -2,8 +2,8 @@ import { Injectable } from '@angular/core';
import { z } from 'zod';
import { Dexie, EntityTable, liveQuery, Observable } from 'Dexie';
import { err, ok } from 'neverthrow';
import { chatDatabase } from '../../infra/database/dexie/service';
import { TypingTable } from '../../infra/database/dexie/schema/typing';
import { chatDatabase } from '../../../infra/database/dexie/service';
import { TypingTable } from '../../../infra/database/dexie/schema/typing';
@@ -28,7 +28,7 @@ export class UserTypingLocalRepository {
async addUserTyping(data: TypingTable) {
data.id = data.chatRoomId + '@' + data.userName
data.id = data.roomId + '@' + data.userName
try {
const result = await chatDatabase.typing.add(data)
return ok(result)
@@ -39,7 +39,7 @@ export class UserTypingLocalRepository {
async removeUserTyping(data: TypingTable) {
const id = data.chatRoomId + '@' + data.userName
const id = data.roomId + '@' + data.userName
try {
const result = await chatDatabase.typing.delete(id)
return ok(result)
@@ -53,4 +53,11 @@ export class UserTypingLocalRepository {
return liveQuery(() => chatDatabase.typing.toArray());
}
getUserTypingLiveByRoomId(roomId: string) {
return liveQuery(() => chatDatabase.typing
.where('roomId')
.equals(roomId)
.sortBy('id')
);
}
}
@@ -1,25 +0,0 @@
import { Injectable } from '@angular/core';
import { SignalRService } from '../../infra/socket/signal-r.service';
import { SessionStore } from 'src/app/store/session.service';
@Injectable({
providedIn: 'root'
})
export class UserTypingRemoteRepositoryService {
constructor(
private socket: SignalRService
) { }
sendTyping(roomId) {
return this.socket.sendData({
method: 'Typing',
data: {
roomId,
UserName:SessionStore.user.FullName,
userId:SessionStore.user.UserId
},
})
}
}
@@ -2,9 +2,11 @@ import { Injectable } from '@angular/core';
import { create } from 'domain';
import { SessionStore } from 'src/app/store/session.service';
import { RoomRemoteDataSourceService } from '../../data/repository/room/room-remote-repository.service';
import { RoomSocketRepositoryService } from '../../data/repository/room/room-socket-repository.service';
import { captureAndReraiseAsync } from 'src/app/services/decorators/captureAndReraiseAsync';
import { RoomInputDTO } from '../../data/dto/room/roomInputDTO';
import { RoomLocalRepository } from '../../data/repository/room/room-local-repository.service';
import { TracingType, XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer';
@Injectable({
providedIn: 'root'
@@ -14,31 +16,36 @@ export class CreateRoomUseCaseService {
constructor(
private roomRemoteDataSourceService: RoomRemoteDataSourceService,
private roomLocalDataSourceService: RoomLocalRepository,
private RoomSocketRepositoryService: RoomSocketRepositoryService
) { }
@captureAndReraiseAsync('RoomRepositoryService/create')
async execute(data: RoomInputDTO) {
@XTracerAsync({name:'room-create-use-case.service', module:'chat', bugPrint: true, waitNThrow: 5000})
async execute(data: RoomInputDTO, tracing?: TracingType) {
const result = await this.roomRemoteDataSourceService.createRoom(data)
const result = await this.RoomSocketRepositoryService.CreateGroup(data)
// const result = await this.roomRemoteDataSourceService.createRoom(data)
if(result.isOk()) {
if(!result.value.data.createdBy) {
console.log(result.value)
if(!result?.value?.createdBy) {
let dataObject;
result.value.data.createdBy = {
result.value.createdBy = {
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId,
}
dataObject = result.value.data
dataObject = result.value
}
const localResult = await this.roomLocalDataSourceService.createRoom(result.value.data)
const localResult = await this.roomLocalDataSourceService.createRoom(result.value)
return localResult.map(e => result.value)
} else {
tracing.hasError("socket close");
console.log(result.error)
}
return result
@@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
import { SignalRService } from '../../infra/socket/signal-r.service';
import { SessionStore } from 'src/app/store/session.service';
import { UserTypingRemoteRepositoryService } from '../../data/repository/user-typing-live-data-source.service';
import { UserTypingRemoteRepositoryService } from '../../data/repository/typing/user-typing-live-data-source.service';
@Injectable({
providedIn: 'root'
@@ -3,12 +3,11 @@ import { EntityTable } from 'Dexie';
export const TypingTableSchema = z.object({
id: z.string().optional(),
userId: z.string().optional(),
userId: z.number().optional(),
userName: z.string(),
chatRoomId: z.string(),
entryDate: z.string()
roomId: z.string(),
})
export type TypingTable = z.infer<typeof TypingTableSchema>
export type DexieTypingsTable = EntityTable<TypingTable, 'id'>;
export const TypingTableColumn = 'id, userId, userName, chatRoomId, entryDate'
export const TypingTableColumn = 'id, userId, userName, roomId, entryDate'
@@ -5,7 +5,6 @@ import { SignalRConnection, SocketMessage } from './signalR';
import { Plugins } from '@capacitor/core';
import { UserTypingDTO } from '../../data/dto/typing/typingInputDTO';
import { MessageOutPutDataDTO } from '../../data/dto/message/messageOutputDTO';
import { MessageDeleteInputDTO } from '../../data/dto/message/messageDeleteInputDTO';
import { z } from 'zod';
import { filter, map, switchMap } from 'rxjs/operators';
import { Result } from 'neverthrow';
@@ -27,7 +26,7 @@ export type ISignalRInput = z.infer<typeof SignalRInputSchema>;
providedIn: 'root'
})
export class SignalRService {
private connection: SignalRConnection;
private connection!: SignalRConnection;
private connectingSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
private sendDataSubject: BehaviorSubject<{method: string, data: any}> = new BehaviorSubject<{method: string, data: any}>(null);
+47 -20
View File
@@ -16,6 +16,11 @@ export interface SocketMessage<T> {
data: T
}
export enum EnumSocketError {
catch = 1,
close
}
export class SignalRConnection {
private hubConnection: signalR.HubConnection;
@@ -73,9 +78,16 @@ export class SignalRConnection {
this.disconnectSubject.next(true)
this.pendingRequests.forEach((_, requestId) => {
const { reject } = this.pendingRequests.get(requestId);
reject(err(false));
this.pendingRequests.delete(requestId);
const data = this.pendingRequests.get(requestId);
if(data) {
const { reject } = data
reject(err({
type: EnumSocketError.close
}));
this.pendingRequests.delete(requestId);
}
});
if(this.reconnect) {
@@ -111,16 +123,25 @@ export class SignalRConnection {
return new Promise((resolve, reject) => {
if(this.connectionStateSubject.value == true) {
try {
this.pendingRequests.set(input.data.requestId, { resolve, reject: (data: any) => resolve(data) });
this.hubConnection.invoke(input.method, input.data)
this.hubConnection.invoke(input.method, input.data)
this.sendDataSubject.pipe(
filter((message) => input.data.requestId == message?.data.requestId),
first()
).subscribe(value => {
resolve(ok(value.data as unknown as T))
console.log('Received valid value:', value);
});
} catch(error) {
resolve(err({
type: EnumSocketError.catch
}))
}
this.sendDataSubject.pipe(
filter((message) => input.data.requestId == message?.data.requestId),
first()
).subscribe(value => {
resolve(ok(value.data as unknown as T))
console.log('Received valid value:', value);
});
} else {
this.sendLaterSubject.next({method: 'SendMessage', args: input})
@@ -134,10 +155,11 @@ export class SignalRConnection {
const methods = ['ReceiveMessage', 'TypingMessage', 'AvailableUsers',
'ReadAt', 'DeleteMessage', 'UpdateMessage', 'GroupAddedMembers',
'GroupDeletedMembers']
'GroupDeletedMembers', 'UserAddGroup']
for(const method of methods) {
this.hubConnection.on(method, (message: MessageOutPutDataDTO) => {
this.hubConnection.on(method, (message: any) => {
console.log({message})
this.messageSubject.next(message);
this.sendDataSubject.next({
method: method,
@@ -147,11 +169,6 @@ export class SignalRConnection {
}
}
public getMessages() {
return this.messageSubject.asObservable()
}
public getConnectionState(): Observable<boolean> {
return this.connectionStateSubject.asObservable();
}
@@ -160,8 +177,6 @@ export class SignalRConnection {
return this.disconnectSubject.asObservable();
}
public getData() {
return this.sendDataSubject.asObservable()
}
@@ -174,6 +189,18 @@ export class SignalRConnection {
.then(() => {
console.log('Connection closed by user');
this.connectionStateSubject.next(false);
this.pendingRequests.forEach((_, requestId) => {
const data = this.pendingRequests.get(requestId);
if(data) {
const { reject } = data
reject(err({
type: EnumSocketError.close
}));
this.pendingRequests.delete(requestId);
}
});
})
.catch(err => console.log('Error while closing connection: ' + err));
}
+23 -2
View File
@@ -1,8 +1,29 @@
{
"compileOnSave": false,
"compilerOptions": {
"strict": true,
"target": "ES2020",
"module": "CommonJS"
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"skipLibCheck": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "es2020",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
//"target": "es5",
"lib": [
"es2018",
"dom"
],
"inlineSources": true,
"sourceRoot": "/"
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
},
"include": [
"./**/*.ts" // Include all TypeScript files in the current directory and subdirectories