2
0

useClassroom.ts 28 KB

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