AppDelegate.m 82 KB

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