webRtcManager.m 44 KB

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