RAUploadOperation.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. //
  2. // RAUploadOperation.m
  3. // test_autolayout
  4. //
  5. // Created by Ray on 03/05/2017.
  6. // Copyright © 2017 USAI. All rights reserved.
  7. //
  8. #import "RAUploadOperation.h"
  9. #import "NetworkUtils.h"
  10. #import <UIKit/UIKit.h>
  11. #import "AppDelegate.h"
  12. #import "RAUtils.h"
  13. #import "const.h"
  14. #import "RASingleton.h"
  15. //static const NSTimeInterval waitTimeIntervalDelta = 60 * 3;
  16. @interface RAUploadOperation ()
  17. {
  18. // NSString* _threadName;
  19. // NSString* _url;
  20. BOOL executing;
  21. BOOL finished;
  22. NSMutableDictionary* _taskinfo;
  23. int _maxRetry;
  24. NSURLSessionTask *_urlSessionTask;
  25. }
  26. @property (nonatomic,assign) NSTimeInterval joinTimeInterval;///<开始等待时间
  27. @property (nonatomic,assign) NSTimeInterval waitTimeInterval;///<需要等待的时间
  28. @end
  29. @implementation RAUploadOperation
  30. - (instancetype)initWithTaskinfo:(NSMutableDictionary*)taskinfo retry:(int) maxRetry
  31. {
  32. self = [super init];
  33. if (self) {
  34. // if (name!=nil)
  35. // _threadName = name;
  36. _maxRetry = maxRetry;
  37. // executing = NO;
  38. // finished = NO;
  39. _taskinfo=taskinfo;
  40. }
  41. return self;
  42. }
  43. - (BOOL)isConcurrent {
  44. return YES;
  45. }
  46. //
  47. - (BOOL)isExecuting {
  48. return executing;
  49. }
  50. - (BOOL)isFinished {
  51. return finished;
  52. }
  53. - (void)start
  54. {
  55. [self willChangeValueForKey:@"isExecuting"];
  56. executing = true;
  57. _taskinfo[@"status"]=[NSNumber numberWithInt:TaskStatusStart];
  58. [self didChangeValueForKey:@"isExecuting"];
  59. DebugLog(@"---------------start--------------------");
  60. // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  61. __weak typeof(self) weakself = self;
  62. __block NSMutableDictionary* block_task = _taskinfo;
  63. [_taskinfo removeObjectForKey:@"msg"]; // 重试开始消息仍然存在,需要清除
  64. // NSString *md5 = [RAUtils md5WithFile:[self filePath:_taskinfo ]];
  65. DebugLog(@"task %@",_taskinfo);
  66. NSString* file_path = [self filePath:_taskinfo];
  67. BOOL noFileTag = [[_taskinfo objectForKey:@"noFile"] boolValue]; // Apex Drivers 2018.6.6
  68. if(file_path==nil && !noFileTag)
  69. {
  70. DebugLog(@"error no file");
  71. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  72. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  73. [self willChangeValueForKey:@"isFinished"];
  74. finished = true;
  75. [self didChangeValueForKey:@"isFinished"];
  76. return;
  77. }
  78. _urlSessionTask = [NetworkUtils upload:[self filePath:_taskinfo ] Params:_taskinfo[@"params"] ToHost:_taskinfo[@"url"] Result:^(NSMutableDictionary *result) {
  79. blockDebugLog(@"upload result: %@",result);
  80. int r=[result[@"result"] intValue];
  81. if(r==2|| r==RESULT_BARCODE_ERROR)
  82. {
  83. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusFinish];
  84. if(r==2) {
  85. block_task[@"msg"]=@"upload successful";
  86. // after V1.07 上传成功后移除文件
  87. NSString *path = [weakself filePath:self->_taskinfo];
  88. if (path != nil) {
  89. [RAUtils removeFileAtPath:path];
  90. }
  91. }
  92. else
  93. block_task[@"msg"]=[@"warning: " stringByAppendingString:result[@"msg"]];
  94. }
  95. else
  96. {
  97. // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  98. BOOL canUpload = [RASingleton.sharedInstance.uploadManager canUpload];
  99. BOOL isReachable = [RASingleton.sharedInstance.uploadManager reachable];
  100. DebugLog(@"can upload %@",@(canUpload));
  101. if (!canUpload) {
  102. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusStop];
  103. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  104. block_task[@"msg"]= @"Can only use wifi to upload";
  105. }
  106. else if (weakself.isCancelled || !isReachable) {
  107. block_task[@"status"] = [NSNumber numberWithInt:TaskStatusStop] ;
  108. block_task[@"progress"] = [NSNumber numberWithDouble:0.0];
  109. block_task[@"msg"]= @"";
  110. }
  111. else if([block_task[@"retry"] intValue]>=self->_maxRetry)
  112. {
  113. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  114. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  115. block_task[@"msg"]=result[@"msg"];
  116. }
  117. else
  118. {
  119. block_task[@"retry"]=[NSNumber numberWithInt:[block_task[@"retry"] intValue]+1];
  120. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusWait];
  121. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  122. block_task[@"msg"]= @"connection lost, retry...";
  123. RAUploadOperation* operation = [[RAUploadOperation alloc] initWithTaskinfo:block_task retry:self->_maxRetry];
  124. operation.updateUI= weakself.updateUI;
  125. operation.completionBlock = weakself.completionBlock;
  126. block_task[@"operation"] = operation;
  127. // [Appdelegate.uploadManager.operation_queue addOperation:operation];
  128. // retry:
  129. operation.joinTimeInterval = [[NSDate date] timeIntervalSince1970];
  130. operation.waitTimeInterval = weakself.waitTimeInterval + RASingleton.sharedInstance.uploadManager.retryTimeInterval;
  131. [RASingleton.sharedInstance.uploadManager addRetryOperation:operation];
  132. // [self upload:url];
  133. }
  134. }
  135. dispatch_async(dispatch_get_main_queue(), ^{
  136. if(weakself.updateUI)
  137. weakself.updateUI();
  138. });
  139. [weakself willChangeValueForKey:@"isFinished"];
  140. self->finished = true;
  141. [weakself didChangeValueForKey:@"isFinished"];
  142. // [self completeOperation];
  143. } Progress:^(NSURLSessionTask *task,double progress) {
  144. // NSDictionary *param = [[NSUserDefaults standardUserDefaults] objectForKey:kUploadSetting];
  145. // BOOL onlyWiFi = false;
  146. // if (param) {
  147. // BOOL onlyWiFi = [[param objectForKey:@"only_wifi"] boolValue];
  148. //
  149. // }
  150. // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  151. BOOL canUpload = [[RAUploadManager sharedManager] canUpload];//[Appdelegate.uploadManager canUpload];
  152. if (!canUpload) {
  153. printf("cancel task on progress");
  154. [task cancel];
  155. return ;
  156. }
  157. dispatch_async(dispatch_get_main_queue(), ^{
  158. // ((UIProgressView*) block_task[@"ui_pregress"]).progress = progress;
  159. block_task[@"progress"]=[NSNumber numberWithFloat:progress];
  160. // NSLog(@"updateUI progress %p",weakself);
  161. DebugLog(@"update UI %@ p:%f",weakself.updateUI,progress);
  162. if(weakself.updateUI)
  163. {
  164. // NSLog(@"updateUI progress CALL");
  165. weakself.updateUI();
  166. }
  167. });
  168. } DecryptHandler:^id(NSString *result) {
  169. return @"bibibi";
  170. }];
  171. //完成下载
  172. // DebugLog(@"operation finish %@",self);
  173. // [self didChangeValueForKey:@"isExecuting"];
  174. }
  175. -(NSString*)filePath:(NSMutableDictionary*)task
  176. {
  177. // NSString *path = [RAUtils appCacheDirectory];
  178. // path= [path stringByAppendingPathComponent:task[@"path"]];
  179. // path= [path stringByAppendingPathComponent:task[@"file"]];
  180. // V1.07 之后图片不再保存到Temp
  181. NSString *file = [task objectForKey:@"file"];
  182. if (file.length == 0) { // Apex Drivers 2018.6.6
  183. return nil;
  184. }
  185. NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  186. NSString *path = [dir stringByAppendingPathComponent:file];
  187. NSFileManager* fmanager = [NSFileManager new];
  188. bool file_exist=[fmanager fileExistsAtPath:path];
  189. if(!file_exist)
  190. return nil;
  191. return path;
  192. }
  193. - (void)dealloc
  194. {
  195. // dumpThreads(@"dealloc");
  196. DebugLog(@"operation Dealloc %@",self);
  197. }
  198. - (void)cancel {
  199. DebugLog(@"operation Cancel %@",self);
  200. if (_urlSessionTask.state == NSURLSessionTaskStateRunning || _urlSessionTask.state == NSURLSessionTaskStateSuspended) {
  201. DebugLog(@"cancel session task");
  202. [_urlSessionTask suspend];
  203. [_urlSessionTask cancel];
  204. }
  205. [super cancel];
  206. }
  207. #pragma mark - Retry
  208. - (NSTimeInterval)theRestOfWaitTimeInterval {
  209. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  210. return self.waitTimeInterval - (currentTime - self.joinTimeInterval);
  211. }
  212. @end