CCNetworking.m 101 KB

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