webRtcManager.m 35 KB

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