CCNetworking.m 94 KB

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