assistant.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // 房间行为助手
  2. import { EVENT, CODEMEG, FROMTYPE } from "../../enum/index.js";
  3. import { getCurrentUser, updateUser, removeRoomAllUsers, getAllRoomUsers, updateRoomUser, removeRoomUser } from "../../service/userService.js";
  4. import { setRoomConfig, getRoomConfig, isRoomMaster } from "../../service/roomConfigService.js";
  5. import { subClient } from "../../connection/redis.js";
  6. const prefix = process.env.REDIS_PREFIX || "chat";
  7. const getInKey = (realKey) => {
  8. return `${prefix}:${realKey}`;
  9. };
  10. export class RoomAssistant {
  11. constructor(socket, redis, room) {
  12. this.socket = socket;
  13. this.redis = redis;
  14. this.roomId = null;
  15. this.hasCall = false;
  16. this.illegalMaster = false;
  17. this.room = room;
  18. this.roomMax = false;
  19. }
  20. /**
  21. * 准备房间
  22. * @param {*} roomSessionId
  23. * @param {*} roomId
  24. * @returns
  25. */
  26. async prepearRoom(roomSessionId, roomId) {
  27. // const uRoomId = await this.redis.get(getInKey(roomSessionId));
  28. // const mergeRoomId = uRoomId || roomId;
  29. // this.roomId = mergeRoomId;
  30. this.room.logger.info("prepearRoom", roomSessionId, roomId);
  31. await this.redis.set(getInKey(roomSessionId), roomId);
  32. return Promise.resolve(roomId);
  33. }
  34. // async prepearRoom(roomSessionId, roomId) {
  35. // const uRoomId = await this.redis.get(getInKey(roomSessionId));
  36. // const mergeRoomId = uRoomId || roomId;
  37. // this.roomId = mergeRoomId;
  38. // this.room.logger.info("prepearRoom", roomSessionId, this.roomId);
  39. // await this.redis.set(getInKey(roomSessionId), mergeRoomId);
  40. // return Promise.resolve(this.roomId);
  41. // }
  42. async destoryRoom(roomSessionId, roomConfigId) {
  43. this.room.logger.info("destoryRoom", roomSessionId, roomConfigId);
  44. await this.redis.del(getInKey(roomSessionId));
  45. await this.redis.del(getInKey(roomConfigId));
  46. this.disconnect();
  47. return Promise.resolve(true);
  48. }
  49. async notifyRoomDismiss(roomId) {
  50. this.socket.broadcast.to(roomId).emit(EVENT.roomDisMiss);
  51. }
  52. /**
  53. * kickPersion LEADER or assistant 房主或助手
  54. */
  55. async kickPersion(roomId, userId) {
  56. console.log("kickPersion", roomId, userId);
  57. getInKey(roomId);
  58. try {
  59. const hasJoin = await this.redis.HVALS(getInKey(roomId), userId);
  60. // const blackListId = ""
  61. if (hasJoin.length > 0) {
  62. await this.redis.hDel(getInKey(roomId), userId);
  63. return Promise.resolve(true);
  64. } else {
  65. return Promise.resolve(false);
  66. }
  67. } catch (error) {
  68. return Promise.resolve(false);
  69. }
  70. }
  71. /**
  72. * 设置助手 LEADER(权限) 房主或助手
  73. * @param {*} roomId
  74. * @param {*} userId
  75. */
  76. async setAssistant(roomId, userId, cancel) {
  77. try {
  78. const userRes = await getCurrentUser(roomId, userId, FROMTYPE.MiniAPP);
  79. const user = JSON.parse(userRes);
  80. const roomConfigRes = await getRoomConfig(roomId);
  81. if (this.room.userId == userId) {
  82. console.log("不能设置自己为助理!");
  83. return;
  84. }
  85. // const role = cancel ? "customer" : "assistant";
  86. const isAssistant = cancel ? 0 : 1;
  87. // assistant是助手,customer是普通角色,操作role会好些
  88. const userObj = Object.assign({}, user, { role: "customer", order: 1, isAssistant });
  89. const roomObj = Object.assign({}, roomConfigRes, { assistantId: cancel ? "" : user.userId });
  90. // console.log("setAssistant", userObj, roomObj);
  91. // console.error("roomObj", roomObj);
  92. await updateRoomUser(roomId, userId, userObj);
  93. // // 更新roomConfig 设置助手id
  94. await setRoomConfig(roomId, roomObj);
  95. const AllRoomUsers = await getAllRoomUsers(roomId);
  96. // 同房间的其他人重置
  97. const resetOther = Array.from(AllRoomUsers)
  98. .filter((i) => i.role !== "leader" && i.userId !== userObj.userId)
  99. .map((roomer) => {
  100. const userKey = `user:${roomer.userId}`;
  101. const unsetUserObj = Object.assign({}, roomer, { isAssistant: 0, role: "customer", order: 2 });
  102. // console.log("同房间的其他人重置", userKey, unsetUserObj);
  103. return updateRoomUser(roomId, userKey, unsetUserObj);
  104. });
  105. //总处理完成
  106. Promise.all(resetOther).then(() => {
  107. this.room.notify.notifyBeAssistant(roomId, userObj, this.room.userId);
  108. });
  109. // console.log("AllRoomUsers", AllRoomUsers);
  110. // callback(user);
  111. } catch (error) {
  112. this.room.logger.error("setAssistant:error", error);
  113. }
  114. }
  115. async getRoomAssistant(roomId) {
  116. const roomConfig = await getRoomConfig(roomId);
  117. const assistantId = roomConfig.assistantId || "";
  118. return Promise.resolve(assistantId);
  119. }
  120. /**
  121. * 设置MIC权 LEADER(权限) 房主或助手
  122. * 主要
  123. * @param {*} roomId
  124. * @param {*} userId
  125. */
  126. async setMicRight(roomId, userId, isAllowMic) {
  127. try {
  128. const userRes = await getCurrentUser(roomId, userId, FROMTYPE.MiniAPP);
  129. const user = JSON.parse(userRes);
  130. const roomConfigRes = await getRoomConfig(roomId);
  131. // if (this.room.userId == userId && this.room.isHoster(this.room.user.role)) {
  132. // console.log("房主不用设置自己的MIC!");
  133. // return;
  134. // }
  135. const reveseMic = Number(isAllowMic) === 0 ? 1 : 0;
  136. console.log("设置MIC权当前用户:: %s 新MIC权", user.userId, reveseMic);
  137. const userObj = Object.assign({}, user, { isAllowMic: reveseMic });
  138. const roomObj = Object.assign({}, roomConfigRes, { allowMicId: user.userId });
  139. await updateRoomUser(roomId, userId, userObj);
  140. await setRoomConfig(roomId, roomObj);
  141. const AllRoomUsers = await getAllRoomUsers(roomId);
  142. // 已存在的设置为false
  143. let preMicUser = null;
  144. const resetOther = Array.from(AllRoomUsers)
  145. .filter((i) => i.role !== "leader" && i.userId !== userObj.userId)
  146. .map((roomer) => {
  147. if (Number(roomer.isAllowMic) === 1) {
  148. preMicUser = roomer.userId;
  149. }
  150. const userKey = `user:${roomer.userId}`;
  151. const unsetUserObj = Object.assign({}, roomer, { isAllowMic: 0 });
  152. return updateRoomUser(roomId, userKey, unsetUserObj);
  153. });
  154. Promise.all(resetOther).then(() => {
  155. this.room.notify.notifyBeHasMic(roomId, userObj, this.room.userId, preMicUser);
  156. });
  157. } catch (error) {
  158. this.room.logger.error("setMicRight::error", error);
  159. }
  160. }
  161. /**
  162. * 创建房间 LEADER or assistant 房主或助手
  163. * @param {*string} roomId
  164. * @param {*string} userId
  165. * @param {*Object} user
  166. */
  167. async buildRoom(roomId, userId, user) {
  168. const hasJoin = await this.redis.HVALS(getInKey(roomId), userId);
  169. if (hasJoin.length === 0) {
  170. await this.redis.hSet(getInKey(roomId), userId, JSON.stringify(user));
  171. }
  172. }
  173. /**
  174. * 关闭房间
  175. * @param {*} roomId
  176. */
  177. async removeRoom(roomId) {
  178. this.room.logger.info("removeRoom", { roomId });
  179. await this.redis.del(getInKey(roomId));
  180. }
  181. /**
  182. * 加入房间
  183. * @param {*} roomId
  184. * @param {*} userId
  185. * @param {*} user
  186. */
  187. async joinRoom(roomId, userId, user) {
  188. const hasRoom = await this.redis.exists(getInKey(roomId));
  189. const isJoinRoom = await this.redis.hExists(getInKey(roomId), userId);
  190. if (hasRoom) {
  191. await this.redis.hSet(getInKey(roomId), userId, JSON.stringify(user));
  192. } else {
  193. await this.buildRoom(roomId, userId, user);
  194. this.room.logger.error("不存在房间", roomId);
  195. }
  196. this.socket.join(roomId);
  197. this.room.logger.info("加入房间 :", { userId, roomId, user });
  198. // if (!isJoinRoom) {
  199. // this.room.logger.info("加入房间 :", { userId, roomId, user });
  200. // const AllRoomUsers = await getAllRoomUsers(roomId);
  201. // const roomConfig = await getRoomConfig(roomId);
  202. // this.socket.emit(EVENT.roomIn, {
  203. // user,
  204. // roomsPerson: AllRoomUsers,
  205. // roomsConfig: roomConfig,
  206. // });
  207. // this.socket.broadcast.to(roomId).emit(EVENT.someOneInRoom, {
  208. // user,
  209. // roomsPerson: AllRoomUsers,
  210. // roomsConfig: roomConfig,
  211. // });
  212. // } else {
  213. // this.room.logger.info(`已加入房间 :`, { userId });
  214. // }
  215. }
  216. /**
  217. * 退出房间
  218. * @param {*} roomId
  219. * @param {*} userId
  220. * @param {*} user
  221. */
  222. async leaveRoom(roomId, userId, user) {
  223. try {
  224. await this.redis.hDel(getInKey(roomId), userId);
  225. await removeRoomUser(roomId, userId);
  226. const AllRoomUsers = await getAllRoomUsers(roomId);
  227. const roomConfig = await getRoomConfig(roomId);
  228. this.room.logger.info("退出房间", userId, AllRoomUsers);
  229. this.socket.broadcast.to(roomId).emit(EVENT.roomOut, {
  230. user,
  231. roomsPerson: AllRoomUsers,
  232. roomsConfig: roomConfig,
  233. });
  234. this.socket.broadcast.to(roomId).emit(EVENT.someOneLeaveRoom, {
  235. user,
  236. roomsPerson: AllRoomUsers,
  237. });
  238. await this.socket.leave(roomId);
  239. } catch (error) {
  240. console.log("leaveRoom::error", error);
  241. }
  242. }
  243. /**
  244. * 房主关闭房间
  245. * @param {*} clientRoom
  246. * @param {*} userUniqueId
  247. * @param {*} roomUniqueId
  248. */
  249. async closeRoom(roomId, userId, user) {
  250. try {
  251. this.room.logger.info("房主关闭房间", userId);
  252. console.log("isInRoom", this.socket.rooms.has(roomId));
  253. this.socket.broadcast.to(roomId).emit(EVENT.roomClose, { code: 3002, msg: CODEMEG[3002] });
  254. await removeRoomAllUsers(roomId);
  255. this.socket.leave(roomId);
  256. } catch (error) {
  257. this.room.logger.error("RoomAssistant::closeRoom", error);
  258. }
  259. }
  260. /**
  261. * 呼叫房间
  262. * @param {*} roomId
  263. * @param {*} userId
  264. * @param {*} user
  265. */
  266. async startCall(roomId, userId, user) {
  267. try {
  268. if (!this.roomMax) {
  269. if (user.oid) {
  270. console.log("hasDuplicateUser-存在oid", user.oid);
  271. const hasDuplicateUser = await this.getOpenidInRoom(roomId, user.oid);
  272. if (hasDuplicateUser && hasDuplicateUser.length > 0) {
  273. const removeAll = [];
  274. Array.from(hasDuplicateUser).forEach((duplicateUser) => {
  275. if (duplicateUser.userId !== user.userId) {
  276. console.log("duplicateUser-去重用户", duplicateUser);
  277. const deleteUserKey = `user:${duplicateUser.userId}`;
  278. console.log("deleteUserKey", deleteUserKey);
  279. removeAll.push(removeRoomUser(roomId, deleteUserKey));
  280. } else {
  281. user = Object.assign({}, user, {
  282. isAllowMic: Number(duplicateUser.isAllowMic),
  283. voiceStatus: Number(duplicateUser.voiceStatus),
  284. });
  285. console.log("在房间内延续部分数据", user);
  286. if (Number(duplicateUser.isAllowMic) === 1) {
  287. console.log("在房间内延续强制开MIC voiceStatus", Number(duplicateUser.voiceStatus));
  288. this.socket.broadcast.to(this.room.syncId).emit(EVENT.serverOnMic, {
  289. voiceStatus: Number(duplicateUser.voiceStatus),
  290. });
  291. }
  292. }
  293. });
  294. const res = await Promise.all(removeAll);
  295. console.log("去重完成", res);
  296. }
  297. }
  298. if (!this.room.isHoster(user.role)) {
  299. this.room.logger.info("不是房主", JSON.stringify(user));
  300. await this.joinRoom(roomId, userId, user);
  301. } else {
  302. const hasRoom = await this.redis.hVals(getInKey(roomId));
  303. if (hasRoom.length === 0) {
  304. this.illegalMaster = false;
  305. this.room.logger.info("房主主动创建房间 :", { roomId, userId });
  306. await this.buildRoom(roomId, userId, user);
  307. } else {
  308. //TODO
  309. const checkIsRoomMaster = await isRoomMaster(roomId, userId);
  310. console.log("isRoomMaster", checkIsRoomMaster);
  311. if (checkIsRoomMaster) {
  312. this.illegalMaster = false;
  313. this.room.logger.info("房主已存在房间 :", { roomId, userId, from: user.from });
  314. await this.joinRoom(roomId, userId, user);
  315. // this.notifyUserJitter(roomId);
  316. } else {
  317. this.room.logger.error("存在非法房主", roomId, userId);
  318. this.illegalMaster = true;
  319. this.socket.broadcast.to(this.room.syncId).emit(EVENT.unKnowError);
  320. }
  321. }
  322. }
  323. user.isInRoom = true;
  324. this.hasCall = true;
  325. const AllRoomUsers = await getAllRoomUsers(roomId);
  326. const roomConfig = await getRoomConfig(roomId);
  327. await updateRoomUser(roomId, userId, user);
  328. this.room.logger.info("roomId", roomId);
  329. this.room.logger.info("AllRoomUsers", AllRoomUsers.length);
  330. this.socket.emit(EVENT.roomIn, {
  331. user,
  332. roomsPerson: AllRoomUsers,
  333. roomsConfig: roomConfig,
  334. });
  335. this.socket.emit(EVENT.someOneInRoom, {
  336. user,
  337. roomsPerson: AllRoomUsers,
  338. });
  339. this.socket.broadcast.to(roomId).emit(EVENT.someOneInRoom, {
  340. user,
  341. roomsPerson: AllRoomUsers,
  342. });
  343. } else {
  344. this.room.logger.warn("超出房间上限");
  345. this.socket.emit(EVENT.roomMaximum, user);
  346. this.socket.broadcast.to(this.room.syncId).emit(EVENT.roomMaximum, user);
  347. }
  348. // await this.notifyUsersChange(roomId, user, true);
  349. } catch (error) {
  350. this.room.logger.error("assistant::startCall:", error);
  351. }
  352. }
  353. async notifyUserJitter(roomId, userId) {
  354. const AllRoomUsers = await getAllRoomUsers(roomId);
  355. const roomConfig = await getRoomConfig(roomId);
  356. const currentUser = await getCurrentUser(userId, FROMTYPE.MiniAPP);
  357. const user = JSON.parse(currentUser);
  358. await updateRoomUser(roomId, userId, user);
  359. this.room.logger.info("notifyUserJitter", roomId, AllRoomUsers.length);
  360. this.socket.emit(EVENT.roomIn, {
  361. user,
  362. roomsPerson: AllRoomUsers,
  363. roomsConfig: roomConfig,
  364. });
  365. this.socket.broadcast.to(roomId).emit(EVENT.someOneInRoom, {
  366. user,
  367. roomsPerson: AllRoomUsers,
  368. });
  369. }
  370. /**
  371. * 通知房间人员变动
  372. */
  373. async notifyUsersChange(roomId, user, inter = true) {
  374. const AllRoomUsers = await getAllRoomUsers(roomId);
  375. // const roomConfig = await getRoomConfig(roomId);
  376. this.room.logger.info("notifyUsersChange", roomId, AllRoomUsers.length);
  377. const actionName = inter ? "inRoom" : "outRoom";
  378. this.socket.broadcast.to(roomId).emit(EVENT.roomPersonChange, {
  379. user: user,
  380. actionName: actionName,
  381. roomsPerson: AllRoomUsers,
  382. });
  383. }
  384. /**
  385. * 关闭呼叫房间
  386. * @param {*} roomId
  387. * @param {*} userId
  388. * @param {*} user
  389. */
  390. stopCall(roomId, userId, user) {
  391. if (!this.room.isHoster(user.role)) {
  392. this.leaveRoom(roomId, userId, user);
  393. } else {
  394. this.closeRoom(roomId, userId, user);
  395. }
  396. this.removeRoomSession(this.room);
  397. }
  398. async removeRoomSession(roomSessionId) {
  399. await this.redis.del(getInKey(roomSessionId));
  400. }
  401. async getOpenidInRoom(roomId, oid) {
  402. const AllRoomUsers = await getAllRoomUsers(roomId);
  403. if (AllRoomUsers.length > 0) {
  404. const users = AllRoomUsers.filter((item) => item.oid === oid);
  405. return Promise.resolve(users);
  406. } else {
  407. return Promise.resolve([]);
  408. }
  409. }
  410. // 下线用户强制上线
  411. async setOnlineStatus(roomId, userId, user) {
  412. user.onlineStatus = 1;
  413. await updateRoomUser(roomId, userId, user);
  414. // this.silentUpdateRoom(roomId);
  415. await this.notifyUsersChange(roomId, user, true);
  416. }
  417. // 静默认更新房间状态
  418. async silentUpdateRoom(roomId) {
  419. const AllRoomUsers = await getAllRoomUsers(roomId);
  420. this.socket.broadcast.to(roomId).emit(EVENT.silentUpdateRoom, {
  421. users: AllRoomUsers,
  422. });
  423. }
  424. async checkRoomMaximum(roomId) {
  425. const roomConfigRes = await getRoomConfig(roomId);
  426. const userLimitNum = Number(roomConfigRes.userLimitNum) || 50;
  427. console.log(`${roomId} 上限人数:`, userLimitNum);
  428. const users = await getAllRoomUsers(roomId);
  429. console.log(`${roomId} 当前人数:`, users.length);
  430. if (users && users.length >= Number(userLimitNum)) {
  431. return Promise.resolve({
  432. isMax: true,
  433. num: userLimitNum,
  434. });
  435. } else {
  436. return Promise.resolve({
  437. isMax: false,
  438. num: userLimitNum,
  439. });
  440. }
  441. }
  442. // 主动断开
  443. async disconnect() {
  444. try {
  445. const syncId = this.room.syncId;
  446. const roomId = this.room.roomId;
  447. const userId = this.room.userId;
  448. this.socket.leave(syncId);
  449. this.socket.leave(roomId);
  450. await removeRoomUser(roomId, userId);
  451. await this.redis.del(getInKey(syncId));
  452. await this.redis.del(getInKey(userId));
  453. this.notifyUsersChange(roomId, this.room.user, false);
  454. } catch (error) {
  455. console.log("disconnect::error", error);
  456. }
  457. }
  458. // RoomSessionId 房间有效时间
  459. setRoomUnlimit(roomSessionId) {
  460. return this.redis.expire(getInKey(roomSessionId), -1);
  461. }
  462. setRoomAvailableBySeconds(roomSessionId, seconds) {
  463. return this.redis.expire(getInKey(roomSessionId), seconds);
  464. }
  465. setRoomAvailableByHours(roomSessionId, hours) {
  466. return this.redis.expire(getInKey(roomSessionId), 60 * 60 * hours);
  467. }
  468. watchRoomExpired(callback) {
  469. subClient.subscribe("__keyevent@0__:expired", this.watchRoomExpiredFn);
  470. }
  471. async watchRoomExpiredFn(key) {
  472. console.log("key=> ", key);
  473. }
  474. unWatchRoomExpired() {
  475. subClient.unsubscribe("__keyevent@0__:expired", this.watchRoomExpiredFn);
  476. }
  477. }