nasMixUploadManager.m 39 KB

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