CCNetworking.m 99 KB

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