浏览代码

事件通道

gemercheung 2 年之前
父节点
当前提交
bef0e09820

+ 5 - 0
log/.46f0af219249542fdc264b9b0460d72fee271bbf-audit.json

@@ -14,6 +14,11 @@
             "date": 1676422429133,
             "name": "D:\\codes\\daikan\\socket-server-v4\\log\\2023-02-15.log",
             "hash": "b1410283ed4fb79aeeb9d673071592ae53cf16293856d13796ee9dd324fe8c08"
+        },
+        {
+            "date": 1676508231970,
+            "name": "D:\\codes\\daikan\\socket-server-v4\\log\\2023-02-16.log",
+            "hash": "eb40924a4d09ab101e29fbb5ff18f149f8ff001a793bb99c2c5ec52f63e6ed95"
         }
     ],
     "hashType": "sha256"

+ 43 - 27
src/room/room.service.ts

@@ -1,5 +1,5 @@
 import { InjectRedis } from '@liaoliaots/nestjs-redis';
-import { forwardRef, Inject, Injectable } from '@nestjs/common';
+import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
 import { Redis } from 'ioredis';
 
 import { SocketGateway } from 'src/socket/socket.gateway';
@@ -11,9 +11,9 @@ export class RoomService {
     @Inject(forwardRef(() => SocketGateway))
     private readonly socketGateway: SocketGateway,
     @InjectRedis() private readonly redis: Redis,
-    private readonly userService: UsersService,
-  ) {}
-
+    private readonly userService: UsersService, //
+  ) { }
+  private readonly logger = new Logger('user');
   private _userInfo = {} as UserInfoType;
   private _roomConfig = {} as RoomConfigType;
 
@@ -32,7 +32,6 @@ export class RoomService {
    * @param userInfo
    */
   initUserProfile(userInfo: UserInfoParams): void {
-    console.log('userInfo', userInfo);
     this._userInfo = {
       RoomId: userInfo.roomId,
       Role: userInfo.role,
@@ -47,16 +46,7 @@ export class RoomService {
       InTime: Date.now(),
     };
   }
-  /**
-   * 初始化房间配置
-   * @param userInfo
-   */
-  async handleRoomConfig(
-    RoomId: string,
-    RoomConfig: RoomConfigType,
-  ): Promise<void> {
-    await this.userService.setRoomConfig(RoomId, RoomConfig);
-  }
+
   /**
    * 加入房间
    * @param userInfo
@@ -64,7 +54,6 @@ export class RoomService {
 
   async handleUserJoin(userInfo: UserInfoParams): Promise<void> {
     this.initUserProfile(userInfo);
-    console.log(this._userId);
     let blockJoin = false;
     if (this._roomId?.length && this._userId?.length) {
       //房主设置房间配置
@@ -73,7 +62,7 @@ export class RoomService {
           this._roomId,
           this._userId,
         );
-
+        //检查房主非法性
         if (isValid) {
           await this.userService.setRoomConfig(
             this._roomId,
@@ -85,24 +74,21 @@ export class RoomService {
             type: 'invalid-master',
             code: 303,
           });
+          this.logger.warn(`303:invalid-master`, 'join-error');
         }
       }
       const isExist = await this.userService.isUserInRooms(
         this._roomId,
         this._userId,
       );
-      if (!isExist) {
-        if (this._isLeader) {
-          this._roomConfig = userInfo.roomConfig;
-          this.handleRoomConfig(this._roomId, this._roomConfig);
-        }
-        this.userService.insertUser(this._userInfo);
-      } else {
-        this.userService.updateUsers(this._userInfo);
-      }
-      const roomUsers = await this.userService.getRoomUsers(this._roomId);
 
       if (!blockJoin) {
+        if (!isExist) {
+          this.userService.insertUser(this._userInfo);
+        } else {
+          this.userService.updateUsers(this._userInfo);
+        }
+        const roomUsers = await this.userService.getRoomUsers(this._roomId);
         this.socketGateway.server.emit('join', {
           user: this._userInfo,
           members: roomUsers,
@@ -114,18 +100,48 @@ export class RoomService {
             members: roomUsers,
           });
         }
+        this.logger.log(
+          JSON.stringify(this._userInfo),
+          `join-user-${this._userInfo.Role}`,
+        );
       }
     } else {
       this.socketGateway.server.emit('action', { type: 'error', code: 403 });
+      this.logger.warn(`403:not roomId and userId`, 'join-error');
     }
   }
+  /**
+   *  房间action大通道
+   * @param message
+   */
+  async handleUserAction(message: any) {
+    // this.socketGateway.server.to(this._roomId).emit('action', message);
+  }
 
   /**
+   *  房间sync大通道
+   * @param message
+   */
+  async handleSyncAction(message: any) {
+    this.socketGateway.server.to(this._roomId).emit('sync', message);
+  }
+
+  /**
+   *  房间paint大通道
+   * @param message
+   */
+  async handlePaintAction(message: any) {
+    this.socketGateway.server.to(this._roomId).emit('paint', message);
+  }
+  /**
    * 解散房间
    */
 
   async handleRoomDismiss(): Promise<void> {
     await this.userService.delRoom(this._roomId);
     await this.userService.delRoomConfig(this._roomId);
+    this.socketGateway.server
+      .to(this._roomId)
+      .emit('action', { type: 'leader-dismiss' });
   }
 }

+ 1 - 0
src/room/user.d.ts

@@ -10,6 +10,7 @@ interface UserInfoType {
   JoinTime?: Timestamp;
   InTime?: Timestamp;
   Order?: number;
+  isOnline?: boolean;
 }
 
 interface UserInfoParams {

+ 1 - 2
src/room/users/users.service.ts

@@ -69,10 +69,9 @@ export class UsersService {
       const exist = await this.redis.hget(`kankan:socket:roomConfig`, RoomId);
       if (exist) {
         const master: RoomConfigType = JSON.parse(exist);
-        console.log('isRoomMaster', master.masterId);
         return master.masterId === userId;
       } else {
-        return false;
+        return true;
       }
     } catch (error) {
       return false;

+ 17 - 0
src/socket/socket.gateway.ts

@@ -59,4 +59,21 @@ export class SocketGateway
     socket.join(message.roomId);
     await this.roomService.handleUserJoin(message);
   }
+
+  // 订阅action通道
+  @SubscribeMessage('action')
+  async handleActionMessage(@MessageBody() message: any): Promise<void> {
+    await this.roomService.handleUserAction(message);
+  }
+
+  // 订阅sync通道
+  @SubscribeMessage('sync')
+  async handleSyncMessage(@MessageBody() message: any): Promise<void> {
+    await this.roomService.handleSyncAction(message);
+  }
+  // 订阅paint通道
+  @SubscribeMessage('paint')
+  async handlePaintessage(@MessageBody() message: any): Promise<void> {
+    await this.roomService.handlePaintAction(message);
+  }
 }