nasMixUploadManager.m 38 KB

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