routes_io_exam.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import { Variables } from './router_io.ts';
  2. import type { QuizContent, QuizState, Answer } from '../client/mobile/components/Exam/types.ts';
  3. interface ExamRoomData {
  4. roomId: string;
  5. userId?: string;
  6. }
  7. interface ExamQuestionData extends ExamRoomData {
  8. question: QuizContent;
  9. }
  10. interface ExamAnswerData extends ExamRoomData {
  11. questionId: string;
  12. answer: Answer;
  13. }
  14. interface ExamPriceData extends ExamRoomData {
  15. date: string;
  16. price: string;
  17. }
  18. export function setupExamEvents({ socket, apiClient }: Variables) {
  19. // 加入考试房间
  20. socket.on('exam:join', async (data: ExamRoomData) => {
  21. try {
  22. const { roomId } = data;
  23. const user = socket.user;
  24. if (!user) {
  25. socket.emit('error', '未授权访问');
  26. return;
  27. }
  28. // 加入房间
  29. socket.join(roomId);
  30. // 通知用户加入成功
  31. socket.emit('exam:joined', {
  32. roomId,
  33. message: `成功加入考试房间: ${roomId}`
  34. });
  35. // 通知房间其他用户有新成员加入
  36. socket.to(roomId).emit('exam:memberJoined', {
  37. roomId,
  38. userId: user.id,
  39. username: user.username
  40. });
  41. console.log(`用户 ${user.username} 加入考试房间 ${roomId}`);
  42. } catch (error) {
  43. console.error('加入考试房间失败:', error);
  44. socket.emit('error', '加入考试房间失败');
  45. }
  46. });
  47. // 离开考试房间
  48. socket.on('exam:leave', async (data: ExamRoomData) => {
  49. try {
  50. const { roomId } = data;
  51. const user = socket.user;
  52. if (!user) {
  53. socket.emit('error', '未授权访问');
  54. return;
  55. }
  56. // 离开房间
  57. socket.leave(roomId);
  58. // 通知用户离开成功
  59. socket.emit('exam:left', {
  60. roomId,
  61. message: `已离开考试房间: ${roomId}`
  62. });
  63. // 通知房间其他用户有成员离开
  64. socket.to(roomId).emit('exam:memberLeft', {
  65. roomId,
  66. userId: user.id,
  67. username: user.username
  68. });
  69. console.log(`用户 ${user.username} 离开考试房间 ${roomId}`);
  70. } catch (error) {
  71. console.error('离开考试房间失败:', error);
  72. socket.emit('error', '离开考试房间失败');
  73. }
  74. });
  75. // 发送考试房间消息
  76. socket.on('exam:message', async (data: {
  77. roomId: string;
  78. message: {
  79. type: string;
  80. content: any;
  81. }
  82. }) => {
  83. try {
  84. const { roomId, message } = data;
  85. const user = socket.user;
  86. if (!user) {
  87. socket.emit('error', '未授权访问');
  88. return;
  89. }
  90. // 广播消息到房间
  91. socket.to(roomId).emit('exam:message', {
  92. roomId,
  93. message: {
  94. ...message,
  95. from: user.id,
  96. username: user.username,
  97. timestamp: new Date().toISOString()
  98. }
  99. });
  100. console.log(`用户 ${user.username} 在房间 ${roomId} 发送消息: ${message.type}`);
  101. } catch (error) {
  102. console.error('发送考试消息失败:', error);
  103. socket.emit('error', '发送考试消息失败');
  104. }
  105. });
  106. // 推送题目
  107. socket.on('exam:question', async (data: ExamQuestionData) => {
  108. try {
  109. const { roomId, question } = data;
  110. const user = socket.user;
  111. if (!user) {
  112. socket.emit('error', '未授权访问');
  113. return;
  114. }
  115. // 存储当前问题状态到Redis
  116. const questionKey = `exam:${roomId}:current_question`;
  117. await apiClient.redis.hset(questionKey, 'date', String(question.date));
  118. await apiClient.redis.hset(questionKey, 'price', String(question.price));
  119. await apiClient.redis.hset(questionKey, 'updated_at', new Date().toISOString());
  120. // TODO: 需要Redis服务端配置自动过期或通过其他方式实现TTL
  121. // 广播题目到房间
  122. // socket.to(roomId).emit('exam:question', {
  123. // roomId,
  124. // question: {
  125. // ...question,
  126. // timestamp: new Date().toISOString()
  127. // }
  128. // });
  129. const quizState:QuizState = {
  130. id: `question-${Date.now()}`,
  131. date: question.date,
  132. price: question.price
  133. }
  134. socket.to(roomId).emit('exam:question', quizState);
  135. console.log(`用户 ${user.username} 在房间 ${roomId} 推送题目`);
  136. } catch (error) {
  137. console.error('推送题目失败:', error);
  138. socket.emit('error', '推送题目失败');
  139. }
  140. });
  141. // 存储答案
  142. socket.on('exam:storeAnswer', async (data: ExamAnswerData) => {
  143. try {
  144. const { roomId, questionId, answer } = data;
  145. const user = socket.user;
  146. if (!user) {
  147. socket.emit('error', '未授权访问');
  148. return;
  149. }
  150. // 存储答案到Redis
  151. const answerKey = `exam:${roomId}:${questionId}:answers`;
  152. await apiClient.redis.hset(answerKey, String(user.id), JSON.stringify({
  153. username: user.username,
  154. date: answer.date,
  155. price: answer.price,
  156. holdingStock: answer.holdingStock,
  157. holdingCash: answer.holdingCash,
  158. profitAmount: answer.profitAmount,
  159. profitPercent: answer.profitPercent,
  160. totalProfitAmount: answer.totalProfitAmount,
  161. totalProfitPercent: answer.totalProfitPercent
  162. }));
  163. // 广播答案更新到房间
  164. socket.to(roomId).emit('exam:answerUpdated', {
  165. roomId,
  166. questionId,
  167. userId: user.id,
  168. username: user.username
  169. });
  170. console.log(`用户 ${user.username} 在房间 ${roomId} 存储答案`);
  171. } catch (error) {
  172. console.error('存储答案失败:', error);
  173. socket.emit('error', '存储答案失败');
  174. }
  175. });
  176. // 获取答案
  177. socket.on('exam:getAnswers', async (data: {
  178. roomId: string;
  179. questionId: string;
  180. }, callback: (answers: Answer[]) => void) => {
  181. try {
  182. const { roomId, questionId } = data;
  183. const user = socket.user;
  184. if (!user) {
  185. socket.emit('error', '未授权访问');
  186. return;
  187. }
  188. // 从Redis获取答案
  189. const answerKey = `exam:${roomId}:${questionId}:answers`;
  190. const answers = await apiClient.redis.hgetall(answerKey);
  191. // 转换为前端需要的格式
  192. const formattedAnswers: Answer[] = Object.entries(answers).map(([userId, answerStr]) => {
  193. const answer = JSON.parse(answerStr);
  194. return {
  195. ...answer,
  196. userId
  197. };
  198. });
  199. callback(formattedAnswers);
  200. } catch (error) {
  201. console.error('获取答案失败:', error);
  202. socket.emit('error', '获取答案失败');
  203. callback([]);
  204. }
  205. });
  206. // 清理房间数据
  207. socket.on('exam:cleanup', async (data: {
  208. roomId: string;
  209. questionId?: string;
  210. }) => {
  211. try {
  212. const { roomId, questionId } = data;
  213. const user = socket.user;
  214. if (!user) {
  215. socket.emit('error', '未授权访问');
  216. return;
  217. }
  218. if (questionId) {
  219. // 清理特定问题的数据
  220. const answerKey = `exam:${roomId}:${questionId}:answers`;
  221. const keys = await apiClient.redis.keys(answerKey);
  222. if (keys.length > 0) {
  223. await Promise.all(keys.map((key) => apiClient.redis.del(key)))
  224. }
  225. } else {
  226. // 清理整个房间的数据
  227. const keys = await apiClient.redis.keys(`exam:${roomId}:*`);
  228. if (keys.length > 0) {
  229. await Promise.all(keys.map((key) => apiClient.redis.del(key)))
  230. }
  231. }
  232. socket.emit('exam:cleaned', {
  233. roomId,
  234. message: questionId
  235. ? `已清理房间 ${roomId} 的问题 ${questionId} 数据`
  236. : `已清理房间 ${roomId} 的所有数据`
  237. });
  238. console.log(`用户 ${user.username} 清理房间 ${roomId} 数据`);
  239. } catch (error) {
  240. console.error('清理房间数据失败:', error);
  241. socket.emit('error', '清理房间数据失败');
  242. }
  243. });
  244. // 存储价格历史
  245. socket.on('exam:storePrice', async (data: ExamPriceData) => {
  246. try {
  247. const { roomId, date, price } = data;
  248. const user = socket.user;
  249. if (!user) {
  250. socket.emit('error', '未授权访问');
  251. return;
  252. }
  253. // 存储价格到Redis
  254. const priceKey = `exam:${roomId}:prices`;
  255. await apiClient.redis.hset(priceKey, date, price);
  256. console.log(`用户 ${user.username} 存储房间 ${roomId} 的价格历史: ${date} - ${price}`);
  257. } catch (error) {
  258. console.error('存储价格历史失败:', error);
  259. socket.emit('error', '存储价格历史失败');
  260. }
  261. });
  262. // 获取历史价格
  263. socket.on('exam:getPrice', async (data: {
  264. roomId: string;
  265. date: string;
  266. }, callback: (price: string) => void) => {
  267. try {
  268. const { roomId, date } = data;
  269. const user = socket.user;
  270. if (!user) {
  271. socket.emit('error', '未授权访问');
  272. return;
  273. }
  274. // 从Redis获取价格
  275. const priceKey = `exam:${roomId}:prices`;
  276. const price = await apiClient.redis.hget(priceKey, date);
  277. callback(price || '0');
  278. } catch (error) {
  279. console.error('获取历史价格失败:', error);
  280. socket.emit('error', '获取历史价格失败');
  281. callback('0');
  282. }
  283. });
  284. // 获取所有价格历史
  285. socket.on('exam:getPrices', async (data: {
  286. roomId: string;
  287. }, callback: (prices: Record<string, string>) => void) => {
  288. try {
  289. const { roomId } = data;
  290. const user = socket.user;
  291. if (!user) {
  292. socket.emit('error', '未授权访问');
  293. return;
  294. }
  295. // 从Redis获取所有价格
  296. const priceKey = `exam:${roomId}:prices`;
  297. const priceMap = await apiClient.redis.hgetall(priceKey);
  298. callback(priceMap);
  299. } catch (error) {
  300. console.error('获取所有价格历史失败:', error);
  301. socket.emit('error', '获取所有价格历史失败');
  302. callback({});
  303. }
  304. });
  305. }