CCNetworking.m 100 KB

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