nasMixBackupsManager.m 32 KB

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