CCNetworking.m 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. //
  2. // CCNetworking.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 01/06/15.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCNetworking.h"
  24. #import "AppDelegate.h"
  25. #import "CCCertificate.h"
  26. #import "TableAccount+CoreDataClass.h"
  27. #import "NSDate+ISO8601.h"
  28. #import "NSString+Encode.h"
  29. @interface CCNetworking ()
  30. {
  31. NSManagedObjectContext *_context;
  32. NSMutableDictionary *_taskData;
  33. CCMetadata *_currentProgressMetadata;
  34. NSString *_activeAccount;
  35. NSString *_activePassword;
  36. NSString *_activeUser;
  37. NSString *_activeUrl;
  38. NSString *_directoryUser;
  39. }
  40. @end
  41. @implementation CCNetworking
  42. + (CCNetworking *)sharedNetworking {
  43. static CCNetworking *sharedNetworking;
  44. @synchronized(self)
  45. {
  46. if (!sharedNetworking) {
  47. sharedNetworking = [[CCNetworking alloc] init];
  48. }
  49. return sharedNetworking;
  50. }
  51. }
  52. - (id)init
  53. {
  54. self = [super init];
  55. _context = [NSManagedObjectContext MR_context];
  56. _taskData = [[NSMutableDictionary alloc] init];
  57. _currentProgressMetadata = [[CCMetadata alloc] init];
  58. _delegates = [[NSMutableDictionary alloc] init];
  59. // Initialization Sessions
  60. [self sessionDownload];
  61. [self sessionDownloadForeground];
  62. [self sessionWWanDownload];
  63. [self sessionUpload];
  64. [self sessionUploadForeground];
  65. [self sessionWWanUpload];
  66. [self sharedOCCommunication];
  67. [self settingAccount];
  68. return self;
  69. }
  70. - (void)settingDelegate:(id <CCNetworkingDelegate>)delegate
  71. {
  72. _delegate = delegate;
  73. }
  74. - (void)settingAccount
  75. {
  76. TableAccount *tableAccount = [CCCoreData getActiveAccount];
  77. _activeAccount = tableAccount.account;
  78. _activePassword = tableAccount.password;
  79. _activeUser = tableAccount.user;
  80. _activeUrl = tableAccount.url;
  81. _directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  82. }
  83. #pragma --------------------------------------------------------------------------------------------
  84. #pragma mark ===== Session =====
  85. #pragma --------------------------------------------------------------------------------------------
  86. - (NSURLSession *)sessionDownload
  87. {
  88. static NSURLSession *sessionDownload = nil;
  89. if (sessionDownload == nil) {
  90. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  91. configuration.allowsCellularAccess = YES;
  92. configuration.sessionSendsLaunchEvents = YES;
  93. configuration.discretionary = NO;
  94. configuration.HTTPMaximumConnectionsPerHost = 1;
  95. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  96. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  97. sessionDownload.sessionDescription = k_download_session;
  98. }
  99. return sessionDownload;
  100. }
  101. - (NSURLSession *)sessionDownloadForeground
  102. {
  103. static NSURLSession *sessionDownloadForeground = nil;
  104. if (sessionDownloadForeground == nil) {
  105. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  106. configuration.allowsCellularAccess = YES;
  107. configuration.discretionary = NO;
  108. configuration.HTTPMaximumConnectionsPerHost = 1;
  109. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  110. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  111. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  112. }
  113. return sessionDownloadForeground;
  114. }
  115. - (NSURLSession *)sessionWWanDownload
  116. {
  117. static NSURLSession *sessionWWanDownload = nil;
  118. if (sessionWWanDownload == nil) {
  119. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  120. configuration.allowsCellularAccess = NO;
  121. configuration.sessionSendsLaunchEvents = YES;
  122. configuration.discretionary = NO;
  123. configuration.HTTPMaximumConnectionsPerHost = 1;
  124. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  125. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  126. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  127. }
  128. return sessionWWanDownload;
  129. }
  130. - (NSURLSession *)sessionUpload
  131. {
  132. static NSURLSession *sessionUpload = nil;
  133. if (sessionUpload == nil) {
  134. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  135. configuration.allowsCellularAccess = YES;
  136. configuration.sessionSendsLaunchEvents = YES;
  137. configuration.discretionary = NO;
  138. configuration.HTTPMaximumConnectionsPerHost = 1;
  139. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  140. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  141. sessionUpload.sessionDescription = k_upload_session;
  142. }
  143. return sessionUpload;
  144. }
  145. - (NSURLSession *)sessionUploadForeground
  146. {
  147. static NSURLSession *sessionUploadForeground;
  148. if (sessionUploadForeground == nil) {
  149. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  150. configuration.allowsCellularAccess = YES;
  151. configuration.discretionary = NO;
  152. configuration.HTTPMaximumConnectionsPerHost = 1;
  153. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  154. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  155. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  156. }
  157. return sessionUploadForeground;
  158. }
  159. - (NSURLSession *)sessionWWanUpload
  160. {
  161. static NSURLSession *sessionWWanUpload = nil;
  162. if (sessionWWanUpload == nil) {
  163. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  164. configuration.allowsCellularAccess = NO;
  165. configuration.sessionSendsLaunchEvents = YES;
  166. configuration.discretionary = NO;
  167. configuration.HTTPMaximumConnectionsPerHost = 1;
  168. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  169. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  170. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  171. }
  172. return sessionWWanUpload;
  173. }
  174. - (OCCommunication *)sharedOCCommunication
  175. {
  176. static OCCommunication* sharedOCCommunication = nil;
  177. if (sharedOCCommunication == nil)
  178. {
  179. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  180. configuration.allowsCellularAccess = YES;
  181. configuration.discretionary = NO;
  182. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  183. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  184. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  185. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  186. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  187. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:nil andNetworkSessionManager:networkSessionManager];
  188. }
  189. return sharedOCCommunication;
  190. }
  191. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  192. {
  193. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  194. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  195. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  196. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  197. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  198. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  199. return nil;
  200. }
  201. - (void)invalidateAndCancelAllSession
  202. {
  203. [[self sessionDownload] invalidateAndCancel];
  204. [[self sessionDownloadForeground] invalidateAndCancel];
  205. [[self sessionWWanDownload] invalidateAndCancel];
  206. [[self sessionUpload] invalidateAndCancel];
  207. [[self sessionUploadForeground] invalidateAndCancel];
  208. [[self sessionWWanUpload] invalidateAndCancel];
  209. }
  210. - (void)settingSessionsDownload:(BOOL)download upload:(BOOL)upload taskStatus:(NSInteger)taskStatus activeAccount:(NSString *)activeAccount activeUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  211. {
  212. if (download) {
  213. [[self sessionDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  214. for (NSURLSessionTask *task in downloadTasks)
  215. if (taskStatus == k_taskStatusCancel) [task cancel];
  216. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  217. else if (taskStatus == k_taskStatusResume) [task resume];
  218. }];
  219. [[self sessionDownloadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  220. for (NSURLSessionTask *task in downloadTasks)
  221. if (taskStatus == k_taskStatusCancel) [task cancel];
  222. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  223. else if (taskStatus == k_taskStatusResume) [task resume];
  224. }];
  225. [[self sessionWWanDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  226. for (NSURLSessionTask *task in downloadTasks)
  227. if (taskStatus == k_taskStatusCancel) [task cancel];
  228. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  229. else if (taskStatus == k_taskStatusResume) [task resume];
  230. }];
  231. }
  232. if (upload) {
  233. [[self sessionUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  234. for (NSURLSessionTask *task in uploadTasks)
  235. if (taskStatus == k_taskStatusCancel) [task cancel];
  236. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  237. else if (taskStatus == k_taskStatusResume) [task resume];
  238. }];
  239. [[self sessionUploadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  240. for (NSURLSessionTask *task in uploadTasks)
  241. if (taskStatus == k_taskStatusCancel) [task cancel];
  242. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  243. else if (taskStatus == k_taskStatusResume) [task resume];
  244. }];
  245. [[self sessionWWanUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  246. for (NSURLSessionTask *task in uploadTasks)
  247. if (taskStatus == k_taskStatusCancel) [task cancel];
  248. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  249. else if (taskStatus == k_taskStatusResume) [task resume];
  250. }];
  251. }
  252. // COREDATA FILE SYSTEM
  253. if (download && taskStatus == k_taskStatusCancel) {
  254. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierDone sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'download')", _activeAccount] context:_context];
  255. }
  256. if (upload && taskStatus == k_taskStatusCancel) {
  257. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(session CONTAINS 'upload')"]];
  258. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  259. [CCUtility removeAllFileID_UPLOAD_ActiveUser:activeUser activeUrl:activeUrl];
  260. });
  261. }
  262. #ifndef EXTENSION
  263. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  264. [app updateApplicationIconBadgeNumber];
  265. });
  266. #endif
  267. }
  268. - (void)settingSession:(NSString *)sessionDescription sessionTaskIdentifier:(NSUInteger)sessionTaskIdentifier taskStatus:(NSInteger)taskStatus
  269. {
  270. NSURLSession *session = [self getSessionfromSessionDescription:sessionDescription];
  271. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  272. if ([sessionDescription containsString:@"download"])
  273. for (NSURLSessionTask *task in downloadTasks)
  274. if (task.taskIdentifier == sessionTaskIdentifier) {
  275. if (taskStatus == k_taskStatusCancel) [task cancel];
  276. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  277. else if (taskStatus == k_taskStatusResume) [task resume];
  278. }
  279. if ([sessionDescription containsString:@"upload"])
  280. for (NSURLSessionTask *task in uploadTasks)
  281. if (task.taskIdentifier == sessionTaskIdentifier) {
  282. if (taskStatus == k_taskStatusCancel) [task cancel];
  283. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  284. else if (taskStatus == k_taskStatusResume) [task resume];
  285. }
  286. }];
  287. }
  288. #pragma --------------------------------------------------------------------------------------------
  289. #pragma mark ===== URLSession download/upload =====
  290. #pragma --------------------------------------------------------------------------------------------
  291. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  292. {
  293. // The pinnning check
  294. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  295. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  296. } else {
  297. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  298. }
  299. }
  300. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  301. {
  302. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  303. NSString *fileName = [url lastPathComponent];
  304. NSString *serverUrl = [self getServerUrlFromUrl:url];
  305. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(session = %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))",session.sessionDescription, task.taskIdentifier, task.taskIdentifier] context:_context];
  306. NSInteger errorCode;
  307. NSString *fileID = metadata.fileID;
  308. NSString *rev = metadata.rev;
  309. NSDate *date = [NSDate date];
  310. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  311. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  312. // remove Current Progress Metadata
  313. _currentProgressMetadata = nil;
  314. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  315. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  316. errorCode = error.code;
  317. } else {
  318. if (httpResponse.statusCode > 0)
  319. errorCode = httpResponse.statusCode;
  320. else
  321. errorCode = error.code;
  322. // Request trusted certificated
  323. if (errorCode == NSURLErrorServerCertificateUntrusted)
  324. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  325. }
  326. // ----------------------- DOWNLOAD -----------------------
  327. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  328. NSDictionary *fields = [httpResponse allHeaderFields];
  329. if (errorCode == 0) {
  330. rev = [CCUtility removeForbiddenCharacters:[fields objectForKey:@"OC-ETag"] hasServerForbiddenCharactersSupport:NO];
  331. date = [dateFormatter dateFromString:[fields objectForKey:@"Date"]];
  332. // Activity
  333. [CCCoreData addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault account:metadata.account activeUrl:_activeUrl];
  334. } else {
  335. // Activity
  336. [CCCoreData addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:[NSString stringWithFormat:@"Server: %@ Error: %@", serverUrl, [CCError manageErrorKCF:errorCode withNumberError:YES]] type:k_activityTypeFailure verbose:k_activityVerboseDefault account:metadata.account activeUrl:_activeUrl];
  337. }
  338. dispatch_async(dispatch_get_main_queue(), ^{
  339. // Notification change session
  340. if (metadata) {
  341. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, task, nil];
  342. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  343. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID rev:rev date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  344. } else {
  345. NSLog(@"[LOG] Serius error internal download : metadata not found");
  346. }
  347. });
  348. }
  349. // ------------------------ UPLOAD -----------------------
  350. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  351. NSDictionary *fields = [httpResponse allHeaderFields];
  352. if (errorCode == 0) {
  353. fileID = [CCUtility removeForbiddenCharacters:[fields objectForKey:@"OC-FileId"] hasServerForbiddenCharactersSupport:NO];
  354. rev = [CCUtility removeForbiddenCharacters:[fields objectForKey:@"OC-ETag"] hasServerForbiddenCharactersSupport:NO];
  355. date = [dateFormatter dateFromString:[fields objectForKey:@"Date"]];
  356. // Activity
  357. [CCCoreData addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault account:metadata.account activeUrl:_activeUrl];
  358. } else {
  359. // Activity
  360. [CCCoreData addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:[NSString stringWithFormat:@"Server: %@ Error: %@", serverUrl, [CCError manageErrorKCF:errorCode withNumberError:YES]] type:k_activityTypeFailure verbose:k_activityVerboseDefault account:metadata.account activeUrl:_activeUrl];
  361. }
  362. dispatch_async(dispatch_get_main_queue(), ^{
  363. // Notification change session
  364. if (fileID && metadata ) {
  365. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, task, nil];
  366. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  367. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID rev:rev date:date serverUrl:serverUrl errorCode:errorCode];
  368. } else {
  369. NSLog(@"[LOG] Serius error internal upload : fileID or metadata not found");
  370. }
  371. });
  372. }
  373. }
  374. #pragma --------------------------------------------------------------------------------------------
  375. #pragma mark ===== Download =====
  376. #pragma --------------------------------------------------------------------------------------------
  377. - (void)downloadFile:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl downloadData:(BOOL)downloadData downloadPlist:(BOOL)downloadPlist selector:(NSString *)selector selectorPost:(NSString *)selectorPost session:(NSString *)session taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  378. {
  379. // add delegate
  380. if (delegate)
  381. [_delegates setObject:delegate forKey:metadata.fileID];
  382. if (downloadData) {
  383. // it's in download
  384. if ([CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@) AND (session CONTAINS 'download') AND (sessionTaskIdentifier >= 0)", _activeAccount, metadata.fileID] context:_context]) {
  385. NSLog(@"[LOG] Download file already in progress %@ - %@", metadata.fileNameData, metadata.fileNamePrint);
  386. return;
  387. }
  388. // File exists ?
  389. if ([CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:_activeAccount] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]]) {
  390. NSLog(@"[LOG] Download file already exists %@ - %@", metadata.fileNameData, metadata.fileNamePrint);
  391. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierDone sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, _activeAccount] context:_context];
  392. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  393. [[self getDelegate:metadata.fileID] downloadFileSuccess:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  394. return;
  395. }
  396. [self downloaURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  397. [CCCoreData setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)",metadata.fileID, _activeAccount] context:_context];
  398. }
  399. if (downloadPlist) {
  400. // it's in download
  401. if ([CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@) AND (session CONTAINS 'download') AND (sessionTaskIdentifierPlist >= 0)", _activeAccount, metadata.fileID] context:_context]) {
  402. NSLog(@"[LOG] Download file already in progress %@ - %@", metadata.fileName, metadata.fileNamePrint);
  403. return;
  404. }
  405. [self downloaURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  406. [CCCoreData setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)",metadata.fileID, _activeAccount] context:_context];
  407. }
  408. }
  409. - (void)downloaURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl fileID:(NSString *)fileID session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector
  410. {
  411. NSURLSession *sessionDownload;
  412. NSURL *url;
  413. NSMutableURLRequest *request;
  414. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  415. url = [NSURL URLWithString:serverFileUrl];
  416. request = [NSMutableURLRequest requestWithURL:url];
  417. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  418. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  419. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  420. if ([session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  421. else if ([session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  422. else if ([session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  423. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  424. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  425. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  426. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  427. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadTaskSave:)])
  428. [[self getDelegate:fileID] downloadTaskSave:downloadTask];
  429. if (downloadTask == nil) {
  430. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  431. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  432. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  433. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  434. [CCCoreData setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  435. NSLog(@"[LOG] downloadFileSession TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  436. } else {
  437. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  438. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  439. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = downloadTask.taskIdentifier;
  440. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = downloadTask.taskIdentifier;
  441. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  442. NSLog(@"[LOG] downloadFileSession %@ - %@ Task [%lu %lu]", fileID, fileNamePrint, (unsigned long)sessionTaskIdentifier, (unsigned long)sessionTaskIdentifierPlist);
  443. }
  444. dispatch_async(dispatch_get_main_queue(), ^{
  445. // Refresh datasource if is not a Plist
  446. if ([_delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)] && [CCUtility isCryptoPlistString:fileName] == NO)
  447. [_delegate reloadDatasource:serverUrl fileID:fileID selector:selector];
  448. });
  449. }
  450. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  451. {
  452. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  453. NSString *fileName = [url lastPathComponent];
  454. NSString *serverUrl = [self getServerUrlFromUrl:url];
  455. // if plist return
  456. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  457. return;
  458. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  459. if ([_currentProgressMetadata.fileName isEqualToString:fileName] == NO && [_currentProgressMetadata.fileNameData isEqualToString:fileName] == NO)
  460. _currentProgressMetadata = [CCCoreData getMetadataFromFileName:fileName directoryID:[CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount] activeAccount:_activeAccount context:_context];
  461. dispatch_async(dispatch_get_main_queue(), ^{
  462. if (_currentProgressMetadata) {
  463. NSDictionary* userInfo = @{@"fileID": (_currentProgressMetadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:_currentProgressMetadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  464. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  465. }
  466. });
  467. }
  468. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  469. {
  470. NSURLRequest *url = [downloadTask currentRequest];
  471. NSString *filename = [[url.URL absoluteString] lastPathComponent];
  472. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(session = %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))",session.sessionDescription, downloadTask.taskIdentifier, downloadTask.taskIdentifier] context:_context];
  473. // If the record metadata do not exists, exit
  474. if (!metadata)
  475. return;
  476. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  477. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  478. NSString *destinationFilePath;
  479. if ([CCUtility isCryptoPlistString:filename]) {
  480. destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], filename];
  481. } else {
  482. if (metadata.cryptated) destinationFilePath = [NSString stringWithFormat:@"%@/%@.crypt", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  483. else destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  484. }
  485. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  486. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  487. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  488. }
  489. }
  490. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID rev:(NSString *)rev date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode
  491. {
  492. #ifndef EXTENSION
  493. if (fileID)
  494. [app.listProgressMetadata removeObjectForKey:fileID];
  495. #endif
  496. // If fileID do not exists return.
  497. if (!fileID)
  498. return;
  499. // Progress Task
  500. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  501. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  502. if (errorCode != 0) {
  503. //
  504. // if cancel or was a xxxxxx.plist delete session
  505. //
  506. if (errorCode == kCFURLErrorCancelled || [CCUtility isCryptoPlistString:fileName]) {
  507. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierDone sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  508. } else {
  509. [CCCoreData setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier: k_taskIdentifierError sessionTaskIdentifierPlist: k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  510. }
  511. // Delegate downloadFileFailure:
  512. dispatch_async(dispatch_get_main_queue(), ^{
  513. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  514. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  515. });
  516. NSLog(@"[LOG] Download Failure Session Filename : %@ ERROR : %@", fileName, [NSString stringWithFormat:@"%@", @(errorCode)]);
  517. } else {
  518. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  519. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  520. if ([CCUtility isCryptoPlistString:fileName]) metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  521. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  522. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:metadata.sessionTaskIdentifier sessionTaskIdentifierPlist:metadata.sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  523. } else {
  524. [CCCoreData setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:metadata.sessionTaskIdentifier sessionTaskIdentifierPlist:metadata.sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  525. }
  526. // DATA
  527. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) {
  528. [CCCoreData downloadFile:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  529. }
  530. // download File Success
  531. dispatch_async(dispatch_get_main_queue(), ^{
  532. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  533. [[self getDelegate:fileID] downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  534. });
  535. NSLog(@"[LOG] Download Success Session Metadata : %@ - FileNamePrint : %@ - fileID : %@ - Task : [%i %i]", metadata.fileName, metadata.fileNamePrint, metadata.fileID, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  536. }
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Upload =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)uploadFileFromAssetLocalIdentifier:(NSString *)assetLocalIdentifier fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  542. {
  543. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil];
  544. if (!result.count) {
  545. [CCCoreData addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Internal error image/video not found [1]" type:k_activityVerboseDefault verbose:k_activityVerboseHigh account:_activeAccount activeUrl:_activeUrl];
  546. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  547. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"Internal error image/video not found" errorCode: k_CCErrorInternalError];
  548. return;
  549. }
  550. PHAsset *asset = result[0];
  551. PHAssetMediaType assetMediaType = asset.mediaType;
  552. NSDate *assetDate = asset.creationDate;
  553. __block NSError *error = nil;
  554. // create fileName
  555. NSString *assetFileName = [asset valueForKey:@"filename"];
  556. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", _directoryUser, fileName];
  557. //delegate
  558. if (delegate == nil)
  559. delegate = self.delegate;
  560. // VIDEO
  561. if (assetMediaType == PHAssetMediaTypeVideo) {
  562. // Automatic Upload video encrypted ?
  563. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  564. cryptated = [CCCoreData getCameraUploadCryptatedVideoActiveAccount:_activeAccount];
  565. @autoreleasepool {
  566. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  567. options.version = PHVideoRequestOptionsVersionOriginal;
  568. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  569. if ([asset isKindOfClass:[AVURLAsset class]]) {
  570. NSData *data = [[NSData alloc] initWithContentsOfURL:[(AVURLAsset *)asset URL] options:0 error:&error];
  571. if (!error || [data length] > 0) {
  572. [data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  573. } else {
  574. if (!error)
  575. error = [NSError errorWithDomain:@"it.twsweb.cryptocloud" code:kCFURLErrorFileDoesNotExist userInfo:nil];
  576. }
  577. } else {
  578. error = [NSError errorWithDomain:@"it.twsweb.cryptocloud" code:kCFURLErrorFileDoesNotExist userInfo:nil];
  579. }
  580. dispatch_async(dispatch_get_main_queue(), ^{
  581. if (error) {
  582. // Activity
  583. [CCCoreData addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_read_file_error_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  584. // Error for uploadFileFailure
  585. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  586. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"_read_file_error_" errorCode:error.code];
  587. } else {
  588. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:NO assetFileName:assetFileName assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  589. }
  590. });
  591. }];
  592. }
  593. }
  594. // IMAGE
  595. if (assetMediaType == PHAssetMediaTypeImage) {
  596. // Automatic Upload photo encrypted ?
  597. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  598. cryptated = [CCCoreData getCameraUploadCryptatedPhotoActiveAccount:_activeAccount];
  599. @autoreleasepool {
  600. PHImageRequestOptions *options = [PHImageRequestOptions new];
  601. options.synchronous = NO;
  602. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  603. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  604. dispatch_async(dispatch_get_main_queue(), ^{
  605. if (error) {
  606. // Activity
  607. [CCCoreData addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_read_file_error_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  608. // Error for uploadFileFailure
  609. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  610. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"_read_file_error_" errorCode:error.code];
  611. } else {
  612. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:NO assetFileName:assetFileName assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  613. }
  614. });
  615. }];
  616. }
  617. }
  618. }
  619. - (void)uploadFile:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  620. {
  621. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:onlyPlist assetFileName:nil assetDate:nil assetMediaType:PHAssetMediaTypeUnknown assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  622. }
  623. - (void)uploadTemplate:(NSString *)fileNamePrint fileNameCrypto:(NSString *)fileNameCrypto serverUrl:(NSString *)serverUrl session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  624. {
  625. [self upload:fileNameCrypto serverUrl:serverUrl cryptated:YES template:YES onlyPlist:NO assetFileName:fileNamePrint assetDate:nil assetMediaType:PHAssetMediaTypeUnknown assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  626. }
  627. - (void)upload:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated template:(BOOL)template onlyPlist:(BOOL)onlyPlist assetFileName:(NSString *)assetFileName assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType assetLocalIdentifier:(NSString *)assetLocalIdentifier session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  628. {
  629. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount];
  630. NSString *fileNameCrypto;
  631. // create Metadata
  632. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_activeAccount];
  633. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_activeAccount activeUrl:_activeUrl];
  634. CCMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath];
  635. //fileID
  636. NSString *uploadID = [k_uploadSessionID stringByAppendingString:[CCUtility createRandomString:16]];
  637. //add delegate
  638. if (delegate)
  639. [_delegates setObject:delegate forKey:uploadID];
  640. if (onlyPlist == YES) {
  641. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  642. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  643. metadata.date = [NSDate new];
  644. metadata.fileID = uploadID;
  645. metadata.directoryID = directoryID;
  646. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:fileName];
  647. metadata.assetLocalIdentifier = assetLocalIdentifier;
  648. metadata.session = session;
  649. metadata.sessionID = uploadID;
  650. metadata.sessionSelector = selector;
  651. metadata.sessionSelectorPost = selectorPost;
  652. metadata.typeFile = k_metadataTypeFile_unknown;
  653. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  654. [self uploadURLSession:fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  655. }
  656. else if (cryptated == YES) {
  657. if (template == YES) {
  658. // copy from temp to directory user
  659. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  660. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:[fileName stringByAppendingString:@".plist"]] toPath:[NSString stringWithFormat:@"%@/%@.plist", _directoryUser, fileName]];
  661. fileNameCrypto = fileName; // file Name Crypto
  662. fileName = assetFileName; // file Name Print
  663. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  664. metadata.date = [NSDate new];
  665. metadata.fileID = uploadID;
  666. metadata.directoryID = directoryID;
  667. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  668. metadata.fileNameData = fileNameCrypto;
  669. metadata.assetLocalIdentifier = assetLocalIdentifier;
  670. metadata.session = session;
  671. metadata.sessionID = uploadID;
  672. metadata.sessionSelector = selector;
  673. metadata.sessionSelectorPost = selectorPost;
  674. metadata.typeFile = k_metadataTypeFile_template;
  675. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  676. // DATA
  677. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  678. // PLIST
  679. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  680. }
  681. if (template == NO) {
  682. NSString *passcode = [[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]];
  683. fileNameCrypto = [[CCCrypto sharedManager] encryptWithCreatePlist:fileName fileNameEncrypted:fileName passcode:passcode directoryUser:_directoryUser];
  684. // Encrypted file error
  685. if (fileNameCrypto == nil) {
  686. dispatch_async(dispatch_get_main_queue(), ^{
  687. NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_error_", nil), fileName, @""];
  688. UIAlertController *alertController= [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  689. UIAlertAction* ok = [UIAlertAction actionWithTitle: NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  690. handler:^(UIAlertAction * action) {
  691. [alertController dismissViewControllerAnimated:YES completion:nil];
  692. }];
  693. [alertController addAction:ok];
  694. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  695. alertWindow.rootViewController = [[UIViewController alloc]init];
  696. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  697. [alertWindow makeKeyAndVisible];
  698. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  699. // Error for uploadFileFailure
  700. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  701. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_encrypt_error_", nil) errorCode:0];
  702. });
  703. return;
  704. }
  705. metadata.cryptated = YES;
  706. metadata.date = [NSDate new];
  707. metadata.fileID = uploadID;
  708. metadata.directoryID = directoryID;
  709. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  710. metadata.fileNameData = fileNameCrypto;
  711. metadata.fileNamePrint = fileName;
  712. metadata.assetLocalIdentifier = assetLocalIdentifier;
  713. metadata.session = session;
  714. metadata.sessionID = uploadID;
  715. metadata.sessionSelector = selector;
  716. metadata.sessionSelectorPost = selectorPost;
  717. metadata.title = [self getTitleFromPlistName:fileNameCrypto];
  718. metadata.type = k_metadataType_file;
  719. if (errorCode == 403) {
  720. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  721. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  722. dispatch_async(dispatch_get_main_queue(), ^{
  723. // Activity
  724. [CCCoreData addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  725. // Error for uploadFileFailure
  726. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  727. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  728. });
  729. return;
  730. }];
  731. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  732. // -- remove record --
  733. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, [fileNameCrypto stringByAppendingString:@".plist"], directoryID] context:nil];
  734. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser activeAccount:_activeAccount];
  735. #ifndef EXTENSION
  736. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  737. #endif
  738. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  739. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  740. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  741. // DATA
  742. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  743. // PLIST
  744. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  745. }];
  746. [alertController addAction:cancelAction];
  747. [alertController addAction:overwriteAction];
  748. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  749. alertWindow.rootViewController = [[UIViewController alloc]init];
  750. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  751. [alertWindow makeKeyAndVisible];
  752. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  753. } else {
  754. #ifndef EXTENSION
  755. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  756. #endif
  757. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  758. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  759. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  760. // DATA
  761. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  762. // PLIST
  763. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  764. }
  765. }
  766. }
  767. else if (cryptated == NO) {
  768. metadata.cryptated = NO;
  769. metadata.date = [NSDate new];
  770. metadata.fileID = uploadID;
  771. metadata.directoryID = directoryID;
  772. metadata.fileName = fileName;
  773. metadata.fileNameData = fileName;
  774. metadata.fileNamePrint = fileName;
  775. metadata.assetLocalIdentifier = assetLocalIdentifier;
  776. metadata.session = session;
  777. metadata.sessionID = uploadID;
  778. metadata.sessionSelector = selector;
  779. metadata.sessionSelectorPost = selectorPost;
  780. metadata.type = k_metadataType_file;
  781. // File exists ???
  782. if (errorCode == 403) {
  783. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  784. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  785. dispatch_async(dispatch_get_main_queue(), ^{
  786. // Activity
  787. [CCCoreData addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  788. // Error for uploadFileFailure
  789. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  790. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  791. });
  792. return;
  793. }];
  794. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  795. // -- remove record --
  796. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, fileName, directoryID] context:nil];
  797. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser activeAccount:_activeAccount];
  798. // -- Go to Upload --
  799. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  800. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  801. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  802. }];
  803. [alertController addAction:cancelAction];
  804. [alertController addAction:overwriteAction];
  805. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  806. alertWindow.rootViewController = [[UIViewController alloc] init];
  807. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  808. [alertWindow makeKeyAndVisible];
  809. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  810. } else {
  811. // -- Go to upload --
  812. #ifndef EXTENSION
  813. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  814. #endif
  815. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  816. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  817. }
  818. }
  819. }
  820. - (void)uploadFileMetadata:(CCMetadata *)metadata taskStatus:(NSInteger)taskStatus
  821. {
  822. BOOL send = NO;
  823. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  824. if (metadata.cryptated) {
  825. // ENCRYPTED
  826. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData]] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]) {
  827. send = YES;
  828. [self uploadURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetDate:nil assetMediaType:PHAssetMediaTypeUnknown assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  829. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetDate:nil assetMediaType:PHAssetMediaTypeUnknown assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  830. }
  831. } else {
  832. // PLAIN
  833. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  834. send = YES;
  835. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetDate:nil assetMediaType:PHAssetMediaTypeUnknown assetLocalIdentifier:nil cryptated:NO onlyPlist:NO selector:metadata.sessionSelector];
  836. }
  837. }
  838. if (send) {
  839. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  840. // update Coredata
  841. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", metadata.sessionID, _activeAccount] context:_context];
  842. } else {
  843. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  844. #ifndef EXTENSION
  845. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  846. [alertView show];
  847. #endif
  848. }
  849. }
  850. - (void)uploadURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID session:(NSString *)session taskStatus:(NSInteger)taskStatus assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType assetLocalIdentifier:(NSString *)assetLocalIdentifier cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist selector:(NSString *)selector
  851. {
  852. NSURLSession *sessionUpload;
  853. NSURL *url;
  854. NSMutableURLRequest *request;
  855. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  856. url = [NSURL URLWithString:fileNamePath];
  857. request = [NSMutableURLRequest requestWithURL:url];
  858. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  859. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  860. [request setHTTPMethod:@"PUT"];
  861. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  862. // Rename with the SessionID
  863. NSString *fileNameForUpload;
  864. if ([CCUtility isFileNotCryptated:fileName]) fileNameForUpload = sessionID;
  865. else fileNameForUpload = fileName;
  866. if (!onlyPlist) {
  867. if ([CCUtility isFileNotCryptated:fileName])
  868. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  869. if ([CCUtility isCryptoPlistString:fileName])
  870. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNamePrint] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  871. }
  872. // file NOT exists
  873. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  874. dispatch_async(dispatch_get_main_queue(), ^{
  875. // Activity
  876. [CCCoreData addActivityClient:fileName fileID:sessionID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_not_present_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  877. // Error for uploadFileFailure
  878. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  879. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  880. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount]];
  881. });
  882. return;
  883. }
  884. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  885. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  886. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  887. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  888. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  889. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  890. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  891. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadTaskSave:)])
  892. [[self getDelegate:sessionID] uploadTaskSave:uploadTask];
  893. // COREDATA
  894. if (uploadTask == nil) {
  895. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  896. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  897. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  898. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  899. [CCCoreData setMetadataSession:session sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] context:_context];
  900. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  901. } else {
  902. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  903. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  904. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = uploadTask.taskIdentifier;
  905. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = uploadTask.taskIdentifier;
  906. [CCCoreData setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] context:_context];
  907. // Delete record on Table Automatic Upload
  908. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  909. [CCCoreData deleteTableAutomaticUploadForAccount:_activeAccount assetLocalIdentifier:assetLocalIdentifier];
  910. NSLog(@"[LOG] Upload file %@ - %@ TaskIdentifier %lu", fileName,fileNamePrint, (unsigned long)uploadTask.taskIdentifier);
  911. }
  912. dispatch_async(dispatch_get_main_queue(), ^{
  913. // refresh main
  914. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  915. [self.delegate reloadDatasource:serverUrl fileID:nil selector:selector];
  916. });
  917. }
  918. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  919. {
  920. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  921. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  922. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  923. if (data)
  924. [_taskData setObject:[data copy] forKey:taskIdentifier];
  925. }
  926. }
  927. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  928. {
  929. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  930. NSString *fileName = [url lastPathComponent];
  931. NSString *serverUrl = [self getServerUrlFromUrl:url];
  932. // if plist return
  933. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  934. return;
  935. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  936. if ([_currentProgressMetadata.fileName isEqualToString:fileName] == NO && [_currentProgressMetadata.fileNameData isEqualToString:fileName] == NO)
  937. _currentProgressMetadata = [CCCoreData getMetadataFromFileName:fileName directoryID:[CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount] activeAccount:_activeAccount context:_context];
  938. //NSLog(@"[LOG] %@ - %f", fileName, progress);
  939. dispatch_async(dispatch_get_main_queue(), ^{
  940. if (_currentProgressMetadata) {
  941. if (_currentProgressMetadata) {
  942. NSDictionary* userInfo = @{@"fileID": (_currentProgressMetadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:_currentProgressMetadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  943. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  944. }
  945. }
  946. });
  947. }
  948. - (void)uploadFileSuccessFailure:(CCMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID rev:(NSString *)rev date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  949. {
  950. NSString *sessionID = metadata.sessionID;
  951. // Progress Task
  952. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  953. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  954. // ERRORE
  955. if (errorCode != 0) {
  956. #ifndef EXTENSION
  957. if (sessionID)
  958. [app.listProgressMetadata removeObjectForKey:sessionID];
  959. #endif
  960. // Mark error only if not Cancelled Task
  961. if (errorCode != kCFURLErrorCancelled) {
  962. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  963. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  964. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  965. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  966. [CCCoreData setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", metadata.sessionID, _activeAccount] context:_context];
  967. }
  968. dispatch_async(dispatch_get_main_queue(), ^{
  969. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  970. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  971. });
  972. return;
  973. }
  974. // PLAIN or PLIST
  975. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoPlistString:fileName]) {
  976. metadata.fileID = fileID;
  977. metadata.rev = rev;
  978. metadata.date = date;
  979. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  980. if ([CCUtility isFileNotCryptated:fileName])
  981. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  982. // copy ico in new fileID
  983. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  984. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  985. }
  986. // CRYPTO
  987. if ([CCUtility isCryptoString:fileName]) {
  988. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  989. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  990. }
  991. // ALL TASK DONE (PLAIN/CRYPTO)
  992. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  993. #ifndef EXTENSION
  994. if (sessionID)
  995. [app.listProgressMetadata removeObjectForKey:sessionID];
  996. #endif
  997. NSLog(@"[LOG] Insert new upload : %@ - FileNamePrint : %@ - fileID : %@", metadata.fileName, metadata.fileNamePrint, metadata.fileID);
  998. metadata.session = @"";
  999. metadata.sessionError = @"";
  1000. metadata.sessionID = @"";
  1001. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  1002. // rename file sessionID -> fileID
  1003. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  1004. // remove temp icon
  1005. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  1006. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  1007. // if crypto remove filename data
  1008. if (metadata.cryptated)
  1009. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData] error:nil];
  1010. // Local
  1011. if (metadata.directory == NO)
  1012. [CCCoreData addLocalFile:metadata activeAccount:_activeAccount];
  1013. // EXIF
  1014. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1015. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  1016. // Create ICON
  1017. if (metadata.directory == NO)
  1018. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1019. // Optimization
  1020. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  1021. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  1022. // Copy photo or video in the photo album for automatic upload
  1023. if ([metadata.assetLocalIdentifier length] > 0 && [metadata.sessionSelector isEqualToString:selectorUploadAutomatic]) {
  1024. PHAsset *asset;
  1025. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1026. if(result.count){
  1027. asset = result[0];
  1028. [asset saveToAlbum:k_brand completionBlock:^(BOOL success) {
  1029. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileNamePrint, k_brand);
  1030. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileNamePrint, k_brand);
  1031. }];
  1032. }
  1033. }
  1034. dispatch_async(dispatch_get_main_queue(), ^{
  1035. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  1036. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  1037. });
  1038. }
  1039. }
  1040. #pragma --------------------------------------------------------------------------------------------
  1041. #pragma mark ===== Download Verify =====
  1042. #pragma --------------------------------------------------------------------------------------------
  1043. - (void)verifyDownloadInProgress
  1044. {
  1045. NSArray *dataSourceDownload = [CCCoreData getTableMetadataDownloadAccount:_activeAccount];
  1046. NSArray *dataSourceDownloadWWan = [CCCoreData getTableMetadataDownloadWWanAccount:_activeAccount];
  1047. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1048. [dataSource addObjectsFromArray:dataSourceDownload];
  1049. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  1050. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  1051. for (TableMetadata *record in dataSource) {
  1052. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1053. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1054. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1055. BOOL findTask = NO;
  1056. BOOL findTaskPlist = NO;
  1057. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  1058. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  1059. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  1060. if (metadata.sessionTaskIdentifierPlist == downloadTask.taskIdentifier) findTaskPlist = YES;
  1061. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  1062. }
  1063. // DATA
  1064. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  1065. NSLog(@"[LOG] NOT Find metadata Task [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileNameData);
  1066. [CCCoreData setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskDownloadNotFound] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier: k_taskIdentifierError sessionTaskIdentifierPlist: k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, _activeAccount] context:_context];
  1067. dispatch_async(dispatch_get_main_queue(), ^{
  1068. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1069. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1070. });
  1071. }
  1072. // PLIST
  1073. if (findTaskPlist == NO && metadata.sessionTaskIdentifierPlist >= 0) {
  1074. NSLog(@"[LOG] NOT Find metadata TaskPlist [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifierPlist, metadata.fileID, metadata.fileName);
  1075. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, _activeAccount] context:_context];
  1076. dispatch_async(dispatch_get_main_queue(), ^{
  1077. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1078. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1079. });
  1080. }
  1081. }];
  1082. }
  1083. [self automaticDownloadInError];
  1084. }
  1085. - (void)automaticDownloadInError
  1086. {
  1087. NSMutableSet *serversUrl = [[NSMutableSet alloc] init];
  1088. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'download') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1089. NSLog(@"[LOG] Verify re download n. %lu", (unsigned long)[records count]);
  1090. for (TableMetadata *record in records) {
  1091. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1092. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1093. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  1094. [self downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1095. if (metadata.sessionTaskIdentifierPlist == k_taskIdentifierError)
  1096. [self downloadFile:metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1097. [serversUrl addObject:serverUrl];
  1098. NSLog(@"[LOG] Re download file : %@ - %@ [%i %i]", metadata.fileName, metadata.fileNamePrint, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  1099. }
  1100. dispatch_async(dispatch_get_main_queue(), ^{
  1101. for (NSString *serverUrl in serversUrl)
  1102. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1103. [self.delegate reloadDatasource:serverUrl fileID:nil selector:nil];
  1104. });
  1105. }
  1106. #pragma --------------------------------------------------------------------------------------------
  1107. #pragma mark ===== Upload Verify =====
  1108. #pragma --------------------------------------------------------------------------------------------
  1109. - (void)verifyUploadInProgress
  1110. {
  1111. NSArray *dataSourceUpload = [CCCoreData getTableMetadataUploadAccount:_activeAccount];
  1112. NSArray *dataSourceUploadWWan = [CCCoreData getTableMetadataUploadWWanAccount:_activeAccount];
  1113. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1114. [dataSource addObjectsFromArray:dataSourceUpload];
  1115. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1116. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1117. for (TableMetadata *record in dataSource) {
  1118. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1119. __block NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  1120. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1121. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1122. BOOL findTask = NO;
  1123. BOOL findTaskPlist = NO;
  1124. // cerchiamo la corrispondenza dei task
  1125. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1126. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist , (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1127. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1128. if (metadata.sessionTaskIdentifierPlist == uploadTask.taskIdentifier) findTaskPlist = YES;
  1129. if (findTask == YES || findTaskPlist == YES) break;
  1130. }
  1131. // se non c'è (ci sono) il relativo uploadTask.taskIdentifier allora chiediamolo
  1132. if ((metadata.cryptated == YES && findTask == NO && findTaskPlist == NO) || (metadata.cryptated == NO && findTask == NO)) {
  1133. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ (criptated %i) is in progress but there is no task : [%i %i]", metadata.fileNamePrint, metadata.cryptated, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  1134. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1135. if (metadata.sessionTaskIdentifierPlist >= 0) [self readFileVerifyUpload:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1136. }
  1137. }];
  1138. // Notification change session
  1139. dispatch_async(dispatch_get_main_queue(), ^{
  1140. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1141. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1142. });
  1143. }
  1144. [self automaticUploadInError];
  1145. }
  1146. - (void)automaticUploadInError
  1147. {
  1148. NSMutableSet *directoryIDs = [[NSMutableSet alloc] init];
  1149. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'upload') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1150. NSLog(@"[LOG] Verify re upload n. %lu", (unsigned long)[records count]);
  1151. for (TableMetadata *record in records) {
  1152. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1153. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1154. [directoryIDs addObject:metadata.directoryID];
  1155. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1156. }
  1157. dispatch_async(dispatch_get_main_queue(), ^{
  1158. for (NSString *directoryID in directoryIDs)
  1159. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1160. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:nil selector:nil];
  1161. });
  1162. }
  1163. - (void)readFileVerifyUpload:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl
  1164. {
  1165. #ifndef EXTENSION
  1166. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1167. metadataNet.action = actionReadFile;
  1168. metadataNet.fileName = fileName;
  1169. metadataNet.fileNamePrint = fileNamePrint;
  1170. metadataNet.serverUrl = serverUrl;
  1171. metadataNet.selector = selectorReadFileVerifyUpload;
  1172. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1173. #else
  1174. NSLog(@"[LOG] Function not available for extension.");
  1175. #endif
  1176. }
  1177. //
  1178. // File exists : selectorReadFileVerifyUpload
  1179. //
  1180. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1181. {
  1182. NSString *fileName;
  1183. if ([CCUtility isCryptoString:metadata.fileName])
  1184. fileName = [metadata.fileName stringByAppendingString:@".plist"];
  1185. else
  1186. fileName = metadataNet.fileName;
  1187. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1188. CCMetadata *metadataTemp = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)", fileName , directoryID, _activeAccount] context:_context];
  1189. // is completed ?
  1190. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone && metadataTemp.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1191. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1192. NSLog(@"[LOG] Verify read file success, but files already processed");
  1193. dispatch_async(dispatch_get_main_queue(), ^{
  1194. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1195. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:metadataTemp.fileID selector:metadataNet.selector];
  1196. });
  1197. } else {
  1198. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1199. }
  1200. }
  1201. //
  1202. // File do not exists : selectorReadFileVerifyUpload
  1203. //
  1204. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1205. {
  1206. NSString *fileName;
  1207. if ([CCUtility isCryptoString:metadataNet.fileName])
  1208. fileName = [metadataNet.fileName stringByAppendingString:@".plist"];
  1209. else
  1210. fileName = metadataNet.fileName;
  1211. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1212. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)",fileName , directoryID, _activeAccount] context:_context];
  1213. NSInteger error;
  1214. if (errorCode == kOCErrorServerPathNotFound)
  1215. error = k_CCErrorFileUploadNotFound;
  1216. else
  1217. error = errorCode;
  1218. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1219. }
  1220. #pragma --------------------------------------------------------------------------------------------
  1221. #pragma mark ===== Utility =====
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. - (id)getDelegate:(NSString *)fileID
  1224. {
  1225. id delegate = [_delegates objectForKey:fileID];
  1226. if (delegate)
  1227. return delegate;
  1228. else
  1229. return self.delegate;
  1230. }
  1231. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1232. {
  1233. NSString *fileName = [url lastPathComponent];
  1234. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1235. return url;
  1236. }
  1237. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1238. {
  1239. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1240. fileName = [fileName stringByAppendingString:@".plist"];
  1241. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1242. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1243. return [data objectForKey:@"title"];
  1244. }
  1245. @end