useClassroom.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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
  410. const { id: pathClassId } = useParams();
  411. const finalClassId = (classId || pathClassId) as string;
  412. if (!finalClassId) {
  413. setErrorMessage('课堂ID不能为空');
  414. showToast('error', '请输入有效的课堂ID');
  415. return;
  416. }
  417. try {
  418. const gm = imEngine.current.getGroupManager();
  419. const mm = imEngine.current.getMessageManager();
  420. imGroupManager.current = gm || null;
  421. imMessageManager.current = mm || null;
  422. await gm!.joinGroup(finalClassId);
  423. listenGroupEvents();
  424. listenMessageEvents();
  425. await joinRtcChannel(finalClassId);
  426. setIsJoinedClass(true);
  427. setErrorMessage('');
  428. showToast('success', '加入课堂成功');
  429. } catch (err: any) {
  430. setErrorMessage(`加入课堂失败: ${err.message}`);
  431. showToast('error', '加入课堂失败');
  432. if (imGroupManager.current) {
  433. try {
  434. await imGroupManager.current.leaveGroup(finalClassId);
  435. } catch (leaveErr) {
  436. console.error('离开IM群组失败:', leaveErr);
  437. }
  438. }
  439. }
  440. };
  441. const leaveClass = async (): Promise<void> => {
  442. try {
  443. if (imGroupManager.current && classId) {
  444. await imGroupManager.current.leaveGroup(classId);
  445. }
  446. if (aliRtcEngine.current) {
  447. await leaveRtcChannel();
  448. }
  449. setIsJoinedClass(false);
  450. showToast('info', '已离开课堂');
  451. } catch (err) {
  452. console.error('离开课堂失败:', err);
  453. showToast('error', '离开课堂时发生错误');
  454. }
  455. };
  456. const sendMessage = async (): Promise<void> => {
  457. if (!imMessageManager.current || !classId) return;
  458. try {
  459. await imMessageManager.current.sendGroupMessage({
  460. groupId: classId,
  461. data: msgText,
  462. type: 88888,
  463. level: NORMAL,
  464. });
  465. setMsgText('');
  466. setErrorMessage('');
  467. } catch (err: any) {
  468. setErrorMessage(`消息发送失败: ${err.message}`);
  469. }
  470. };
  471. const startClass = async (): Promise<void> => {
  472. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  473. try {
  474. await imMessageManager.current.sendGroupMessage({
  475. groupId: classId,
  476. data: JSON.stringify({ action: 'start_class' }),
  477. type: 88889,
  478. level: HIGH,
  479. });
  480. setClassStatus(ClassStatus.IN_PROGRESS);
  481. showToast('success', '课堂已开始');
  482. } catch (err: any) {
  483. setErrorMessage(`开始上课失败: ${err.message}`);
  484. }
  485. };
  486. const endClass = async (): Promise<void> => {
  487. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  488. try {
  489. await imMessageManager.current.sendGroupMessage({
  490. groupId: classId,
  491. data: JSON.stringify({ action: 'end_class' }),
  492. type: 88889,
  493. level: HIGH,
  494. });
  495. setClassStatus(ClassStatus.ENDED);
  496. showToast('success', '课堂已结束');
  497. try {
  498. await leaveRtcChannel();
  499. } catch (err: any) {
  500. console.error('离开RTC频道失败:', err);
  501. showToast('error', '离开RTC频道失败');
  502. }
  503. } catch (err: any) {
  504. setErrorMessage(`结束上课失败: ${err.message}`);
  505. }
  506. };
  507. const toggleMuteMember = async (userId: string, mute: boolean): Promise<void> => {
  508. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  509. try {
  510. await imMessageManager.current.sendGroupMessage({
  511. groupId: classId,
  512. data: JSON.stringify({
  513. action: 'toggle_mute',
  514. userId,
  515. mute
  516. }),
  517. type: 88890,
  518. level: HIGH,
  519. });
  520. showToast('info', mute ? `已静音用户 ${userId}` : `已取消静音用户 ${userId}`);
  521. } catch (err: any) {
  522. setErrorMessage(`操作失败: ${err.message}`);
  523. }
  524. };
  525. const createClass = async (className: string, maxMembers = 200): Promise<string | null> => {
  526. if (!imEngine.current || !isLoggedIn || role !== Role.Teacher) {
  527. showToast('error', '只有老师可以创建课堂');
  528. return null;
  529. }
  530. try {
  531. const groupManager = imEngine.current.getGroupManager();
  532. if (!groupManager) {
  533. throw new Error('群组管理器未初始化');
  534. }
  535. showToast('info', '正在创建课堂...');
  536. const response = await groupManager.createGroup({
  537. groupName: className,
  538. groupMeta: JSON.stringify({
  539. classType: 'interactive',
  540. creator: userId,
  541. createdAt: Date.now(),
  542. maxMembers
  543. })
  544. });
  545. if (!response?.groupId) {
  546. throw new Error('创建群组失败: 未返回群组ID');
  547. }
  548. try {
  549. await groupManager.joinGroup(response.groupId);
  550. showToast('success', '课堂创建并加入成功');
  551. showMessage(`课堂 ${className} 创建成功,ID: ${response.groupId}`);
  552. setClassId(response.groupId);
  553. setIsJoinedClass(true);
  554. const messageManager = imEngine.current.getMessageManager();
  555. if (messageManager) {
  556. imMessageManager.current = messageManager;
  557. listenMessageEvents();
  558. }
  559. await joinRtcChannel(response.groupId);
  560. setShareLink(`${window.location.href.split('?')[0]}?classId=${response.groupId}`);
  561. return response.groupId;
  562. } catch (joinErr: any) {
  563. throw new Error(`创建成功但加入失败: ${joinErr.message}`);
  564. }
  565. } catch (err: any) {
  566. const errorMsg = err.message.includes('alreadyExist')
  567. ? '课堂已存在'
  568. : `课堂创建失败: ${err.message}`;
  569. setErrorMessage(errorMsg);
  570. showToast('error', errorMsg);
  571. return null;
  572. }
  573. };
  574. const joinRtcChannel = async (classId: string, publishOptions?: {
  575. publishVideo?: boolean
  576. publishAudio?: boolean
  577. publishScreen?: boolean
  578. }) => {
  579. if (!aliRtcEngine.current) return;
  580. const {
  581. publishVideo = false,
  582. publishAudio = false,
  583. publishScreen = false,
  584. } = publishOptions || {};
  585. const timestamp = Math.floor(Date.now() / 1000) + 3600 * 3;
  586. const token = await generateToken(RTC_APP_ID, RTC_APP_KEY, classId, userId, timestamp);
  587. await aliRtcEngine.current.publishLocalVideoStream(publishVideo);
  588. await aliRtcEngine.current.publishLocalAudioStream(publishAudio);
  589. await aliRtcEngine.current.publishLocalScreenShareStream(publishScreen);
  590. await aliRtcEngine.current.joinChannel(
  591. {
  592. channelId: classId,
  593. userId,
  594. appId: RTC_APP_ID,
  595. token,
  596. timestamp,
  597. },
  598. userId
  599. );
  600. };
  601. const leaveRtcChannel = async () => {
  602. if (!aliRtcEngine.current) return;
  603. await aliRtcEngine.current.leaveChannel();
  604. };
  605. // 切换摄像头状态
  606. const toggleCamera = async () => {
  607. if(!aliRtcEngine.current?.isInCall){
  608. showToast('error', '先加入课堂');
  609. return;
  610. }
  611. try {
  612. if (isCameraOn) {
  613. await aliRtcEngine.current?.stopPreview();
  614. await aliRtcEngine.current?.enableLocalVideo(false)
  615. await aliRtcEngine.current?.publishLocalVideoStream(false)
  616. } else {
  617. await aliRtcEngine.current?.setLocalViewConfig('localPreviewer', AliRtcVideoTrack.AliRtcVideoTrackCamera);
  618. await aliRtcEngine.current?.enableLocalVideo(true)
  619. await aliRtcEngine.current?.startPreview();
  620. await aliRtcEngine.current?.publishLocalVideoStream(true)
  621. }
  622. await aliRtcEngine.current?.startAndPublishDefaultDevices()
  623. setIsCameraOn(!isCameraOn);
  624. } catch (err) {
  625. console.error('切换摄像头状态失败:', err);
  626. showToast('error', '切换摄像头失败');
  627. }
  628. };
  629. // 切换音频状态
  630. const toggleAudio = async () => {
  631. if(!aliRtcEngine.current?.isInCall){
  632. showToast('error', '先加入课堂');
  633. return;
  634. }
  635. try {
  636. if (isAudioOn) {
  637. await aliRtcEngine.current?.stopAudioCapture()
  638. await aliRtcEngine.current?.publishLocalAudioStream(false);
  639. } else {
  640. await aliRtcEngine.current?.publishLocalAudioStream(true);
  641. }
  642. await aliRtcEngine.current?.startAndPublishDefaultDevices();
  643. setIsAudioOn(!isAudioOn);
  644. } catch (err) {
  645. console.error('切换麦克风状态失败:', err);
  646. showToast('error', '切换麦克风失败');
  647. }
  648. };
  649. // 切换屏幕分享状态
  650. const toggleScreenShare = async () => {
  651. if(!aliRtcEngine.current?.isInCall){
  652. showToast('error', '先加入课堂');
  653. return;
  654. }
  655. try {
  656. if (isScreenSharing) {
  657. await aliRtcEngine.current?.publishLocalScreenShareStream(false)
  658. await aliRtcEngine.current?.stopScreenShare()
  659. } else {
  660. await aliRtcEngine.current?.publishLocalScreenShareStream(true)
  661. await aliRtcEngine.current?.setLocalViewConfig(
  662. 'screenPreviewer',
  663. AliRtcVideoTrack.AliRtcVideoTrackScreen
  664. );
  665. }
  666. await aliRtcEngine.current?.startAndPublishDefaultDevices()
  667. setIsScreenSharing(!isScreenSharing);
  668. } catch (err) {
  669. console.error('切换屏幕分享失败:', err);
  670. showToast('error', '切换屏幕分享失败');
  671. }
  672. };
  673. const handUp = async (question?: string): Promise<void> => {
  674. if (!imMessageManager.current || !classId || role !== 'student') return;
  675. try {
  676. await imMessageManager.current.sendGroupMessage({
  677. groupId: classId,
  678. data: JSON.stringify({
  679. action: 'hand_up',
  680. studentId: userId,
  681. timestamp: Date.now(),
  682. question
  683. }),
  684. type: 88891,
  685. level: NORMAL,
  686. });
  687. } catch (err: any) {
  688. setErrorMessage(`举手失败: ${err.message}`);
  689. }
  690. };
  691. const muteStudent = async (studentId: string): Promise<void> => {
  692. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  693. try {
  694. await imMessageManager.current.sendGroupMessage({
  695. groupId: classId,
  696. data: JSON.stringify({
  697. action: 'toggle_mute',
  698. userId: studentId,
  699. mute: true
  700. }),
  701. type: 88890,
  702. level: HIGH,
  703. });
  704. showToast('info', `已静音学生 ${studentId}`);
  705. } catch (err: any) {
  706. setErrorMessage(`静音失败: ${err.message}`);
  707. }
  708. };
  709. const kickStudent = async (studentId: string): Promise<void> => {
  710. if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
  711. try {
  712. await imGroupManager.current.leaveGroup(classId);
  713. showToast('info', `已移出学生 ${studentId}`);
  714. } catch (err: any) {
  715. setErrorMessage(`移出失败: ${err.message}`);
  716. }
  717. };
  718. const answerHandUp = async (studentId: string): Promise<void> => {
  719. if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
  720. try {
  721. await imMessageManager.current.sendGroupMessage({
  722. groupId: classId,
  723. data: JSON.stringify({
  724. action: 'answer_hand_up',
  725. studentId
  726. }),
  727. type: 88893,
  728. level: HIGH,
  729. });
  730. showToast('info', `已应答学生 ${studentId} 的举手`);
  731. } catch (err: any) {
  732. setErrorMessage(`应答失败: ${err.message}`);
  733. }
  734. };
  735. const sendQuestion = async (question: string): Promise<void> => {
  736. if (!imMessageManager.current || !classId) return;
  737. try {
  738. await imMessageManager.current.sendGroupMessage({
  739. groupId: classId,
  740. data: question,
  741. type: 88892,
  742. level: NORMAL,
  743. });
  744. } catch (err: any) {
  745. setErrorMessage(`问题发送失败: ${err.message}`);
  746. }
  747. };
  748. // 清理资源
  749. useEffect(() => {
  750. return () => {
  751. if (imGroupManager.current) {
  752. imGroupManager.current.removeAllListeners();
  753. }
  754. if (imMessageManager.current) {
  755. imMessageManager.current.removeAllListeners();
  756. }
  757. if (imEngine.current) {
  758. imEngine.current.removeAllListeners();
  759. }
  760. if (aliRtcEngine.current) {
  761. aliRtcEngine.current.destroy();
  762. }
  763. };
  764. }, []);
  765. return {
  766. // 状态
  767. userId,
  768. setUserId,
  769. isCameraOn,
  770. isAudioOn,
  771. isScreenSharing,
  772. className,
  773. setClassName,
  774. role,
  775. setRole,
  776. classId,
  777. setClassId,
  778. isLoggedIn,
  779. isJoinedClass,
  780. msgText,
  781. setMsgText,
  782. messageList,
  783. errorMessage,
  784. classStatus,
  785. handUpList,
  786. questions,
  787. students,
  788. shareLink,
  789. remoteVideoContainer,
  790. // 方法
  791. login,
  792. joinClass,
  793. leaveClass,
  794. sendMessage,
  795. startClass,
  796. endClass,
  797. toggleMuteMember,
  798. createClass,
  799. toggleCamera,
  800. toggleAudio,
  801. toggleScreenShare,
  802. handUp,
  803. answerHandUp,
  804. sendQuestion,
  805. muteStudent,
  806. kickStudent
  807. };
  808. };