AppDelegate.m 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  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 "AppDelegate.h"
  24. #import "CCNetworking.h"
  25. #import "CCGraphics.h"
  26. #import "CCSynchronize.h"
  27. #import "CCMain.h"
  28. #import <Fabric/Fabric.h>
  29. #import <Crashlytics/Crashlytics.h>
  30. #import "NCBridgeSwift.h"
  31. #import "NCAutoUpload.h"
  32. #import "NCPushNotificationEncryption.h"
  33. #import <QuartzCore/QuartzCore.h>
  34. @class NCViewerRichdocument;
  35. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  36. @end
  37. @implementation AppDelegate
  38. + (void)initialize
  39. {
  40. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  41. }
  42. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  43. {
  44. // Fabric
  45. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  46. [Fabric with:@[[Crashlytics class]]];
  47. }
  48. [CCUtility createDirectoryStandard];
  49. [CCUtility emptyTemporaryDirectory];
  50. // Networking
  51. [[NCCommunicationCommon sharedInstance] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups delegate:[NCNetworking sharedInstance]];
  52. // Verify upgrade
  53. if ([self upgrade]) {
  54. // Set account, if no exists clear all
  55. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  56. if (tableAccount == nil) {
  57. // remove all the keys Chain
  58. [CCUtility deleteAllChainStore];
  59. // remove all the App group key
  60. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  61. } else {
  62. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  63. }
  64. }
  65. // UserDefaults
  66. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  67. // Background Fetch
  68. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  69. // Initialization List & Array
  70. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  71. self.listMainVC = [[NSMutableDictionary alloc] init];
  72. self.arrayDeleteMetadata = [NSMutableArray new];
  73. self.arrayMoveMetadata = [NSMutableArray new];
  74. self.arrayMoveServerUrlTo = [NSMutableArray new];
  75. self.arrayCopyMetadata = [NSMutableArray new];
  76. self.arrayCopyServerUrlTo = [NSMutableArray new];
  77. self.sessionPendingStatusInUpload = [NSMutableArray new];
  78. // Push Notification
  79. [application registerForRemoteNotifications];
  80. // Display notification (sent via APNS)
  81. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  82. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  83. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  84. }];
  85. // setting Reachable in back
  86. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  87. self.reachability = [Reachability reachabilityForInternetConnection];
  88. self.lastReachability = [self.reachability isReachable];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  90. [self.reachability startNotifier];
  91. });
  92. //AV Session
  93. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  94. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  95. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  96. // ProgressView Detail
  97. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  98. // Quick Actions
  99. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  100. [self configDynamicShortcutItems];
  101. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  102. if (shortcutItem)
  103. [self handleShortCutItem:shortcutItem];
  104. }
  105. // Start Timer
  106. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  107. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  108. [self startTimerErrorNetworking];
  109. // Store review
  110. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  111. NCStoreReview *review = [NCStoreReview new];
  112. [review incrementAppRuns];
  113. [review showStoreReview];
  114. }
  115. // Detect Dark mode
  116. if (@available(iOS 13.0, *)) {
  117. if ([CCUtility getDarkModeDetect]) {
  118. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  119. [CCUtility setDarkMode:YES];
  120. } else {
  121. [CCUtility setDarkMode:NO];
  122. }
  123. }
  124. }
  125. if ([NCBrandOptions sharedInstance].disable_intro) {
  126. [CCUtility setIntro:YES];
  127. if (self.activeAccount.length == 0) {
  128. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  129. }
  130. } else {
  131. if ([CCUtility getIntro] == NO) {
  132. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  133. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  134. self.window.rootViewController = navController;
  135. [self.window makeKeyAndVisible];
  136. }
  137. }
  138. // init home
  139. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  140. // Observer
  141. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  142. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  143. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  144. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadedFile:) name:k_notificationCenter_uploadedFile object:nil];
  145. // Passcode
  146. dispatch_async(dispatch_get_main_queue(), ^{
  147. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  148. });
  149. return YES;
  150. }
  151. //
  152. // L' applicazione si dimetterà dallo stato di attivo
  153. //
  154. - (void)applicationWillResignActive:(UIApplication *)application
  155. {
  156. // Test Maintenance
  157. if (self.activeAccount.length == 0 || self.maintenanceMode)
  158. return;
  159. [self updateApplicationIconBadgeNumber];
  160. }
  161. //
  162. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  163. //
  164. - (void)applicationWillEnterForeground:(UIApplication *)application
  165. {
  166. // Test Maintenance
  167. if (self.activeAccount.length == 0 || self.maintenanceMode)
  168. return;
  169. NSLog(@"[LOG] Request Passcode");
  170. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  171. NSLog(@"[LOG] Request Service Server Nextcloud");
  172. [[NCService sharedInstance] startRequestServicesServer];
  173. NSLog(@"[LOG] Initialize Auto upload");
  174. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  175. NSLog(@"[LOG] Read active directory");
  176. [self.activeMain readFileReloadFolder];
  177. NSLog(@"[LOG] Required unsubscribing / subscribing");
  178. [self pushNotification];
  179. NSLog(@"[LOG] RichDocument");
  180. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  181. }
  182. //
  183. // L' applicazione entrerà in primo piano (attivo sempre)
  184. //
  185. - (void)applicationDidBecomeActive:(UIApplication *)application
  186. {
  187. // Test Maintenance
  188. if (self.activeAccount.length == 0 || self.maintenanceMode)
  189. return;
  190. // middelware ping
  191. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  192. NSLog(@"[LOG] Middleware Ping");
  193. [[NCService sharedInstance] middlewarePing];
  194. }
  195. // verify task (download/upload) lost
  196. [self verifyTaskLost];
  197. // verify delete Asset Local Identifiers in auto upload
  198. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:self.activeAccount sessionSelector:selectorUploadAutoUpload];
  199. // Brand
  200. #if defined(HC)
  201. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  202. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  203. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  204. vc.account = account;
  205. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  206. }
  207. #endif
  208. }
  209. //
  210. // L' applicazione è entrata nello sfondo
  211. //
  212. - (void)applicationDidEnterBackground:(UIApplication *)application
  213. {
  214. NSLog(@"[LOG] Enter in Background");
  215. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  216. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  217. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  218. __block UIBackgroundTaskIdentifier background_task;
  219. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  220. //Clean up code. Tell the system that we are done.
  221. [application endBackgroundTask: background_task];
  222. background_task = UIBackgroundTaskInvalid;
  223. }];
  224. }
  225. }
  226. //
  227. // L'applicazione terminerà
  228. //
  229. - (void)applicationWillTerminate:(UIApplication *)application
  230. {
  231. NSLog(@"[LOG] bye bye, Nextcloud !");
  232. }
  233. #pragma --------------------------------------------------------------------------------------------
  234. #pragma mark ===== Login / checkErrorNetworking =====
  235. #pragma --------------------------------------------------------------------------------------------
  236. - (void)checkErrorNetworking
  237. {
  238. // test
  239. if (self.activeAccount.length == 0 || self.maintenanceMode)
  240. return;
  241. // check unauthorized server (401)
  242. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  243. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  244. }
  245. // check certificate untrusted (-1202)
  246. if ([CCUtility getCertificateError:self.activeAccount]) {
  247. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  248. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  249. [[NCNetworking sharedInstance] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  250. [self startTimerErrorNetworking];
  251. }]];
  252. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  253. [self startTimerErrorNetworking];
  254. }]];
  255. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  256. // Stop timer error network
  257. [self.timerErrorNetworking invalidate];
  258. }];
  259. }
  260. }
  261. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  262. {
  263. // use appConfig [MDM]
  264. if ([NCBrandOptions sharedInstance].use_configuration) {
  265. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  266. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  267. [self showLoginViewController:self.appConfigView forContext:viewController];
  268. }
  269. return;
  270. }
  271. // only for personalized LoginWeb [customer]
  272. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  273. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  274. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  275. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  276. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  277. }
  278. return;
  279. }
  280. // normal login
  281. if (selector == k_intro_signup) {
  282. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  283. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  284. if (selector == k_intro_signup) {
  285. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  286. } else {
  287. self.activeLoginWeb.urlBase = self.activeUrl;
  288. }
  289. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  290. }
  291. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  292. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  293. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  294. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  295. } else if (openLoginWeb) {
  296. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  297. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  298. self.activeLoginWeb.urlBase = self.activeUrl;
  299. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  300. }
  301. } else {
  302. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  303. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  304. [self showLoginViewController:_activeLogin forContext:viewController];
  305. }
  306. }
  307. }
  308. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  309. {
  310. if (contextViewController == NULL) {
  311. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  312. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  313. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  314. self.window.rootViewController = navController;
  315. [self.window makeKeyAndVisible];
  316. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  317. UINavigationController *navController = ((UINavigationController *)contextViewController);
  318. [navController pushViewController:viewController animated:true];
  319. } else {
  320. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  321. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  322. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  323. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  324. [contextViewController presentViewController:navController animated:true completion:nil];
  325. }
  326. }
  327. - (void)startTimerErrorNetworking
  328. {
  329. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  330. }
  331. #pragma --------------------------------------------------------------------------------------------
  332. #pragma mark ===== Account =====
  333. #pragma --------------------------------------------------------------------------------------------
  334. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  335. {
  336. self.activeAccount = activeAccount;
  337. self.activeUrl = activeUrl;
  338. self.activeUser = activeUser;
  339. self.activeUserID = activeUserID;
  340. self.activePassword = activePassword;
  341. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:activeAccount];
  342. (void)[NCNetworkingNotificationCenter shared];
  343. [[NCCommunicationCommon sharedInstance] setupWithUser:activeUser userId:activeUserID password:activePassword url:activeUrl userAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups nextcloudVersion:capabilities.versionMajor delegate:[NCNetworking sharedInstance]];
  344. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  345. [communication setupNextcloudVersion:[[NCManageDatabase sharedInstance] getServerVersionWithAccount:activeAccount]];
  346. }
  347. - (void)settingWebDavRoot:(NSString *)webdavRoot
  348. {
  349. if (webdavRoot != nil) {
  350. [[NCCommunicationCommon sharedInstance] setupWithWebDavRoot:webdavRoot];
  351. }
  352. }
  353. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  354. {
  355. [self unsubscribingNextcloudServerPushNotification:account url:self.activeUrl withSubscribing:false];
  356. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  357. /* DELETE ALL FILES LOCAL FS */
  358. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  359. for (tableLocalFile *result in results) {
  360. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  361. }
  362. // Clear database
  363. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  364. [CCUtility clearAllKeysEndToEnd:account];
  365. [CCUtility clearAllKeysPushNotification:account];
  366. [CCUtility setCertificateError:account error:false];
  367. [CCUtility setPassword:account password:nil];
  368. if (wipe) {
  369. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  370. if ([listAccount count] > 0) {
  371. NSString *newAccount = listAccount[0];
  372. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  373. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  374. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  375. } else {
  376. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  377. }
  378. }
  379. }
  380. #pragma --------------------------------------------------------------------------------------------
  381. #pragma mark ===== Push Notifications =====
  382. #pragma --------------------------------------------------------------------------------------------
  383. - (void)pushNotification
  384. {
  385. // test
  386. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  387. return;
  388. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  389. NSString *token = [CCUtility getPushNotificationToken:result.account];
  390. if (![token isEqualToString:self.pushKitToken]) {
  391. if (token != nil) {
  392. // unsubscribing + subscribing
  393. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  394. } else {
  395. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  396. }
  397. }
  398. }
  399. }
  400. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  401. {
  402. // test
  403. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  404. return;
  405. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  406. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  407. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  408. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  409. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:account url:url pushToken:self.pushKitToken Hash:pushTokenHash devicePublicKey:pushDevicePublicKey completion:^(NSString *accountCompletion, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  410. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  411. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  412. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  413. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  414. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  415. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  416. } else if (errorCode != 0) {
  417. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  418. } else {
  419. NSLog(@"[LOG] It has been changed user during networking process, error.");
  420. }
  421. }];
  422. }
  423. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  424. {
  425. // test
  426. if (self.activeAccount.length == 0 || self.maintenanceMode)
  427. return;
  428. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  429. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  430. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  431. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  432. if (errorCode == 0) {
  433. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  434. [CCUtility setPushNotificationPublicKey:account data:nil];
  435. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  436. [CCUtility setPushNotificationPrivateKey:account data:nil];
  437. [CCUtility setPushNotificationToken:account token:nil];
  438. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  439. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  440. if (self.pushKitToken != nil && subscribing) {
  441. [self subscribingNextcloudServerPushNotification:account url:url];
  442. }
  443. } else if (errorCode != 0) {
  444. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  445. } else {
  446. NSLog(@"[LOG] It has been changed user during networking process, error.");
  447. }
  448. }];
  449. }
  450. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  451. {
  452. //Called when a notification is delivered to a foreground app.
  453. completionHandler(UNNotificationPresentationOptionAlert);
  454. }
  455. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  456. {
  457. completionHandler();
  458. }
  459. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  460. {
  461. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  462. [self pushNotification];
  463. }
  464. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  465. {
  466. NSString *message = [userInfo objectForKey:@"subject"];
  467. if (message) {
  468. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  469. for (tableAccount *result in results) {
  470. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  471. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  472. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  473. if (decryptedMessage) {
  474. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  475. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  476. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  477. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  478. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  479. if (delete) {
  480. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  481. } else if (deleteAll) {
  482. [self cleanAllNotifications];
  483. }
  484. }
  485. }
  486. }
  487. }
  488. completionHandler(UIBackgroundFetchResultNoData);
  489. }
  490. - (void)cleanAllNotifications
  491. {
  492. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  493. }
  494. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  495. {
  496. // Check in pending notifications
  497. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  498. for (UNNotificationRequest *notificationRequest in requests) {
  499. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  500. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  501. if (decryptedMessage) {
  502. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  503. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  504. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  505. if (nid == notificationId) {
  506. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  507. }
  508. }
  509. }
  510. }];
  511. // Check in delivered notifications
  512. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  513. for (UNNotification *notification in notifications) {
  514. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  515. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  516. if (decryptedMessage) {
  517. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  518. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  519. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  520. if (nid == notificationId) {
  521. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  522. }
  523. }
  524. }
  525. }];
  526. }
  527. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  528. {
  529. const char *data = [deviceToken bytes];
  530. NSMutableString *token = [NSMutableString string];
  531. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  532. [token appendFormat:@"%02.2hhX", data[i]];
  533. }
  534. return [token copy];
  535. }
  536. #pragma --------------------------------------------------------------------------------------------
  537. #pragma mark ==== NotificationCenter ====
  538. #pragma --------------------------------------------------------------------------------------------
  539. - (void)deleteFile:(NSNotification *)notification
  540. {
  541. if (self.arrayDeleteMetadata.count > 0) {
  542. tableMetadata *metadata = self.arrayDeleteMetadata.firstObject;
  543. [self.arrayDeleteMetadata removeObjectAtIndex:0];
  544. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  545. if (account) {
  546. [[NCNetworking sharedInstance] deleteMetadata:metadata account:metadata.account user:account.user userID:account.userID password:[CCUtility getPassword:metadata.account] url:account.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  547. } else {
  548. [self deleteFile:[NSNotification new]];
  549. }
  550. }
  551. }
  552. - (void)moveFile:(NSNotification *)notification
  553. {
  554. if (self.arrayMoveMetadata.count > 0) {
  555. tableMetadata *metadata = self.arrayMoveMetadata.firstObject;
  556. NSString *serverUrlTo = self.arrayMoveServerUrlTo.firstObject;
  557. [self.arrayMoveMetadata removeObjectAtIndex:0];
  558. [self.arrayMoveServerUrlTo removeObjectAtIndex:0];
  559. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  560. if (account) {
  561. [[NCNetworking sharedInstance] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  562. } else {
  563. [self moveFile:[NSNotification new]];
  564. }
  565. }
  566. }
  567. - (void)copyFile:(NSNotification *)notification
  568. {
  569. if (self.arrayCopyMetadata.count > 0) {
  570. tableMetadata *metadata = self.arrayCopyMetadata.firstObject;
  571. NSString *serverUrlTo = self.arrayCopyServerUrlTo.firstObject;
  572. [self.arrayCopyMetadata removeObjectAtIndex:0];
  573. [self.arrayCopyServerUrlTo removeObjectAtIndex:0];
  574. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  575. if (account) {
  576. [[NCNetworking sharedInstance] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  577. } else {
  578. [self copyFile:[NSNotification new]];
  579. }
  580. }
  581. }
  582. - (void)uploadedFile:(NSNotification *)notification
  583. {
  584. NSDictionary *userInfo = notification.userInfo;
  585. tableMetadata *metadata = userInfo[@"metadata"];
  586. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  587. if (errorCode == 0) {
  588. // verify delete Asset Local Identifiers in auto upload
  589. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:metadata.account sessionSelector:selectorUploadAutoUpload];
  590. }
  591. }
  592. #pragma --------------------------------------------------------------------------------------------
  593. #pragma mark ===== Quick Actions - ShotcutItem =====
  594. #pragma --------------------------------------------------------------------------------------------
  595. - (void)configDynamicShortcutItems
  596. {
  597. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  598. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  599. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  600. // add the array to our app
  601. if (shortcutMedia)
  602. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  603. }
  604. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  605. {
  606. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  607. completionHandler(handledShortCutItem);
  608. }
  609. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  610. {
  611. BOOL handled = NO;
  612. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  613. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  614. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  615. dispatch_async(dispatch_get_main_queue(), ^{
  616. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  617. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  618. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  619. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  620. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  621. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  622. if (splitViewController.isCollapsed) {
  623. [navigationControllerMaster popToRootViewControllerAnimated:false];
  624. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  625. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  626. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  627. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  628. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  629. }
  630. }
  631. } else {
  632. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  633. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  634. }
  635. }
  636. }
  637. }
  638. }
  639. });
  640. handled = YES;
  641. }
  642. return handled;
  643. }
  644. #pragma --------------------------------------------------------------------------------------------
  645. #pragma mark ===== ApplicationIconBadgeNumber =====
  646. #pragma --------------------------------------------------------------------------------------------
  647. - (void)updateApplicationIconBadgeNumber
  648. {
  649. if (self.activeAccount.length == 0 || self.maintenanceMode)
  650. return;
  651. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  652. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  653. NSInteger counterUpload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  654. NSInteger total = counterDownload + counterUpload;
  655. dispatch_async(dispatch_get_main_queue(), ^{
  656. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  657. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  658. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  659. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  660. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  661. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  662. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  663. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  664. if (total > 0) {
  665. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  666. } else {
  667. [tabBarItem setBadgeValue:nil];
  668. }
  669. }
  670. }
  671. }
  672. });
  673. });
  674. }
  675. #pragma --------------------------------------------------------------------------------------------
  676. #pragma mark ===== TabBarController =====
  677. #pragma --------------------------------------------------------------------------------------------
  678. - (void)createTabBarController:(UITabBarController *)tabBarController
  679. {
  680. UITabBarItem *item;
  681. NSLayoutConstraint *constraint;
  682. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  683. // File
  684. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  685. [item setTitle:NSLocalizedString(@"_home_", nil)];
  686. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  687. item.selectedImage = item.image;
  688. // Favorites
  689. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  690. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  691. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  692. item.selectedImage = item.image;
  693. // (PLUS INVISIBLE)
  694. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  695. item.title = @"";
  696. item.image = nil;
  697. item.enabled = false;
  698. // Media
  699. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  700. [item setTitle:NSLocalizedString(@"_media_", nil)];
  701. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  702. item.selectedImage = item.image;
  703. // More
  704. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  705. [item setTitle:NSLocalizedString(@"_more_", nil)];
  706. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  707. item.selectedImage = item.image;
  708. // Plus Button
  709. int buttonSize = 56;
  710. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  711. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  712. buttonPlus.tag = 99;
  713. [buttonPlus setImage:buttonImage forState:UIControlStateNormal];
  714. buttonPlus.backgroundColor = NCBrandColor.sharedInstance.brand;
  715. buttonPlus.layer.cornerRadius = buttonSize / 2;
  716. buttonPlus.layer.masksToBounds = NO;
  717. buttonPlus.layer.shadowOffset = CGSizeMake(0, 0);
  718. buttonPlus.layer.shadowRadius = 3.0f;
  719. buttonPlus.layer.shadowOpacity = 0.5;
  720. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  721. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  722. [tabBarController.tabBar addSubview:buttonPlus];
  723. if (safeAreaBottom > 0) {
  724. // X
  725. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  726. [tabBarController.view addConstraint:constraint];
  727. // Y
  728. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:-(buttonSize / 2)];
  729. [tabBarController.view addConstraint:constraint];
  730. // Width
  731. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  732. [tabBarController.view addConstraint:constraint];
  733. // Height
  734. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  735. [tabBarController.view addConstraint:constraint];
  736. } else {
  737. // X
  738. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  739. [tabBarController.view addConstraint:constraint];
  740. // Y
  741. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-(buttonSize / 2)];
  742. [tabBarController.view addConstraint:constraint];
  743. // Width
  744. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  745. [tabBarController.view addConstraint:constraint];
  746. // Height
  747. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  748. [tabBarController.view addConstraint:constraint];
  749. }
  750. }
  751. - (void)handleTouchTabbarCenter:(id)sender
  752. {
  753. // Test Maintenance
  754. if (self.maintenanceMode)
  755. return;
  756. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  757. if ([tableDirectory.permissions containsString:@"CK"]) {
  758. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  759. [self showMenuInViewController: vc];
  760. } else {
  761. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  762. }
  763. }
  764. - (NSString *)getTabBarControllerActiveServerUrl
  765. {
  766. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  767. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  768. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  769. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  770. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  771. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  772. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  773. NSInteger index = tabBarController.selectedIndex;
  774. // select active serverUrl
  775. if (index == k_tabBarApplicationIndexFile) {
  776. serverUrl = self.activeMain.serverUrl;
  777. } else if (index == k_tabBarApplicationIndexFavorite) {
  778. if (self.activeFavorites.serverUrl)
  779. serverUrl = self.activeFavorites.serverUrl;
  780. } else if (index == k_tabBarApplicationIndexMedia) {
  781. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  782. }
  783. }
  784. }
  785. }
  786. return serverUrl;
  787. }
  788. #pragma --------------------------------------------------------------------------------------------
  789. #pragma mark ===== Theming Color =====
  790. #pragma --------------------------------------------------------------------------------------------
  791. - (void)settingThemingColorBrand
  792. {
  793. if (self.activeAccount.length == 0 || self.maintenanceMode)
  794. return;
  795. if ([NCBrandOptions sharedInstance].use_themingColor) {
  796. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  797. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  798. UIColor *color = NCBrandColor.sharedInstance.brand;
  799. BOOL isTooLight = NCBrandColor.sharedInstance.brand.isTooLight;
  800. BOOL isTooDark = NCBrandColor.sharedInstance.brand.isTooDark;
  801. if (isTooLight) {
  802. color = [NCBrandColor.sharedInstance.brand darkerBy:10];
  803. } else if (isTooDark) {
  804. color = [NCBrandColor.sharedInstance.brand lighterBy:10];
  805. }
  806. NCBrandColor.sharedInstance.brand = color;
  807. } else {
  808. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  809. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  810. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  811. }
  812. [[NCMainCommon sharedInstance] createImagesThemingColor];
  813. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  814. }
  815. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  816. {
  817. // Dark Mode
  818. [NCBrandColor.sharedInstance setDarkMode];
  819. // View
  820. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  821. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  822. // NavigationBar
  823. if (viewController.navigationController.navigationBar) {
  824. if (![self.reachability isReachable]) {
  825. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  826. }
  827. }
  828. [self configureNavBarForViewController:viewController];
  829. //tabBar
  830. if (viewController.tabBarController.tabBar) {
  831. viewController.tabBarController.tabBar.translucent = NO;
  832. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.backgroundView;
  833. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  834. }
  835. //tabBar button Plus
  836. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  837. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  838. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  839. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  840. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  841. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  842. [tabBarController.tabBar setNeedsDisplay];
  843. UIButton *button = [tabBarController.view viewWithTag:99];
  844. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  845. [button setImage:buttonImage forState:UIControlStateNormal];
  846. button.backgroundColor = NCBrandColor.sharedInstance.brand;
  847. }
  848. }
  849. }
  850. // TableView
  851. if (tableView) {
  852. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  853. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  854. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  855. [tableView reloadData];
  856. }
  857. // CollectionView
  858. if (collectionView) {
  859. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  860. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  861. [collectionView reloadData];
  862. }
  863. // Tint Color GLOBAL WINDOW
  864. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  865. }
  866. #pragma --------------------------------------------------------------------------------------------
  867. #pragma mark ===== reachabilityChanged =====
  868. #pragma --------------------------------------------------------------------------------------------
  869. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  870. {
  871. if ([self.reachability isReachable]) {
  872. if (self.lastReachability == NO) {
  873. NSLog(@"[LOG] Request Service Server Nextcloud");
  874. [[NCService sharedInstance] startRequestServicesServer];
  875. }
  876. NSLog(@"[LOG] Reachability Changed: Reachable");
  877. self.lastReachability = YES;
  878. } else {
  879. if (self.lastReachability == YES) {
  880. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  881. }
  882. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  883. self.lastReachability = NO;
  884. }
  885. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  886. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  887. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_setTitleMain object:nil];
  888. }
  889. #pragma --------------------------------------------------------------------------------------------
  890. #pragma mark ===== Fetch =====
  891. #pragma --------------------------------------------------------------------------------------------
  892. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  893. {
  894. // Test Maintenance
  895. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  896. completionHandler(UIBackgroundFetchResultNoData);
  897. return;
  898. }
  899. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  900. // Verify new photo
  901. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  902. // after 20 sec
  903. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  904. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  905. if ([records count] > 0) {
  906. completionHandler(UIBackgroundFetchResultNewData);
  907. } else {
  908. completionHandler(UIBackgroundFetchResultNoData);
  909. }
  910. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  911. });
  912. }
  913. #pragma --------------------------------------------------------------------------------------------
  914. #pragma mark ===== Operation Networking & Session =====
  915. #pragma --------------------------------------------------------------------------------------------
  916. //
  917. // Method called by the system when all the background task has end
  918. //
  919. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  920. {
  921. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  922. // after 20 sec
  923. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  924. self.backgroundSessionCompletionHandler = completionHandler;
  925. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  926. self.backgroundSessionCompletionHandler = nil;
  927. completionHandler();
  928. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  929. });
  930. }
  931. #pragma --------------------------------------------------------------------------------------------
  932. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  933. #pragma --------------------------------------------------------------------------------------------
  934. - (void)loadAutoDownloadUpload
  935. {
  936. if (self.activeAccount.length == 0 || self.maintenanceMode)
  937. return;
  938. tableMetadata *metadataForUpload, *metadataForDownload;
  939. long counterDownload = 0, counterUpload = 0;
  940. NSUInteger sizeDownload = 0, sizeUpload = 0;
  941. NSMutableArray *uploaded = [NSMutableArray new];
  942. NSPredicate *predicate;
  943. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  944. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  945. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  946. // E2EE only 1
  947. for(tableMetadata *metadata in metadatasDownload) {
  948. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  949. }
  950. for(tableMetadata *metadata in metadatasUpload) {
  951. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  952. }
  953. // Counter
  954. counterDownload = [metadatasDownload count];
  955. counterUpload = [metadatasUpload count];
  956. // Size
  957. for (tableMetadata *metadata in metadatasDownload) {
  958. sizeDownload = sizeDownload + metadata.size;
  959. }
  960. for (tableMetadata *metadata in metadatasUpload) {
  961. sizeUpload = sizeUpload + metadata.size;
  962. }
  963. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  964. // Stop Timer
  965. [_timerProcessAutoDownloadUpload invalidate];
  966. // ------------------------- <selector Download> -------------------------
  967. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  968. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  969. if (metadataForDownload) {
  970. if ([CCUtility isFolderEncrypted:metadataForDownload.serverUrl e2eEncrypted:metadataForDownload.e2eEncrypted account:metadataForDownload.account]) {
  971. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  972. maxConcurrentOperationDownloadUpload = 1;
  973. metadataForDownload.status = k_metadataStatusInDownload;
  974. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  975. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  976. break;
  977. } else {
  978. metadataForDownload.status = k_metadataStatusInDownload;
  979. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  980. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  981. counterDownload++;
  982. sizeDownload = sizeDownload + metadata.size;
  983. }
  984. } else {
  985. break;
  986. }
  987. }
  988. // ------------------------- <selector Upload> -------------------------
  989. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  990. if (sizeUpload > k_maxSizeOperationUpload) {
  991. break;
  992. }
  993. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  994. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadFile, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  995. } else {
  996. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload];
  997. }
  998. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  999. // Verify modify file
  1000. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  1001. break;
  1002. }
  1003. if (metadataForUpload) {
  1004. // Verify modify file
  1005. BOOL isAleadyInUpload = false;
  1006. for (tableMetadata *metadata in metadatasUpload) {
  1007. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  1008. isAleadyInUpload = true;
  1009. }
  1010. }
  1011. if (isAleadyInUpload == false) {
  1012. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1013. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1014. maxConcurrentOperationDownloadUpload = 1;
  1015. metadataForUpload.status = k_metadataStatusInUpload;
  1016. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1017. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1018. break;
  1019. } else {
  1020. metadataForUpload.status = k_metadataStatusInUpload;
  1021. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1022. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1023. counterUpload++;
  1024. sizeUpload = sizeUpload + metadata.size;
  1025. // For verify modify file
  1026. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1027. }
  1028. } else {
  1029. break;
  1030. }
  1031. } else {
  1032. break;
  1033. }
  1034. }
  1035. // ------------------------- <selector Auto Upload> -------------------------
  1036. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1037. if (sizeUpload > k_maxSizeOperationUpload) {
  1038. break;
  1039. }
  1040. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1041. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUpload, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1042. } else {
  1043. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload];
  1044. }
  1045. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1046. if (metadataForUpload) {
  1047. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1048. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1049. maxConcurrentOperationDownloadUpload = 1;
  1050. metadataForUpload.status = k_metadataStatusInUpload;
  1051. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1052. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1053. break;
  1054. } else {
  1055. metadataForUpload.status = k_metadataStatusInUpload;
  1056. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1057. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1058. counterUpload++;
  1059. sizeUpload = sizeUpload + metadata.size;
  1060. }
  1061. } else {
  1062. break;
  1063. }
  1064. }
  1065. // ------------------------- <selector Auto Upload All> ----------------------
  1066. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1067. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1068. NSInteger errorCount = [metadatas count];
  1069. if (errorCount >= k_maxErrorAutoUploadAll) {
  1070. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1071. } else {
  1072. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1073. if (sizeUpload > k_maxSizeOperationUpload) {
  1074. break;
  1075. }
  1076. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1077. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1078. } else {
  1079. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload];
  1080. }
  1081. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"session" ascending:YES];
  1082. if (metadataForUpload) {
  1083. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1084. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1085. maxConcurrentOperationDownloadUpload = 1;
  1086. metadataForUpload.status = k_metadataStatusInUpload;
  1087. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1088. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1089. break;
  1090. } else {
  1091. metadataForUpload.status = k_metadataStatusInUpload;
  1092. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1093. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1094. counterUpload++;
  1095. sizeUpload = sizeUpload + metadata.size;
  1096. }
  1097. } else {
  1098. break;
  1099. }
  1100. }
  1101. }
  1102. // No Download/upload available ? --> remove errors for retry
  1103. //
  1104. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1105. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1106. for (tableMetadata *metadata in metadatas) {
  1107. if (metadata.status == k_metadataStatusDownloadError)
  1108. metadata.status = k_metadataStatusWaitDownload;
  1109. else if (metadata.status == k_metadataStatusUploadError)
  1110. metadata.status = k_metadataStatusWaitUpload;
  1111. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1112. }
  1113. }
  1114. // Upload in pending
  1115. //
  1116. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1117. for (tableMetadata *metadata in metadatasInUpload) {
  1118. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1119. metadata.status = k_metadataStatusWaitUpload;
  1120. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1121. } else {
  1122. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1123. }
  1124. }
  1125. if (metadatasInUpload.count == 0) {
  1126. [self.sessionPendingStatusInUpload removeAllObjects];
  1127. }
  1128. // Start Timer
  1129. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1130. }
  1131. - (void)startLoadAutoDownloadUpload
  1132. {
  1133. if (self.timerProcessAutoDownloadUpload.isValid) {
  1134. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1135. }
  1136. }
  1137. - (void)verifyTaskLost
  1138. {
  1139. // DOWNLOAD
  1140. //
  1141. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1142. for (tableMetadata *metadata in matadatasInDownloading) {
  1143. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1144. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1145. NSURLSessionTask *findTask;
  1146. for (NSURLSessionTask *task in downloadTasks) {
  1147. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1148. findTask = task;
  1149. }
  1150. }
  1151. if (!findTask) {
  1152. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1153. metadata.status = k_metadataStatusWaitDownload;
  1154. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1155. }
  1156. }];
  1157. }
  1158. // UPLOAD
  1159. //
  1160. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1161. for (tableMetadata *metadata in metadatasUploading) {
  1162. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1163. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1164. NSURLSessionTask *findTask;
  1165. for (NSURLSessionTask *task in uploadTasks) {
  1166. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1167. findTask = task;
  1168. }
  1169. }
  1170. if (!findTask) {
  1171. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1172. metadata.status = k_metadataStatusWaitUpload;
  1173. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1174. }
  1175. }];
  1176. }
  1177. }
  1178. #pragma --------------------------------------------------------------------------------------------
  1179. #pragma mark ===== OpenURL =====
  1180. #pragma --------------------------------------------------------------------------------------------
  1181. // Method called from iOS system to send a file from other app.
  1182. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1183. {
  1184. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1185. return YES;
  1186. NSString *scheme = url.scheme;
  1187. dispatch_time_t timer = 0;
  1188. if (self.activeMain == nil) timer = 1;
  1189. if ([scheme isEqualToString:@"nextcloud"]) {
  1190. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1191. NSString *action = url.host;
  1192. if ([action isEqualToString:@"open-file"]) {
  1193. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1194. NSArray *queryItems = urlComponents.queryItems;
  1195. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1196. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1197. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1198. tableAccount *matchedAccount = nil;
  1199. // verify parameter
  1200. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1201. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1202. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1203. [alertController addAction:okAction];
  1204. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1205. } else {
  1206. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1207. if (account) {
  1208. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1209. NSString *activeAccountUser = account.user;
  1210. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1211. matchedAccount = account;
  1212. } else {
  1213. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1214. for (tableAccount *account in accounts) {
  1215. NSURL *accountURL = [NSURL URLWithString:account.url];
  1216. NSString *accountUser = account.user;
  1217. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1218. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1219. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1220. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1221. }
  1222. }
  1223. }
  1224. if (matchedAccount) {
  1225. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1226. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1227. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1228. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1229. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1230. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1231. if (splitViewController.isCollapsed) {
  1232. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1233. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1234. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1235. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1236. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1237. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1238. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1239. }
  1240. }
  1241. }
  1242. } else {
  1243. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1244. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1245. }
  1246. }
  1247. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1248. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1249. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1250. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1251. if ([path containsString:@"/"]) {
  1252. // Push
  1253. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1254. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1255. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  1256. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  1257. } else {
  1258. // Reload folder
  1259. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1260. self.activeMain.blinkFileNamePath = fileNamePath;
  1261. [self.activeMain readFolder:serverUrl];
  1262. }
  1263. });
  1264. });
  1265. }
  1266. }
  1267. }
  1268. } else {
  1269. NSString *domain = [[NSURL URLWithString:link] host];
  1270. NSString *fileName = [path lastPathComponent];
  1271. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1272. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1273. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1274. [alertController addAction:okAction];
  1275. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1276. }
  1277. }
  1278. }
  1279. }
  1280. });
  1281. return YES;
  1282. }
  1283. NSError *error;
  1284. NSLog(@"[LOG] the path is: %@", url.path);
  1285. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1286. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1287. if (self.activeAccount) {
  1288. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1289. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1290. if (error == nil) {
  1291. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1292. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1293. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1294. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1295. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1296. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1297. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1298. });
  1299. }
  1300. }
  1301. }
  1302. }
  1303. return YES;
  1304. }
  1305. #pragma --------------------------------------------------------------------------------------------
  1306. #pragma mark ===== Passcode + Delegate =====
  1307. #pragma --------------------------------------------------------------------------------------------
  1308. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  1309. {
  1310. LAContext *laContext = [LAContext new];
  1311. NSError *error;
  1312. if ([[CCUtility getBlockCode] length] == 0 || [self.activeAccount length] == 0 || [CCUtility getOnlyLockDir]) return;
  1313. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  1314. if (@available(iOS 13.0, *)) {
  1315. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  1316. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  1317. }
  1318. }
  1319. self.passcodeViewController.delegate = self;
  1320. self.passcodeViewController.allowCancel = false;
  1321. self.passcodeViewController.keypadButtonShowLettering = false;
  1322. if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  1323. if (error == NULL) {
  1324. if (laContext.biometryType == LABiometryTypeFaceID) {
  1325. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  1326. self.passcodeViewController.allowBiometricValidation = true;
  1327. self.passcodeViewController.automaticallyPromptForBiometricValidation = automaticallyPromptForBiometricValidation;
  1328. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  1329. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  1330. self.passcodeViewController.allowBiometricValidation = true;
  1331. self.passcodeViewController.automaticallyPromptForBiometricValidation = automaticallyPromptForBiometricValidation;
  1332. } else {
  1333. NSLog(@"No Biometric support");
  1334. }
  1335. }
  1336. }
  1337. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  1338. }
  1339. - (void)didTapCancelInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1340. {
  1341. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1342. }
  1343. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1344. {
  1345. return [code isEqualToString:[CCUtility getBlockCode]];
  1346. }
  1347. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1348. {
  1349. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1350. if (success) {
  1351. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1352. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1353. });
  1354. }
  1355. }];
  1356. }
  1357. #pragma --------------------------------------------------------------------------------------------
  1358. #pragma mark ===== Maintenance Mode =====
  1359. #pragma --------------------------------------------------------------------------------------------
  1360. - (void)maintenanceMode:(BOOL)mode
  1361. {
  1362. self.maintenanceMode = mode;
  1363. }
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. #pragma mark ===== UPGRADE =====
  1366. #pragma --------------------------------------------------------------------------------------------
  1367. - (BOOL)upgrade
  1368. {
  1369. #ifdef DEBUG
  1370. //self.maintenanceMode = YES;
  1371. #endif
  1372. NSString *actualVersion = [CCUtility getVersion];
  1373. NSString *actualBuild = [CCUtility getBuild];
  1374. /* ---------------------- UPGRADE VERSION ----------------------- */
  1375. // VERSION < 2.17.6
  1376. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1377. // Remove All old Photo Library
  1378. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1379. }
  1380. // VERSION == 2.17.6
  1381. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1382. // Build < 10
  1383. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1384. // Remove All old Photo Library
  1385. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1386. }
  1387. }
  1388. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1389. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1390. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1391. }
  1392. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1393. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1394. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1395. NSString *account = @"";
  1396. NSString *directoryUser = @"";
  1397. NSString *fileName;
  1398. for (tableLocalFile *record in records) {
  1399. if (![account isEqualToString:record.account]) {
  1400. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1401. if (tableAccount) {
  1402. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1403. account = record.account;
  1404. }
  1405. }
  1406. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1407. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1408. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1409. }
  1410. }
  1411. });
  1412. }
  1413. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1414. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1415. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1416. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1417. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1418. }
  1419. }
  1420. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1421. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1422. for (tableAccount *record in records) {
  1423. [CCUtility setPassword:record.account password:record.password];
  1424. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1425. }
  1426. }
  1427. return YES;
  1428. }
  1429. @end