AppDelegate.m 80 KB

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