nasMixBackupsManager.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. //
  2. // nasMixBackupsManager.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/8/30.
  6. //
  7. #import "nasMixBackupsManager.h"
  8. #import "customUploadOperation.h"
  9. #import "nasUploadFileManager.h"
  10. #import "frpFileExistModel.h"
  11. #import "frpUploadModel.h"
  12. #define Kboundary3 @"Boundaryhxd"
  13. @interface nasMixBackupsManager ()<NSURLSessionDataDelegate>
  14. //排队等候下载的上传地址数组
  15. @property(nonatomic,strong) NSMutableArray *uploadWaitingUrlArr;
  16. //正在下载的上传地址数组
  17. @property(nonatomic,strong) NSMutableArray *uploadingOperationArr;
  18. @property(nonatomic,assign) NSInteger speedShowCount;//内网的情况 多少次才刷新一次
  19. @end
  20. @implementation nasMixBackupsManager
  21. + (instancetype)shareManager {
  22. static nasMixUploadManager *_instance;
  23. static dispatch_once_t onceToken;
  24. dispatch_once(&onceToken, ^{
  25. _instance = [[self alloc] init];
  26. });
  27. return _instance;
  28. }
  29. - (instancetype)init {
  30. if (self = [super init]) {
  31. _maxUploadLoadCount = 1;
  32. if ([pingManager shareManager].isPingOk)
  33. {
  34. _speedShowCount = 3;
  35. }
  36. else{
  37. _speedShowCount = 0;
  38. }
  39. //[self registeNotification];
  40. }
  41. return self;
  42. }
  43. /** 添加要上传的 模型 */
  44. - (void)addBackupsWithModels:(NSArray *)fileModels{
  45. HLog(@"添加备份任务-- %ld",fileModels.count)
  46. for (uploadFileDataModel *model in fileModels) {
  47. BOOL needAddType = YES;
  48. //1. 排查上传中
  49. for (customUploadOperation *operationDoing in self.uploadingOperationArr) {
  50. if([operationDoing.fileModel.filename isEqualToString:model.filename]){
  51. needAddType = NO;
  52. break;
  53. }
  54. }
  55. //1. 排查等待下载
  56. for (uploadFileDataModel *waitModel in self.uploadWaitingUrlArr) {
  57. if([waitModel.filename isEqualToString:model.filename]){
  58. needAddType = NO;
  59. break;
  60. }
  61. }
  62. if(needAddType){
  63. [self.uploadWaitingUrlArr addObject:model];
  64. }
  65. }
  66. //启动上传
  67. [self beginUpload];
  68. }
  69. //在添加XX后 启动下载
  70. - (void)beginUpload
  71. {
  72. BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)];
  73. if(!isCanUseCellular){//不允许流量上传
  74. //
  75. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
  76. mainBlock(^{
  77. [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileSuspendAllNotification object:nil];
  78. [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show];
  79. });
  80. return;
  81. }
  82. }
  83. if(ksharedAppDelegate.DisabledFileTransferType){
  84. if(ksharedAppDelegate.isImageNewFor130){
  85. [[iToast makeText:NSLocalizedString(@"File_Transfer_Disable_tip",nil)] show];
  86. }
  87. else{
  88. [[iToast makeText:NSLocalizedString(@"File_Transfer_Disable_tip2",nil)] show];
  89. }
  90. return;
  91. }
  92. @synchronized (self) {
  93. if(self.uploadingOperationArr.count == _maxUploadLoadCount){
  94. HLog(@"正在上传的数量达到了最大值 %ld",_maxUploadLoadCount)
  95. return;
  96. }
  97. if(self.uploadWaitingUrlArr.count == 0){
  98. HLog(@"没有等待中的上传任务")
  99. return;
  100. }
  101. NSInteger canAddTaskNumber = _maxUploadLoadCount - self.uploadingOperationArr.count;
  102. for (int i=0; i<canAddTaskNumber; i++) {
  103. if(self.uploadWaitingUrlArr.count >= 1){
  104. //创建上传任务
  105. uploadFileDataModel *WaitingModel = self.uploadWaitingUrlArr.firstObject;
  106. __block customUploadOperation * operation = [customUploadOperation new];
  107. operation.fileModel = WaitingModel;
  108. //等待下载中的任务
  109. [self.uploadWaitingUrlArr removeObjectAtIndex:0];
  110. //添加到下载中数组
  111. [self.uploadingOperationArr addObject:operation];
  112. [self checkFileUploadStateWithOperation:operation];
  113. //[weakSelf handleTaskDidUploadWith:operation withState:state];
  114. }
  115. }
  116. }
  117. }
  118. #pragma mark 检测文件是否上传过了
  119. - (void)checkFileUploadStateWithOperation:(customUploadOperation*)operation
  120. {
  121. NSMutableDictionary*paraDict = [NSMutableDictionary new];
  122. if(operation.fileModel.savePath){
  123. NSString *absPath = [[NSString alloc] initWithFormat:@"%@%@",operation.fileModel.savePath,operation.fileModel.filename];
  124. [paraDict setValue:absPath forKey:@"absPath"];
  125. NSNumber *totalBytesNumber = [NSNumber numberWithLong:operation.fileModel.totalBytes];
  126. [paraDict setValue:totalBytesNumber forKey:@"fileSize"];
  127. }
  128. KWeakSelf
  129. [[netWorkManager shareInstance] cloudPhoneGETCallBackCode:@"isFileExist" Parameters:paraDict success:^(id _Nonnull responseObject) {
  130. frpFileExistModel *model = [[frpFileExistModel alloc] initWithDictionary:responseObject error:nil];
  131. if(model && model.status == 0){
  132. [weakSelf checkFileUploadStateFunAfterNetWith:model WithOperation:operation];
  133. }
  134. else{
  135. [weakSelf handleUploadFailOneFileBy:operation];
  136. //FileExistRet(-1);
  137. }
  138. } failure:^(NSError * _Nonnull error) {
  139. HLog(@"%@",error)
  140. //FileExistRet(-1);
  141. [weakSelf handleUploadFailOneFileBy:operation];
  142. }];
  143. }
  144. #pragma mark 检测分家是否存在后处理 是否要上传
  145. - (void)checkFileUploadStateFunAfterNetWith:(frpFileExistModel*)model WithOperation:(customUploadOperation*)operation
  146. {
  147. if(!model){
  148. [self handleUploadFailOneFileBy:operation];
  149. return;
  150. }
  151. operation.fileModel.didUploadBytes = 0;
  152. operation.fileModel.taskId = model.data.fileTaskId;
  153. if(!model.data.exist){//未上传过
  154. [self prepareToUploadFileWithOperation:operation];
  155. }
  156. else if(model.data.isComplete){//上传过了 并且文件上传完了
  157. //判断下文件创建长度是否一致 一致则是上传完了 不一致 重新上传一个 可能是同名的文件而已
  158. if(model.data.size >= operation.fileModel.totalBytes){//上传完了
  159. // mainBlock(^{
  160. // [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  161. // });
  162. [self handleUploadDoneOneFileBy:operation];
  163. }
  164. else{//未上传完 isComplete 这个字段有问题
  165. operation.fileModel.didUploadBytes = model.data.size;
  166. [self prepareToUploadFileWithOperation:operation];
  167. }
  168. }
  169. else{//上传过了 未上传完成
  170. operation.fileModel.didUploadBytes = model.data.size;
  171. [self prepareToUploadFileWithOperation:operation];
  172. }
  173. }
  174. #pragma mark 处理任务失败
  175. #pragma mark 准备上传文件
  176. - (void)prepareToUploadFileWithOperation:(customUploadOperation*)operation
  177. {
  178. NSMutableDictionary *paraDict = [NSMutableDictionary new];
  179. NSString* taskUid = operation.fileModel.taskId;
  180. if(!taskUid || taskUid.length == 0){
  181. taskUid = [iTools getTaskUidStr];
  182. operation.fileModel.taskId = taskUid;
  183. }
  184. [paraDict setObject:taskUid forKey:@"taskId"];
  185. [paraDict setObject:@0 forKey:@"position"];
  186. [paraDict setObject:@"true" forKey:@"isLast"];
  187. if(operation.fileModel.savePath){
  188. [paraDict setObject:operation.fileModel.savePath forKey:@"savePath"];
  189. }
  190. else{
  191. HLog(@"获取保存路径失败")
  192. return;
  193. }
  194. if(operation.fileModel.filename){
  195. [paraDict setObject:operation.fileModel.filename forKey:@"filename"];
  196. }
  197. else{
  198. HLog(@"获取用户名失败")
  199. return;
  200. }
  201. KWeakSelf
  202. if(operation.fileModel.curUploadFileType == uploadFileTypeImage){
  203. [paraDict setObject:@1 forKey:@"imageType"];
  204. if(!operation.fileModel.imageData){
  205. NSString*pathStr = [cachesFileManager getFilePathWithName:operation.fileModel.filename type:operation.fileModel.curUploadFileType];
  206. NSData *imageData = [NSData dataWithContentsOfFile:pathStr];
  207. if (!imageData) {
  208. if(!operation.fileModel.asset){
  209. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  210. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  211. PHAsset *asset = fetchResult.firstObject;
  212. operation.fileModel.asset = asset;
  213. }
  214. [[PHImageManager defaultManager] requestImageDataForAsset:operation.fileModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
  215. // 直接得到最终的 NSData 数据
  216. if (imageData) {
  217. operation.fileModel.imageData = imageData;
  218. [weakSelf afterGetImageDataFunWithOperation:operation];
  219. }
  220. else{
  221. [weakSelf handleUploadFailOneFileBy:operation];
  222. }
  223. }];
  224. return;
  225. }
  226. operation.fileModel.imageData = imageData;
  227. }
  228. NSData *curData = operation.fileModel.imageData;
  229. operation.onceDataLengt = [curData length];
  230. [self startUpload:paraDict operation:operation data:curData success:^(id _Nonnull responseObject) {
  231. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  232. if(model && model.position == operation.fileModel.totalBytes){
  233. HLog(@"%@备份完成 数据正常",operation.fileModel.filename)
  234. [weakSelf handleUploadDoneOneFileBy:operation];
  235. }
  236. else if(model && model.position > operation.fileModel.totalBytes){
  237. HLog(@"%@备份完成 数据异常 -- position:%ld -- totalBytes:%ld",operation.fileModel.filename,model.position,operation.fileModel.totalBytes)
  238. [weakSelf handleUploadDoneOneFileBy:operation];
  239. }
  240. else{
  241. HLog(@"%@备份完成一片 %ld",operation.fileModel.filename,model.position)
  242. }
  243. } faild:^(NSError * _Nonnull error) {
  244. HLog(@"%@备份失败",operation.fileModel.filename)
  245. [weakSelf handleUploadFailOneFileBy:operation];
  246. }];
  247. }
  248. else{
  249. [paraDict setObject:@1 forKey:@"videoType"];
  250. [paraDict setObject:@"false" forKey:@"isLast"];
  251. if(![cachesFileManager checkFileIsSaveState:operation.fileModel.filename withType:uploadFileTypeVideo]){
  252. if(!operation.fileModel.asset){
  253. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  254. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  255. PHAsset *asset = fetchResult.firstObject;
  256. operation.fileModel.asset = asset;
  257. }
  258. //真正的视频数据
  259. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  260. options.version = PHVideoRequestOptionsVersionOriginal;
  261. [[PHImageManager defaultManager] requestAVAssetForVideo:operation.fileModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  262. if ([asset isKindOfClass:[AVURLAsset class]]) {
  263. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  264. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:operation.fileModel.filename error:nil];
  265. if (isSuc) {
  266. [weakSelf afterGetVideoDataFunWithOperation:operation];
  267. }
  268. else{
  269. [weakSelf handleUploadFailOneFileBy:operation];
  270. }
  271. }
  272. else{
  273. [weakSelf handleUploadFailOneFileBy:operation];
  274. }
  275. }];
  276. return;
  277. }
  278. long curPosition = operation.fileModel.didUploadBytes;
  279. [self beginUploadVideoDataFunBy:operation with:curPosition withPara:paraDict success:^(id _Nonnull responseObject) {
  280. } faild:^(NSError * _Nonnull error) {
  281. }];
  282. }
  283. }
  284. #pragma mark 视频上传
  285. - (void)beginUploadVideoDataFunBy:(customUploadOperation*)operation with:(NSInteger)position withPara:(NSMutableDictionary*)paraDict success:(netWork_Success)success faild:(netWork_Faild)faildStr
  286. {
  287. if(operation.isCancelType){
  288. HLog(@"防止取消不了任务生效")
  289. return;
  290. }
  291. BOOL isLastPicece = NO;
  292. if((operation.fileModel.totalBytes - position) <= MaxNasUploadPieceSzie){
  293. [paraDict setObject:@"true" forKey:@"isLast"];
  294. isLastPicece = YES;
  295. }
  296. else{
  297. [paraDict setObject:@"false" forKey:@"isLast"];
  298. }
  299. [paraDict setObject:[NSNumber numberWithLong:position] forKey:@"position"];
  300. //视频数据切片
  301. __block NSData *videoData = [self cutVideoFileFunAtIndex:position withMaxLenght:MaxNasUploadPieceSzie withModel:operation.fileModel];
  302. if(!videoData ||videoData.length ==0){
  303. HLog(@"视频没获取到")
  304. [self handleUploadFailOneFileBy:operation];
  305. return;
  306. }
  307. operation.onceDataLengt = [videoData length];
  308. KWeakSelf
  309. [self startUpload:paraDict operation:operation data:videoData success:^(id _Nonnull responseObject) {
  310. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  311. if(model && model.position >= operation.fileModel.totalBytes){
  312. HLog(@"%@上传完成 000",operation.fileModel.filename)
  313. [weakSelf handleUploadDoneOneFileBy:operation];
  314. }
  315. else{
  316. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  317. [weakSelf beginUploadVideoDataFunBy:operation with:model.position withPara:paraDict success:^(id _Nonnull responseObject) {
  318. success(responseObject);
  319. } faild:^(NSError * _Nonnull error) {
  320. NSError *err = error;
  321. if(error.code != -999){
  322. faildStr(err);
  323. }
  324. }];
  325. }
  326. } faild:^(NSError * _Nonnull error) {
  327. HLog(@"%@上传失败",operation.fileModel.filename)
  328. [weakSelf handleUploadFailOneFileBy:operation];
  329. }];
  330. }
  331. #pragma mark 分段读视频文件
  332. -(NSData*)cutVideoFileFunAtIndex:(NSUInteger)dataIndex withMaxLenght:(NSInteger)maxLengt withModel:(uploadFileDataModel*)dataModel{
  333. NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  334. NSFileManager *manager0 = [NSFileManager defaultManager];
  335. if(![manager0 fileExistsAtPath:filePath]) {
  336. return [NSData new];
  337. }
  338. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  339. // 设置分段读取的大小,这里以每次读取1KB为例
  340. const NSUInteger chunkSize = maxLengt;//cutVideoPieceSzie;//5 * 1024 *1024;
  341. NSMutableData *data = [NSMutableData data];
  342. if (fileHandle) {
  343. long long endOfFile = [fileHandle seekToEndOfFile];
  344. if(dataModel.totalBytes == 0
  345. || dataModel.totalBytes < endOfFile){//异常处理
  346. dataModel.totalBytes = endOfFile;
  347. }
  348. //异常处理
  349. if(endOfFile == dataIndex){
  350. dataModel.totalBytes = endOfFile;
  351. dataModel.didUploadBytes = endOfFile;
  352. dataModel.curUploadStateType = uploadStateDone;
  353. [fileHandle closeFile];
  354. return data;
  355. }
  356. if (endOfFile >= chunkSize) {
  357. // 读取文件的分段数据到某个位置
  358. [fileHandle seekToFileOffset:dataIndex];
  359. // 读取文件的分段数据
  360. NSData* chunk = [fileHandle readDataOfLength:chunkSize];
  361. if (chunk) {
  362. [data appendData:chunk];
  363. }
  364. }
  365. else{
  366. // 读取文件的分段数据到某个位置
  367. [fileHandle seekToFileOffset:dataIndex];
  368. [data appendData:[fileHandle readDataToEndOfFile]];
  369. }
  370. // 在这里可以对文件内容进行处理
  371. // ...
  372. // 关闭文件句柄
  373. [fileHandle closeFile];
  374. }
  375. HLog(@"视频切片完成 dataIndex:%ld --长度:%ld",dataIndex,[data length])
  376. return data;
  377. }
  378. #pragma mark 处理上传完成
  379. - (void)handleUploadDoneOneFileBy:(customUploadOperation*)operation
  380. {
  381. [[NSNotificationCenter defaultCenter] postNotificationName:nasBackupsTaskExeEnd object:operation.fileModel];
  382. [_uploadingOperationArr removeObject:operation];
  383. //[self beginUpload];
  384. [[nasBackupsManager shareInstance] backupsFileDoneFun];
  385. }
  386. #pragma mark 处理删除失败
  387. - (void)handleUploadFailOneFileBy:(customUploadOperation*)operation
  388. {
  389. operation.fileModel.curUploadStateType = uploadStateFail;
  390. [[NSNotificationCenter defaultCenter] postNotificationName:nasBackupsTaskExeError object:operation.fileModel];
  391. [_uploadingOperationArr removeObject:operation];
  392. //[self beginUpload];
  393. [[nasBackupsManager shareInstance] changeBackupsFileStateToFailWith:@""];
  394. }
  395. #pragma mark 根据 asset 获取到图片数据
  396. - (void)afterGetImageDataFunWithOperation:(customUploadOperation*)operation
  397. {
  398. [cachesFileManager getFileNameWithContent:operation.fileModel.imageData fileName:operation.fileModel.filename type:uploadFileTypeImage];
  399. [self prepareToUploadFileWithOperation:operation];
  400. }
  401. #pragma mark 根据 asset 获取到视频数据
  402. - (void)afterGetVideoDataFunWithOperation:(customUploadOperation*)operation
  403. {
  404. [self prepareToUploadFileWithOperation:operation];
  405. }
  406. #pragma mark 开始上传
  407. - (void)startUpload:(NSMutableDictionary *)params operation:(customUploadOperation*)operation data:(NSData *)data success:(netWork_Success)success faild:(netWork_Faild)faildStr {
  408. NSString *urlString = ksharedAppDelegate.NASFileByBoxService;
  409. urlString = [[NSString alloc] initWithFormat:@"%@uploadFile",urlString];
  410. NSURL *URL = [NSURL URLWithString:urlString];
  411. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  412. [request setHTTPMethod:@"POST"];
  413. //请求体
  414. NSMutableData *bodyData = [self getBodyDataWithRequest:request withModel:operation.fileModel withData:data withPara:params];
  415. //设置请求体
  416. [request setHTTPMethod:@"POST"];
  417. [request setHTTPBody:bodyData];
  418. //设置请求体长度
  419. NSInteger length = [bodyData length];
  420. [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
  421. //设置 POST请求文件上传
  422. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary3] forHTTPHeaderField:@"Content-Type"];
  423. KWeakSelf
  424. //回话对象
  425. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  426. operation.session = session;
  427. //请求task
  428. /*
  429. 第一个参数:请求对象
  430. 第二个参数:传递是要上传的数据(请求体)
  431. 第三个参数:
  432. */
  433. NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  434. //解析
  435. [weakSelf handleCustomUploadResultBy:data withResponse:response withError:error success:success faild:faildStr];
  436. }];
  437. // NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  438. // NSURL *filePathUrl = [NSURL URLWithString:filePath];
  439. //
  440. // NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:filePathUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  441. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  442. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  443. // }];
  444. // NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  445. //
  446. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  447. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  448. //
  449. //// NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  450. //// NSDictionary *dict = (NSDictionary *)object;
  451. //// NSLog(@"=====%@",[dict objectForKey:@"success"]);
  452. // }];
  453. //执行Task
  454. [uploadTask resume];
  455. operation.dataTask = uploadTask;
  456. }
  457. #pragma mark 用系统方法写的上传处理
  458. - (void)handleCustomUploadResultBy:(NSData*)data withResponse:(NSURLResponse*)response withError:(NSError*)error success:(netWork_Success)success faild:(netWork_Faild)faildStr{
  459. if(error){
  460. HLog(@"上传错误:%@",error)
  461. if(error.code != -999){
  462. faildStr(error);
  463. }
  464. return;
  465. }
  466. NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  467. NSDictionary *dict = (NSDictionary *)object;
  468. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:dict error:nil];
  469. if(model && [model.msg isEqualToString:@"success"]){
  470. success(dict);
  471. }
  472. else{
  473. NSError *err = [NSError new];
  474. faildStr(err);
  475. }
  476. }
  477. - (NSMutableData *)getBodyDataWithRequest:(NSMutableURLRequest *)request withModel:(uploadFileDataModel*)dataModel withData:(NSData*)data withPara:(NSMutableDictionary*)params{
  478. //1 边界符号要配置请求头里面去
  479. /*
  480. multipart/form-data 是表单格式
  481. charset=utf-8 是utf-8编码
  482. bounary 是表单开头
  483. */
  484. [request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", Kboundary3] forHTTPHeaderField:@"Content-Type"];
  485. /// body
  486. NSMutableData *boydData = [NSMutableData data];
  487. // 2.1 边界符号(开始边界)
  488. //2.1.1 其它参数
  489. NSMutableString *paraString = [NSMutableString new];
  490. //[paraString appendFormat:@"--%@\r\n",Kboundary];//\n:换行 \n:切换到行首
  491. for (NSString *key in params) {
  492. NSString *value = params[key];
  493. [paraString appendFormat:@"--%@\r\n",Kboundary3];//\n:换行 \n:切换到行首
  494. [paraString appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
  495. [paraString appendFormat:@"\r\n"];
  496. [paraString appendFormat:@"\r\n"];
  497. [paraString appendFormat:@"%@\r\n",value];
  498. }
  499. //[boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  500. // body每一个段内容以换行符作为结束标示
  501. NSString *fileBeginBoundary = [NSString stringWithFormat:@"--%@\r\n", Kboundary3];
  502. //[boydData appendData:[fileBeginBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  503. [paraString appendString:fileBeginBoundary];
  504. // 2.2 属性配置 名字;key;类型
  505. NSString *serverFileKey = @"image"; //key
  506. //NSString *serverFileKey = @"file";
  507. NSString *serverContentTypes = @"image/png"; //类型
  508. if (dataModel.curUploadFileType == uploadFileTypeVideo) {
  509. serverFileKey = @"video";
  510. serverContentTypes = @"video/mp4";
  511. }
  512. NSString *serverFileName = dataModel.filename; //name
  513. // filename已命名文件; name相当于一个key, 这个名字和服务器保持一致
  514. /*
  515. 理解key,表单发送给服务端,服务端拿到数据之后,可以将任务解析成一个字典了imageDict;图片数据会通过这个字典里面的name来获取图片(伪代码 image = imageDict[serverFileKey])
  516. */
  517. //2.3 拼接数据(创建一个字符串来拼装)
  518. NSMutableString *string = [NSMutableString new];
  519. [string appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\" ", @"file", serverFileName];
  520. //[string appendFormat:@"%@", KNewLine];
  521. [string appendFormat:@"\r\n"];
  522. [string appendFormat:@"Content-Type:%@", serverContentTypes];
  523. // [string appendFormat:@"%@", KNewLine];
  524. // [string appendFormat:@"%@", KNewLine];
  525. [string appendFormat:@"\r\n"];
  526. [string appendFormat:@"\r\n"];
  527. // [boydData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
  528. [paraString appendString:string];
  529. [boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  530. // 2.3 拼接数据(拼接文件数据)
  531. [boydData appendData:data];
  532. // 2.4 边界符号 (结束边界)
  533. NSString *fileEndBoundary = [NSString stringWithFormat:@"\r\n--%@--", Kboundary3];
  534. [boydData appendData:[fileEndBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  535. return boydData;
  536. }
  537. #pragma mark 上传的文件已存在
  538. - (void)handleTaskDidUploadWith:(customUploadOperation*)operation withState:(NSInteger)state
  539. {
  540. // if(state == 1){
  541. // [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  542. // }
  543. [self.uploadingOperationArr removeObject:operation];
  544. NSMutableArray *delArr = [NSMutableArray new];
  545. [delArr addObject:operation.fileModel];
  546. [[nasUploadFileManager shareInstance] deleteUploadFileRecordBy:delArr withDelCache:NO complete:^(BOOL isSuccess) {
  547. if (isSuccess) {
  548. }
  549. }];
  550. [self beginUpload];
  551. }
  552. #pragma mark - <NSURLSessionDataDelegate>
  553. // ssl 服务 证书信任
  554. - (void)URLSession:(NSURLSession *)session
  555. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  556. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
  557. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  558. return;
  559. }
  560. // 信任该插件
  561. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  562. // 第一个参数 告诉系统如何处置
  563. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  564. }
  565. //当请求协议是https的时候回调用该方法
  566. //Challenge 挑战 质询(受保护空间)
  567. //NSURLAuthenticationMethodServerTrust 服务器信任证书
  568. - (void)URLSession:(NSURLSession *)session
  569. task:(NSURLSessionTask *)task
  570. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  571. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
  572. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  573. return;
  574. }
  575. // 信任该插件
  576. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  577. // 第一个参数 告诉系统如何处置
  578. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  579. }
  580. // 接受到响应调用
  581. - (void)URLSession:(NSURLSession *)session
  582. dataTask:(NSURLSessionDataTask *)dataTask
  583. didReceiveResponse:(NSURLResponse *)response
  584. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
  585. completionHandler(NSURLSessionResponseAllow);
  586. }
  587. // 上传进度
  588. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
  589. //每包发送的大小bytesSent,totalBytesSent已经上传了多少;totalBytesExpectedToSend总共要发送多少
  590. // 32768 = 32KB
  591. HLog(@"didSendBodyData: %lld--%lld-%lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
  592. for (customUploadOperation*operation in _uploadingOperationArr) {
  593. if(operation.dataTask == task){
  594. operation.fileModel.didUploadBytes += bytesSent;
  595. //调整下大小 因为上传的数据 除了data 长度 还包含了 参数大小
  596. if(totalBytesSent == totalBytesExpectedToSend){
  597. operation.fileModel.didUploadBytes -= (totalBytesExpectedToSend - operation.onceDataLengt);
  598. }
  599. operation.i ++;
  600. if(operation.i >= _speedShowCount){
  601. [nasBackupsManager shareInstance].curPhotosBackupsTaskMod.didUploadBytes = operation.fileModel.didUploadBytes;
  602. [[nasBackupsManager shareInstance] changeBackupsFileStateFun];
  603. operation.i = 0;
  604. }
  605. break;
  606. }
  607. }
  608. }
  609. #pragma mark 取消单个任务
  610. - (void)cancelUploadTaskFunWith:(uploadFileDataModel*)fileModel
  611. {
  612. HLog(@"取消任务-- %@--%@",fileModel.filename,fileModel.taskId)
  613. @synchronized (self) {
  614. for (uploadFileDataModel*waitModel in _uploadWaitingUrlArr) {
  615. if([waitModel.filename isEqualToString:fileModel.filename]){
  616. [_uploadWaitingUrlArr removeObject:waitModel];
  617. return;
  618. }
  619. }
  620. for (customUploadOperation*operation in _uploadingOperationArr) {
  621. if([operation.fileModel.filename isEqualToString:fileModel.filename]){
  622. operation.isCancelType = YES;
  623. [operation.dataTask cancel];
  624. [_uploadingOperationArr removeObject:operation];
  625. [self beginUpload];
  626. break;
  627. }
  628. }
  629. }
  630. }
  631. #pragma mark 取消所有任务
  632. - (void)cancelUploadAllTaskFun
  633. {
  634. HLog(@"取消所有任务")
  635. @synchronized (self) {
  636. [_uploadWaitingUrlArr removeAllObjects];
  637. for (customUploadOperation*operation in _uploadingOperationArr) {
  638. operation.isCancelType = YES;
  639. [operation.dataTask cancel];
  640. }
  641. [_uploadingOperationArr removeAllObjects];
  642. }
  643. }
  644. #pragma mark 判断是否在上传中
  645. - (BOOL)checkUploadTaskDoingFun
  646. {
  647. if(_uploadWaitingUrlArr.count >0 || _uploadingOperationArr.count>0){
  648. return YES;
  649. }
  650. return NO;
  651. }
  652. #pragma mark - lazy load
  653. - (NSMutableArray *)uploadWaitingUrlArr {
  654. if (!_uploadWaitingUrlArr) {
  655. _uploadWaitingUrlArr = [NSMutableArray array];
  656. }
  657. return _uploadWaitingUrlArr;
  658. }
  659. - (NSMutableArray *)uploadingOperationArr {
  660. if (!_uploadingOperationArr) {
  661. _uploadingOperationArr = [NSMutableArray array];
  662. }
  663. return _uploadingOperationArr;
  664. }
  665. @end