AppDelegate.m 90 KB

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