syncDeviceController.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { BasicController } from "./basicController.js";
  2. // import { RoomAssistant } from "./assistant.js";
  3. import { getAllRoomUsers, updateRoomUser, isUserInRoom } from "../service/userService.js";
  4. import { FROMTYPE, EVENT } from "../enum/index.js";
  5. const prefix = process.env.REDIS_PREFIX || "chat";
  6. const getInKey = (realKey) => {
  7. return `${prefix}:${realKey}`;
  8. };
  9. export class SyncDeviceController extends BasicController {
  10. constructor(...args) {
  11. super(...args);
  12. this.room = args[3];
  13. }
  14. async run() {
  15. if (this.room.user) {
  16. const syncId = this.room.syncId;
  17. const userId = this.room.userId;
  18. const from = this.room.user.from;
  19. this.joinSyncClient(syncId, userId, from);
  20. this.initAction();
  21. } else {
  22. this.logger.error("roomController:init: 初始化失败!");
  23. }
  24. }
  25. async joinSyncClient(syncId, userId, from) {
  26. this.logger.info("syncId", { syncId, userId, from });
  27. try {
  28. await this.redisCli.hSet(getInKey(syncId), from, userId);
  29. this.socket.join(syncId);
  30. } catch (error) {
  31. this.logger.error("joinSyncClient", error);
  32. }
  33. }
  34. initAction() {
  35. this.socket.on(EVENT.clientSyncAction, (data) => {
  36. this.socket.broadcast.to(this.room.syncId).emit(EVENT.clientSyncAction, data);
  37. });
  38. this.socket.on(EVENT.changeVoiceStatus, async ({ status }) => {
  39. try {
  40. const from = this.room.user.from;
  41. const roomId = this.room.roomId;
  42. const user = await this.room.currentUser();
  43. const isInRoom = await isUserInRoom(roomId, user.userId);
  44. if (isInRoom) {
  45. const updateUser = {
  46. ...isInRoom,
  47. onlineStatus: 1,
  48. voiceStatus: Number(status),
  49. };
  50. const isUpdate = await updateRoomUser(this.room.roomId, this.room.userId, updateUser);
  51. const AllRoomUsers = await getAllRoomUsers(this.room.roomId);
  52. this.logger.info("changeVoiceStatus", { roomId: this.room.roomId, updateUser, AllRoomUsers: AllRoomUsers.length });
  53. this.socket.broadcast.to(this.room.roomId).emit(EVENT.changeVoiceStatus, {
  54. user: updateUser,
  55. roomsPerson: AllRoomUsers,
  56. });
  57. this.socket.broadcast.to(this.room.syncId).emit(EVENT.changeVoiceStatus, {
  58. user: updateUser,
  59. roomsPerson: AllRoomUsers,
  60. });
  61. }
  62. } catch (error) {
  63. this.logger.error("event::changeVoiceStatus", error);
  64. }
  65. });
  66. }
  67. }