CCNetworking.m 101 KB

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