webSocketManager+downloadFile.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. //
  2. // webSocketManager+downloadFile.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/6/20.
  6. //
  7. #import "webSocketManager+downloadFile.h"
  8. #import "cachesFileManager.h"
  9. #import "downloadManager.h"
  10. @implementation webSocketManager (downloadFile)
  11. - (void)begindownloadFileFunBy:(couldPhoneFileModel *)couldPhoneFileMod
  12. {
  13. self.curDownloadFileModel = couldPhoneFileMod;
  14. if(!self.curDownloadFileModel
  15. || ![self.curDownloadFileModel isKindOfClass:[couldPhoneFileModel class]]){
  16. return;
  17. }
  18. [self ApplyDownloadFileFun];
  19. }
  20. #pragma mark 申请下载缩略图
  21. - (void)ApplyDownloadFileFun
  22. {
  23. self.downloadFileTaskUid = [iTools getTaskUidStr];
  24. if([self.downloadFileTaskUid isEqualToString:self.backupsTaskUid]
  25. ||[self.downloadFileTaskUid isEqualToString:self.taskUid]
  26. ||[self.downloadFileTaskUid isEqualToString:self.downloadThumbnailTaskUid])
  27. {//重新生成taskUid
  28. [self ApplyDownloadFileFun];
  29. return;
  30. }
  31. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  32. NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
  33. long didDownloadBytes = 0;
  34. NSFileManager *manager0 = [NSFileManager defaultManager];
  35. if([manager0 fileExistsAtPath:pathStr]) {
  36. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:pathStr]; // 创建文件句柄
  37. if (fileHandle) {
  38. didDownloadBytes = [fileHandle seekToEndOfFile];
  39. // 关闭文件句柄
  40. [fileHandle closeFile];
  41. }
  42. }
  43. NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes];
  44. //[self.commandChannelManager rc_sendData:commandStr];
  45. }
  46. - (void)downloadFileFunServiceResponseFun:(NSData *)fileData with:(BOOL)isDownloadDone
  47. {
  48. if(isDownloadDone){
  49. [self handleDownloadDoneFun];
  50. return;
  51. }
  52. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  53. NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
  54. NSFileManager *manager0 = [NSFileManager defaultManager];
  55. long long endOfFile = 0;
  56. if(![manager0 fileExistsAtPath:pathStr]) {
  57. [cachesFileManager getFileNameWithContent:fileData fileName:fileName type:DownLoadFileType];
  58. }
  59. else{
  60. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:pathStr]; // 创建文件句柄
  61. if (fileHandle) {
  62. endOfFile = [fileHandle seekToEndOfFile];
  63. if (endOfFile >= 0) {
  64. if(endOfFile == self.curDownloadFileModel.didDownloadBytes){
  65. [fileHandle writeData:fileData];
  66. }
  67. }
  68. endOfFile = [fileHandle seekToEndOfFile];
  69. // 关闭文件句柄
  70. [fileHandle closeFile];
  71. }
  72. }
  73. long didDownloadBytes = fileData.length;
  74. if(endOfFile > 0){
  75. didDownloadBytes = endOfFile;
  76. }
  77. self.curDownloadFileModel.didDownloadBytes = didDownloadBytes;
  78. // if(isDownloadDone || endOfFile == self.curDownloadFileModel.length){
  79. // [self handleDownloadDoneFun];
  80. // }
  81. // else
  82. {//获取下一片
  83. [[downloadManager shareInstance] DownloadFileChangeingOneFileFun];
  84. if([downloadManager shareInstance].isSuspendType){
  85. return;
  86. }
  87. BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)];
  88. if(!isCanUseCellular){//不允许流量上传
  89. //
  90. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
  91. [[downloadManager shareInstance] suspendDownloadFileFun:YES withModel:nil];
  92. mainBlock(^{
  93. [[NSNotificationCenter defaultCenter] postNotificationName:downloadFileSuspendAllNotification object:nil];
  94. [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show];
  95. });
  96. return;
  97. }
  98. }
  99. NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes];
  100. //[self.commandChannelManager rc_sendData:commandStr];
  101. }
  102. }
  103. - (void)handleDownloadDoneFun
  104. {
  105. if(self.nasFullPath && self.nasFullPath.length >0){
  106. HLog(@"前面一个保存流程没走完")
  107. return;
  108. }
  109. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  110. NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
  111. if([self.curDownloadFileModel.fileType containsString:@"jpg"]){
  112. if([iTools canSaveFileToAlbumByPhoto:YES withName:fileName]){
  113. UIImage *image = [UIImage imageWithContentsOfFile:pathStr];
  114. if(image){
  115. [self loadImageFinished:image];
  116. }
  117. else{
  118. [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  119. [[downloadManager shareInstance] DownloadFileFailOneFileFun];
  120. }
  121. }
  122. else{
  123. [self loadOtherDataFinished];
  124. }
  125. }
  126. else if([self.curDownloadFileModel.fileType isEqualToString:@"video"]){
  127. if([iTools canSaveFileToAlbumByPhoto:NO withName:fileName]){
  128. [self loadVideoFinished];
  129. }
  130. else{
  131. [self loadOtherDataFinished];
  132. }
  133. }
  134. else
  135. {
  136. [self loadOtherDataFinished];
  137. }
  138. }
  139. - (void)loadImageFinished:(UIImage *)image
  140. {
  141. [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  142. //写入图片到相册
  143. PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
  144. } completionHandler:^(BOOL success, NSError * _Nullable error) {
  145. //NSLog(@"success = %d, error = %@", success, error);
  146. if (success) {
  147. HLog(@"已将图片保存至相册");
  148. //NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  149. //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  150. } else {
  151. HLog(@"未能将图片保存至相册");
  152. // mainBlock(^{
  153. // [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show];
  154. // });
  155. }
  156. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  157. [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  158. [[downloadManager shareInstance] DownloadFileDoneOneFileFun];
  159. }];
  160. }
  161. - (void)loadVideoFinished
  162. {
  163. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  164. NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
  165. PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
  166. [photoLibrary performChanges:^{
  167. [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL
  168. fileURLWithPath:pathStr]];
  169. } completionHandler:^(BOOL success, NSError * _Nullable error) {
  170. if (success) {
  171. HLog(@"已将视频保存至相册");
  172. //NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  173. //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  174. } else {
  175. HLog(@"未能将视频保存至相册");
  176. }
  177. [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  178. [[downloadManager shareInstance] DownloadFileDoneOneFileFun];
  179. }];
  180. }
  181. //下载音频 文件等
  182. - (void)loadOtherDataFinished
  183. {
  184. [[downloadManager shareInstance] DownloadFileDoneOneFileFun];
  185. NSString *fileName = [self.curDownloadFileModel getFileNameFun];
  186. NSString*filePath = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
  187. [self saveDownDoneFileToPhoneFunBy:filePath withKey:self.curDownloadFileModel.path];
  188. }
  189. #pragma mark 处理保存操作
  190. - (void)saveDownDoneFileToPhoneFunBy:(NSString*)filePath withKey:(NSString *)key{
  191. if (self.isShowingFileDocumentPickerType) {
  192. HLog(@"上一个任务保存到问题---没保存完");
  193. return;
  194. }
  195. if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
  196. HLog(@"没有找到文件:%@",filePath);
  197. return;
  198. }
  199. self.wsDownloadSaveFilePath = filePath;
  200. self.wsDownloadDonwPlishPath = key;
  201. NSURL * fileURL = [NSURL fileURLWithPath:filePath];
  202. UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:fileURL inMode:UIDocumentPickerModeExportToService];
  203. // 设置代理
  204. documentPickerVC.delegate = self;
  205. // 设置模态弹出方式
  206. documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
  207. //[self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
  208. [ksharedAppDelegate.window.rootViewController presentViewController:documentPickerVC animated:YES completion:nil];
  209. self.isShowingFileDocumentPickerType = YES;
  210. }
  211. #pragma mark - UIDocumentPickerDelegate
  212. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
  213. // 获取授权
  214. BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
  215. if (fileUrlAuthozied) {
  216. // 通过文件协调工具来得到新的文件地址,以此得到文件保护功能
  217. NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
  218. NSError *error;
  219. [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
  220. // 读取文件
  221. NSString *fileName = [newURL lastPathComponent];
  222. NSError *error = nil;
  223. //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
  224. if (error) {
  225. // 读取出错
  226. if(self.nasFullPath){
  227. self.nasFullPath = nil;
  228. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  229. [self checkSaveNasFileAgainFun];
  230. });
  231. }
  232. else{
  233. self.wsDownloadSaveFilePath = nil;
  234. self.wsDownloadDonwPlishPath = nil;
  235. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  236. [self checkSaveWebsocketFileAgainFun];
  237. });
  238. }
  239. } else {
  240. NSLog(@"222 fileName : %@", fileName);
  241. if(!self.nasFullPath){
  242. // websock下载流程
  243. [[NSFileManager defaultManager] removeItemAtPath:self.wsDownloadSaveFilePath error:nil];
  244. //[cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
  245. [[downloadManager shareInstance] deleteDownloadDonePlistInfoBy:self.wsDownloadDonwPlishPath];
  246. self.wsDownloadSaveFilePath = nil;
  247. self.wsDownloadDonwPlishPath = nil;
  248. [self checkSaveWebsocketFileAgainFun];
  249. }
  250. else{
  251. //nas下载流程
  252. [[NSFileManager defaultManager] removeItemAtPath:self.nasFullPath error:nil];
  253. [[boxDownloadFileManager shareInstance] deleteDownloadDonePlistInfoBy:self.nasFullPath];
  254. self.nasFullPath = nil;
  255. [self checkSaveNasFileAgainFun];
  256. }
  257. }
  258. self.isShowingFileDocumentPickerType = NO;
  259. }];
  260. [urls.firstObject stopAccessingSecurityScopedResource];
  261. } else {
  262. // 授权失败
  263. if(self.nasFullPath){
  264. self.nasFullPath = nil;
  265. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  266. [self checkSaveNasFileAgainFun];
  267. });
  268. }
  269. else{
  270. self.wsDownloadSaveFilePath = nil;
  271. self.wsDownloadDonwPlishPath = nil;
  272. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  273. [self checkSaveWebsocketFileAgainFun];
  274. });
  275. }
  276. self.isShowingFileDocumentPickerType = NO;
  277. }
  278. }
  279. #pragma mark 再次读取下载完成数据做保存操作
  280. - (void)checkSaveNasFileAgainFun
  281. {
  282. [[boxDownloadFileManager shareInstance] checkDownloadDonePlistInfoFun];
  283. [[nasDownloadFileManager shareInstance] checkDownloadDonePlistInfoFun];
  284. }
  285. #pragma mark 再次读取ws下载完成数据做保存操作
  286. - (void)checkSaveWebsocketFileAgainFun
  287. {
  288. [[downloadManager shareInstance] checkDownloadDonePlistInfoFun];
  289. }
  290. @end