syncDeviceController.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { BasicController } from "./basicController.js";
  2. // import { RoomAssistant } from "./assistant.js";
  3. import { getAllRoomUsers, updateRoomUser } 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 current = await this.room.currentUser();
  41. const updateUser = {
  42. ...current,
  43. // onlineStatus: 1,
  44. voiceStatus: status,
  45. };
  46. const isUpdate = await updateRoomUser(this.room.roomId, this.room.userId, updateUser);
  47. const AllRoomUsers = await getAllRoomUsers(this.room.roomId);
  48. this.logger.info("changeVoiceStatus", { roomId: this.room.roomId, updateUser, AllRoomUsers: AllRoomUsers.length });
  49. this.socket.broadcast.to(this.room.roomId).emit(EVENT.changeVoiceStatus, {
  50. user: updateUser,
  51. roomsPerson: AllRoomUsers,
  52. });
  53. this.socket.broadcast.to(this.room.syncId).emit(EVENT.changeVoiceStatus, {
  54. user: updateUser,
  55. roomsPerson: AllRoomUsers,
  56. });
  57. } catch (error) {
  58. this.logger.error("event::changeVoiceStatus", error);
  59. }
  60. });
  61. }
  62. }