瀏覽代碼

增加actions业务通道service

gemercheung 2 年之前
父節點
當前提交
d53ba9ecdc

+ 21 - 0
src/room/actions/action.d.ts

@@ -0,0 +1,21 @@
+interface ActionsParams {
+  type: string;
+  data: any;
+}
+type actionType =
+  | 'user-init'
+  | 'danmumsg'
+  | 'changeScene'
+  | 'user-join'
+  | 'user-leave'
+  | 'users-muted'
+  | 'users-words'
+  | 'leader-dismiss'
+  | 'user-paint'
+  | 'tagclick'
+  | 'tag-image-index'
+  | 'ask-currentscene'
+  | 'answer-currentscene'
+  | 'error'
+  | 'sync-floor'
+  | 'room-valid-time';

+ 17 - 0
src/room/actions/actions.service.ts

@@ -0,0 +1,17 @@
+import { InjectRedis } from '@liaoliaots/nestjs-redis';
+import { forwardRef, Inject, Injectable } from '@nestjs/common';
+import { Redis } from 'ioredis';
+import { RoomService } from '../room.service';
+
+@Injectable()
+export class ActionsService {
+  constructor(
+    @InjectRedis() private readonly redis: Redis,
+    @Inject(forwardRef(() => RoomService))
+    private roomService: RoomService,
+  ) {}
+
+  async handleAllAction(data: ActionsParams): Promise<void> {
+    console.log('ActionsParams', data);
+  }
+}

+ 2 - 1
src/room/room.module.ts

@@ -3,10 +3,11 @@ import { SocketGateway } from 'src/socket/socket.gateway';
 
 import { RoomService } from './room.service';
 import { UsersService } from './users/users.service';
+import { ActionsService } from './actions/actions.service';
 
 @Module({
   imports: [],
-  providers: [RoomService, SocketGateway, UsersService],
+  providers: [RoomService, SocketGateway, UsersService, ActionsService],
   exports: [RoomService],
 })
 export class RoomModule {}

+ 57 - 5
src/room/room.service.ts

@@ -3,6 +3,7 @@ import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
 import { Redis } from 'ioredis';
 
 import { SocketGateway } from 'src/socket/socket.gateway';
+import { ActionsService } from './actions/actions.service';
 import { UsersService } from './users/users.service';
 
 @Injectable()
@@ -11,12 +12,13 @@ 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 actionsService: ActionsService,
+  ) {}
   private readonly logger = new Logger('user');
-  private _userInfo = {} as UserInfoType;
+  public _userInfo = {} as UserInfoType;
   private _roomConfig = {} as RoomConfigType;
-
+  private isJoin = false;
   private get _roomId(): string {
     return this._userInfo.RoomId;
   }
@@ -37,15 +39,49 @@ export class RoomService {
       Role: userInfo.role,
       UserId: userInfo.userId,
       Avatar: userInfo.avatar,
-      Nickname: userInfo.nickname,
+      Nickname:
+        decodeURIComponent(userInfo.nickname) || `用户[${userInfo.userId}]`,
       IsClient: userInfo.isClient,
       IsMuted: true,
       IsWords: true,
       Order: userInfo.role === 'leader' ? 0 : 1,
       JoinTime: Date.now(),
       InTime: Date.now(),
+      IsOnline: true,
     };
   }
+  async handleUserOnline() {
+    this._userInfo.IsOnline = true;
+    if (this._userId && this._roomId) {
+      await this.userService.updateUserOnlineState(
+        this._roomId,
+        this._userId,
+        true,
+      );
+      const roomUsers = await this.userService.getRoomUsers(this._roomId);
+      this.isJoin &&
+        this.socketGateway.server.to(this._roomId).emit('action', {
+          type: 'rooms-status',
+          members: roomUsers,
+        });
+    }
+  }
+
+  async handleUserOffline() {
+    this._userInfo.IsOnline = false;
+    if (this._userId && this._roomId) {
+      await this.userService.updateUserOnlineState(
+        this._roomId,
+        this._userId,
+        false,
+      );
+      const roomUsers = await this.userService.getRoomUsers(this._roomId);
+      this.socketGateway.server.to(this._roomId).emit('action', {
+        type: 'rooms-status',
+        members: roomUsers,
+      });
+    }
+  }
 
   /**
    * 加入房间
@@ -100,6 +136,7 @@ export class RoomService {
             members: roomUsers,
           });
         }
+        this.isJoin = true;
         this.logger.log(
           JSON.stringify(this._userInfo),
           `join-user-${this._userInfo.Role}`,
@@ -115,6 +152,7 @@ export class RoomService {
    * @param message
    */
   async handleUserAction(message: any) {
+    this.actionsService.handleAllAction(message);
     // this.socketGateway.server.to(this._roomId).emit('action', message);
   }
 
@@ -133,6 +171,20 @@ export class RoomService {
   async handlePaintAction(message: any) {
     this.socketGateway.server.to(this._roomId).emit('paint', message);
   }
+
+  /**
+   *  房间T人
+   * @param message
+   */
+  async handleKickAction(userId: string) {
+    await this.userService.deleteRoomUser(this._roomId, userId);
+    this.socketGateway.server.to(this._roomId).emit('action', {
+      type: 'kick-user',
+      data: {
+        userId: userId,
+      },
+    });
+  }
   /**
    * 解散房间
    */

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

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

+ 22 - 0
src/room/users/users.service.ts

@@ -41,6 +41,10 @@ export class UsersService {
     );
   }
 
+  async deleteRoomUser(RoomId: string, UserId: string) {
+    return this.redis.hdel(`kankan:socket:rooms:${RoomId}`, UserId);
+  }
+
   async getRoomUsers(RoomId: string): Promise<UserInfoType[]> {
     const res = await this.redis.hvals(`kankan:socket:rooms:${RoomId}`);
     const allUsers = Array.from(res)
@@ -77,4 +81,22 @@ export class UsersService {
       return false;
     }
   }
+  async updateUserOnlineState(
+    RoomId: string,
+    UserId: string,
+    status = true,
+  ): Promise<void> {
+    const user = await this.redis.hget(`kankan:socket:rooms:${RoomId}`, UserId);
+    if (user) {
+      const userObj: UserInfoType = JSON.parse(user);
+      const updateObj: UserInfoType = Object.assign({}, userObj, {
+        IsOnline: status,
+      });
+      this.redis.hset(
+        `kankan:socket:rooms:${RoomId}`,
+        UserId,
+        JSON.stringify(updateObj),
+      );
+    }
+  }
 }

+ 6 - 5
src/socket/socket.gateway.ts

@@ -25,18 +25,19 @@ console.log('SOCKET_PATH-0', process.env.SOCKET_PATH);
   // parser: require('socket.io-msgpack-parser'),
 })
 export class SocketGateway
-  implements OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection
-{
+  implements OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection {
   constructor(
     @InjectRedis() private readonly redis: Redis,
     private readonly roomService: RoomService,
-  ) {}
+  ) { }
 
   @WebSocketServer() server: Server;
-  handleConnection(client: any, ...args: any[]) {
+  async handleConnection(client: any, ...args: any[]) {
     // console.log('handleConnection', client, args);
+    await this.roomService.handleUserOnline();
   }
-  handleDisconnect(client: any) {
+  async handleDisconnect(client: any) {
+    await this.roomService.handleUserOffline();
     // console.log('handleDisconnect', client);
   }
   afterInit(server: any) {