webRtcManager.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. //
  2. // webRtcManager.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/9/5.
  6. //
  7. #import "webRtcManager.h"
  8. #import "webRtcManager+StatisticsReport.h"
  9. #import "RcGameWQKeyChain.h"
  10. #import "errorAlertTool.h"
  11. #import "webRtcManager+downloadNasFile.h"
  12. @interface webRtcManager ()<MediaStreamClientEventsDelegate>
  13. {
  14. NSMutableArray *commandSendCheckArr;//需要检测任务是否发出的的指令
  15. NSTimer *linkCheckSecondTimer; // 检测链接状态
  16. }
  17. //第一次链接设备 要发送指令信息 实现单点登录
  18. @property (nonatomic, assign)BOOL didSendfristMsg;
  19. @end
  20. @implementation webRtcManager
  21. + (instancetype)shareManager {
  22. static webRtcManager *_instance;
  23. static dispatch_once_t onceToken;
  24. dispatch_once(&onceToken, ^{
  25. _instance = [[self alloc] init];
  26. });
  27. return _instance;
  28. }
  29. - (instancetype)init {
  30. if (self = [super init]) {
  31. //[self registeNotification];
  32. _mediaStream = [[RTC_OBJC_TYPE(AMediaStream) alloc] initWithFrame:CGRectZero];
  33. [_mediaStream setEventDelegate:self];
  34. linkCheckSecondTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerChange) userInfo:nil repeats:YES];
  35. [[NSRunLoop currentRunLoop] addTimer:linkCheckSecondTimer forMode:NSRunLoopCommonModes];
  36. }
  37. return self;
  38. }
  39. #pragma mark 十秒一次的timer检测
  40. - (void)timerChange{
  41. [self checkChannelLinkStateFun];
  42. }
  43. #pragma mark 检测链接是否OK
  44. - (void)checkChannelLinkStateFun
  45. {
  46. if(_channelState != RTCDataChannelStateOpen
  47. ||(_ConnectionState != RTCIceConnectionStateConnected
  48. && _ConnectionState != RTCIceConnectionStateCompleted)
  49. ){
  50. [self relinkWebRtcFun];
  51. }
  52. }
  53. #pragma mark 关闭链接
  54. - (void)closeLinkWebRtcFun
  55. {
  56. KWeakSelf
  57. mainBlock(^{
  58. [weakSelf.mediaStream disconnect];
  59. });
  60. }
  61. #pragma mark 开始链接
  62. - (void)beginToLinkWebRtcFun
  63. {
  64. KWeakSelf
  65. mainBlock(^{
  66. [weakSelf secondBeginToLinkWebRtcFun];
  67. });
  68. }
  69. - (void)secondBeginToLinkWebRtcFun
  70. {
  71. if(ksharedAppDelegate.isWebSockLinkOKAginType
  72. || !ksharedAppDelegate.DeviceWebRtcMsgMod){
  73. return;
  74. }
  75. webRtcMsgModel * _webRtcMsgMod = ksharedAppDelegate.DeviceWebRtcMsgMod;
  76. //链接用
  77. NSString *signallingUrl = [[NSString alloc] initWithFormat:@"%@:%@",_webRtcMsgMod.data.signalling.domainName,_webRtcMsgMod.data.signalling.port];
  78. NSURL *url = [NSURL URLWithString:signallingUrl];
  79. //ice用
  80. NSString *iceUrl = [[NSString alloc] initWithFormat:@"%@:%@",_webRtcMsgMod.data.turn.domainName,_webRtcMsgMod.data.turn.port];
  81. NSMutableDictionary *ice = [NSMutableDictionary new];
  82. if(iceUrl){
  83. [ice setValue:iceUrl forKey:@"CHINANET"];
  84. [ice setValue:iceUrl forKey:@"CMNET"];
  85. [ice setValue:iceUrl forKey:@"UNICOM"];
  86. }
  87. NSString *roomName = _webRtcMsgMod.data.uniqueIdentifier;
  88. NSInteger result = [_mediaStream startUploadChannel:url ice:ice sn:roomName token:@"vclusters"];
  89. HLog(@"result:%ld",result)
  90. [_mediaStream setShouldGetStats:YES];
  91. }
  92. - (void)relinkWebRtcFun{
  93. ksharedAppDelegate.isWebSockLinkOKAginType = NO;
  94. [self beginToLinkWebRtcFun];
  95. }
  96. #pragma mark webrtc P2P通道发送消息
  97. - (void)send_data:(NSString *)dataStr
  98. {
  99. [_mediaStream sendData:dataStr];
  100. HLog(@"客户端发出命令:%@",dataStr);
  101. }
  102. #pragma mark 盒子链接成功后需要处理的各种各样事情
  103. - (void)handlAllMsgAfterDidLinkFun
  104. {
  105. _isRebootIngType = NO;
  106. _isResetingType = NO;
  107. _isChangeBoxType = NO;
  108. ksharedAppDelegate.isWebSockLinkOKAginType = YES;
  109. //获取云机尺寸 兼容 720*1080 &1080*1920 不同分辨率的展示和触控
  110. NSString *getPhoneSizeStr = [RCCommandHelp getPhoneSizecommand];
  111. [self send_data:getPhoneSizeStr];
  112. //判断是否为需要改机
  113. BOOL isNeedRandomChangeParams = [HWDataManager getBoolWithKey:Const_need_random_Change_Params];
  114. if(isNeedRandomChangeParams)
  115. {
  116. NSString *commondStr = @"{\"type\":\"randomChangeParams\"}";
  117. [self send_data:commondStr];
  118. [HWDataManager setBoolWithKey:Const_need_random_Change_Params value:NO];
  119. }
  120. [self fristConnectNeedGiveAMsgFun];
  121. [self updateCopydata];
  122. // 报链接失败 后面又连接上了
  123. [[errorAlertTool shareInstance] dismissErrorAlertFun];
  124. //处理相册备份
  125. [[nasBackupsManager shareInstance] AutohandlePhotosBackupsFun];
  126. //获取磁盘外挂
  127. [self getExtraFilesListFun];
  128. [self getBaseInfoFun];
  129. [self getTvStatusFun];
  130. }
  131. #pragma mark 盒子第一次连接成功 给ws发送信息 单点登录 把其他账号挤下去
  132. - (void)fristConnectNeedGiveAMsgFun{
  133. if(!_didSendfristMsg )
  134. {
  135. [self getSysInfoFun];
  136. // NSString *curOaidStr = [RcGameWQKeyChain getOaidStringFun];
  137. // if(!curOaidStr){
  138. // curOaidStr = @"";
  139. // }
  140. // //未调通挤下线
  141. // NSString *commondStr = [[NSString alloc] initWithFormat:@"{\"type\":\"login\",\"value\":\"%@\"}",curOaidStr];
  142. // [self send_data:commondStr];
  143. // [self addCommandSendTaskFunWithType:@"offline_notification" WithCommandStr:commondStr];
  144. _didSendfristMsg = YES;
  145. [self getPreferredLanguage];
  146. NSString *commondStr2 = @"{\"type\":\"TvStatus\"}";
  147. [self send_data:commondStr2];
  148. }
  149. }
  150. #pragma mark 语言和市区 同步云机
  151. -(void)getPreferredLanguage
  152. {//{"data":{"language":"zh-CN","timeZone":"Etc/GMT+8"},"type":"setLanguages"}
  153. // iOS 获取设备当前语言的代码
  154. NSString *preferredLanguage = [[[NSBundle mainBundle] preferredLocalizations] firstObject];
  155. HLog(@"当前语言:%@", preferredLanguage);
  156. //en-US 英文 ja-JP 日文
  157. NSArray *arLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
  158. NSLog(@"arLanguages:%@",arLanguages);
  159. ///获取设备当前地区的代码和APP语言环境
  160. NSString *languageCode = [NSLocale preferredLanguages][0];
  161. //目前支持 中文(简体 繁体) 英文 日语
  162. if([languageCode rangeOfString:@"zh-Hans"].location != NSNotFound)
  163. {
  164. preferredLanguage = @"zh-CN";
  165. }
  166. else if([languageCode rangeOfString:@"zh-Hant"].location != NSNotFound)
  167. {
  168. preferredLanguage = @"zh-HK";
  169. }
  170. else if([languageCode rangeOfString:@"ja-"].location != NSNotFound)
  171. {
  172. preferredLanguage = @"ja-JP";
  173. }
  174. else{
  175. preferredLanguage = @"en-US";
  176. }
  177. // if([languageCode rangeOfString:preferredLanguage].location != NSNotFound){
  178. // preferredLanguage = languageCode;
  179. // }
  180. // else{
  181. // preferredLanguage = @"en-US";
  182. // }
  183. NSString*gmtStr = [self UTCOffset];
  184. HLog(@"%@",gmtStr);
  185. // //获取名字,如“GMT+08:00
  186. NSString *commondStr = [NSString stringWithFormat:@"{\"type\":\"setLanguages\",\"data\":{\"language\":\"%@\",\"timeZone\":\"%@\"}}",preferredLanguage,gmtStr];
  187. [self send_data:commondStr];
  188. }
  189. #pragma mark 获取云机系统镜像等信息
  190. - (void)getSysInfoFun
  191. {
  192. NSString *commondStr = @"{\"type\":\"getSysInfo\"}";
  193. [self send_data:commondStr];
  194. }
  195. -(NSString *)UTCOffset {
  196. NSTimeZone *localTZ = [NSTimeZone localTimeZone];
  197. float offset = localTZ.secondsFromGMT/3600.0;
  198. if(offset > 0){
  199. return [NSString stringWithFormat:@"Etc/GMT+%g",offset];
  200. }
  201. return [NSString stringWithFormat:@"Etc/GMT%g",offset];
  202. }
  203. #pragma mark 收到系统信息消息回调处理
  204. - (void)getCouldPhoneSysInfoResponseFun:(NSDictionary *)dataDict{
  205. couldphoneSysInfoModel *model = [[couldphoneSysInfoModel alloc] initWithDictionary:dataDict error:nil];
  206. //[[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneSysInfoNotification object:model];
  207. // NSString *hostImgVer = model.data.data.hostImgVer;
  208. // NSString *MyNewVersion = model.data.data.MyNewVersion;
  209. NSString *hostImgVer = model.data.hostImgVer;
  210. NSString *MyNewVersion = model.data.MyNewVersion;
  211. //test code
  212. // hostImgVer = @"1.2.3";
  213. // MyNewVersion = @"1.2.0";
  214. //判断当前版本号 待更新版本
  215. if (!hostImgVer || hostImgVer.length < 3
  216. ||!MyNewVersion || MyNewVersion.length < 3) {
  217. return;
  218. }
  219. NSArray *versionArr = [hostImgVer componentsSeparatedByString:@"."];
  220. NSArray *MyNewVersionArr = [MyNewVersion componentsSeparatedByString:@"."];
  221. NSInteger versionArrCount = versionArr.count;
  222. NSInteger MyNewVersionArrCount = MyNewVersionArr.count;
  223. NSInteger maxCount = versionArrCount < MyNewVersionArrCount ? versionArrCount:MyNewVersionArrCount;
  224. BOOL isNeedShowType = NO;
  225. //判断是否要更新镜像框
  226. if(maxCount > 0){
  227. for (int i=0; i<maxCount; i++) {
  228. NSString * numberStr1 = versionArr[i];
  229. NSString * numberStr2 = MyNewVersionArr[i];
  230. if(numberStr2.intValue > numberStr1.intValue){
  231. isNeedShowType =YES;
  232. break;
  233. }
  234. }
  235. }
  236. if(isNeedShowType){
  237. ksharedAppDelegate.isNeedShowImageNewType = YES;
  238. }
  239. //是否禁用文件传输 (1.3以及以上的镜像可以使用文件传输)
  240. if(versionArr.count >= 3)
  241. {
  242. NSString * oneStr = versionArr[0];
  243. NSString * twoStr = versionArr[1];
  244. NSString * threeStr = versionArr[2];
  245. if(oneStr.integerValue <=1 && twoStr.integerValue <=3 && threeStr.integerValue <=0){//禁用
  246. ksharedAppDelegate.DisabledFileTransferType = YES;
  247. if(MyNewVersionArr.count >= 3)
  248. {
  249. NSString * newOneStr = MyNewVersionArr[0];
  250. NSString * newTwoStr = MyNewVersionArr[1];
  251. NSString * newThreeStr = MyNewVersionArr[2];
  252. if(newOneStr.integerValue >=1 && newTwoStr.integerValue >=3 && newThreeStr.integerValue >= 1){
  253. ksharedAppDelegate.isImageNewFor130 = YES;
  254. }
  255. else{
  256. ksharedAppDelegate.isImageNewFor130 = NO;
  257. }
  258. }
  259. }
  260. else{
  261. ksharedAppDelegate.DisabledFileTransferType = NO;
  262. }
  263. }
  264. [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneSysInfoNotification object:model];
  265. }
  266. #pragma mark 添加消息重复机制
  267. -(void)addCommandSendTaskFunWithType:(NSString*)type WithCommandStr:(NSString*)commandStr
  268. {
  269. if(!commandSendCheckArr){
  270. commandSendCheckArr = [NSMutableArray new];
  271. }
  272. BOOL didAddType = NO;
  273. for (commandSendCheckModel *model in commandSendCheckArr) {
  274. if([model.type isEqualToString:type]){
  275. didAddType = YES;
  276. model.reSendNum = 0;
  277. model.sendTimerStamp = [iTools getNowTimeStamp];
  278. break;
  279. }
  280. }
  281. if(!didAddType){
  282. commandSendCheckModel *model = [commandSendCheckModel new];
  283. model.commandStr = commandStr;
  284. model.type = type;
  285. model.reSendNum = 0;
  286. model.sendTimerStamp = [iTools getNowTimeStamp];
  287. [commandSendCheckArr addObject:model];
  288. }
  289. }
  290. #pragma mark 删除代理确认收到的消息
  291. -(void)deleteCommandSendTaskFunWith:(NSString*)type
  292. {
  293. if(commandSendCheckArr && commandSendCheckArr.count >0){
  294. NSArray *taskArr = [NSArray arrayWithArray:commandSendCheckArr];
  295. for (commandSendCheckModel *model in taskArr) {
  296. if([type isEqualToString:model.type]){
  297. [commandSendCheckArr removeObject:model];
  298. }
  299. }
  300. }
  301. }
  302. #pragma mark 复制手机消息到云机
  303. - (void)updateCopydata{
  304. UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
  305. NSString *str = [pasteboard string];
  306. HLog(@"__________%s______%@____",__func__,str);
  307. if ([str rangeOfString:@"CVLUSTERS_NOUSE_"].location != NSNotFound)
  308. {
  309. str = nil;
  310. }
  311. if (str && str.length >0)
  312. {
  313. //HLog(@"hxd111 cutting %@",str);
  314. /*发送数据*/
  315. NSString *dataStr = [RCCommandHelp commandCuttingWithContent:str];
  316. [self send_data:dataStr];
  317. //pasteboard.string = @"";
  318. }
  319. }
  320. #pragma mark 获取云机以及外挂磁盘
  321. - (void)getExtraFilesListFun
  322. {
  323. // NSString *ExtraCommondStr = [RCCommandHelp getExtraFilesList];
  324. // [self send_data:ExtraCommondStr];
  325. //改走http方案
  326. [[NSNotificationCenter defaultCenter] postNotificationName:getExtraFilesDoneNotification object:nil];/*发送通知*/
  327. }
  328. #pragma mark 获取到云机以及外挂磁盘信息
  329. - (void)getExtraFilesResponseFun:(NSDictionary *)dataDict
  330. {
  331. cloudPhoneExtraFileListModel *model = [[cloudPhoneExtraFileListModel alloc] initWithDictionary:dataDict error:nil];
  332. ksharedAppDelegate.cloudPhoneExtraFileListMod = model;
  333. [[NSNotificationCenter defaultCenter] postNotificationName:getExtraFilesDoneNotification object:dataDict];/*发送通知*/
  334. }
  335. #pragma mark 获取云机基本信息
  336. - (void)getBaseInfoFun
  337. {
  338. NSString *commondStr = @"{\"type\":\"getBaseInfo\"}";
  339. [self send_data:commondStr];
  340. }
  341. #pragma mark 获取到云机基本信息
  342. - (void)getCouldPhoneBaseInfoResponseFun:(NSDictionary *)dataDict
  343. {
  344. couldPhoneBaseInfoModel *model = [[couldPhoneBaseInfoModel alloc] initWithDictionary:dataDict error:nil];
  345. [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneBaseInfoNotification object:model];
  346. }
  347. #pragma mark 获取到TV投屏状态
  348. - (void)getCouldPhoneTvStatusResponseFun:(NSDictionary *)dataDict
  349. {
  350. TvStatusModel *model = [[TvStatusModel alloc] initWithDictionary:dataDict error:nil];
  351. ksharedAppDelegate.TvStatusMod = model;
  352. [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneTvStatusNotification object:model];
  353. // if(![model.msg containsString:@"PushStreamBActivity"])
  354. // {
  355. // return;
  356. // }
  357. //
  358. // UIViewController*topVc = self.navigationController.viewControllers.lastObject;
  359. // if([topVc isKindOfClass:[PlayerViewController class]]){
  360. // [[iToast makeText:NSLocalizedString(@"tv_p2p_ing",nil)] show];
  361. // }
  362. }
  363. #pragma mark 重启云机
  364. - (void)needToRebootFun
  365. {
  366. NSString *commondStr = @"{\"type\":\"reboot\"}";
  367. [self send_data:commondStr];
  368. //添加到任务监听
  369. [self addCommandSendTaskFunWithType:@"reboot" WithCommandStr:commondStr];
  370. //数据埋点
  371. [[netWorkManager shareInstance] DataEmbeddingPointBy:3 withEventValue:@"Cloud_restart"];
  372. _isRebootIngType = YES;
  373. }
  374. #pragma mark 恢复出厂设置
  375. - (void)needToResetFun
  376. {
  377. NSString *commondStr = @"{\"type\":\"reset\"}";
  378. [self send_data:commondStr];
  379. //添加到任务监听
  380. [self addCommandSendTaskFunWithType:@"reset" WithCommandStr:commondStr];
  381. //数据埋点
  382. [[netWorkManager shareInstance] DataEmbeddingPointBy:3 withEventValue:@"Cloud_restore_factory"];
  383. _isResetingType = YES;
  384. }
  385. #pragma mark 获取TV投屏状态
  386. - (void)getTvStatusFun
  387. {
  388. NSString *commondStr = @"{\"type\":\"TvStatus\"}";
  389. [self send_data:commondStr];
  390. }
  391. #pragma mark 关闭TV投屏状态
  392. - (void)offTvFun
  393. {
  394. NSString *commondStr = @"{\"type\":\"TvOff\"}";
  395. [self send_data:commondStr];
  396. }
  397. #pragma mark 开启TV投屏状态
  398. - (void)onTvFun
  399. {
  400. NSString *commondStr = @"{\"type\":\"wakeupTV\"}";
  401. [self send_data:commondStr];
  402. }
  403. #pragma mark 创建备份文件夹
  404. - (void)createBackupsFolderBy:(NSString*)backupsDefaultPath
  405. {
  406. NSString *folderName = backupsDefaultPath;
  407. if(folderName && folderName.length >0){
  408. NSString * commandStr = [RCCommandHelp applyForCreateFolderwithFolderName:folderName];
  409. [self send_data:commandStr];
  410. }
  411. }
  412. #pragma mark 获取备份文件夹列表
  413. - (void)getBackupFolderListFun
  414. {
  415. NSString * commandStr = [RCCommandHelp getCreateFolderList];
  416. [self send_data:commandStr];
  417. }
  418. #pragma mark 创建文件夹回调
  419. - (void)createFolderResponseFun:(NSDictionary *)dataDict
  420. {
  421. couldPhoneCommonModel *model = [[couldPhoneCommonModel alloc] initWithDictionary:dataDict error:nil];
  422. if(model){
  423. NSNumber *curNum = [NSNumber numberWithInteger:model.status];
  424. [[NSNotificationCenter defaultCenter] postNotificationName:createFolderDoneNotification object:curNum];/*发送通知*/
  425. }
  426. }
  427. - (void)getFolderListResponseFun:(NSDictionary *)dataDict
  428. {
  429. [[NSNotificationCenter defaultCenter] postNotificationName:getFolderListDoneNotification object:dataDict];/*发送通知*/
  430. }
  431. - (void)searchFileListResponseFun:(NSDictionary *)dataDict
  432. {
  433. [[NSNotificationCenter defaultCenter] postNotificationName:searchFileListDoneNotification object:dataDict];/*发送通知*/
  434. }
  435. #pragma mark U盘插入相关
  436. - (void)getExtraMediaEventResponseFun:(NSDictionary *)dataDict
  437. {
  438. mainBlock((^{
  439. extraMediaEventModel *model = [[extraMediaEventModel alloc] initWithDictionary:dataDict error:nil];
  440. NSString *tip = nil;
  441. if(model.data.event == 0){
  442. tip = NSLocalizedString(@"disk_insertion_tip",nil);
  443. [self showInsertPopViewFun:model.data.name];
  444. }
  445. else if(model.data.event == 1){
  446. tip = NSLocalizedString(@"disk_extract_tip",nil);
  447. }
  448. else if(model.data.event == 2){
  449. tip = NSLocalizedString(@"disk_save_extract_tip",nil);
  450. }
  451. NSString *totalTips = [[NSString alloc] initWithFormat:@"%@%@",model.data.name,tip];
  452. [[iToast makeText:totalTips] show];
  453. }));
  454. }
  455. #pragma mark 显示插入UI弹框
  456. - (void)showInsertPopViewFun:(NSString*)name
  457. {
  458. if(self->curUSBInsertPopV){
  459. [self->curUSBInsertPopV removeFromSuperview];
  460. self->curUSBInsertPopV = nil;
  461. }
  462. self->curUSBInsertPopV = [[USBInsertPopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) withName:name];
  463. [[iTools getKeyWindow] addSubview:self->curUSBInsertPopV];
  464. }
  465. #pragma mark 收到的webrtc消息处理
  466. - (void)handleWebRtcMsgResponseBy:(NSData*)message
  467. {
  468. if([message isKindOfClass:[NSMutableString class]] || [message isKindOfClass:[NSString class]])
  469. {
  470. message = [(NSString *)message dataUsingEncoding:(NSUTF8StringEncoding)];
  471. }
  472. NSError *error = nil;
  473. NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:message options:NSJSONReadingMutableContainers error:&error];
  474. HLog(@"webRtc P2P 通道接收消息:------------------%@",dataDict);
  475. // if([message isKindOfClass:[NSData class]] && [message length] == 0){
  476. // if(type == RCSocketCloudPhoneReceiveTypeForPong)
  477. // {
  478. // [weakSelf keepWebSocketOKFun];
  479. // }
  480. // return;
  481. // }
  482. //
  483. // HLog(@"webSocket指令通道接收消息:------------------\n%@",message);
  484. //
  485. // if([message isKindOfClass:[NSMutableString class]] || [message isKindOfClass:[NSString class]])
  486. // {
  487. // message = [(NSString *)message dataUsingEncoding:(NSUTF8StringEncoding)];
  488. // }
  489. //
  490. // NSError *error = nil;
  491. // NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:message options:NSJSONReadingMutableContainers error:&error];
  492. if(!dataDict){
  493. //[weakSelf handleDownloadResponseFunBy:message];
  494. return;
  495. }
  496. if(![dataDict isKindOfClass:[NSDictionary class]]){
  497. //[__NSCFString allKeys] unrecognized selector sent to ins
  498. return;
  499. }
  500. if(![[dataDict allKeys] containsObject:@"type"]){
  501. return;
  502. }
  503. NSString *messageType = dataDict[@"type"];
  504. if ([messageType isEqualToString:@"cutting"]) {
  505. //[[iToast makeText:@"复制成功"] show];
  506. }
  507. // else if ([messageType isEqualToString:@"forwardMsgRep"]){/*转发的回复*/
  508. //
  509. // cloudPhoneCommonModel *model = [[cloudPhoneCommonModel alloc] initWithDictionary:dataDict error:nil];
  510. // if(!model){
  511. // return;
  512. // }
  513. //
  514. // if([model.data.msg isEqualToString:@"only one socket"]||
  515. // [model.data.msg isEqualToString:@"only one socket2"]){
  516. // [weakSelf deleteCommandSendTaskFunWith:@"offline_notification"];
  517. // }
  518. // }
  519. // else if ([messageType isEqualToString:@"forwardMsg"]){/*转发*/
  520. // /*获取指令类型*/
  521. // NSString *code = nil;
  522. // if ([[dataDict allKeys] containsObject:@"data"]) {
  523. // NSDictionary *data = dataDict[@"data"];
  524. //
  525. // if([data isKindOfClass:[NSString class]]){
  526. // NSString * dataStr = (NSString*)data;
  527. // if([dataStr isEqualToString:@"offline_notification"]){
  528. // HLog(@"被别人挤下线了");
  529. // [weakSelf LogoutByOtherFun];
  530. // }
  531. //
  532. // return;
  533. // }
  534. // else if ([data isKindOfClass:[NSDictionary class]] && [[data allKeys] containsObject:@"code"]) {
  535. // code = [data objectForKey:@"code"];
  536. //
  537. // if (![code isKindOfClass:[NSString class]]) {
  538. // code = [NSString stringWithFormat:@"%ld",[code integerValue]];
  539. // }
  540. // }
  541. // }
  542. //
  543. // /*获取用户名*/
  544. // NSString *useName = nil;
  545. // if ([[dataDict allKeys] containsObject:@"data"]) {
  546. // NSDictionary *data = dataDict[@"data"];
  547. // if ([[data allKeys] containsObject:@"userName"]) {
  548. // //useName = [data objectForKey:@"userName"];
  549. // }
  550. // }
  551. //
  552. //
  553. // if ([code isEqualToString:@"phoneSizeChange"]){/*分辨率改变*/
  554. // if ([[dataDict allKeys] containsObject:@"data"]) {
  555. // NSDictionary *data = dataDict[@"data"];
  556. // if ([[data allKeys] containsObject:@"width"]) {
  557. // ksharedAppDelegate.couldPhone_W_PHONE = [[data objectForKey:@"width"] integerValue];
  558. // }
  559. // if ([[data allKeys] containsObject:@"height"]) {
  560. // ksharedAppDelegate.couldPhone_H_PHONE = [[data objectForKey:@"height"] integerValue];
  561. // }
  562. //
  563. // if (ksharedAppDelegate.couldPhone_W_PHONE > ksharedAppDelegate.couldPhone_H_PHONE) {
  564. // CGFloat temp = ksharedAppDelegate.couldPhone_W_PHONE;
  565. // ksharedAppDelegate.couldPhone_W_PHONE = ksharedAppDelegate.couldPhone_H_PHONE;
  566. // ksharedAppDelegate.couldPhone_H_PHONE = temp;
  567. // }
  568. // }
  569. // }
  570. // }
  571. else if ([messageType isEqualToString:@"getPhoneSize"] || [messageType isEqualToString:@"setPhoneSize"]){
  572. //NSString *sn = nil;
  573. if([messageType isEqualToString:@"setPhoneSize"]){
  574. self.isDiDChangePhoneSizeType = YES;
  575. }
  576. if ([[dataDict allKeys] containsObject:@"data"]) {
  577. NSDictionary *data = dataDict[@"data"];
  578. if ([[data allKeys] containsObject:@"status"]) {
  579. NSInteger status = [[data objectForKey:@"status"] integerValue];
  580. if (status == 0) {/*不是当前设备直接返回*/
  581. if ([[data allKeys] containsObject:@"width"]) {
  582. ksharedAppDelegate.couldPhone_W_PHONE = [[data objectForKey:@"width"] integerValue];
  583. }
  584. if ([[data allKeys] containsObject:@"height"]) {
  585. ksharedAppDelegate.couldPhone_H_PHONE = [[data objectForKey:@"height"] integerValue];
  586. }
  587. if (ksharedAppDelegate.couldPhone_W_PHONE > ksharedAppDelegate.couldPhone_H_PHONE) {
  588. CGFloat temp = ksharedAppDelegate.couldPhone_W_PHONE;
  589. ksharedAppDelegate.couldPhone_W_PHONE = ksharedAppDelegate.couldPhone_H_PHONE;
  590. ksharedAppDelegate.couldPhone_H_PHONE = temp;
  591. }
  592. }
  593. }
  594. }
  595. }
  596. // else if ([messageType isEqualToString:@"sync_wifi"]){
  597. // [weakSelf sync_wifiBackHandleFun];
  598. // }
  599. // else if ([messageType isEqualToString:@"reProduceText"]){
  600. // if ([[dataDict allKeys] containsObject:@"data"]) {
  601. // NSDictionary *data = dataDict[@"data"];
  602. //
  603. // if ([[data allKeys] containsObject:@"text"]) {
  604. // NSString *pasteboardStr = [data objectForKey:@"text"];
  605. // UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
  606. // pasteboard.string = pasteboardStr;
  607. // }
  608. // }
  609. // }
  610. // else if ([messageType isEqualToString:@"downAdnInstallRep"]){
  611. // if ([[dataDict allKeys] containsObject:@"data"]) {
  612. // NSDictionary *data = dataDict[@"data"];
  613. //
  614. // if ([[data allKeys] containsObject:@"status"]) {
  615. // NSString *status = [data objectForKey:@"status"];
  616. // if ([status isEqualToString:@"1"]) {
  617. // mainBlock(^{
  618. // // [[iToast makeText:@"App下载完成"] show];
  619. // });
  620. // }else if ([status isEqualToString:@"0"]){
  621. // mainBlock(^{
  622. // //[[iToast makeText:@"App下载中"] show];
  623. // });
  624. // }
  625. // }
  626. // }
  627. // }
  628. // else if ([messageType isEqualToString:@"shakeit"]){
  629. // HLog(@"\n-----摇一摇成功------");
  630. // }else if ([messageType isEqualToString:@"keyboardFeedbackBean"]){/*调起键盘*/
  631. // HLog(@"\n-----待处理 调起键盘------");
  632. // // [weakSelf keyboardFeedbackBeanFun];
  633. // }else if ([messageType isEqualToString:@"FileRandomReady"]
  634. // ||[messageType isEqualToString:@"FilePartReady"]
  635. // ){/*申请文件上传得到答复*/
  636. // [weakSelf applyUploadFileServiceResponseFun:dataDict];
  637. // }
  638. // else if ([messageType isEqualToString:@"uploadFileRandomRet"]
  639. // ||[messageType isEqualToString:@"uploadFilePartRet"]
  640. // ){/*文件上传得到答复*/
  641. // [weakSelf upLoadFileFunServiceResponseFun:dataDict];
  642. // }
  643. // else if ([messageType isEqualToString:@"backUpFileRandomReady"]
  644. // ||[messageType isEqualToString:@"backUpPartReady"]
  645. // ){/*文件备份得到答复*/
  646. // [weakSelf applyBackupsFileServiceResponseFun:dataDict];
  647. // }
  648. // else if ([messageType isEqualToString:@"backUpFileRandomRet"]
  649. // ||[messageType isEqualToString:@"backUpFilePartRet"]){/*文件备份得到答复*/
  650. // [weakSelf backupsFileFunServiceResponseFun:dataDict];
  651. // }
  652. else if ([messageType isEqualToString:@"getBaseInfo"]){/*获取云机的基本信息*/
  653. [self getCouldPhoneBaseInfoResponseFun:dataDict];
  654. }
  655. else if ([messageType isEqualToString:@"getSysInfo"]){/*获取云机的系统信息*/
  656. [self getCouldPhoneSysInfoResponseFun:dataDict];
  657. }
  658. else if ([messageType isEqualToString:@"TvStatus"]){/*获取TV投屏信息*/
  659. [self getCouldPhoneTvStatusResponseFun:dataDict];
  660. }
  661. else if ([messageType isEqualToString:@"TvOff"]){/*关闭TV投屏*/
  662. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  663. [self getTvStatusFun];
  664. });
  665. }
  666. else if ([messageType isEqualToString:@"wakeupTV"]){/*开启TV投屏*/
  667. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  668. [self getTvStatusFun];
  669. });
  670. }
  671. else if ([messageType isEqualToString:@"reboot"]){/*重启*/
  672. //[weakSelf stopForceStartTimerFun];
  673. }
  674. else if ([messageType isEqualToString:@"mkdir"]){/*创建文件夹*/
  675. [self createFolderResponseFun:dataDict];
  676. }
  677. else if ([messageType isEqualToString:@"getBackupPath"]){/*创建文件夹*/
  678. [self getFolderListResponseFun:dataDict];
  679. }
  680. else if ([messageType isEqualToString:@"search"]){/*创建文件夹*/
  681. [self searchFileListResponseFun:dataDict];
  682. }
  683. else if ([messageType isEqualToString:@"getExtraFiles"]){/*获取云机产品信息*/
  684. [self getExtraFilesResponseFun:dataDict];
  685. }
  686. else if ([messageType isEqualToString:@"extraMediaEvent"]){/*磁盘插拔*/
  687. [self getExtraMediaEventResponseFun:dataDict];
  688. [self getExtraFilesListFun];
  689. }
  690. else if ([messageType isEqualToString:@"reset"]){/**/
  691. [self deleteCommandSendTaskFunWith:@"reset"];
  692. }
  693. }
  694. #pragma mark WebRTC 回调 MediaStreamClientEventsDelegate
  695. #pragma mark 不能再这里函数判断 这个是推拉流的
  696. -(void)onChangeConnectionStateFromPeerName:(NSString*)peerName didChangeIceConnectionState:(RTCIceConnectionState)state
  697. {
  698. HLog(@"channel P2P onChangeConnectionStateFromPeerName: state:%ld",state)
  699. self.ConnectionState = state;
  700. switch (state) {
  701. case RTCIceConnectionStateConnected:{
  702. //链接成功
  703. }
  704. break;
  705. case RTCIceConnectionStateCompleted:
  706. //链接完成
  707. break;
  708. case RTCIceConnectionStateFailed:
  709. case RTCIceConnectionStateDisconnected:
  710. case RTCIceConnectionStateClosed:
  711. //链接关闭
  712. [self relinkWebRtcFun];
  713. break;
  714. default:
  715. break;
  716. }
  717. }
  718. #pragma mark 通道连接状态变化监听
  719. - (void)dataChannelDidChangeFromPeerName:(NSString*)peerName State:(RTCDataChannelState)state
  720. {
  721. HLog(@"webRtc P2P dataChannelDidChangeFromPeerName: state:%ld",state)
  722. self.channelState = state;
  723. switch (state) {
  724. case RTCDataChannelStateConnecting:
  725. {
  726. }
  727. break;
  728. case RTCDataChannelStateOpen:
  729. {
  730. //链接成功
  731. [self handlAllMsgAfterDidLinkFun];
  732. }
  733. break;
  734. case RTCDataChannelStateClosing:
  735. {
  736. }
  737. break;
  738. case RTCDataChannelStateClosed:
  739. {
  740. //链接断开
  741. [self relinkWebRtcFun];
  742. }
  743. break;
  744. default:
  745. break;
  746. }
  747. }
  748. -(void)onChannelDataFromPeerName:(NSString*)peerName buffer:(RTC_OBJC_TYPE(RTCDataBuffer) *)buffer
  749. {
  750. //HLog(@"onIceConnectedFromPeerName:%@",buffer.data);
  751. if(buffer && buffer.data){
  752. KWeakSelf
  753. mainBlock(^{
  754. [weakSelf handleWebRtcMsgResponseBy:buffer.data];
  755. });
  756. }
  757. }
  758. -(void)didGetStats:(NSString*)peerName stats:(RTC_OBJC_TYPE(RTCStatisticsReport) *)stats
  759. {
  760. //HLog(@"didGetStats:%@",stats)
  761. if(!_needToReportWebRtcType){
  762. [self reportWebRtcRePoportTypeIsChannel:YES withStats:stats];
  763. _needToReportWebRtcType = YES;
  764. [_mediaStream setShouldGetStats:NO];
  765. }
  766. }
  767. -(void)onAuthResultFromPeerName:(NSString*)peerName code:(int)code descriptions:(NSString*)descriptions
  768. {
  769. HLog(@"webRtc P2P onAuthResultFromPeerName")
  770. }
  771. @end