// // webSocketManager+downloadFile.m // 双子星云手机 // // Created by xd h on 2024/6/20. // #import "webSocketManager+downloadFile.h" #import "cachesFileManager.h" #import "downloadManager.h" @implementation webSocketManager (downloadFile) - (void)begindownloadFileFunBy:(couldPhoneFileModel *)couldPhoneFileMod { self.curDownloadFileModel = couldPhoneFileMod; if(!self.curDownloadFileModel || ![self.curDownloadFileModel isKindOfClass:[couldPhoneFileModel class]]){ return; } [self ApplyDownloadFileFun]; } #pragma mark 申请下载缩略图 - (void)ApplyDownloadFileFun { self.downloadFileTaskUid = [iTools getTaskUidStr]; if([self.downloadFileTaskUid isEqualToString:self.backupsTaskUid] ||[self.downloadFileTaskUid isEqualToString:self.taskUid] ||[self.downloadFileTaskUid isEqualToString:self.downloadThumbnailTaskUid]) {//重新生成taskUid [self ApplyDownloadFileFun]; return; } NSString *fileName = [self.curDownloadFileModel getFileNameFun]; NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType]; long didDownloadBytes = 0; NSFileManager *manager0 = [NSFileManager defaultManager]; if([manager0 fileExistsAtPath:pathStr]) { NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:pathStr]; // 创建文件句柄 if (fileHandle) { didDownloadBytes = [fileHandle seekToEndOfFile]; // 关闭文件句柄 [fileHandle closeFile]; } } NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes]; [self.commandChannelManager rc_sendData:commandStr]; } - (void)downloadFileFunServiceResponseFun:(NSData *)fileData with:(BOOL)isDownloadDone { if(isDownloadDone){ [self handleDownloadDoneFun]; return; } NSString *fileName = [self.curDownloadFileModel getFileNameFun]; NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType]; NSFileManager *manager0 = [NSFileManager defaultManager]; long long endOfFile = 0; if(![manager0 fileExistsAtPath:pathStr]) { [cachesFileManager getFileNameWithContent:fileData fileName:fileName type:DownLoadFileType]; } else{ NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:pathStr]; // 创建文件句柄 if (fileHandle) { endOfFile = [fileHandle seekToEndOfFile]; if (endOfFile >= 0) { if(endOfFile == self.curDownloadFileModel.didDownloadBytes){ [fileHandle writeData:fileData]; } } endOfFile = [fileHandle seekToEndOfFile]; // 关闭文件句柄 [fileHandle closeFile]; } } long didDownloadBytes = fileData.length; if(endOfFile > 0){ didDownloadBytes = endOfFile; } self.curDownloadFileModel.didDownloadBytes = didDownloadBytes; // if(isDownloadDone || endOfFile == self.curDownloadFileModel.length){ // [self handleDownloadDoneFun]; // } // else {//获取下一片 [[downloadManager shareInstance] DownloadFileChangeingOneFileFun]; if([downloadManager shareInstance].isSuspendType){ return; } BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)]; if(!isCanUseCellular){//不允许流量上传 // if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){ [[downloadManager shareInstance] suspendDownloadFileFun:YES withModel:nil]; mainBlock(^{ [[NSNotificationCenter defaultCenter] postNotificationName:downloadFileSuspendAllNotification object:nil]; [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show]; }); return; } } NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes]; [self.commandChannelManager rc_sendData:commandStr]; } } - (void)handleDownloadDoneFun { if(self.nasFullPath && self.nasFullPath.length >0){ HLog(@"前面一个保存流程没走完") return; } NSString *fileName = [self.curDownloadFileModel getFileNameFun]; NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType]; if([self.curDownloadFileModel.fileType containsString:@"jpg"]){ if([iTools canSaveFileToAlbumByPhoto:YES withName:fileName]){ UIImage *image = [UIImage imageWithContentsOfFile:pathStr]; if(image){ [self loadImageFinished:image]; } else{ [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; [[downloadManager shareInstance] DownloadFileFailOneFileFun]; } } else{ [self loadOtherDataFinished]; } } else if([self.curDownloadFileModel.fileType isEqualToString:@"video"]){ if([iTools canSaveFileToAlbumByPhoto:NO withName:fileName]){ [self loadVideoFinished]; } else{ [self loadOtherDataFinished]; } } else { [self loadOtherDataFinished]; } } - (void)loadImageFinished:(UIImage *)image { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ //写入图片到相册 PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; } completionHandler:^(BOOL success, NSError * _Nullable error) { //NSLog(@"success = %d, error = %@", success, error); if (success) { HLog(@"已将图片保存至相册"); //NSString *fileName = [self.curDownloadFileModel getFileNameFun]; //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; } else { HLog(@"未能将图片保存至相册"); // mainBlock(^{ // [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show]; // }); } NSString *fileName = [self.curDownloadFileModel getFileNameFun]; [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; [[downloadManager shareInstance] DownloadFileDoneOneFileFun]; }]; } - (void)loadVideoFinished { NSString *fileName = [self.curDownloadFileModel getFileNameFun]; NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType]; PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary]; [photoLibrary performChanges:^{ [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:pathStr]]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if (success) { HLog(@"已将视频保存至相册"); //NSString *fileName = [self.curDownloadFileModel getFileNameFun]; //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; } else { HLog(@"未能将视频保存至相册"); } [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; [[downloadManager shareInstance] DownloadFileDoneOneFileFun]; }]; } //下载音频 文件等 - (void)loadOtherDataFinished { [[downloadManager shareInstance] DownloadFileDoneOneFileFun]; NSString *fileName = [self.curDownloadFileModel getFileNameFun]; NSString*filePath = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType]; [self saveDownDoneFileToPhoneFunBy:filePath withKey:self.curDownloadFileModel.path]; } #pragma mark 处理保存操作 - (void)saveDownDoneFileToPhoneFunBy:(NSString*)filePath withKey:(NSString *)key{ if (self.isShowingFileDocumentPickerType) { HLog(@"上一个任务保存到问题---没保存完"); return; } if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){ HLog(@"没有找到文件:%@",filePath); return; } self.wsDownloadSaveFilePath = filePath; self.wsDownloadDonwPlishPath = key; NSURL * fileURL = [NSURL fileURLWithPath:filePath]; UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:fileURL inMode:UIDocumentPickerModeExportToService]; // 设置代理 documentPickerVC.delegate = self; // 设置模态弹出方式 documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet; //[self.navigationController presentViewController:documentPickerVC animated:YES completion:nil]; [ksharedAppDelegate.window.rootViewController presentViewController:documentPickerVC animated:YES completion:nil]; self.isShowingFileDocumentPickerType = YES; } #pragma mark - UIDocumentPickerDelegate - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray *)urls { // 获取授权 BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource]; if (fileUrlAuthozied) { // 通过文件协调工具来得到新的文件地址,以此得到文件保护功能 NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init]; NSError *error; [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) { // 读取文件 NSString *fileName = [newURL lastPathComponent]; NSError *error = nil; //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error]; if (error) { // 读取出错 if(self.nasFullPath){ self.nasFullPath = nil; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self checkSaveNasFileAgainFun]; }); } else{ self.wsDownloadSaveFilePath = nil; self.wsDownloadDonwPlishPath = nil; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self checkSaveWebsocketFileAgainFun]; }); } } else { NSLog(@"222 fileName : %@", fileName); if(!self.nasFullPath){ // websock下载流程 [[NSFileManager defaultManager] removeItemAtPath:self.wsDownloadSaveFilePath error:nil]; //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil]; [[downloadManager shareInstance] deleteDownloadDonePlistInfoBy:self.wsDownloadDonwPlishPath]; self.wsDownloadSaveFilePath = nil; self.wsDownloadDonwPlishPath = nil; [self checkSaveWebsocketFileAgainFun]; } else{ //nas下载流程 [[NSFileManager defaultManager] removeItemAtPath:self.nasFullPath error:nil]; [[boxDownloadFileManager shareInstance] deleteDownloadDonePlistInfoBy:self.nasFullPath]; self.nasFullPath = nil; [self checkSaveNasFileAgainFun]; } } self.isShowingFileDocumentPickerType = NO; }]; [urls.firstObject stopAccessingSecurityScopedResource]; } else { // 授权失败 if(self.nasFullPath){ self.nasFullPath = nil; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self checkSaveNasFileAgainFun]; }); } else{ self.wsDownloadSaveFilePath = nil; self.wsDownloadDonwPlishPath = nil; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self checkSaveWebsocketFileAgainFun]; }); } self.isShowingFileDocumentPickerType = NO; } } #pragma mark 再次读取下载完成数据做保存操作 - (void)checkSaveNasFileAgainFun { [[boxDownloadFileManager shareInstance] checkDownloadDonePlistInfoFun]; [[nasDownloadFileManager shareInstance] checkDownloadDonePlistInfoFun]; } #pragma mark 再次读取ws下载完成数据做保存操作 - (void)checkSaveWebsocketFileAgainFun { [[downloadManager shareInstance] checkDownloadDonePlistInfoFun]; } @end