OCNetworking.m 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. //
  2. // OCnetworking.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "OCNetworking.h"
  24. #import "CCUtility.h"
  25. #import "CCGraphics.h"
  26. #import "CCCertificate.h"
  27. #import "NSString+Encode.h"
  28. #import "NCBridgeSwift.h"
  29. @implementation OCNetworking
  30. + (OCNetworking *)sharedManager {
  31. static OCNetworking *sharedManager;
  32. @synchronized(self)
  33. {
  34. if (!sharedManager) {
  35. sharedManager = [OCNetworking new];
  36. }
  37. return sharedManager;
  38. }
  39. }
  40. - (id)init
  41. {
  42. self = [super init];
  43. [self sharedOCCommunication];
  44. return self;
  45. }
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== OCCommunication =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (OCCommunication *)sharedOCCommunication
  50. {
  51. static OCCommunication* sharedOCCommunication = nil;
  52. if (sharedOCCommunication == nil)
  53. {
  54. // Network
  55. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  56. configuration.allowsCellularAccess = YES;
  57. configuration.discretionary = NO;
  58. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  59. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  60. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  61. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  62. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  63. // Download
  64. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  65. configurationDownload.allowsCellularAccess = YES;
  66. configurationDownload.discretionary = NO;
  67. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  68. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  69. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  70. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  71. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  72. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  73. return NSURLSessionAuthChallengePerformDefaultHandling;
  74. }];
  75. // Upload
  76. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  77. configurationUpload.allowsCellularAccess = YES;
  78. configurationUpload.discretionary = NO;
  79. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  80. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  81. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  82. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  83. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  84. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  85. return NSURLSessionAuthChallengePerformDefaultHandling;
  86. }];
  87. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  88. }
  89. return sharedOCCommunication;
  90. }
  91. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  92. {
  93. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  94. if (sharedOCCommunicationExtensionDownload == nil)
  95. {
  96. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  97. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  98. config.HTTPMaximumConnectionsPerHost = 1;
  99. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  100. config.timeoutIntervalForRequest = k_timeout_upload;
  101. config.sessionSendsLaunchEvents = YES;
  102. [config setAllowsCellularAccess:YES];
  103. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  104. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  105. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  106. return NSURLSessionAuthChallengePerformDefaultHandling;
  107. }];
  108. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  109. }
  110. return sharedOCCommunicationExtensionDownload;
  111. }
  112. #pragma --------------------------------------------------------------------------------------------
  113. #pragma mark ===== Server =====
  114. #pragma --------------------------------------------------------------------------------------------
  115. - (void)checkServerUrl:(NSString *)serverUrl user:(NSString *)user userID:(NSString *)userID password:(NSString *)password completion:(void (^)(NSString *message, NSInteger errorCode))completion
  116. {
  117. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  118. [communication setCredentialsWithUser:user andUserID:userID andPassword:password];
  119. [communication setUserAgent:[CCUtility getUserAgent]];
  120. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  121. completion(nil, 0);
  122. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  123. NSString *message;
  124. NSInteger errorCode = response.statusCode;
  125. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  126. errorCode = error.code;
  127. // Error
  128. if (errorCode == 503)
  129. message = NSLocalizedString(@"_server_error_retry_", nil);
  130. else
  131. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  132. completion(message, errorCode);
  133. }];
  134. }
  135. - (void)serverStatusUrl:(NSString *)serverUrl completion:(void(^)(NSString *serverProductName, NSInteger versionMajor, NSInteger versionMicro, NSInteger versionMinor, NSString *message, NSInteger errorCode))completion
  136. {
  137. NSString *urlTest = [serverUrl stringByAppendingString:k_serverStatus];
  138. // Remove stored cookies
  139. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  140. for (NSHTTPCookie *cookie in [storage cookies])
  141. {
  142. [storage deleteCookie:cookie];
  143. }
  144. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  145. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  146. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  147. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  148. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  149. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  150. dispatch_sync(dispatch_get_main_queue(), ^{
  151. if (error) {
  152. NSString *message;
  153. NSInteger errorCode;
  154. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  155. errorCode = httpResponse.statusCode;
  156. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  157. errorCode = error.code;
  158. // Error
  159. if (errorCode == 503)
  160. message = NSLocalizedString(@"_server_error_retry_", nil);
  161. else
  162. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  163. completion(nil, 0, 0, 0, message, errorCode);
  164. } else {
  165. NSString *serverProductName = @"";
  166. NSString *serverVersion = @"0.0.0";
  167. NSString *serverVersionString = @"0.0.0";
  168. NSInteger versionMajor = 0;
  169. NSInteger versionMicro = 0;
  170. NSInteger versionMinor = 0;
  171. NSError *error;
  172. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  173. if (error) {
  174. completion(nil, 0, 0, 0, NSLocalizedString(@"_no_nextcloud_found_", nil), k_CCErrorInternalError);
  175. return;
  176. }
  177. serverProductName = [[jsongParsed valueForKey:@"productname"] lowercaseString];
  178. serverVersion = [jsongParsed valueForKey:@"version"];
  179. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  180. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  181. if (arrayVersion.count == 1) {
  182. versionMajor = [arrayVersion[0] integerValue];
  183. } else if (arrayVersion.count == 2) {
  184. versionMajor = [arrayVersion[0] integerValue];
  185. versionMinor = [arrayVersion[1] integerValue];
  186. } else if (arrayVersion.count >= 3) {
  187. versionMajor = [arrayVersion[0] integerValue];
  188. versionMinor = [arrayVersion[1] integerValue];
  189. versionMicro = [arrayVersion[2] integerValue];
  190. }
  191. completion(serverProductName, versionMajor, versionMicro, versionMinor, nil, 0);
  192. }
  193. });
  194. }];
  195. [task resume];
  196. }
  197. - (void)downloadContentsOfUrl:(NSString *)serverUrl completion:(void(^)(NSData *data, NSString *message, NSInteger errorCode))completion
  198. {
  199. // Remove stored cookies
  200. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  201. for (NSHTTPCookie *cookie in [storage cookies])
  202. {
  203. [storage deleteCookie:cookie];
  204. }
  205. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverUrl] cachePolicy:0 timeoutInterval:20.0];
  206. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  207. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  208. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  209. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  210. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  211. dispatch_sync(dispatch_get_main_queue(), ^{
  212. if (error) {
  213. NSString *message;
  214. NSInteger errorCode;
  215. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  216. errorCode = httpResponse.statusCode;
  217. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  218. errorCode = error.code;
  219. // Error
  220. if (errorCode == 503)
  221. message = NSLocalizedString(@"_server_error_retry_", nil);
  222. else
  223. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  224. completion(nil, message, errorCode);
  225. } else {
  226. completion(data, nil, 0);
  227. }
  228. });
  229. }];
  230. [task resume];
  231. }
  232. #pragma --------------------------------------------------------------------------------------------
  233. #pragma mark ===== download / upload =====
  234. #pragma --------------------------------------------------------------------------------------------
  235. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication completion:(void (^)(NSString *account, int64_t length, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  236. {
  237. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  238. if (tableAccount == nil) {
  239. completion(account, 0, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  240. } else if ([CCUtility getPassword:account].length == 0) {
  241. completion(account, 0, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  242. }
  243. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  244. [communication setUserAgent:[CCUtility getUserAgent]];
  245. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  246. //float percent = roundf (progress.fractionCompleted * 100);
  247. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  248. int64_t totalUnitCount = 0;
  249. NSDate *date = [NSDate date];
  250. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  251. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  252. [dateFormatter setLocale:enUSPOSIXLocale];
  253. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  254. NSError *error;
  255. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  256. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  257. if(contentLength) {
  258. totalUnitCount = (int64_t) [contentLength longLongValue];
  259. }
  260. NSString *dateString = [fields objectForKey:@"Date"];
  261. if (dateString) {
  262. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  263. date = [NSDate date];
  264. }
  265. } else {
  266. date = [NSDate date];
  267. }
  268. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  269. if (etag == nil) {
  270. completion(account, 0, nil, nil, NSLocalizedString(@"Internal error", nil), k_CCErrorInternalError);
  271. } else {
  272. completion(account, totalUnitCount, etag, date, nil, 0);
  273. }
  274. } failureRequest:^(NSURLResponse *response, NSError *error) {
  275. NSString *message;
  276. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  277. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  278. errorCode = error.code;
  279. // Server Unauthorized
  280. if (errorCode == kOCErrorServerUnauthorized) {
  281. [CCUtility setPassword:account password:nil];
  282. }
  283. // Error
  284. if (errorCode == 503)
  285. message = NSLocalizedString(@"_server_error_retry_", nil);
  286. else
  287. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  288. completion(account, 0, nil, nil, message, errorCode);
  289. }];
  290. return sessionTask;
  291. }
  292. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account url:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  293. {
  294. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  295. if (tableAccount == nil) {
  296. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  297. } else if ([CCUtility getPassword:account].length == 0) {
  298. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  299. }
  300. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  301. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  302. [communication setUserAgent:[CCUtility getUserAgent]];
  303. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  304. //float percent = roundf (progress.fractionCompleted * 100);
  305. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  306. completion(account, nil, 0);
  307. } failureRequest:^(NSURLResponse *response, NSError *error) {
  308. NSString *message;
  309. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  310. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  311. errorCode = error.code;
  312. // Server Unauthorized
  313. if (errorCode == kOCErrorServerUnauthorized) {
  314. [CCUtility setPassword:account password:nil];
  315. }
  316. // Error
  317. if (errorCode == 503)
  318. message = NSLocalizedString(@"_server_error_retry_", nil);
  319. else
  320. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  321. completion(account, message, errorCode);
  322. }];
  323. return sessionTask;
  324. }
  325. - (NSURLSessionTask *)uploadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath progress:(void(^)(NSProgress *progress))uploadProgress completion:(void(^)(NSString *account, NSString *fileID, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  326. {
  327. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  328. if (tableAccount == nil) {
  329. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  330. } else if ([CCUtility getPassword:account].length == 0) {
  331. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  332. }
  333. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  334. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  335. [communication setUserAgent:[CCUtility getUserAgent]];
  336. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  337. uploadProgress(progress);
  338. //float percent = roundf (progress.fractionCompleted * 100);
  339. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  340. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  341. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  342. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  343. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  344. completion(account, fileID, etag, date, nil, 0);
  345. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  346. NSString *message;
  347. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  348. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  349. errorCode = error.code;
  350. // Server Unauthorized
  351. if (errorCode == kOCErrorServerUnauthorized) {
  352. [CCUtility setPassword:account password:nil];
  353. }
  354. // Error
  355. if (errorCode == 503)
  356. message = NSLocalizedString(@"_server_error_retry_", nil);
  357. else
  358. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  359. completion(account, nil, nil, nil, message, errorCode);
  360. } failureBeforeRequest:^(NSError *error) {
  361. completion(account, nil, nil, nil, error.description, error.code);
  362. }];
  363. return sessionTask;
  364. }
  365. #pragma --------------------------------------------------------------------------------------------
  366. #pragma mark ===== WebDav =====
  367. #pragma --------------------------------------------------------------------------------------------
  368. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  369. {
  370. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  371. if (tableAccount == nil) {
  372. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  373. } else if ([CCUtility getPassword:account].length == 0) {
  374. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  375. }
  376. NSString *url = tableAccount.url;
  377. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  378. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:url];
  379. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  380. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  381. [communication setUserAgent:[CCUtility getUserAgent]];
  382. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  383. // Check items > 0
  384. if ([items count] == 0) {
  385. #ifndef EXTENSION
  386. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  387. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  388. #endif
  389. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  390. } else {
  391. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  392. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  393. // directory [0]
  394. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  395. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  396. NSMutableArray *metadatas = [NSMutableArray new];
  397. tableMetadata *metadataFolder = [tableMetadata new];
  398. NSString *serverUrlFolder;
  399. // Metadata . (self Folder)
  400. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:url]]) {
  401. // root folder
  402. serverUrlFolder = k_serverUrl_root;
  403. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  404. } else {
  405. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  406. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  407. }
  408. // Add metadata folder
  409. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  410. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  411. NSString *first = [(OCFileDto*)a fileName];
  412. NSString *second = [(OCFileDto*)b fileName];
  413. return [[first lowercaseString] compare:[second lowercaseString]];
  414. }];
  415. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  416. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  417. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  418. // Skip hidden files
  419. if (fileName.length > 0) {
  420. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  421. continue;
  422. } else {
  423. continue;
  424. }
  425. if (itemDto.isDirectory) {
  426. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  427. }
  428. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  429. }
  430. completion(account, metadatas, metadataFolder, nil, 0);
  431. }
  432. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  433. NSString *message;
  434. NSInteger errorCode = response.statusCode;
  435. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  436. errorCode = error.code;
  437. // Server Unauthorized
  438. if (errorCode == kOCErrorServerUnauthorized) {
  439. [CCUtility setPassword:account password:nil];
  440. }
  441. // Error
  442. if (errorCode == 503)
  443. message = NSLocalizedString(@"_server_error_retry_", nil);
  444. else
  445. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  446. completion(account, nil, nil, message, errorCode);
  447. }];
  448. }
  449. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  450. {
  451. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  452. if (tableAccount == nil) {
  453. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  454. } else if ([CCUtility getPassword:account].length == 0) {
  455. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  456. }
  457. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  458. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  459. NSString *fileNamePath;
  460. if (fileName) {
  461. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  462. } else {
  463. fileName= @".";
  464. fileNamePath = serverUrl;
  465. }
  466. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  467. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  468. [communication setUserAgent:[CCUtility getUserAgent]];
  469. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  470. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  471. if ([items count] > 0) {
  472. tableMetadata *metadata = [tableMetadata new];
  473. OCFileDto *itemDto = [items objectAtIndex:0];
  474. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  475. completion(account, metadata, nil, 0);
  476. // BUG 1038 item == 0
  477. } else {
  478. #ifndef EXTENSION
  479. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  480. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  481. #endif
  482. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  483. }
  484. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  485. NSString *message;
  486. NSInteger errorCode = response.statusCode;
  487. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  488. errorCode = error.code;
  489. // Server Unauthorized
  490. if (errorCode == kOCErrorServerUnauthorized) {
  491. [CCUtility setPassword:account password:nil];
  492. }
  493. // Error
  494. if (errorCode == 503)
  495. message = NSLocalizedString(@"_server_error_retry_", nil);
  496. else
  497. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  498. completion(account, nil, message, errorCode);
  499. }];
  500. }
  501. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  502. {
  503. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  504. if (tableAccount == nil) {
  505. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  506. } else if ([CCUtility getPassword:account].length == 0) {
  507. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  508. }
  509. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  510. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  511. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  512. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  513. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  514. [communication setUserAgent:[CCUtility getUserAgent]];
  515. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  516. NSDictionary *fields = [response allHeaderFields];
  517. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  518. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  519. completion(account, fileID, date, nil, 0);
  520. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  521. NSString *message;
  522. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  523. message = nil;
  524. else
  525. message = [CCError manageErrorOC:response.statusCode error:error];
  526. NSInteger errorCode = response.statusCode;
  527. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  528. errorCode = error.code;
  529. // Server Unauthorized
  530. if (errorCode == kOCErrorServerUnauthorized) {
  531. [CCUtility setPassword:account password:nil];
  532. }
  533. completion(account, nil, nil, message, errorCode);
  534. } errorBeforeRequest:^(NSError *error) {
  535. NSString *message;
  536. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  537. message = nil;
  538. else {
  539. if (error.code == OCErrorForbidenCharacters)
  540. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  541. else
  542. message = NSLocalizedString(@"_unknow_response_server_", nil);
  543. }
  544. completion(account, nil, nil, message, error.code);
  545. }];
  546. }
  547. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  548. {
  549. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  550. if (tableAccount == nil) {
  551. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  552. } else if ([CCUtility getPassword:account].length == 0) {
  553. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  554. }
  555. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  556. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  557. [communication setUserAgent:[CCUtility getUserAgent]];
  558. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  559. completion(account, nil, 0);
  560. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  561. NSString *message;
  562. NSInteger errorCode = response.statusCode;
  563. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  564. errorCode = error.code;
  565. // Server Unauthorized
  566. if (errorCode == kOCErrorServerUnauthorized) {
  567. [CCUtility setPassword:account password:nil];
  568. }
  569. // Error
  570. if (errorCode == 503)
  571. message = NSLocalizedString(@"_server_error_retry_", nil);
  572. else
  573. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  574. completion(account, message, errorCode);
  575. }];
  576. }
  577. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  578. {
  579. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  580. if (tableAccount == nil) {
  581. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  582. } else if ([CCUtility getPassword:account].length == 0) {
  583. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  584. }
  585. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  586. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  587. [communication setUserAgent:[CCUtility getUserAgent]];
  588. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  589. completion(account, nil, 0);
  590. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  591. NSString *message;
  592. NSInteger errorCode = response.statusCode;
  593. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  594. errorCode = error.code;
  595. // Server Unauthorized
  596. if (errorCode == kOCErrorServerUnauthorized) {
  597. [CCUtility setPassword:account password:nil];
  598. }
  599. // Error
  600. if (errorCode == 503) {
  601. message = NSLocalizedString(@"_server_error_retry_", nil);
  602. } else {
  603. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  604. }
  605. completion(account, message, errorCode);
  606. } errorBeforeRequest:^(NSError *error) {
  607. NSString *message;
  608. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  609. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  610. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  611. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  612. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  613. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  614. } else {
  615. message = NSLocalizedString(@"_unknow_response_server_", nil);
  616. }
  617. completion(account, message, error.code);
  618. }];
  619. }
  620. - (void)searchWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl contentType:(NSArray *)contentType lteDateLastModified:(NSDate *)lteDateLastModified gteDateLastModified:(NSDate *)gteDateLastModified depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  621. {
  622. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  623. if (tableAccount == nil) {
  624. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  625. } else if ([CCUtility getPassword:account].length == 0) {
  626. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  627. }
  628. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  629. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  630. NSString *lteDateLastModifiedString;
  631. NSString *gteDateLastModifiedString;
  632. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  633. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  634. NSString *url = tableAccount.url;
  635. NSString *userID = tableAccount.userID;
  636. if (lteDateLastModified) {
  637. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  638. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  639. [dateFormatter setLocale:enUSPOSIXLocale];
  640. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  641. lteDateLastModifiedString = [dateFormatter stringFromDate:lteDateLastModified];
  642. }
  643. if (gteDateLastModified) {
  644. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  645. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  646. [dateFormatter setLocale:enUSPOSIXLocale];
  647. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  648. gteDateLastModifiedString = [dateFormatter stringFromDate:gteDateLastModified];
  649. }
  650. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  651. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  652. [communication setUserAgent:[CCUtility getUserAgent]];
  653. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", fileName] depth:depth lteDateLastModified:lteDateLastModifiedString gteDateLastModified:gteDateLastModifiedString contentType:contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  654. NSMutableArray *metadatas = [NSMutableArray new];
  655. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  656. for (OCFileDto *itemDto in items) {
  657. NSString *serverUrl;
  658. BOOL isFolderEncrypted;
  659. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  660. // Skip hidden files
  661. if (fileName.length > 0) {
  662. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  663. continue;
  664. } else
  665. continue;
  666. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, userID]];
  667. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  668. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  669. serverUrl = [CCUtility stringAppendServerUrl:[url stringByAppendingString:k_webDAV] addFileName:serverPath];
  670. if (itemDto.isDirectory) {
  671. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  672. }
  673. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  674. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  675. }
  676. completion(account, metadatas, nil, 0);
  677. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  678. NSString *message;
  679. NSInteger errorCode = response.statusCode;
  680. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  681. errorCode = error.code;
  682. // Server Unauthorized
  683. if (errorCode == kOCErrorServerUnauthorized) {
  684. [CCUtility setPassword:account password:nil];
  685. }
  686. // Error
  687. if (errorCode == 503) {
  688. message = NSLocalizedString(@"_server_error_retry_", nil);
  689. } else {
  690. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  691. }
  692. completion(account, nil, message, errorCode);
  693. }];
  694. }
  695. #pragma --------------------------------------------------------------------------------------------
  696. #pragma mark ===== downloadPreview =====
  697. #pragma --------------------------------------------------------------------------------------------
  698. /*
  699. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  700. {
  701. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  702. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  703. completion(nil, 0);
  704. } else {
  705. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  706. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  707. [communication setUserAgent:[CCUtility getUserAgent]];
  708. [communication getRemoteThumbnailByServer:_activeUrl ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:_activeUrl] withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  709. [thumbnail writeToFile:file atomically:YES];
  710. completion(nil, 0);
  711. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  712. NSString *message;
  713. NSInteger errorCode = response.statusCode;
  714. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  715. errorCode = error.code;
  716. // Error
  717. if (errorCode == 503)
  718. message = NSLocalizedString(@"_server_error_retry_", nil);
  719. else
  720. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  721. completion(message, errorCode);
  722. }];
  723. }
  724. }
  725. */
  726. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  727. {
  728. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  729. if (tableAccount == nil) {
  730. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  731. } else if ([CCUtility getPassword:account].length == 0) {
  732. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  733. }
  734. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  735. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  736. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  737. [communication setUserAgent:[CCUtility getUserAgent]];
  738. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:tableAccount.url] withWidth:width andHeight:height andA:1 andMode:@"cover" path:@"" onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  739. [preview writeToFile:file atomically:YES];
  740. completion(account, [UIImage imageWithData:preview], nil, 0);
  741. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  742. NSString *message;
  743. NSInteger errorCode = response.statusCode;
  744. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  745. errorCode = error.code;
  746. // Server Unauthorized
  747. if (errorCode == kOCErrorServerUnauthorized) {
  748. [CCUtility setPassword:account password:nil];
  749. }
  750. // Error
  751. if (errorCode == 503)
  752. message = NSLocalizedString(@"_server_error_retry_", nil);
  753. else
  754. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  755. completion(account, nil, message, errorCode);
  756. }];
  757. }
  758. - (void)downloadPreviewWithAccount:(NSString *)account serverPath:(NSString *)serverPath fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  759. {
  760. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  761. if (tableAccount == nil) {
  762. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  763. } else if ([CCUtility getPassword:account].length == 0) {
  764. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  765. }
  766. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  767. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  768. [communication setUserAgent:[CCUtility getUserAgent]];
  769. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:@"" withWidth:0 andHeight:0 andA:0 andMode:@"" path:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  770. [preview writeToFile:fileNamePath atomically:YES];
  771. completion(account, [UIImage imageWithData:preview], nil, 0);
  772. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  773. NSString *message;
  774. NSInteger errorCode = response.statusCode;
  775. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  776. errorCode = error.code;
  777. // Server Unauthorized
  778. if (errorCode == kOCErrorServerUnauthorized) {
  779. [CCUtility setPassword:account password:nil];
  780. }
  781. // Error
  782. if (errorCode == 503)
  783. message = NSLocalizedString(@"_server_error_retry_", nil);
  784. else
  785. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  786. completion(account, nil, message, errorCode);
  787. }];
  788. }
  789. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  790. {
  791. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  792. if (tableAccount == nil) {
  793. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  794. } else if ([CCUtility getPassword:account].length == 0) {
  795. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  796. }
  797. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  798. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  799. completion(account, [UIImage imageWithContentsOfFile:file], nil, 0);
  800. } else {
  801. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  802. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  803. [communication setUserAgent:[CCUtility getUserAgent]];
  804. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  805. [preview writeToFile:file atomically:YES];
  806. completion(account, [UIImage imageWithData:preview], nil, 0);
  807. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  808. NSString *message;
  809. NSInteger errorCode = response.statusCode;
  810. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  811. errorCode = error.code;
  812. // Server Unauthorized
  813. if (errorCode == kOCErrorServerUnauthorized) {
  814. [CCUtility setPassword:account password:nil];
  815. }
  816. // Error
  817. if (errorCode == 503)
  818. message = NSLocalizedString(@"_server_error_retry_", nil);
  819. else
  820. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  821. completion(account, nil, message, errorCode);
  822. }];
  823. }
  824. }
  825. #pragma --------------------------------------------------------------------------------------------
  826. #pragma mark ===== Favorite =====
  827. #pragma --------------------------------------------------------------------------------------------
  828. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  829. {
  830. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  831. if (tableAccount == nil) {
  832. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  833. } else if ([CCUtility getPassword:account].length == 0) {
  834. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  835. }
  836. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  837. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  838. NSString *url = tableAccount.url;
  839. NSString *userID = tableAccount.userID;
  840. NSString *path = [url stringByAppendingString:k_dav];
  841. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  842. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  843. [communication setUserAgent:[CCUtility getUserAgent]];
  844. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  845. NSMutableArray *metadatas = [NSMutableArray new];
  846. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  847. // Order by fileNamePath
  848. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  849. OCFileDto *record1 = obj1, *record2 = obj2;
  850. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  851. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  852. return [path1 compare:path2];
  853. }];
  854. for(OCFileDto *itemDto in items) {
  855. NSString *serverUrl;
  856. BOOL isFolderEncrypted;
  857. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  858. // Skip hidden files
  859. if (fileName.length > 0) {
  860. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  861. continue;
  862. } else
  863. continue;
  864. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, userID]];
  865. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  866. if ([serverPath hasSuffix:@"/"])
  867. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  868. serverUrl = [CCUtility stringAppendServerUrl:[url stringByAppendingString:k_webDAV] addFileName:serverPath];
  869. if (itemDto.isDirectory) {
  870. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  871. }
  872. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  873. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  874. }
  875. completion(account, metadatas, nil, 0);
  876. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  877. NSString *message;
  878. NSInteger errorCode = response.statusCode;
  879. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  880. errorCode = error.code;
  881. // Server Unauthorized
  882. if (errorCode == kOCErrorServerUnauthorized) {
  883. [CCUtility setPassword:account password:nil];
  884. }
  885. // Error
  886. if (errorCode == 503)
  887. message = NSLocalizedString(@"_server_error_retry_", nil);
  888. else
  889. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  890. completion(account, nil, message, errorCode);
  891. }];
  892. }
  893. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  894. {
  895. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  896. if (tableAccount == nil) {
  897. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  898. } else if ([CCUtility getPassword:account].length == 0) {
  899. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  900. }
  901. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  902. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  903. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  904. [communication setUserAgent:[CCUtility getUserAgent]];
  905. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  906. completion(account, nil, 0);
  907. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  908. NSString *message;
  909. NSInteger errorCode = response.statusCode;
  910. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  911. errorCode = error.code;
  912. // Server Unauthorized
  913. if (errorCode == kOCErrorServerUnauthorized) {
  914. [CCUtility setPassword:account password:nil];
  915. }
  916. // Error
  917. if (errorCode == 503)
  918. message = NSLocalizedString(@"_server_error_retry_", nil);
  919. else
  920. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  921. completion(account, message, errorCode);
  922. }];
  923. }
  924. #pragma --------------------------------------------------------------------------------------------
  925. #pragma mark ===== Share =====
  926. #pragma --------------------------------------------------------------------------------------------
  927. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  928. {
  929. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  930. if (tableAccount == nil) {
  931. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  932. } else if ([CCUtility getPassword:account].length == 0) {
  933. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  934. }
  935. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  936. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  937. [communication setUserAgent:[CCUtility getUserAgent]];
  938. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  939. completion(account, items, nil, 0);
  940. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  941. NSString *message;
  942. NSInteger errorCode = response.statusCode;
  943. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  944. errorCode = error.code;
  945. // Server Unauthorized
  946. if (errorCode == kOCErrorServerUnauthorized) {
  947. [CCUtility setPassword:account password:nil];
  948. }
  949. // Error
  950. if (errorCode == 503) {
  951. message = NSLocalizedString(@"_server_error_retry_", nil);
  952. } else {
  953. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  954. }
  955. completion(account, nil, message, errorCode);
  956. }];
  957. }
  958. - (void)shareWithAccount:(NSString *)account fileName:(NSString *)fileName password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  959. {
  960. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  961. if (tableAccount == nil) {
  962. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  963. } else if ([CCUtility getPassword:account].length == 0) {
  964. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  965. }
  966. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  967. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  968. [communication setUserAgent:[CCUtility getUserAgent]];
  969. [communication shareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPassword:[password encodeString:NSUTF8StringEncoding] andPermission:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  970. completion(account, nil, 0);
  971. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  972. NSString *message;
  973. NSInteger errorCode = response.statusCode;
  974. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  975. errorCode = error.code;
  976. // Server Unauthorized
  977. if (errorCode == kOCErrorServerUnauthorized) {
  978. [CCUtility setPassword:account password:nil];
  979. }
  980. // Error
  981. if (errorCode == 503) {
  982. message = NSLocalizedString(@"_server_error_retry_", nil);
  983. } else {
  984. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  985. }
  986. completion(account, message, errorCode);
  987. }];
  988. }
  989. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  990. - (void)shareUserGroupWithAccount:(NSString *)account userOrGroup:(NSString *)userOrGroup fileName:(NSString *)fileName permission:(NSInteger)permission shareeType:(NSInteger)shareeType completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  991. {
  992. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  993. if (tableAccount == nil) {
  994. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  995. } else if ([CCUtility getPassword:account].length == 0) {
  996. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  997. }
  998. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  999. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1000. [communication setUserAgent:[CCUtility getUserAgent]];
  1001. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1002. completion(account, nil, 0);
  1003. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1004. NSString *message;
  1005. NSInteger errorCode = response.statusCode;
  1006. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1007. errorCode = error.code;
  1008. // Server Unauthorized
  1009. if (errorCode == kOCErrorServerUnauthorized) {
  1010. [CCUtility setPassword:account password:nil];
  1011. }
  1012. // Error
  1013. if (errorCode == 503) {
  1014. message = NSLocalizedString(@"_server_error_retry_", nil);
  1015. } else {
  1016. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1017. }
  1018. completion(account, message, errorCode);
  1019. }];
  1020. }
  1021. - (void)shareUpdateAccount:(NSString *)account shareID:(NSInteger)shareID password:(NSString *)password permission:(NSInteger)permission expirationTime:(NSString *)expirationTime hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1022. {
  1023. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1024. if (tableAccount == nil) {
  1025. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1026. } else if ([CCUtility getPassword:account].length == 0) {
  1027. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1028. }
  1029. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1030. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1031. [communication setUserAgent:[CCUtility getUserAgent]];
  1032. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1033. completion(account, nil, 0);
  1034. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1035. NSString *message;
  1036. NSInteger errorCode = response.statusCode;
  1037. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1038. errorCode = error.code;
  1039. // Server Unauthorized
  1040. if (errorCode == kOCErrorServerUnauthorized) {
  1041. [CCUtility setPassword:account password:nil];
  1042. }
  1043. // Error
  1044. if (errorCode == 503) {
  1045. message = NSLocalizedString(@"_server_error_retry_", nil);
  1046. } else {
  1047. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1048. }
  1049. completion(account, message, errorCode);
  1050. }];
  1051. }
  1052. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1053. {
  1054. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1055. if (tableAccount == nil) {
  1056. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1057. } else if ([CCUtility getPassword:account].length == 0) {
  1058. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1059. }
  1060. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1061. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1062. [communication setUserAgent:[CCUtility getUserAgent]];
  1063. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1064. completion(account, nil, 0);
  1065. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1066. NSString *message;
  1067. NSInteger errorCode = response.statusCode;
  1068. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1069. errorCode = error.code;
  1070. // Server Unauthorized
  1071. if (errorCode == kOCErrorServerUnauthorized) {
  1072. [CCUtility setPassword:account password:nil];
  1073. }
  1074. // Error
  1075. if (errorCode == 503) {
  1076. message = NSLocalizedString(@"_server_error_retry_", nil);
  1077. } else {
  1078. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1079. }
  1080. completion(account, message, errorCode);
  1081. }];
  1082. }
  1083. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  1084. {
  1085. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1086. if (tableAccount == nil) {
  1087. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1088. } else if ([CCUtility getPassword:account].length == 0) {
  1089. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1090. }
  1091. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1092. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1093. [communication setUserAgent:[CCUtility getUserAgent]];
  1094. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  1095. completion(account, itemList, nil, 0);
  1096. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1097. NSString *message;
  1098. NSInteger errorCode = response.statusCode;
  1099. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1100. errorCode = error.code;
  1101. // Server Unauthorized
  1102. if (errorCode == kOCErrorServerUnauthorized) {
  1103. [CCUtility setPassword:account password:nil];
  1104. }
  1105. // Error
  1106. if (errorCode == 503) {
  1107. message = NSLocalizedString(@"_server_error_retry_", nil);
  1108. } else {
  1109. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1110. }
  1111. completion(account, nil, message, errorCode);
  1112. }];
  1113. }
  1114. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  1115. {
  1116. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1117. if (tableAccount == nil) {
  1118. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1119. } else if ([CCUtility getPassword:account].length == 0) {
  1120. completion(account, 0, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1121. }
  1122. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1123. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1124. [communication setUserAgent:[CCUtility getUserAgent]];
  1125. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  1126. completion(account, permissions, nil ,0);
  1127. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1128. NSString *message;
  1129. NSInteger errorCode = response.statusCode;
  1130. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1131. errorCode = error.code;
  1132. // Server Unauthorized
  1133. if (errorCode == kOCErrorServerUnauthorized) {
  1134. [CCUtility setPassword:account password:nil];
  1135. }
  1136. // Error
  1137. if (errorCode == 503) {
  1138. message = NSLocalizedString(@"_server_error_retry_", nil);
  1139. } else {
  1140. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1141. }
  1142. completion(account, nil, message, errorCode);
  1143. }];
  1144. }
  1145. #pragma --------------------------------------------------------------------------------------------
  1146. #pragma mark ===== VAR =====
  1147. #pragma --------------------------------------------------------------------------------------------
  1148. - (void)getActivityWithAccount:(NSString *)account since:(NSInteger)since limit:(NSInteger)limit link:(NSString *)link completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  1149. {
  1150. BOOL previews = false;
  1151. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1152. if (tableAccount == nil) {
  1153. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1154. } else if ([CCUtility getPassword:account].length == 0) {
  1155. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1156. }
  1157. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1158. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  1159. previews = true;
  1160. }
  1161. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1162. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1163. [communication setUserAgent:[CCUtility getUserAgent]];
  1164. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] since:since limit:limit previews:previews link:link onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  1165. completion(account, listOfActivity, nil, 0);
  1166. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1167. NSString *message;
  1168. NSInteger errorCode = response.statusCode;
  1169. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1170. errorCode = error.code;
  1171. // Server Unauthorized
  1172. if (errorCode == kOCErrorServerUnauthorized) {
  1173. [CCUtility setPassword:account password:nil];
  1174. }
  1175. // Error
  1176. if (errorCode == 503)
  1177. message = NSLocalizedString(@"_server_error_retry_", nil);
  1178. else
  1179. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1180. completion(account, nil, message, errorCode);
  1181. }];
  1182. }
  1183. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  1184. {
  1185. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1186. if (tableAccount == nil) {
  1187. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1188. } else if ([CCUtility getPassword:account].length == 0) {
  1189. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1190. }
  1191. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1192. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1193. [communication setUserAgent:[CCUtility getUserAgent]];
  1194. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1195. completion(account, listOfExternalSites, nil, 0);
  1196. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1197. NSString *message;
  1198. NSInteger errorCode = response.statusCode;
  1199. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1200. errorCode = error.code;
  1201. // Server Unauthorized
  1202. if (errorCode == kOCErrorServerUnauthorized) {
  1203. [CCUtility setPassword:account password:nil];
  1204. }
  1205. // Error
  1206. if (errorCode == 503) {
  1207. message = NSLocalizedString(@"_server_error_retry_", nil);
  1208. } else {
  1209. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1210. }
  1211. completion(account, nil, message, errorCode);
  1212. }];
  1213. }
  1214. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1215. {
  1216. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1217. if (tableAccount == nil) {
  1218. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1219. } else if ([CCUtility getPassword:account].length == 0) {
  1220. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1221. }
  1222. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1223. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1224. [communication setUserAgent:[CCUtility getUserAgent]];
  1225. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1226. completion(account, listOfNotifications, nil, 0);
  1227. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1228. NSString *message;
  1229. NSInteger errorCode = response.statusCode;
  1230. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1231. errorCode = error.code;
  1232. // Server Unauthorized
  1233. if (errorCode == kOCErrorServerUnauthorized) {
  1234. [CCUtility setPassword:account password:nil];
  1235. }
  1236. // Error
  1237. if (errorCode == 503) {
  1238. message = NSLocalizedString(@"_server_error_retry_", nil);
  1239. } else {
  1240. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1241. }
  1242. completion(account, nil, message, errorCode);
  1243. }];
  1244. }
  1245. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1246. {
  1247. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1248. if (tableAccount == nil) {
  1249. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1250. } else if ([CCUtility getPassword:account].length == 0) {
  1251. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1252. }
  1253. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1254. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1255. [communication setUserAgent:[CCUtility getUserAgent]];
  1256. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1257. completion(account, nil, 0);
  1258. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1259. NSString *message;
  1260. NSInteger errorCode = response.statusCode;
  1261. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1262. errorCode = error.code;
  1263. // Server Unauthorized
  1264. if (errorCode == kOCErrorServerUnauthorized) {
  1265. [CCUtility setPassword:account password:nil];
  1266. }
  1267. // Error
  1268. if (errorCode == 503) {
  1269. message = NSLocalizedString(@"_server_error_retry_", nil);
  1270. } else {
  1271. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1272. }
  1273. completion(account, message, errorCode);
  1274. }];
  1275. }
  1276. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1277. {
  1278. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1279. if (tableAccount == nil) {
  1280. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1281. } else if ([CCUtility getPassword:account].length == 0) {
  1282. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1283. }
  1284. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1285. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1286. [communication setUserAgent:[CCUtility getUserAgent]];
  1287. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1288. completion(account, capabilities, nil, 0);
  1289. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1290. NSString *message;
  1291. NSInteger errorCode = response.statusCode;
  1292. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1293. errorCode = error.code;
  1294. // Server Unauthorized
  1295. if (errorCode == kOCErrorServerUnauthorized) {
  1296. [CCUtility setPassword:account password:nil];
  1297. }
  1298. // Error
  1299. if (errorCode == 503) {
  1300. message = NSLocalizedString(@"_server_error_retry_", nil);
  1301. } else {
  1302. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1303. }
  1304. completion(account, nil, message, errorCode);
  1305. }];
  1306. }
  1307. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1308. {
  1309. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1310. if (tableAccount == nil) {
  1311. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1312. } else if ([CCUtility getPassword:account].length == 0) {
  1313. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1314. }
  1315. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1316. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1317. [communication setUserAgent:[CCUtility getUserAgent]];
  1318. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1319. completion(account, userProfile, nil, 0);
  1320. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1321. NSString *message;
  1322. NSInteger errorCode = response.statusCode;
  1323. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1324. errorCode = error.code;
  1325. // Server Unauthorized
  1326. if (errorCode == kOCErrorServerUnauthorized) {
  1327. [CCUtility setPassword:account password:nil];
  1328. }
  1329. // Error
  1330. if (errorCode == 503) {
  1331. message = NSLocalizedString(@"_server_error_retry_", nil);
  1332. } else {
  1333. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1334. }
  1335. completion(account, nil, message, errorCode);
  1336. }];
  1337. }
  1338. #pragma --------------------------------------------------------------------------------------------
  1339. #pragma mark ===== Push Notification =====
  1340. #pragma --------------------------------------------------------------------------------------------
  1341. - (void)subscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey completion:(void(^)(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode))completion
  1342. {
  1343. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1344. if (tableAccount == nil) {
  1345. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1346. } else if ([CCUtility getPassword:account].length == 0) {
  1347. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1348. }
  1349. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1350. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1351. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1352. #ifdef DEBUG
  1353. proxyServerPath = @"http://127.0.0.1:8088";
  1354. proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1355. #endif
  1356. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1357. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1358. [communication setUserAgent:[CCUtility getUserAgent]];
  1359. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1360. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1361. signature = [CCUtility URLEncodeStringFromString:signature];
  1362. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1363. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1364. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1365. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1366. NSString *message;
  1367. NSInteger errorCode = response.statusCode;
  1368. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1369. errorCode = error.code;
  1370. // Server Unauthorized
  1371. if (errorCode == kOCErrorServerUnauthorized) {
  1372. [CCUtility setPassword:account password:nil];
  1373. }
  1374. // Error
  1375. if (errorCode == 503)
  1376. message = NSLocalizedString(@"_server_error_retry_", nil);
  1377. else
  1378. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1379. completion(account, nil, nil, nil, message, errorCode);
  1380. }];
  1381. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1382. NSString *message;
  1383. NSInteger errorCode = response.statusCode;
  1384. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1385. errorCode = error.code;
  1386. // Server Unauthorized
  1387. if (errorCode == kOCErrorServerUnauthorized) {
  1388. [CCUtility setPassword:account password:nil];
  1389. }
  1390. // Error
  1391. if (errorCode == 503)
  1392. message = NSLocalizedString(@"_server_error_retry_", nil);
  1393. else
  1394. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1395. completion(account, nil, nil, nil, message, errorCode);
  1396. }];
  1397. }
  1398. - (void)unsubscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature publicKey:(NSString *)publicKey completion:(void (^)(NSString *account ,NSString *message, NSInteger errorCode))completion {
  1399. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1400. if (tableAccount == nil) {
  1401. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1402. } else if ([CCUtility getPassword:account].length == 0) {
  1403. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1404. }
  1405. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1406. #ifdef DEBUG
  1407. proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1408. #endif
  1409. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1410. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1411. [communication setUserAgent:[CCUtility getUserAgent]];
  1412. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1413. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1414. completion(account, nil, 0);
  1415. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1416. NSString *message;
  1417. NSInteger errorCode = response.statusCode;
  1418. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1419. errorCode = error.code;
  1420. // Server Unauthorized
  1421. if (errorCode == kOCErrorServerUnauthorized) {
  1422. [CCUtility setPassword:account password:nil];
  1423. }
  1424. // Error
  1425. if (errorCode == 503)
  1426. message = NSLocalizedString(@"_server_error_retry_", nil);
  1427. else
  1428. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1429. completion(account, message, errorCode);
  1430. }];
  1431. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1432. NSString *message;
  1433. NSInteger errorCode = response.statusCode;
  1434. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1435. errorCode = error.code;
  1436. // Server Unauthorized
  1437. if (errorCode == kOCErrorServerUnauthorized) {
  1438. [CCUtility setPassword:account password:nil];
  1439. }
  1440. // Error
  1441. if (errorCode == 503)
  1442. message = NSLocalizedString(@"_server_error_retry_", nil);
  1443. else
  1444. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1445. completion(account, message, errorCode);
  1446. }];
  1447. }
  1448. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  1449. {
  1450. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  1451. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1452. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1453. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1454. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1455. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1456. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1457. if (error) {
  1458. NSString *message;
  1459. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1460. NSInteger errorCode = httpResponse.statusCode;
  1461. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1462. errorCode = error.code;
  1463. // Error
  1464. if (errorCode == 503)
  1465. message = NSLocalizedString(@"_server_error_retry_", nil);
  1466. else
  1467. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1468. completion(nil, message, errorCode);
  1469. } else {
  1470. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  1471. completion(jsongParsed, nil, 0);
  1472. }
  1473. }];
  1474. [task resume];
  1475. }
  1476. #pragma --------------------------------------------------------------------------------------------
  1477. #pragma mark ===== Manage Mobile Editor OCS API =====
  1478. #pragma --------------------------------------------------------------------------------------------
  1479. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1480. {
  1481. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1482. if (tableAccount == nil) {
  1483. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1484. } else if ([CCUtility getPassword:account].length == 0) {
  1485. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1486. }
  1487. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1488. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1489. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1490. [communication setUserAgent:[CCUtility getUserAgent]];
  1491. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1492. completion(account, link, nil, 0);
  1493. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1494. NSString *message;
  1495. NSInteger errorCode = response.statusCode;
  1496. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1497. errorCode = error.code;
  1498. // Server Unauthorized
  1499. if (errorCode == kOCErrorServerUnauthorized) {
  1500. [CCUtility setPassword:account password:nil];
  1501. }
  1502. // Error
  1503. if (errorCode == 503)
  1504. message = NSLocalizedString(@"_server_error_retry_", nil);
  1505. else
  1506. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1507. completion(account, nil,message, errorCode);
  1508. }];
  1509. }
  1510. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1511. {
  1512. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1513. if (tableAccount == nil) {
  1514. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1515. } else if ([CCUtility getPassword:account].length == 0) {
  1516. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1517. }
  1518. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1519. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1520. [communication setUserAgent:[CCUtility getUserAgent]];
  1521. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1522. completion(account, listOfTemplate, nil, 0);
  1523. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1524. NSString *message;
  1525. NSInteger errorCode = response.statusCode;
  1526. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1527. errorCode = error.code;
  1528. // Server Unauthorized
  1529. if (errorCode == kOCErrorServerUnauthorized) {
  1530. [CCUtility setPassword:account password:nil];
  1531. }
  1532. // Error
  1533. if (errorCode == 503)
  1534. message = NSLocalizedString(@"_server_error_retry_", nil);
  1535. else
  1536. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1537. completion(account, nil, message, errorCode);
  1538. }];
  1539. }
  1540. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1541. {
  1542. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1543. if (tableAccount == nil) {
  1544. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1545. } else if ([CCUtility getPassword:account].length == 0) {
  1546. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1547. }
  1548. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1549. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1550. [communication setUserAgent:[CCUtility getUserAgent]];
  1551. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1552. completion(account, url, nil, 0);
  1553. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1554. NSString *message;
  1555. NSInteger errorCode = response.statusCode;
  1556. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1557. errorCode = error.code;
  1558. // Server Unauthorized
  1559. if (errorCode == kOCErrorServerUnauthorized) {
  1560. [CCUtility setPassword:account password:nil];
  1561. }
  1562. // Error
  1563. if (errorCode == 503)
  1564. message = NSLocalizedString(@"_server_error_retry_", nil);
  1565. else
  1566. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1567. completion(account, nil, message, errorCode);
  1568. }];
  1569. }
  1570. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1571. {
  1572. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1573. if (tableAccount == nil) {
  1574. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1575. } else if ([CCUtility getPassword:account].length == 0) {
  1576. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1577. }
  1578. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1579. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1580. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1581. [communication setUserAgent:[CCUtility getUserAgent]];
  1582. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1583. completion(account, url, nil, 0);
  1584. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1585. NSString *message;
  1586. NSInteger errorCode = response.statusCode;
  1587. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1588. errorCode = error.code;
  1589. // Server Unauthorized
  1590. if (errorCode == kOCErrorServerUnauthorized) {
  1591. [CCUtility setPassword:account password:nil];
  1592. }
  1593. // Error
  1594. if (errorCode == 503)
  1595. message = NSLocalizedString(@"_server_error_retry_", nil);
  1596. else
  1597. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1598. completion(account, nil, message, errorCode);
  1599. }];
  1600. }
  1601. #pragma --------------------------------------------------------------------------------------------
  1602. #pragma mark ===== Trash =====
  1603. #pragma --------------------------------------------------------------------------------------------
  1604. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1605. {
  1606. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1607. if (tableAccount == nil) {
  1608. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1609. } else if ([CCUtility getPassword:account].length == 0) {
  1610. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1611. }
  1612. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1613. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1614. [communication setUserAgent:[CCUtility getUserAgent]];
  1615. [communication listingTrash:[serverUrl stringByAppendingString:path] depth:depth onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1616. // Check items > 0
  1617. if ([items count] == 0) {
  1618. #ifndef EXTENSION
  1619. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1620. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1621. #endif
  1622. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1623. } else {
  1624. NSMutableArray *listTrash = [NSMutableArray new];
  1625. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1626. if ([items count] > 1) {
  1627. for (NSUInteger i=1; i < [items count]; i++) {
  1628. OCFileDto *itemDto = [items objectAtIndex:i];
  1629. tableTrash *trash = [tableTrash new];
  1630. trash.account = account;
  1631. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1632. trash.directory = itemDto.isDirectory;
  1633. trash.fileID = itemDto.ocId;
  1634. trash.fileName = itemDto.fileName;
  1635. NSArray *array = [itemDto.filePath componentsSeparatedByString:path];
  1636. long len = [[array objectAtIndex:0] length];
  1637. trash.filePath = [itemDto.filePath substringFromIndex:len];
  1638. trash.size = itemDto.size;
  1639. trash.trashbinFileName = itemDto.trashbinFileName;
  1640. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1641. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1642. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1643. [listTrash addObject:trash];
  1644. }
  1645. }
  1646. completion(account, listTrash, nil, 0);
  1647. }
  1648. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1649. NSString *message;
  1650. NSInteger errorCode = response.statusCode;
  1651. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1652. errorCode = error.code;
  1653. // Server Unauthorized
  1654. if (errorCode == kOCErrorServerUnauthorized) {
  1655. [CCUtility setPassword:account password:nil];
  1656. }
  1657. // Error
  1658. if (errorCode == 503)
  1659. message = NSLocalizedString(@"_server_error_retry_", nil);
  1660. else
  1661. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1662. completion(account, nil,message, errorCode);
  1663. }];
  1664. }
  1665. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1666. {
  1667. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1668. if (tableAccount == nil) {
  1669. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1670. } else if ([CCUtility getPassword:account].length == 0) {
  1671. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1672. }
  1673. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1674. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1675. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1676. [communication setUserAgent:[CCUtility getUserAgent]];
  1677. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1678. completion(account, nil, 0);
  1679. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1680. NSString *message;
  1681. NSInteger errorCode = response.statusCode;
  1682. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1683. errorCode = error.code;
  1684. // Server Unauthorized
  1685. if (errorCode == kOCErrorServerUnauthorized) {
  1686. [CCUtility setPassword:account password:nil];
  1687. }
  1688. // Error
  1689. if (errorCode == 503)
  1690. message = NSLocalizedString(@"_server_error_retry_", nil);
  1691. else
  1692. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1693. completion(account, message, errorCode);
  1694. }];
  1695. }
  1696. #pragma --------------------------------------------------------------------------------------------
  1697. #pragma mark ===== Third Parts =====
  1698. #pragma --------------------------------------------------------------------------------------------
  1699. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1700. {
  1701. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1702. if (tableAccount == nil) {
  1703. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1704. } else if ([CCUtility getPassword:account].length == 0) {
  1705. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1706. }
  1707. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1708. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1709. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1710. [communication setUserAgent:[CCUtility getUserAgent]];
  1711. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1712. completion(account, userProfile, nil, 0);
  1713. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1714. NSString *message;
  1715. NSInteger errorCode = response.statusCode;
  1716. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1717. errorCode = error.code;
  1718. // Server Unauthorized
  1719. if (errorCode == kOCErrorServerUnauthorized) {
  1720. [CCUtility setPassword:account password:nil];
  1721. }
  1722. // Error
  1723. if (errorCode == 503)
  1724. message = NSLocalizedString(@"_server_error_retry_", nil);
  1725. else
  1726. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1727. completion(account, nil,message, errorCode);
  1728. }];
  1729. }
  1730. - (void)putHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl address:(NSString *)address businesssize:(NSString *)businesssize businesstype:(NSString *)businesstype city:(NSString *)city company:(NSString *)company country:(NSString *)country displayname:(NSString *)displayname email:(NSString *)email phone:(NSString *)phone role_:(NSString *)role_ twitter:(NSString *)twitter website:(NSString *)website zip:(NSString *)zip completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1731. {
  1732. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1733. if (tableAccount == nil) {
  1734. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1735. } else if ([CCUtility getPassword:account].length == 0) {
  1736. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1737. }
  1738. // Create JSON
  1739. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1740. if (address) [dataDic setValue:address forKey:@"address"];
  1741. if (businesssize) {
  1742. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  1743. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  1744. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  1745. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  1746. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  1747. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  1748. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  1749. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  1750. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  1751. }
  1752. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  1753. if (city) [dataDic setValue:city forKey:@"city"];
  1754. if (company) [dataDic setValue:company forKey:@"company"];
  1755. if (country) [dataDic setValue:country forKey:@"country"];
  1756. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  1757. if (email) [dataDic setValue:email forKey:@"email"];
  1758. if (phone) [dataDic setValue:phone forKey:@"phone"];
  1759. if (role_) [dataDic setValue:role_ forKey:@"role"];
  1760. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  1761. if (website) [dataDic setValue:website forKey:@"website"];
  1762. if (zip) [dataDic setValue:zip forKey:@"zip"];
  1763. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1764. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1765. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1766. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1767. [communication setUserAgent:[CCUtility getUserAgent]];
  1768. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1769. completion(account, nil, 0);
  1770. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1771. NSString *message;
  1772. NSInteger errorCode = response.statusCode;
  1773. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1774. errorCode = error.code;
  1775. // Server Unauthorized
  1776. if (errorCode == kOCErrorServerUnauthorized) {
  1777. [CCUtility setPassword:account password:nil];
  1778. }
  1779. // Error
  1780. if (errorCode == 503)
  1781. message = NSLocalizedString(@"_server_error_retry_", nil);
  1782. else
  1783. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1784. completion(account, message, errorCode);
  1785. }];
  1786. }
  1787. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  1788. {
  1789. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1790. if (tableAccount == nil) {
  1791. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1792. } else if ([CCUtility getPassword:account].length == 0) {
  1793. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1794. }
  1795. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  1796. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1797. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1798. [communication setUserAgent:[CCUtility getUserAgent]];
  1799. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  1800. completion(account, features, nil, 0);
  1801. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1802. NSString *message;
  1803. NSInteger errorCode = response.statusCode;
  1804. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1805. errorCode = error.code;
  1806. // Server Unauthorized
  1807. if (errorCode == kOCErrorServerUnauthorized) {
  1808. [CCUtility setPassword:account password:nil];
  1809. }
  1810. // Error
  1811. if (errorCode == 503)
  1812. message = NSLocalizedString(@"_server_error_retry_", nil);
  1813. else
  1814. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1815. completion(account, nil,message, errorCode);
  1816. }];
  1817. }
  1818. /*
  1819. - (void)middlewarePing
  1820. {
  1821. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1822. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1823. [communication setUserAgent:[CCUtility getUserAgent]];
  1824. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1825. [self complete];
  1826. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1827. NSInteger errorCode = response.statusCode;
  1828. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1829. errorCode = error.code;
  1830. // Error
  1831. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1832. if (errorCode == 503)
  1833. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1834. else
  1835. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1836. }
  1837. // Request trusted certificated
  1838. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1839. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1840. [self complete];
  1841. }];
  1842. }
  1843. */
  1844. #pragma --------------------------------------------------------------------------------------------
  1845. #pragma mark ===== didReceiveChallenge =====
  1846. #pragma --------------------------------------------------------------------------------------------
  1847. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  1848. {
  1849. // The pinnning check
  1850. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1851. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1852. } else {
  1853. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1854. }
  1855. }
  1856. @end
  1857. #pragma --------------------------------------------------------------------------------------------
  1858. #pragma mark ===== OCURLSessionManager =====
  1859. #pragma --------------------------------------------------------------------------------------------
  1860. @implementation OCURLSessionManager
  1861. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1862. {
  1863. // The pinnning check
  1864. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1865. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1866. } else {
  1867. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1868. }
  1869. }
  1870. @end