nasMixUploadManager.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
  290. options.networkAccessAllowed = YES; // Allow downloading from iCloud
  291. options.version = PHImageRequestOptionsVersionCurrent;
  292. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  293. [[PHImageManager defaultManager] requestImageDataForAsset:operation.fileModel.asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
  294. // 直接得到最终的 NSData 数据
  295. if (imageData) {
  296. operation.fileModel.imageData = imageData;
  297. if(operation.fileModel.totalBytes == 0){
  298. operation.fileModel.totalBytes = [imageData length];
  299. }
  300. [weakSelf afterGetImageDataFunWithOperation:operation];
  301. }
  302. else{
  303. HLog(@"\n\n\n\nrequestImageDataForAsset fail imageData nil\n\n\n")
  304. [weakSelf handleUploadFailOneFileBy:operation];
  305. }
  306. }];
  307. return;
  308. }
  309. operation.fileModel.imageData = imageData;
  310. }
  311. HLog(@"%@开始上传--%ld",operation.fileModel.filename,operation.fileModel.totalBytes)
  312. NSData *curData = operation.fileModel.imageData;
  313. operation.onceDataLengt = [curData length];
  314. if(operation.fileModel.totalBytes == 0){//异常处理
  315. operation.fileModel.totalBytes = operation.onceDataLengt;
  316. }
  317. [self startUpload:paraDict operation:operation data:curData success:^(id _Nonnull responseObject) {
  318. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  319. if(model && model.position == operation.fileModel.totalBytes && model.position != 0){
  320. HLog(@"%@上传完成 000---%ld",operation.fileModel.filename,operation.fileModel.totalBytes)
  321. [weakSelf handleUploadDoneOneFileBy:operation];
  322. }
  323. else{
  324. HLog(@"%@上传完成异常 %ld---%ld",operation.fileModel.filename,model.position,operation.fileModel.totalBytes)
  325. [weakSelf handleUploadDoneOneFileBy:operation];
  326. }
  327. } faild:^(NSError * _Nonnull error) {
  328. HLog(@"%@上传失败",operation.fileModel.filename)
  329. [weakSelf handleUploadFailOneFileBy:operation];
  330. }];
  331. }
  332. else{
  333. [paraDict setObject:@1 forKey:@"videoType"];
  334. [paraDict setObject:@"false" forKey:@"isLast"];
  335. if(![cachesFileManager checkFileIsSaveState:operation.fileModel.filename withType:uploadFileTypeVideo]){
  336. if(!operation.fileModel.asset){
  337. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  338. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  339. PHAsset *asset = fetchResult.firstObject;
  340. operation.fileModel.asset = asset;
  341. }
  342. //真正的视频数据
  343. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  344. options.version = PHVideoRequestOptionsVersionOriginal;
  345. options.networkAccessAllowed = YES; // Allow downloading from iCloud
  346. [[PHImageManager defaultManager] requestAVAssetForVideo:operation.fileModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  347. if ([asset isKindOfClass:[AVURLAsset class]]) {
  348. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  349. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:operation.fileModel.filename error:nil];
  350. if (isSuc) {
  351. [weakSelf afterGetVideoDataFunWithOperation:operation];
  352. }
  353. else{
  354. [weakSelf handleUploadFailOneFileBy:operation];
  355. }
  356. }
  357. else{
  358. [weakSelf handleUploadFailOneFileBy:operation];
  359. }
  360. }];
  361. return;
  362. }
  363. long curPosition = operation.fileModel.didUploadBytes;
  364. [self beginUploadVideoDataFunBy:operation with:curPosition withPara:paraDict success:^(id _Nonnull responseObject) {
  365. } faild:^(NSError * _Nonnull error) {
  366. }];
  367. }
  368. }
  369. #pragma mark 视频上传
  370. - (void)beginUploadVideoDataFunBy:(customUploadOperation*)operation with:(NSInteger)position withPara:(NSMutableDictionary*)paraDict success:(netWork_Success)success faild:(netWork_Faild)faildStr
  371. {
  372. if(operation.isCancelType){
  373. HLog(@"防止取消不了任务生效")
  374. return;
  375. }
  376. BOOL isLastPicece = NO;
  377. if((operation.fileModel.totalBytes - position) <= MaxNasUploadPieceSzie){
  378. [paraDict setObject:@"true" forKey:@"isLast"];
  379. isLastPicece = YES;
  380. }
  381. else{
  382. [paraDict setObject:@"false" forKey:@"isLast"];
  383. }
  384. [paraDict setObject:[NSNumber numberWithLong:position] forKey:@"position"];
  385. //视频数据切片
  386. __block NSData *videoData = [self cutVideoFileFunAtIndex:position withMaxLenght:MaxNasUploadPieceSzie withModel:operation.fileModel withOperation:operation];
  387. if(!videoData ||videoData.length ==0){
  388. HLog(@"视频没获取到")
  389. [self handleUploadFailOneFileBy:operation];
  390. return;
  391. }
  392. operation.onceDataLengt = [videoData length];
  393. KWeakSelf
  394. [self startUpload:paraDict operation:operation data:videoData success:^(id _Nonnull responseObject) {
  395. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  396. if(model && model.position >= operation.fileModel.totalBytes){
  397. HLog(@"%@上传完成 001",operation.fileModel.filename)
  398. [weakSelf handleUploadDoneOneFileBy:operation];
  399. }
  400. else{
  401. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  402. [weakSelf beginUploadVideoDataFunBy:operation with:model.position withPara:paraDict success:^(id _Nonnull responseObject) {
  403. success(responseObject);
  404. } faild:^(NSError * _Nonnull error) {
  405. NSError *err = error;
  406. if(error.code != -999){
  407. faildStr(err);
  408. }
  409. }];
  410. }
  411. } faild:^(NSError * _Nonnull error) {
  412. HLog(@"%@上传失败",operation.fileModel.filename)
  413. [weakSelf handleUploadFailOneFileBy:operation];
  414. }];
  415. }
  416. #pragma mark 分段读视频文件
  417. -(NSData*)cutVideoFileFunAtIndex:(NSUInteger)dataIndex withMaxLenght:(NSInteger)maxLengt withModel:(uploadFileDataModel*)dataModel withOperation:(customUploadOperation*)operation{
  418. //return [operation cutVideoFileFunAtIndex:dataIndex withMaxLenght:maxLengt];
  419. HLog(@"视频切片开始 线程:%@",[NSThread currentThread]);
  420. NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  421. NSFileManager *manager0 = [NSFileManager defaultManager];
  422. if(![manager0 fileExistsAtPath:filePath]) {
  423. return [NSData new];
  424. }
  425. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  426. // 设置分段读取的大小,这里以每次读取1KB为例
  427. const NSUInteger chunkSize = maxLengt;//cutVideoPieceSzie;//5 * 1024 *1024;
  428. NSMutableData *data = [NSMutableData data];
  429. if (fileHandle) {
  430. long long endOfFile = [fileHandle seekToEndOfFile];
  431. if(dataModel.totalBytes == 0
  432. || dataModel.totalBytes < endOfFile){//异常处理
  433. dataModel.totalBytes = endOfFile;
  434. }
  435. //异常处理
  436. if(endOfFile == dataIndex){
  437. dataModel.totalBytes = endOfFile;
  438. dataModel.didUploadBytes = endOfFile;
  439. dataModel.curUploadStateType = uploadStateDone;
  440. [fileHandle closeFile];
  441. return data;
  442. }
  443. if (endOfFile >= chunkSize) {
  444. // 读取文件的分段数据到某个位置
  445. [fileHandle seekToFileOffset:dataIndex];
  446. // 读取文件的分段数据
  447. NSData* chunk = [fileHandle readDataOfLength:chunkSize];
  448. if (chunk) {
  449. [data appendData:chunk];
  450. }
  451. }
  452. else{
  453. // 读取文件的分段数据到某个位置
  454. [fileHandle seekToFileOffset:dataIndex];
  455. [data appendData:[fileHandle readDataToEndOfFile]];
  456. }
  457. // 在这里可以对文件内容进行处理
  458. // ...
  459. // 关闭文件句柄
  460. [fileHandle closeFile];
  461. }
  462. HLog(@"视频切片完成 dataIndex:%ld --长度:%ld",dataIndex,[data length])
  463. return data;
  464. }
  465. #pragma mark 处理上传完成
  466. - (void)handleUploadDoneOneFileBy:(customUploadOperation*)operation
  467. {
  468. HLog(@"handleUploadDoneOneFileBy")
  469. [[NSNotificationCenter defaultCenter] postNotificationName:nasUploadTaskExeEnd object:operation.fileModel];
  470. [self beginUploadAfterDeleteOperationBy:operation];
  471. }
  472. #pragma mark 处理删除失败
  473. - (void)handleUploadFailOneFileBy:(customUploadOperation*)operation
  474. {
  475. operation.fileModel.curUploadStateType = uploadStateFail;
  476. [[NSNotificationCenter defaultCenter] postNotificationName:nasUploadTaskExeError object:operation.fileModel];
  477. [self beginUploadAfterDeleteOperationBy:operation];
  478. }
  479. #pragma mark 根据 asset 获取到图片数据
  480. - (void)afterGetImageDataFunWithOperation:(customUploadOperation*)operation
  481. {
  482. [cachesFileManager getFileNameWithContent:operation.fileModel.imageData fileName:operation.fileModel.filename type:uploadFileTypeImage];
  483. [self prepareToUploadFileWithOperation:operation];
  484. }
  485. #pragma mark 根据 asset 获取到视频数据
  486. - (void)afterGetVideoDataFunWithOperation:(customUploadOperation*)operation
  487. {
  488. [self prepareToUploadFileWithOperation:operation];
  489. }
  490. #pragma mark 开始上传
  491. - (void)startUpload:(NSMutableDictionary *)params operation:(customUploadOperation*)operation data:(NSData *)data success:(netWork_Success)success faild:(netWork_Faild)faildStr {
  492. NSString *urlString = ksharedAppDelegate.NASFileByBoxService;
  493. urlString = [[NSString alloc] initWithFormat:@"%@uploadFile",urlString];
  494. NSURL *URL = [NSURL URLWithString:urlString];
  495. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  496. [request setHTTPMethod:@"POST"];
  497. //请求体
  498. NSMutableData *bodyData = [self getBodyDataWithRequest:request withModel:operation.fileModel withData:data withPara:params];
  499. //设置请求体
  500. [request setHTTPMethod:@"POST"];
  501. [request setHTTPBody:bodyData];
  502. //设置请求体长度
  503. NSInteger length = [bodyData length];
  504. [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
  505. //设置 POST请求文件上传
  506. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary2] forHTTPHeaderField:@"Content-Type"];
  507. KWeakSelf
  508. //回话对象
  509. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  510. operation.session = session;
  511. //请求task
  512. /*
  513. 第一个参数:请求对象
  514. 第二个参数:传递是要上传的数据(请求体)
  515. 第三个参数:
  516. */
  517. NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  518. //解析
  519. [weakSelf handleCustomUploadResultBy:data withResponse:response withError:error success:success faild:faildStr];
  520. }];
  521. // NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  522. // NSURL *filePathUrl = [NSURL URLWithString:filePath];
  523. //
  524. // NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:filePathUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  525. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  526. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  527. // }];
  528. // NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  529. //
  530. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  531. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  532. //
  533. //// NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  534. //// NSDictionary *dict = (NSDictionary *)object;
  535. //// NSLog(@"=====%@",[dict objectForKey:@"success"]);
  536. // }];
  537. //执行Task
  538. [uploadTask resume];
  539. operation.dataTask = uploadTask;
  540. }
  541. #pragma mark 用系统方法写的上传处理
  542. - (void)handleCustomUploadResultBy:(NSData*)data withResponse:(NSURLResponse*)response withError:(NSError*)error success:(netWork_Success)success faild:(netWork_Faild)faildStr{
  543. if(error){
  544. HLog(@"上传错误:%@",error)
  545. // -1005 网络中断 1009 网络似乎中断
  546. if(error.code == -1005
  547. ||error.code == -1009){//网络中断
  548. [[nasUploadFileManager shareInstance] saveUploadingTaskByNetWorkErrorFun];
  549. return;
  550. }
  551. if(error.code != -999){
  552. faildStr(error);
  553. }
  554. return;
  555. }
  556. NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  557. NSDictionary *dict = (NSDictionary *)object;
  558. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:dict error:nil];
  559. if(model && [model.msg isEqualToString:@"success"]){
  560. success(dict);
  561. }
  562. else{
  563. NSError *err = [NSError new];
  564. faildStr(err);
  565. }
  566. }
  567. - (NSMutableData *)getBodyDataWithRequest:(NSMutableURLRequest *)request withModel:(uploadFileDataModel*)dataModel withData:(NSData*)data withPara:(NSMutableDictionary*)params{
  568. //1 边界符号要配置请求头里面去
  569. /*
  570. multipart/form-data 是表单格式
  571. charset=utf-8 是utf-8编码
  572. bounary 是表单开头
  573. */
  574. [request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", Kboundary2] forHTTPHeaderField:@"Content-Type"];
  575. /// body
  576. NSMutableData *boydData = [NSMutableData data];
  577. // 2.1 边界符号(开始边界)
  578. //2.1.1 其它参数
  579. NSMutableString *paraString = [NSMutableString new];
  580. //[paraString appendFormat:@"--%@\r\n",Kboundary];//\n:换行 \n:切换到行首
  581. for (NSString *key in params) {
  582. NSString *value = params[key];
  583. [paraString appendFormat:@"--%@\r\n",Kboundary2];//\n:换行 \n:切换到行首
  584. [paraString appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
  585. [paraString appendFormat:@"\r\n"];
  586. [paraString appendFormat:@"\r\n"];
  587. [paraString appendFormat:@"%@\r\n",value];
  588. }
  589. //[boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  590. // body每一个段内容以换行符作为结束标示
  591. NSString *fileBeginBoundary = [NSString stringWithFormat:@"--%@\r\n", Kboundary2];
  592. //[boydData appendData:[fileBeginBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  593. [paraString appendString:fileBeginBoundary];
  594. // 2.2 属性配置 名字;key;类型
  595. NSString *serverFileKey = @"image"; //key
  596. //NSString *serverFileKey = @"file";
  597. NSString *serverContentTypes = @"image/png"; //类型
  598. if (dataModel.curUploadFileType == uploadFileTypeVideo) {
  599. serverFileKey = @"video";
  600. serverContentTypes = @"video/mp4";
  601. }
  602. NSString *serverFileName = dataModel.filename; //name
  603. // filename已命名文件; name相当于一个key, 这个名字和服务器保持一致
  604. /*
  605. 理解key,表单发送给服务端,服务端拿到数据之后,可以将任务解析成一个字典了imageDict;图片数据会通过这个字典里面的name来获取图片(伪代码 image = imageDict[serverFileKey])
  606. */
  607. //2.3 拼接数据(创建一个字符串来拼装)
  608. NSMutableString *string = [NSMutableString new];
  609. [string appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\" ", @"file", serverFileName];
  610. //[string appendFormat:@"%@", KNewLine];
  611. [string appendFormat:@"\r\n"];
  612. [string appendFormat:@"Content-Type:%@", serverContentTypes];
  613. // [string appendFormat:@"%@", KNewLine];
  614. // [string appendFormat:@"%@", KNewLine];
  615. [string appendFormat:@"\r\n"];
  616. [string appendFormat:@"\r\n"];
  617. // [boydData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
  618. [paraString appendString:string];
  619. [boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  620. // 2.3 拼接数据(拼接文件数据)
  621. [boydData appendData:data];
  622. // 2.4 边界符号 (结束边界)
  623. NSString *fileEndBoundary = [NSString stringWithFormat:@"\r\n--%@--", Kboundary2];
  624. [boydData appendData:[fileEndBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  625. return boydData;
  626. }
  627. #pragma mark 上传的文件已存在
  628. - (void)handleTaskDidUploadWith:(customUploadOperation*)operation withState:(NSInteger)state
  629. {
  630. if(state == 1){
  631. [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  632. }
  633. HLog(@"上传的文件已存在 删除任务:_uploadingOperationArr:%@",_uploadingOperationArr);
  634. [self.uploadingOperationArr removeObject:operation];
  635. NSMutableArray *delArr = [NSMutableArray new];
  636. [delArr addObject:operation.fileModel];
  637. [[nasUploadFileManager shareInstance] deleteUploadFileRecordBy:delArr withDelCache:NO complete:^(BOOL isSuccess) {
  638. if (isSuccess) {
  639. }
  640. }];
  641. [self beginUploadAfterDeleteOperationBy:nil];
  642. }
  643. #pragma mark - <NSURLSessionDataDelegate>
  644. // ssl 服务 证书信任
  645. - (void)URLSession:(NSURLSession *)session
  646. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  647. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
  648. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  649. return;
  650. }
  651. // 信任该插件
  652. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  653. // 第一个参数 告诉系统如何处置
  654. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  655. }
  656. //当请求协议是https的时候回调用该方法
  657. //Challenge 挑战 质询(受保护空间)
  658. //NSURLAuthenticationMethodServerTrust 服务器信任证书
  659. - (void)URLSession:(NSURLSession *)session
  660. task:(NSURLSessionTask *)task
  661. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  662. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
  663. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  664. return;
  665. }
  666. // 信任该插件
  667. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  668. // 第一个参数 告诉系统如何处置
  669. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  670. }
  671. // 接受到响应调用
  672. - (void)URLSession:(NSURLSession *)session
  673. dataTask:(NSURLSessionDataTask *)dataTask
  674. didReceiveResponse:(NSURLResponse *)response
  675. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
  676. completionHandler(NSURLSessionResponseAllow);
  677. }
  678. // 上传进度
  679. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
  680. //每包发送的大小bytesSent,totalBytesSent已经上传了多少;totalBytesExpectedToSend总共要发送多少
  681. // 32768 = 32KB
  682. HLog(@"didSendBodyData: %lld--%lld-%lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
  683. @synchronized (self) {
  684. for (customUploadOperation*operation in _uploadingOperationArr) {
  685. HLog(@"正在遍历数组 _uploadingOperationArr:%@",_uploadingOperationArr);
  686. if(operation.dataTask == task){
  687. operation.fileModel.didUploadBytes += bytesSent;
  688. //调整下大小 因为上传的数据 除了data 长度 还包含了 参数大小
  689. if(totalBytesSent == totalBytesExpectedToSend){
  690. operation.fileModel.didUploadBytes -= (totalBytesExpectedToSend - operation.onceDataLengt);
  691. }
  692. NSTimeInterval curTime = [[NSDate date] timeIntervalSince1970];
  693. NSTimeInterval timeDiff = curTime - operation.preNotTimeInterval;
  694. //HLog(@"控制刷新时间为1秒:%f",timeDiff);
  695. CGFloat RefreshTimer = 0.8;
  696. if(operation.fileModel.totalBytes <= 5*1024*1024){//小于5M 事实
  697. RefreshTimer = 0.2;
  698. }
  699. if (operation.preNotTimeInterval <= 0
  700. || timeDiff > RefreshTimer ) {
  701. operation.preNotTimeInterval = curTime;
  702. [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileUploadingNotification object:operation.fileModel];
  703. }
  704. break;
  705. }
  706. }
  707. }
  708. }
  709. #pragma mark 取消单个任务
  710. - (void)cancelUploadTaskFunWith:(uploadFileDataModel*)fileModel
  711. {
  712. HLog(@"取消任务-- %@--%@",fileModel.filename,fileModel.taskId)
  713. @synchronized (self) {
  714. for (customUploadOperation*operation in _uploadingOperationArr) {
  715. HLog(@"正在遍历数组 _uploadingOperationArr:%@",_uploadingOperationArr);
  716. if([operation.fileModel.localIdentifier isEqualToString:fileModel.localIdentifier]){
  717. operation.isCancelType = YES;
  718. [operation.dataTask cancel];
  719. if(operation.fileHandle){
  720. [operation closeFileHandleFun];
  721. }
  722. [self beginUploadAfterDeleteOperationBy:operation];
  723. return;
  724. }
  725. }
  726. for (uploadFileDataModel*waitModel in _uploadWaitingUrlArr) {
  727. if(//[waitModel.filename isEqualToString:fileModel.filename]
  728. [waitModel.localIdentifier isEqualToString:fileModel.localIdentifier]){
  729. [_uploadWaitingUrlArr removeObject:waitModel];
  730. [self beginUploadAfterDeleteOperationBy:nil];
  731. return;
  732. }
  733. }
  734. }
  735. }
  736. #pragma mark 取消所有任务
  737. - (void)cancelUploadAllTaskFun
  738. {
  739. HLog(@"取消所有任务")
  740. @synchronized (self) {
  741. [_uploadWaitingUrlArr removeAllObjects];
  742. for (customUploadOperation*operation in _uploadingOperationArr) {
  743. HLog(@"正在遍历数组 _uploadingOperationArr:%@",_uploadingOperationArr);
  744. operation.isCancelType = YES;
  745. [operation.dataTask cancel];
  746. if(operation.fileHandle){
  747. [operation closeFileHandleFun];
  748. }
  749. }
  750. [_uploadingOperationArr removeAllObjects];
  751. }
  752. }
  753. #pragma mark 判断是否在上传中
  754. - (BOOL)checkUploadTaskDoingFun
  755. {
  756. if(_uploadWaitingUrlArr.count >0 || _uploadingOperationArr.count>0){
  757. return YES;
  758. }
  759. return NO;
  760. }
  761. - (BOOL)isUploadIngType
  762. {
  763. if(self.uploadWaitingUrlArr.count >0){
  764. return YES;
  765. }
  766. if(self.uploadingOperationArr.count >0){
  767. return YES;
  768. }
  769. return NO;
  770. }
  771. #pragma mark - lazy load
  772. - (NSMutableArray *)uploadWaitingUrlArr {
  773. if (!_uploadWaitingUrlArr) {
  774. _uploadWaitingUrlArr = [NSMutableArray array];
  775. }
  776. return _uploadWaitingUrlArr;
  777. }
  778. - (NSMutableArray *)uploadingOperationArr {
  779. if (!_uploadingOperationArr) {
  780. _uploadingOperationArr = [NSMutableArray array];
  781. }
  782. return _uploadingOperationArr;
  783. }
  784. @end