useClassroom.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. import { useState, useEffect, useRef } from 'react';
  2. import { useParams } from 'react-router';
  3. // @ts-types="../../../share/aliyun-rtc-sdk.d.ts"
  4. import AliRtcEngine, { AliRtcSubscribeState, AliRtcVideoTrack } from 'aliyun-rtc-sdk';
  5. import { toast } from 'react-toastify';
  6. export enum Role {
  7. Teacher = 'admin',
  8. Student = 'student'
  9. }
  10. // 从SDK中提取需要的类型和枚举
  11. type ImEngine = InstanceType<typeof AliVCInteraction.ImEngine>;
  12. type ImGroupManager = AliVCInteraction.AliVCIMGroupManager;
  13. type ImMessageManager = AliVCInteraction.AliVCIMMessageManager;
  14. type ImLogLevel = AliVCInteraction.ImLogLevel;
  15. type ImMessageLevel = AliVCInteraction.ImMessageLevel;
  16. const { ERROR } = AliVCInteraction.ImLogLevel;
  17. const { NORMAL, HIGH } = AliVCInteraction.ImMessageLevel;
  18. interface ImUser {
  19. userId: string;
  20. userExtension?: string;
  21. }
  22. interface ImGroupMessage {
  23. groupId: string;
  24. type: number;
  25. data: string;
  26. sender?: ImUser;
  27. timestamp?: number;
  28. }
  29. // 互动消息类型
  30. enum InteractionAction {
  31. HandUp = 'hand_up',
  32. CancelHandUp = 'cancel_hand_up',
  33. AnswerHandUp = 'answer_hand_up'
  34. }
  35. interface InteractionMessage {
  36. action: InteractionAction;
  37. studentId: string;
  38. studentName?: string;
  39. timestamp?: number;
  40. question?: string;
  41. }
  42. interface HandUpRequest {
  43. studentId: string;
  44. studentName?: string;
  45. timestamp: number;
  46. question?: string;
  47. }
  48. interface Question {
  49. studentId: string;
  50. studentName?: string;
  51. question: string;
  52. timestamp: number;
  53. }
  54. export enum ClassStatus {
  55. NOT_STARTED = 'not_started',
  56. IN_PROGRESS = 'in_progress',
  57. ENDED = 'ended'
  58. }
  59. // 配置信息
  60. const IM_APP_ID = '4c2ab5e1b1b0';
  61. const IM_APP_KEY = '314bb5eee5b623549e8a41574ba3ff32';
  62. const IM_APP_SIGN = 'H4sIAAAAAAAE/wCQAG//zguHB+lYCilkv7diSkk4GmcvLuds+InRu9vFOFebMwm/jEgsK5bBT85Z0owObMxG58uXHyPFlPEBEDQm9FswNJ+KmX0VDYkcfdPPWkafA6Hc0B6F+p5De9yJfPEfHzwo/DHMaygbHfLmBgUtmKveq421sJr/gNBz9D04Ewsg39us+ao0NegzLt7xtXvFXXXJAAAA//8BAAD//yoav6aQAAAA';
  63. const RTC_APP_ID = 'a5842c2a-d94a-43be-81de-1fdb712476e1';
  64. const RTC_APP_KEY = 'b71d65f4f84c450f6f058f4ad507bd42';
  65. export const useClassroom = () => {
  66. // 状态管理
  67. const [userId, setUserId] = useState<string>('');
  68. const [isCameraOn, setIsCameraOn] = useState<boolean>(false);
  69. const [isAudioOn, setIsAudioOn] = useState<boolean>(false);
  70. const [isScreenSharing, setIsScreenSharing] = useState<boolean>(false);
  71. const [className, setClassName] = useState<string>('');
  72. const [role, setRole] = useState<Role | undefined>();
  73. const [classId, setClassId] = useState<string>('');
  74. const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
  75. const [isJoinedClass, setIsJoinedClass] = useState<boolean>(false);
  76. const [msgText, setMsgText] = useState<string>('');
  77. const [messageList, setMessageList] = useState<string[]>([]);
  78. const [errorMessage, setErrorMessage] = useState<string>('');
  79. const [classStatus, setClassStatus] = useState<ClassStatus>(ClassStatus.NOT_STARTED);
  80. const [handUpList, setHandUpList] = useState<HandUpRequest[]>([]);
  81. const [questions, setQuestions] = useState<Question[]>([]);
  82. const [students, setStudents] = useState<Array<{id: string, name: string}>>([]);
  83. const [shareLink, setShareLink] = useState<string>('');
  84. // SDK实例
  85. const imEngine = useRef<ImEngine | null>(null);
  86. const imGroupManager = useRef<ImGroupManager | null>(null);
  87. const imMessageManager = useRef<ImMessageManager | null>(null);
  88. const aliRtcEngine = useRef<AliRtcEngine | null>(null);
  89. const remoteVideoElMap = useRef<Record<string, HTMLVideoElement>>({});
  90. const remoteVideoContainer = useRef<HTMLDivElement>(null);
  91. // 辅助函数
  92. const showMessage = (text: string): void => {
  93. setMessageList((prevMessageList) => [...prevMessageList, text])
  94. };
  95. const showToast = (type: 'info' | 'success' | 'error', message: string): void => {
  96. toast[type](message);
  97. };
  98. const hex = (buffer: ArrayBuffer): string => {
  99. const hexCodes = [];
  100. const view = new DataView(buffer);
  101. for (let i = 0; i < view.byteLength; i += 4) {
  102. const value = view.getUint32(i);
  103. const stringValue = value.toString(16);
  104. const padding = '00000000';
  105. const paddedValue = (padding + stringValue).slice(-padding.length);
  106. hexCodes.push(paddedValue);
  107. }
  108. return hexCodes.join('');
  109. };
  110. const generateToken = async (
  111. appId: string,
  112. appKey: string,
  113. channelId: string,
  114. userId: string,
  115. timestamp: number
  116. ): Promise<string> => {
  117. const encoder = new TextEncoder();
  118. const data = encoder.encode(`${appId}${appKey}${channelId}${userId}${timestamp}`);
  119. const hash = await crypto.subtle.digest('SHA-256', data);
  120. return hex(hash);
  121. };
  122. const generateImToken = async (userId: string, role: string): Promise<string> => {
  123. const nonce = 'AK_4';
  124. const timestamp = Math.floor(Date.now() / 1000) + 3600 * 3;
  125. const pendingShaStr = `${IM_APP_ID}${IM_APP_KEY}${userId}${nonce}${timestamp}${role}`;
  126. const encoder = new TextEncoder();
  127. const data = encoder.encode(pendingShaStr);
  128. const hash = await crypto.subtle.digest('SHA-256', data);
  129. return hex(hash);
  130. };
  131. // 事件监听函数
  132. const listenImEvents = (): void => {
  133. if (!imEngine.current) return;
  134. if (!role) return;
  135. imEngine.current.on('connectsuccess', () => {
  136. showMessage('IM连接成功');
  137. });
  138. imEngine.current.on('disconnect', async (code: number) => {
  139. showMessage(`IM断开连接: ${code}`);
  140. // 自动重连
  141. try {
  142. const imToken = await generateImToken(userId, role);
  143. await imEngine.current!.login({
  144. user: {
  145. userId,
  146. userExtension: '{}'
  147. },
  148. userAuth: {
  149. nonce: 'AK_4',
  150. timestamp: Math.floor(Date.now() / 1000) + 3600 * 3,
  151. token: imToken,
  152. role
  153. }
  154. });
  155. showMessage('IM自动重连成功');
  156. } catch (err: unknown) {
  157. const error = err as Error;
  158. showMessage(`IM自动重连失败: ${error.message}`);
  159. }
  160. });
  161. };
  162. const listenGroupEvents = (): void => {
  163. if (!imGroupManager.current) return;
  164. imGroupManager.current.on('memberchange', (groupId: string, memberCount: number, joinUsers: ImUser[], leaveUsers: ImUser[]) => {
  165. showMessage(`成员变更: 加入${joinUsers.length}人, 离开${leaveUsers.length}人`);
  166. });
  167. };
  168. const listenMessageEvents = (): void => {
  169. if (!imMessageManager.current) return;
  170. imMessageManager.current.on('recvgroupmessage', (msg: AliVCInteraction.ImMessage, groupId: string) => {
  171. if (msg.type === 88889) { // 课堂状态消息
  172. try {
  173. const data = JSON.parse(msg.data);
  174. if (data.action === 'start_class') {
  175. setClassStatus(ClassStatus.IN_PROGRESS);
  176. showMessage('老师已开始上课');
  177. } else if (data.action === 'end_class') {
  178. setClassStatus(ClassStatus.ENDED);
  179. showMessage('老师已结束上课');
  180. }
  181. } catch (err) {
  182. console.error('解析课堂状态消息失败', err);
  183. }
  184. } else if (msg.type === 88890) { // 静音指令
  185. try {
  186. const data = JSON.parse(msg.data);
  187. if (data.action === 'toggle_mute' && data.userId === userId) {
  188. showMessage(data.mute ? '你已被老师静音' : '老师已取消你的静音');
  189. }
  190. } catch (err) {
  191. console.error('解析静音指令失败', err);
  192. }
  193. } else if (msg.type === 88891) { // 举手消息
  194. try {
  195. const data = JSON.parse(msg.data) as InteractionMessage;
  196. if (data.action === InteractionAction.HandUp) {
  197. const handUpData: HandUpRequest = {
  198. ...data,
  199. timestamp: data.timestamp || Date.now()
  200. };
  201. setHandUpList([...handUpList, handUpData]);
  202. showMessage(`${data.studentName || data.studentId} 举手了`);
  203. } else if (data.action === InteractionAction.CancelHandUp) {
  204. setHandUpList(handUpList.filter(h => h.studentId !== data.studentId));
  205. }
  206. } catch (err) {
  207. console.error('解析举手消息失败', err);
  208. }
  209. } else if (msg.type === 88892) { // 问题消息
  210. try {
  211. const data = JSON.parse(msg.data) as {question: string};
  212. if (typeof data.question === 'string') {
  213. const question: Question = {
  214. studentId: msg.sender?.userId || 'unknown',
  215. studentName: (() => {
  216. try {
  217. return msg.sender?.userExtension ? JSON.parse(msg.sender.userExtension)?.nickname : null;
  218. } catch {
  219. return null;
  220. }
  221. })() || msg.sender?.userId || '未知用户',
  222. question: data.question,
  223. timestamp: msg.timestamp || Date.now()
  224. };
  225. setQuestions([...questions, question]);
  226. }
  227. showMessage(`收到问题: ${data.question}`);
  228. } catch (err) {
  229. console.error('解析问题消息失败', err);
  230. }
  231. } else if (msg.type === 88893) { // 应答消息
  232. try {
  233. const data = JSON.parse(msg.data) as InteractionMessage;
  234. if (data.action === InteractionAction.AnswerHandUp && data.studentId === userId) {
  235. showMessage('老师已应答你的举手');
  236. setHandUpList(handUpList.filter(h => h.studentId !== data.studentId));
  237. }
  238. } catch (err) {
  239. console.error('解析应答消息失败', err);
  240. }
  241. } else if (msg.type === 88888) { // 普通文本消息
  242. showMessage(`${msg.sender?.userId || '未知用户'}: ${msg.data}`);
  243. }
  244. });
  245. };
  246. // RTC相关函数
  247. const removeRemoteVideo = (userId: string, type: 'camera' | 'screen' = 'camera') => {
  248. const vid = `${type}_${userId}`;
  249. const el = remoteVideoElMap.current[vid];
  250. if (el) {
  251. aliRtcEngine.current!.setRemoteViewConfig(null, userId, type === 'camera' ? AliRtcVideoTrack.AliRtcVideoTrackCamera : AliRtcVideoTrack.AliRtcVideoTrackScreen);
  252. el.pause();
  253. remoteVideoContainer.current?.removeChild(el);
  254. delete remoteVideoElMap.current[vid];
  255. }
  256. };
  257. const listenRtcEvents = () => {
  258. if (!aliRtcEngine.current) return;
  259. showMessage('注册rtc事件监听')
  260. aliRtcEngine.current.on('remoteUserOnLineNotify', (userId: string) => {
  261. showMessage(`用户 ${userId} 加入课堂`);
  262. console.log('用户上线通知:', userId);
  263. });
  264. aliRtcEngine.current.on('remoteUserOffLineNotify', (userId: string) => {
  265. showMessage(`用户 ${userId} 离开课堂`);
  266. console.log('用户下线通知:', userId);
  267. removeRemoteVideo(userId, 'camera');
  268. removeRemoteVideo(userId, 'screen');
  269. });
  270. aliRtcEngine.current.on('videoSubscribeStateChanged', (
  271. userId: string,
  272. oldState: AliRtcSubscribeState,
  273. newState: AliRtcSubscribeState,
  274. interval: number,
  275. channelId: string
  276. ) => {
  277. console.log(`视频订阅状态变化: 用户 ${userId}, 旧状态 ${oldState}, 新状态 ${newState}`);
  278. switch(newState) {
  279. case 3: // 订阅成功
  280. try {
  281. console.log('开始创建远程视频元素');
  282. if (remoteVideoElMap.current[`camera_${userId}`]) {
  283. console.log(`用户 ${userId} 的视频元素已存在`);
  284. return;
  285. }
  286. const video = document.createElement('video');
  287. video.autoplay = true;
  288. video.playsInline = true;
  289. video.className = 'w-80 h-45 mr-2 mb-2 bg-black';
  290. if (!remoteVideoContainer.current) {
  291. console.error('远程视频容器未找到');
  292. return;
  293. }
  294. remoteVideoContainer.current.style.display = 'block';
  295. remoteVideoContainer.current.appendChild(video);
  296. remoteVideoElMap.current[`camera_${userId}`] = video;
  297. aliRtcEngine.current!.setRemoteViewConfig(
  298. video,
  299. userId,
  300. AliRtcVideoTrack.AliRtcVideoTrackCamera
  301. );
  302. console.log(`已订阅用户 ${userId} 的视频流`);
  303. showMessage(`已显示用户 ${userId} 的视频`);
  304. } catch (err) {
  305. console.error(`订阅用户 ${userId} 视频流失败:`, err);
  306. showMessage(`订阅用户 ${userId} 视频流失败`);
  307. }
  308. break;
  309. case 1: // 取消订阅
  310. console.log(`取消订阅用户 ${userId} 的视频流`);
  311. removeRemoteVideo(userId, 'camera');
  312. break;
  313. case 2: // 订阅中
  314. console.log(`正在订阅用户 ${userId} 的视频流...`);
  315. break;
  316. default:
  317. console.warn(`未知订阅状态: ${newState}`);
  318. }
  319. });
  320. aliRtcEngine.current.on('screenShareSubscribeStateChanged', (
  321. userId: string,
  322. oldState: AliRtcSubscribeState,
  323. newState: AliRtcSubscribeState,
  324. elapseSinceLastState: number,
  325. channel: string
  326. ) => {
  327. console.log(`屏幕分享订阅状态变更:uid=${userId}, oldState=${oldState}, newState=${newState}`);
  328. switch(newState) {
  329. case 3: // 订阅成功
  330. try {
  331. console.log('开始创建屏幕分享视频元素');
  332. if (remoteVideoElMap.current[`screen_${userId}`]) {
  333. console.log(`用户 ${userId} 的屏幕分享元素已存在`);
  334. return;
  335. }
  336. const video = document.createElement('video');
  337. video.autoplay = true;
  338. video.playsInline = true;
  339. video.className = 'w-80 h-45 mr-2 mb-2 bg-black';
  340. if (!remoteVideoContainer.current) {
  341. console.error('远程视频容器未找到');
  342. return;
  343. }
  344. remoteVideoContainer.current.appendChild(video);
  345. remoteVideoElMap.current[`screen_${userId}`] = video;
  346. aliRtcEngine.current!.setRemoteViewConfig(
  347. video,
  348. userId,
  349. AliRtcVideoTrack.AliRtcVideoTrackScreen
  350. );
  351. console.log(`已订阅用户 ${userId} 的屏幕分享流`);
  352. showMessage(`已显示用户 ${userId} 的屏幕分享`);
  353. } catch (err) {
  354. console.error(`订阅用户 ${userId} 屏幕分享流失败:`, err);
  355. showMessage(`订阅用户 ${userId} 屏幕分享流失败`);
  356. }
  357. break;
  358. case 1: // 取消订阅
  359. console.log(`取消订阅用户 ${userId} 的屏幕分享流`);
  360. removeRemoteVideo(userId, 'screen');
  361. break;
  362. case 2: // 订阅中
  363. console.log(`正在订阅用户 ${userId} 的屏幕分享流...`);
  364. break;
  365. default:
  366. console.warn(`未知屏幕分享订阅状态: ${newState}`);
  367. }
  368. });
  369. };
  370. // 课堂操作方法
  371. const login = async (userId: string): Promise<void> => {
  372. if(!role) return;
  373. try {
  374. const { ImEngine: ImEngineClass } = window.AliVCInteraction;
  375. imEngine.current = ImEngineClass.createEngine();
  376. await imEngine.current.init({
  377. deviceId: 'xxxx',
  378. appId: IM_APP_ID,
  379. appSign: IM_APP_SIGN,
  380. logLevel: ERROR,
  381. });
  382. const imToken = await generateImToken(userId, role);
  383. await imEngine.current.login({
  384. user: {
  385. userId,
  386. userExtension: '{}'
  387. },
  388. userAuth: {
  389. nonce: 'AK_4',
  390. timestamp: Math.floor(Date.now() / 1000) + 3600 * 3,
  391. token: imToken,
  392. role
  393. }
  394. });
  395. aliRtcEngine.current = AliRtcEngine.getInstance();
  396. AliRtcEngine.setLogLevel(0);
  397. listenImEvents();
  398. listenRtcEvents();
  399. setIsLoggedIn(true);
  400. setErrorMessage('');
  401. showToast('success', '登录成功');
  402. } catch (err: any) {
  403. setErrorMessage(`登录失败: ${err.message}`);
  404. showToast('error', '登录失败');
  405. }
  406. };
  407. const joinClass = async (classId?: string): Promise<void> => {
  408. if (!imEngine.current || !aliRtcEngine.current) return;
  409. // 优先使用URL参数中的classId和role
  410. const { id: pathClassId, role: pathRole } = useParams();
  411. const finalClassId = (classId || pathClassId) as string;
  412. if (pathRole && ['teacher', 'student'].includes(pathRole)) {
  413. setRole(pathRole === 'teacher' ? Role.Teacher : Role.Student);
  414. }
  415. if (!finalClassId) {
  416. setErrorMessage('课堂ID不能为空');
  417. showToast('error', '请输入有效的课堂ID');
  418. return;
  419. }
  420. try {
  421. const gm = imEngine.current.getGroupManager();
  422. const mm = imEngine.current.getMessageManager();
  423. imGroupManager.current = gm || null;
  424. imMessageManager.current = mm || null;
  425. await gm!.joinGroup(finalClassId);
  426. listenGroupEvents();
  427. listenMessageEvents();
  428. await joinRtcChannel(finalClassId);
  429. setIsJoinedClass(true);
  430. setErrorMessage('');
  431. showToast('success', '加入课堂成功');
  432. } catch (err: any) {
  433. setErrorMessage(`加入课堂失败: ${err.message}`);
  434. showToast('error', '加入课堂失败');
  435. if (imGroupManager.current) {
  436. try {
  437. await imGroupManager.current.leaveGroup(finalClassId);
  438. } catch (leaveErr) {
  439. console.error('离开IM群组失败:', leaveErr);
  440. }
  441. }
  442. }
  443. };
  444. const leaveClass = async (): Promise<void> => {
  445. try {
  446. if (imGroupManager.current && classId) {
  447. await imGroupManager.current.leaveGroup(classId);
  448. }
  449. if (aliRtcEngine.current) {
  450. await leaveRtcChannel();
  451. }
  452. setIsJoinedClass(false);
  453. showToast('info', '已离开课堂');
  454. } catch (err) {
  455. console.error('离开课堂失败:', err);
  456. showToast('error', '离开课堂时发生错误');
  457. }
  458. };
  459. const sendMessage = async (): Promise<void> => {
  460. if (!imMessageManager.current || !classId) return;
  461. try {
  462. await imMessageManager.current.sendGroupMessage({
  463. groupId: classId,
  464. data: msgText,
  465. type: 88888,
  466. level: NORMAL,
  467. });
  468. setMsgText('');
  469. setErrorMessage('');
  470. } catch (err: any) {
  471. setErrorMessage(`消息发送失败: ${err.message}`);
  472. }
  473. };
  474. const startClass = async (): Promise<void> => {
  475. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  476. try {
  477. await imMessageManager.current.sendGroupMessage({
  478. groupId: classId,
  479. data: JSON.stringify({ action: 'start_class' }),
  480. type: 88889,
  481. level: HIGH,
  482. });
  483. setClassStatus(ClassStatus.IN_PROGRESS);
  484. showToast('success', '课堂已开始');
  485. } catch (err: any) {
  486. setErrorMessage(`开始上课失败: ${err.message}`);
  487. }
  488. };
  489. const endClass = async (): Promise<void> => {
  490. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  491. try {
  492. await imMessageManager.current.sendGroupMessage({
  493. groupId: classId,
  494. data: JSON.stringify({ action: 'end_class' }),
  495. type: 88889,
  496. level: HIGH,
  497. });
  498. setClassStatus(ClassStatus.ENDED);
  499. showToast('success', '课堂已结束');
  500. try {
  501. await leaveRtcChannel();
  502. } catch (err: any) {
  503. console.error('离开RTC频道失败:', err);
  504. showToast('error', '离开RTC频道失败');
  505. }
  506. } catch (err: any) {
  507. setErrorMessage(`结束上课失败: ${err.message}`);
  508. }
  509. };
  510. const toggleMuteMember = async (userId: string, mute: boolean): Promise<void> => {
  511. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  512. try {
  513. await imMessageManager.current.sendGroupMessage({
  514. groupId: classId,
  515. data: JSON.stringify({
  516. action: 'toggle_mute',
  517. userId,
  518. mute
  519. }),
  520. type: 88890,
  521. level: HIGH,
  522. });
  523. showToast('info', mute ? `已静音用户 ${userId}` : `已取消静音用户 ${userId}`);
  524. } catch (err: any) {
  525. setErrorMessage(`操作失败: ${err.message}`);
  526. }
  527. };
  528. const createClass = async (className: string, maxMembers = 200): Promise<string | null> => {
  529. if (!imEngine.current || !isLoggedIn || role !== Role.Teacher) {
  530. showToast('error', '只有老师可以创建课堂');
  531. return null;
  532. }
  533. try {
  534. const groupManager = imEngine.current.getGroupManager();
  535. if (!groupManager) {
  536. throw new Error('群组管理器未初始化');
  537. }
  538. showToast('info', '正在创建课堂...');
  539. const response = await groupManager.createGroup({
  540. groupName: className,
  541. groupMeta: JSON.stringify({
  542. classType: 'interactive',
  543. creator: userId,
  544. createdAt: Date.now(),
  545. maxMembers
  546. })
  547. });
  548. if (!response?.groupId) {
  549. throw new Error('创建群组失败: 未返回群组ID');
  550. }
  551. try {
  552. await groupManager.joinGroup(response.groupId);
  553. showToast('success', '课堂创建并加入成功');
  554. showMessage(`课堂 ${className} 创建成功,ID: ${response.groupId}`);
  555. setClassId(response.groupId);
  556. setIsJoinedClass(true);
  557. const messageManager = imEngine.current.getMessageManager();
  558. if (messageManager) {
  559. imMessageManager.current = messageManager;
  560. listenMessageEvents();
  561. }
  562. await joinRtcChannel(response.groupId);
  563. const baseUrl = window.location.href.split('?')[0].replace(/\/[^/]*$/, '');
  564. setShareLink(`${baseUrl}/mobile/classroom/${response.groupId}/student`);
  565. return response.groupId;
  566. } catch (joinErr: any) {
  567. throw new Error(`创建成功但加入失败: ${joinErr.message}`);
  568. }
  569. } catch (err: any) {
  570. const errorMsg = err.message.includes('alreadyExist')
  571. ? '课堂已存在'
  572. : `课堂创建失败: ${err.message}`;
  573. setErrorMessage(errorMsg);
  574. showToast('error', errorMsg);
  575. return null;
  576. }
  577. };
  578. const joinRtcChannel = async (classId: string, publishOptions?: {
  579. publishVideo?: boolean
  580. publishAudio?: boolean
  581. publishScreen?: boolean
  582. }) => {
  583. if (!aliRtcEngine.current) return;
  584. const {
  585. publishVideo = false,
  586. publishAudio = false,
  587. publishScreen = false,
  588. } = publishOptions || {};
  589. const timestamp = Math.floor(Date.now() / 1000) + 3600 * 3;
  590. const token = await generateToken(RTC_APP_ID, RTC_APP_KEY, classId, userId, timestamp);
  591. await aliRtcEngine.current.publishLocalVideoStream(publishVideo);
  592. await aliRtcEngine.current.publishLocalAudioStream(publishAudio);
  593. await aliRtcEngine.current.publishLocalScreenShareStream(publishScreen);
  594. await aliRtcEngine.current.joinChannel(
  595. {
  596. channelId: classId,
  597. userId,
  598. appId: RTC_APP_ID,
  599. token,
  600. timestamp,
  601. },
  602. userId
  603. );
  604. };
  605. const leaveRtcChannel = async () => {
  606. if (!aliRtcEngine.current) return;
  607. await aliRtcEngine.current.leaveChannel();
  608. };
  609. // 切换摄像头状态
  610. const toggleCamera = async () => {
  611. if(!aliRtcEngine.current?.isInCall){
  612. showToast('error', '先加入课堂');
  613. return;
  614. }
  615. try {
  616. if (isCameraOn) {
  617. await aliRtcEngine.current?.stopPreview();
  618. await aliRtcEngine.current?.enableLocalVideo(false)
  619. await aliRtcEngine.current?.publishLocalVideoStream(false)
  620. } else {
  621. await aliRtcEngine.current?.setLocalViewConfig('localPreviewer', AliRtcVideoTrack.AliRtcVideoTrackCamera);
  622. await aliRtcEngine.current?.enableLocalVideo(true)
  623. await aliRtcEngine.current?.startPreview();
  624. await aliRtcEngine.current?.publishLocalVideoStream(true)
  625. }
  626. await aliRtcEngine.current?.startAndPublishDefaultDevices()
  627. setIsCameraOn(!isCameraOn);
  628. } catch (err) {
  629. console.error('切换摄像头状态失败:', err);
  630. showToast('error', '切换摄像头失败');
  631. }
  632. };
  633. // 切换音频状态
  634. const toggleAudio = async () => {
  635. if(!aliRtcEngine.current?.isInCall){
  636. showToast('error', '先加入课堂');
  637. return;
  638. }
  639. try {
  640. if (isAudioOn) {
  641. await aliRtcEngine.current?.stopAudioCapture()
  642. await aliRtcEngine.current?.publishLocalAudioStream(false);
  643. } else {
  644. await aliRtcEngine.current?.publishLocalAudioStream(true);
  645. }
  646. await aliRtcEngine.current?.startAndPublishDefaultDevices();
  647. setIsAudioOn(!isAudioOn);
  648. } catch (err) {
  649. console.error('切换麦克风状态失败:', err);
  650. showToast('error', '切换麦克风失败');
  651. }
  652. };
  653. // 切换屏幕分享状态
  654. const toggleScreenShare = async () => {
  655. if(!aliRtcEngine.current?.isInCall){
  656. showToast('error', '先加入课堂');
  657. return;
  658. }
  659. try {
  660. if (isScreenSharing) {
  661. await aliRtcEngine.current?.publishLocalScreenShareStream(false)
  662. await aliRtcEngine.current?.stopScreenShare()
  663. } else {
  664. await aliRtcEngine.current?.publishLocalScreenShareStream(true)
  665. await aliRtcEngine.current?.setLocalViewConfig(
  666. 'screenPreviewer',
  667. AliRtcVideoTrack.AliRtcVideoTrackScreen
  668. );
  669. }
  670. await aliRtcEngine.current?.startAndPublishDefaultDevices()
  671. setIsScreenSharing(!isScreenSharing);
  672. } catch (err) {
  673. console.error('切换屏幕分享失败:', err);
  674. showToast('error', '切换屏幕分享失败');
  675. }
  676. };
  677. const handUp = async (question?: string): Promise<void> => {
  678. if (!imMessageManager.current || !classId || role !== 'student') return;
  679. try {
  680. await imMessageManager.current.sendGroupMessage({
  681. groupId: classId,
  682. data: JSON.stringify({
  683. action: 'hand_up',
  684. studentId: userId,
  685. timestamp: Date.now(),
  686. question
  687. }),
  688. type: 88891,
  689. level: NORMAL,
  690. });
  691. } catch (err: any) {
  692. setErrorMessage(`举手失败: ${err.message}`);
  693. }
  694. };
  695. const muteStudent = async (studentId: string): Promise<void> => {
  696. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  697. try {
  698. await imMessageManager.current.sendGroupMessage({
  699. groupId: classId,
  700. data: JSON.stringify({
  701. action: 'toggle_mute',
  702. userId: studentId,
  703. mute: true
  704. }),
  705. type: 88890,
  706. level: HIGH,
  707. });
  708. showToast('info', `已静音学生 ${studentId}`);
  709. } catch (err: any) {
  710. setErrorMessage(`静音失败: ${err.message}`);
  711. }
  712. };
  713. const kickStudent = async (studentId: string): Promise<void> => {
  714. if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
  715. try {
  716. await imGroupManager.current.leaveGroup(classId);
  717. showToast('info', `已移出学生 ${studentId}`);
  718. } catch (err: any) {
  719. setErrorMessage(`移出失败: ${err.message}`);
  720. }
  721. };
  722. const answerHandUp = async (studentId: string): Promise<void> => {
  723. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  724. try {
  725. await imMessageManager.current.sendGroupMessage({
  726. groupId: classId,
  727. data: JSON.stringify({
  728. action: 'answer_hand_up',
  729. studentId
  730. }),
  731. type: 88893,
  732. level: HIGH,
  733. });
  734. showToast('info', `已应答学生 ${studentId} 的举手`);
  735. } catch (err: any) {
  736. setErrorMessage(`应答失败: ${err.message}`);
  737. }
  738. };
  739. const sendQuestion = async (question: string): Promise<void> => {
  740. if (!imMessageManager.current || !classId) return;
  741. try {
  742. await imMessageManager.current.sendGroupMessage({
  743. groupId: classId,
  744. data: question,
  745. type: 88892,
  746. level: NORMAL,
  747. });
  748. } catch (err: any) {
  749. setErrorMessage(`问题发送失败: ${err.message}`);
  750. }
  751. };
  752. // 清理资源
  753. useEffect(() => {
  754. return () => {
  755. if (imGroupManager.current) {
  756. imGroupManager.current.removeAllListeners();
  757. }
  758. if (imMessageManager.current) {
  759. imMessageManager.current.removeAllListeners();
  760. }
  761. if (imEngine.current) {
  762. imEngine.current.removeAllListeners();
  763. }
  764. if (aliRtcEngine.current) {
  765. aliRtcEngine.current.destroy();
  766. }
  767. };
  768. }, []);
  769. return {
  770. // 状态
  771. userId,
  772. setUserId,
  773. isCameraOn,
  774. isAudioOn,
  775. isScreenSharing,
  776. className,
  777. setClassName,
  778. role,
  779. setRole,
  780. classId,
  781. setClassId,
  782. isLoggedIn,
  783. isJoinedClass,
  784. msgText,
  785. setMsgText,
  786. messageList,
  787. errorMessage,
  788. classStatus,
  789. handUpList,
  790. questions,
  791. students,
  792. shareLink,
  793. remoteVideoContainer,
  794. // 方法
  795. login,
  796. joinClass,
  797. leaveClass,
  798. sendMessage,
  799. startClass,
  800. endClass,
  801. toggleMuteMember,
  802. createClass,
  803. toggleCamera,
  804. toggleAudio,
  805. toggleScreenShare,
  806. handUp,
  807. answerHandUp,
  808. sendQuestion,
  809. muteStudent,
  810. kickStudent
  811. };
  812. };