nasMixBackupsManager.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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(@"%@上传完成 000",operation.fileModel.filename)
  234. [weakSelf handleUploadDoneOneFileBy:operation];
  235. }
  236. else{
  237. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  238. }
  239. } faild:^(NSError * _Nonnull error) {
  240. HLog(@"%@上传失败",operation.fileModel.filename)
  241. [weakSelf handleUploadFailOneFileBy:operation];
  242. }];
  243. }
  244. else{
  245. [paraDict setObject:@1 forKey:@"videoType"];
  246. [paraDict setObject:@"false" forKey:@"isLast"];
  247. if(![cachesFileManager checkFileIsSaveState:operation.fileModel.filename withType:uploadFileTypeVideo]){
  248. if(!operation.fileModel.asset){
  249. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  250. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  251. PHAsset *asset = fetchResult.firstObject;
  252. operation.fileModel.asset = asset;
  253. }
  254. //真正的视频数据
  255. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  256. options.version = PHVideoRequestOptionsVersionOriginal;
  257. [[PHImageManager defaultManager] requestAVAssetForVideo:operation.fileModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  258. if ([asset isKindOfClass:[AVURLAsset class]]) {
  259. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  260. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:operation.fileModel.filename error:nil];
  261. if (isSuc) {
  262. [weakSelf afterGetVideoDataFunWithOperation:operation];
  263. }
  264. else{
  265. [weakSelf handleUploadFailOneFileBy:operation];
  266. }
  267. }
  268. else{
  269. [weakSelf handleUploadFailOneFileBy:operation];
  270. }
  271. }];
  272. return;
  273. }
  274. long curPosition = operation.fileModel.didUploadBytes;
  275. [self beginUploadVideoDataFunBy:operation with:curPosition withPara:paraDict success:^(id _Nonnull responseObject) {
  276. } faild:^(NSError * _Nonnull error) {
  277. }];
  278. }
  279. }
  280. #pragma mark 视频上传
  281. - (void)beginUploadVideoDataFunBy:(customUploadOperation*)operation with:(NSInteger)position withPara:(NSMutableDictionary*)paraDict success:(netWork_Success)success faild:(netWork_Faild)faildStr
  282. {
  283. if(operation.isCancelType){
  284. HLog(@"防止取消不了任务生效")
  285. return;
  286. }
  287. BOOL isLastPicece = NO;
  288. if((operation.fileModel.totalBytes - position) <= MaxNasUploadPieceSzie){
  289. [paraDict setObject:@"true" forKey:@"isLast"];
  290. isLastPicece = YES;
  291. }
  292. else{
  293. [paraDict setObject:@"false" forKey:@"isLast"];
  294. }
  295. [paraDict setObject:[NSNumber numberWithLong:position] forKey:@"position"];
  296. //视频数据切片
  297. __block NSData *videoData = [self cutVideoFileFunAtIndex:position withMaxLenght:MaxNasUploadPieceSzie withModel:operation.fileModel];
  298. if(!videoData ||videoData.length ==0){
  299. HLog(@"视频没获取到")
  300. [self handleUploadFailOneFileBy:operation];
  301. return;
  302. }
  303. operation.onceDataLengt = [videoData length];
  304. KWeakSelf
  305. [self startUpload:paraDict operation:operation data:videoData success:^(id _Nonnull responseObject) {
  306. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  307. if(model && model.position >= operation.fileModel.totalBytes){
  308. HLog(@"%@上传完成 000",operation.fileModel.filename)
  309. [weakSelf handleUploadDoneOneFileBy:operation];
  310. }
  311. else{
  312. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  313. [weakSelf beginUploadVideoDataFunBy:operation with:model.position withPara:paraDict success:^(id _Nonnull responseObject) {
  314. success(responseObject);
  315. } faild:^(NSError * _Nonnull error) {
  316. NSError *err = error;
  317. if(error.code != -999){
  318. faildStr(err);
  319. }
  320. }];
  321. }
  322. } faild:^(NSError * _Nonnull error) {
  323. HLog(@"%@上传失败",operation.fileModel.filename)
  324. [weakSelf handleUploadFailOneFileBy:operation];
  325. }];
  326. }
  327. #pragma mark 分段读视频文件
  328. -(NSData*)cutVideoFileFunAtIndex:(NSUInteger)dataIndex withMaxLenght:(NSInteger)maxLengt withModel:(uploadFileDataModel*)dataModel{
  329. NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  330. NSFileManager *manager0 = [NSFileManager defaultManager];
  331. if(![manager0 fileExistsAtPath:filePath]) {
  332. return [NSData new];
  333. }
  334. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  335. // 设置分段读取的大小,这里以每次读取1KB为例
  336. const NSUInteger chunkSize = maxLengt;//cutVideoPieceSzie;//5 * 1024 *1024;
  337. NSMutableData *data = [NSMutableData data];
  338. if (fileHandle) {
  339. long long endOfFile = [fileHandle seekToEndOfFile];
  340. if(dataModel.totalBytes == 0
  341. || dataModel.totalBytes < endOfFile){//异常处理
  342. dataModel.totalBytes = endOfFile;
  343. }
  344. //异常处理
  345. if(endOfFile == dataIndex){
  346. dataModel.totalBytes = endOfFile;
  347. dataModel.didUploadBytes = endOfFile;
  348. dataModel.curUploadStateType = uploadStateDone;
  349. [fileHandle closeFile];
  350. return data;
  351. }
  352. if (endOfFile >= chunkSize) {
  353. // 读取文件的分段数据到某个位置
  354. [fileHandle seekToFileOffset:dataIndex];
  355. // 读取文件的分段数据
  356. NSData* chunk = [fileHandle readDataOfLength:chunkSize];
  357. if (chunk) {
  358. [data appendData:chunk];
  359. }
  360. }
  361. else{
  362. // 读取文件的分段数据到某个位置
  363. [fileHandle seekToFileOffset:dataIndex];
  364. [data appendData:[fileHandle readDataToEndOfFile]];
  365. }
  366. // 在这里可以对文件内容进行处理
  367. // ...
  368. // 关闭文件句柄
  369. [fileHandle closeFile];
  370. }
  371. HLog(@"视频切片完成 dataIndex:%ld --长度:%ld",dataIndex,[data length])
  372. return data;
  373. }
  374. #pragma mark 处理上传完成
  375. - (void)handleUploadDoneOneFileBy:(customUploadOperation*)operation
  376. {
  377. [[NSNotificationCenter defaultCenter] postNotificationName:nasBackupsTaskExeEnd object:operation.fileModel];
  378. [_uploadingOperationArr removeObject:operation];
  379. //[self beginUpload];
  380. [[nasBackupsManager shareInstance] backupsFileDoneFun];
  381. }
  382. #pragma mark 处理删除失败
  383. - (void)handleUploadFailOneFileBy:(customUploadOperation*)operation
  384. {
  385. operation.fileModel.curUploadStateType = uploadStateFail;
  386. [[NSNotificationCenter defaultCenter] postNotificationName:nasBackupsTaskExeError object:operation.fileModel];
  387. [_uploadingOperationArr removeObject:operation];
  388. //[self beginUpload];
  389. [[nasBackupsManager shareInstance] changeBackupsFileStateToFailWith:@"back fail"];
  390. }
  391. #pragma mark 根据 asset 获取到图片数据
  392. - (void)afterGetImageDataFunWithOperation:(customUploadOperation*)operation
  393. {
  394. [cachesFileManager getFileNameWithContent:operation.fileModel.imageData fileName:operation.fileModel.filename type:uploadFileTypeImage];
  395. [self prepareToUploadFileWithOperation:operation];
  396. }
  397. #pragma mark 根据 asset 获取到视频数据
  398. - (void)afterGetVideoDataFunWithOperation:(customUploadOperation*)operation
  399. {
  400. [self prepareToUploadFileWithOperation:operation];
  401. }
  402. #pragma mark 开始上传
  403. - (void)startUpload:(NSMutableDictionary *)params operation:(customUploadOperation*)operation data:(NSData *)data success:(netWork_Success)success faild:(netWork_Faild)faildStr {
  404. NSString *urlString = ksharedAppDelegate.NASFileByBoxService;
  405. urlString = [[NSString alloc] initWithFormat:@"%@uploadFile",urlString];
  406. NSURL *URL = [NSURL URLWithString:urlString];
  407. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  408. [request setHTTPMethod:@"POST"];
  409. //请求体
  410. NSMutableData *bodyData = [self getBodyDataWithRequest:request withModel:operation.fileModel withData:data withPara:params];
  411. //设置请求体
  412. [request setHTTPMethod:@"POST"];
  413. [request setHTTPBody:bodyData];
  414. //设置请求体长度
  415. NSInteger length = [bodyData length];
  416. [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
  417. //设置 POST请求文件上传
  418. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary3] forHTTPHeaderField:@"Content-Type"];
  419. KWeakSelf
  420. //回话对象
  421. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  422. operation.session = session;
  423. //请求task
  424. /*
  425. 第一个参数:请求对象
  426. 第二个参数:传递是要上传的数据(请求体)
  427. 第三个参数:
  428. */
  429. NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  430. //解析
  431. [weakSelf handleCustomUploadResultBy:data withResponse:response withError:error success:success faild:faildStr];
  432. }];
  433. // NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  434. // NSURL *filePathUrl = [NSURL URLWithString:filePath];
  435. //
  436. // NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:filePathUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  437. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  438. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  439. // }];
  440. // NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  441. //
  442. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  443. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  444. //
  445. //// NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  446. //// NSDictionary *dict = (NSDictionary *)object;
  447. //// NSLog(@"=====%@",[dict objectForKey:@"success"]);
  448. // }];
  449. //执行Task
  450. [uploadTask resume];
  451. operation.dataTask = uploadTask;
  452. }
  453. #pragma mark 用系统方法写的上传处理
  454. - (void)handleCustomUploadResultBy:(NSData*)data withResponse:(NSURLResponse*)response withError:(NSError*)error success:(netWork_Success)success faild:(netWork_Faild)faildStr{
  455. if(error){
  456. HLog(@"上传错误:%@",error)
  457. if(error.code != -999){
  458. faildStr(error);
  459. }
  460. return;
  461. }
  462. NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  463. NSDictionary *dict = (NSDictionary *)object;
  464. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:dict error:nil];
  465. if(model && [model.msg isEqualToString:@"success"]){
  466. success(dict);
  467. }
  468. else{
  469. NSError *err = [NSError new];
  470. faildStr(err);
  471. }
  472. }
  473. - (NSMutableData *)getBodyDataWithRequest:(NSMutableURLRequest *)request withModel:(uploadFileDataModel*)dataModel withData:(NSData*)data withPara:(NSMutableDictionary*)params{
  474. //1 边界符号要配置请求头里面去
  475. /*
  476. multipart/form-data 是表单格式
  477. charset=utf-8 是utf-8编码
  478. bounary 是表单开头
  479. */
  480. [request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", Kboundary3] forHTTPHeaderField:@"Content-Type"];
  481. /// body
  482. NSMutableData *boydData = [NSMutableData data];
  483. // 2.1 边界符号(开始边界)
  484. //2.1.1 其它参数
  485. NSMutableString *paraString = [NSMutableString new];
  486. //[paraString appendFormat:@"--%@\r\n",Kboundary];//\n:换行 \n:切换到行首
  487. for (NSString *key in params) {
  488. NSString *value = params[key];
  489. [paraString appendFormat:@"--%@\r\n",Kboundary3];//\n:换行 \n:切换到行首
  490. [paraString appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
  491. [paraString appendFormat:@"\r\n"];
  492. [paraString appendFormat:@"\r\n"];
  493. [paraString appendFormat:@"%@\r\n",value];
  494. }
  495. //[boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  496. // body每一个段内容以换行符作为结束标示
  497. NSString *fileBeginBoundary = [NSString stringWithFormat:@"--%@\r\n", Kboundary3];
  498. //[boydData appendData:[fileBeginBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  499. [paraString appendString:fileBeginBoundary];
  500. // 2.2 属性配置 名字;key;类型
  501. NSString *serverFileKey = @"image"; //key
  502. //NSString *serverFileKey = @"file";
  503. NSString *serverContentTypes = @"image/png"; //类型
  504. if (dataModel.curUploadFileType == uploadFileTypeVideo) {
  505. serverFileKey = @"video";
  506. serverContentTypes = @"video/mp4";
  507. }
  508. NSString *serverFileName = dataModel.filename; //name
  509. // filename已命名文件; name相当于一个key, 这个名字和服务器保持一致
  510. /*
  511. 理解key,表单发送给服务端,服务端拿到数据之后,可以将任务解析成一个字典了imageDict;图片数据会通过这个字典里面的name来获取图片(伪代码 image = imageDict[serverFileKey])
  512. */
  513. //2.3 拼接数据(创建一个字符串来拼装)
  514. NSMutableString *string = [NSMutableString new];
  515. [string appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\" ", @"file", serverFileName];
  516. //[string appendFormat:@"%@", KNewLine];
  517. [string appendFormat:@"\r\n"];
  518. [string appendFormat:@"Content-Type:%@", serverContentTypes];
  519. // [string appendFormat:@"%@", KNewLine];
  520. // [string appendFormat:@"%@", KNewLine];
  521. [string appendFormat:@"\r\n"];
  522. [string appendFormat:@"\r\n"];
  523. // [boydData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
  524. [paraString appendString:string];
  525. [boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  526. // 2.3 拼接数据(拼接文件数据)
  527. [boydData appendData:data];
  528. // 2.4 边界符号 (结束边界)
  529. NSString *fileEndBoundary = [NSString stringWithFormat:@"\r\n--%@--", Kboundary3];
  530. [boydData appendData:[fileEndBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  531. return boydData;
  532. }
  533. #pragma mark 上传的文件已存在
  534. - (void)handleTaskDidUploadWith:(customUploadOperation*)operation withState:(NSInteger)state
  535. {
  536. // if(state == 1){
  537. // [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  538. // }
  539. [self.uploadingOperationArr removeObject:operation];
  540. NSMutableArray *delArr = [NSMutableArray new];
  541. [delArr addObject:operation.fileModel];
  542. [[nasUploadFileManager shareInstance] deleteUploadFileRecordBy:delArr withDelCache:NO complete:^(BOOL isSuccess) {
  543. if (isSuccess) {
  544. }
  545. }];
  546. [self beginUpload];
  547. }
  548. #pragma mark - <NSURLSessionDataDelegate>
  549. // ssl 服务 证书信任
  550. - (void)URLSession:(NSURLSession *)session
  551. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  552. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
  553. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  554. return;
  555. }
  556. // 信任该插件
  557. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  558. // 第一个参数 告诉系统如何处置
  559. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  560. }
  561. //当请求协议是https的时候回调用该方法
  562. //Challenge 挑战 质询(受保护空间)
  563. //NSURLAuthenticationMethodServerTrust 服务器信任证书
  564. - (void)URLSession:(NSURLSession *)session
  565. task:(NSURLSessionTask *)task
  566. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  567. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
  568. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  569. return;
  570. }
  571. // 信任该插件
  572. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  573. // 第一个参数 告诉系统如何处置
  574. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  575. }
  576. // 接受到响应调用
  577. - (void)URLSession:(NSURLSession *)session
  578. dataTask:(NSURLSessionDataTask *)dataTask
  579. didReceiveResponse:(NSURLResponse *)response
  580. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
  581. completionHandler(NSURLSessionResponseAllow);
  582. }
  583. // 上传进度
  584. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
  585. //每包发送的大小bytesSent,totalBytesSent已经上传了多少;totalBytesExpectedToSend总共要发送多少
  586. // 32768 = 32KB
  587. HLog(@"didSendBodyData: %lld--%lld-%lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
  588. for (customUploadOperation*operation in _uploadingOperationArr) {
  589. if(operation.dataTask == task){
  590. operation.fileModel.didUploadBytes += bytesSent;
  591. //调整下大小 因为上传的数据 除了data 长度 还包含了 参数大小
  592. if(totalBytesSent == totalBytesExpectedToSend){
  593. operation.fileModel.didUploadBytes -= (totalBytesExpectedToSend - operation.onceDataLengt);
  594. }
  595. operation.i ++;
  596. if(operation.i >= _speedShowCount){
  597. [nasBackupsManager shareInstance].curPhotosBackupsTaskMod.didUploadBytes = operation.fileModel.didUploadBytes;
  598. [[nasBackupsManager shareInstance] changeBackupsFileStateFun];
  599. // [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileRefreshNotification object:operation.fileModel];
  600. operation.i = 0;
  601. }
  602. break;
  603. }
  604. }
  605. }
  606. #pragma mark 取消单个任务
  607. - (void)cancelUploadTaskFunWith:(uploadFileDataModel*)fileModel
  608. {
  609. HLog(@"取消任务-- %@--%@",fileModel.filename,fileModel.taskId)
  610. @synchronized (self) {
  611. for (uploadFileDataModel*waitModel in _uploadWaitingUrlArr) {
  612. if([waitModel.filename isEqualToString:fileModel.filename]){
  613. [_uploadWaitingUrlArr removeObject:waitModel];
  614. return;
  615. }
  616. }
  617. for (customUploadOperation*operation in _uploadingOperationArr) {
  618. if([operation.fileModel.filename isEqualToString:fileModel.filename]){
  619. operation.isCancelType = YES;
  620. [operation.dataTask cancel];
  621. [_uploadingOperationArr removeObject:operation];
  622. [self beginUpload];
  623. break;
  624. }
  625. }
  626. }
  627. }
  628. #pragma mark 取消所有任务
  629. - (void)cancelUploadAllTaskFun
  630. {
  631. HLog(@"取消所有任务")
  632. @synchronized (self) {
  633. [_uploadWaitingUrlArr removeAllObjects];
  634. for (customUploadOperation*operation in _uploadingOperationArr) {
  635. operation.isCancelType = YES;
  636. [operation.dataTask cancel];
  637. }
  638. [_uploadingOperationArr removeAllObjects];
  639. }
  640. }
  641. #pragma mark 判断是否在上传中
  642. - (BOOL)checkUploadTaskDoingFun
  643. {
  644. if(_uploadWaitingUrlArr.count >0 || _uploadingOperationArr.count>0){
  645. return YES;
  646. }
  647. return NO;
  648. }
  649. #pragma mark - lazy load
  650. - (NSMutableArray *)uploadWaitingUrlArr {
  651. if (!_uploadWaitingUrlArr) {
  652. _uploadWaitingUrlArr = [NSMutableArray array];
  653. }
  654. return _uploadWaitingUrlArr;
  655. }
  656. - (NSMutableArray *)uploadingOperationArr {
  657. if (!_uploadingOperationArr) {
  658. _uploadingOperationArr = [NSMutableArray array];
  659. }
  660. return _uploadingOperationArr;
  661. }
  662. @end