CCNetworking.m 101 KB

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