AppDelegate.m 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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. if (deleteAll) {
  446. notificationId = 0;
  447. }
  448. [[OCNetworking sharedManager] deletingServerNotification:result.url notificationId:notificationId completion:^(NSString *message, NSInteger errorCode) {
  449. NSLog(@"Deleting Server Notification error: %ld", (long)errorCode);
  450. }];
  451. } else {
  452. NSURL *url = [NSURL URLWithString:result.url];
  453. NSString *domain = [url host];
  454. if ([app isEqualToString:@"spreed"]) {
  455. content.title = @"Nextcloud Talk";
  456. if (results.count > 1) { content.subtitle = [NSString stringWithFormat:@"%@ (%@)", result.displayName, domain]; }
  457. if (subject) { content.body = subject; }
  458. } else {
  459. if (results.count > 1) { content.title = [NSString stringWithFormat:@"%@ (%@)", result.displayName, domain]; }
  460. if (subject) { content.body = subject; }
  461. }
  462. content.sound = [UNNotificationSound defaultSound];
  463. /*
  464. [[OCNetworking sharedManager] getServerNotification:result.url notificationId:notificationId completion:^(NSDictionary *json, NSString *message, NSInteger errorCode) {
  465. //
  466. }];
  467. */
  468. NSString *identifier = [NSString stringWithFormat:@"Notification-%@", [NSDate new]];
  469. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  470. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  471. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
  472. }
  473. }
  474. }
  475. }
  476. }
  477. }
  478. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  479. {
  480. const char *data = [deviceToken bytes];
  481. NSMutableString *token = [NSMutableString string];
  482. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  483. [token appendFormat:@"%02.2hhX", data[i]];
  484. }
  485. return [token copy];
  486. }
  487. #pragma --------------------------------------------------------------------------------------------
  488. #pragma mark ===== Quick Actions - ShotcutItem =====
  489. #pragma --------------------------------------------------------------------------------------------
  490. - (void)configDynamicShortcutItems
  491. {
  492. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  493. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  494. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  495. // add the array to our app
  496. if (shortcutMedia)
  497. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  498. }
  499. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  500. {
  501. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  502. completionHandler(handledShortCutItem);
  503. }
  504. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  505. {
  506. BOOL handled = NO;
  507. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  508. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  509. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  510. dispatch_async(dispatch_get_main_queue(), ^{
  511. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  512. if (splitViewController.isCollapsed) {
  513. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  514. for (UINavigationController *nvc in tbc.viewControllers) {
  515. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  516. [nvc popToRootViewControllerAnimated:NO];
  517. }
  518. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  519. } else {
  520. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  521. [nvcDetail popToRootViewControllerAnimated:NO];
  522. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  523. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  524. }
  525. });
  526. handled = YES;
  527. }
  528. return handled;
  529. }
  530. #pragma --------------------------------------------------------------------------------------------
  531. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  532. #pragma --------------------------------------------------------------------------------------------
  533. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  534. {
  535. static NSInteger errorCodePrev = 0;
  536. dispatch_async(dispatch_get_main_queue(), ^{
  537. if (visible) {
  538. switch (errorcode) {
  539. // JDStatusBarNotification
  540. case kCFURLErrorNotConnectedToInternet:
  541. if (errorCodePrev != errorcode)
  542. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  543. errorCodePrev = errorcode;
  544. break;
  545. case kOCErrorServerUnauthorized:
  546. case kOCErrorServerForbidden:
  547. NSLog(@"Error kOCErrorServerUnauthorized - kOCErrorServerForbidden");
  548. break;
  549. // TWMessageBarManager
  550. default:
  551. if (description.length > 0) {
  552. [TWMessageBarManager sharedInstance].styleSheet = self;
  553. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  554. }
  555. break;
  556. }
  557. } else {
  558. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  559. }
  560. });
  561. }
  562. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  563. {
  564. UIColor *backgroundColor = nil;
  565. switch (type)
  566. {
  567. case TWMessageBarMessageTypeError:
  568. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  569. break;
  570. case TWMessageBarMessageTypeSuccess:
  571. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  572. break;
  573. case TWMessageBarMessageTypeInfo:
  574. backgroundColor = NCBrandColor.sharedInstance.brand;
  575. break;
  576. default:
  577. break;
  578. }
  579. return backgroundColor;
  580. }
  581. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  582. {
  583. UIColor *strokeColor = nil;
  584. switch (type)
  585. {
  586. case TWMessageBarMessageTypeError:
  587. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  588. break;
  589. case TWMessageBarMessageTypeSuccess:
  590. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  591. break;
  592. case TWMessageBarMessageTypeInfo:
  593. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  594. break;
  595. default:
  596. break;
  597. }
  598. return strokeColor;
  599. }
  600. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  601. {
  602. UIImage *iconImage = nil;
  603. switch (type)
  604. {
  605. case TWMessageBarMessageTypeError:
  606. iconImage = [UIImage imageNamed:@"icon-error.png"];
  607. break;
  608. case TWMessageBarMessageTypeSuccess:
  609. iconImage = [UIImage imageNamed:@"icon-success.png"];
  610. break;
  611. case TWMessageBarMessageTypeInfo:
  612. iconImage = [UIImage imageNamed:@"icon-info.png"];
  613. break;
  614. default:
  615. break;
  616. }
  617. return iconImage;
  618. }
  619. - (void)updateApplicationIconBadgeNumber
  620. {
  621. if (self.activeAccount.length == 0 || self.maintenanceMode)
  622. return;
  623. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  624. 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];
  625. 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];
  626. NSInteger total = counterDownload + counterUpload;
  627. dispatch_async(dispatch_get_main_queue(), ^{
  628. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  629. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  630. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  631. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  632. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  633. if (total > 0) {
  634. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  635. } else {
  636. [tbItem setBadgeValue:nil];
  637. }
  638. }
  639. });
  640. });
  641. }
  642. #pragma --------------------------------------------------------------------------------------------
  643. #pragma mark ===== TabBarController =====
  644. #pragma --------------------------------------------------------------------------------------------
  645. - (void)createTabBarController:(UITabBarController *)tabBarController
  646. {
  647. UITabBarItem *item;
  648. NSLayoutConstraint *constraint;
  649. CGFloat multiplier = 0;
  650. CGFloat safeAreaBottom = 0;
  651. if (@available(iOS 11, *)) {
  652. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  653. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  654. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  655. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  656. } else {
  657. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  658. }
  659. }
  660. //[self aspectTabBar:tabBarController.tabBar];
  661. // File
  662. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  663. [item setTitle:NSLocalizedString(@"_home_", nil)];
  664. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  665. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  666. // Favorites
  667. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  668. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  669. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  670. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  671. // (PLUS)
  672. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  673. item.title = @"";
  674. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  675. item.enabled = false;
  676. // Media
  677. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  678. [item setTitle:NSLocalizedString(@"_media_", nil)];
  679. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  680. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  681. // More
  682. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  683. [item setTitle:NSLocalizedString(@"_more_", nil)];
  684. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  685. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement];
  686. // Plus Button
  687. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  688. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  689. buttonPlus.tag = 99;
  690. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  691. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  692. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  693. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  694. [tabBarController.tabBar addSubview:buttonPlus];
  695. multiplier = 1.0;
  696. // X
  697. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  698. [tabBarController.view addConstraint:constraint];
  699. // Y
  700. if (safeAreaBottom == 0) {
  701. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  702. } else {
  703. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  704. }
  705. [tabBarController.view addConstraint:constraint];
  706. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  707. // Width
  708. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  709. [tabBarController.view addConstraint:constraint];
  710. // Height
  711. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  712. [tabBarController.view addConstraint:constraint];
  713. }
  714. - (void)plusButtonVisibile:(BOOL)visible
  715. {
  716. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  717. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  718. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  719. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  720. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  721. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  722. if (buttonPlus) {
  723. if (visible) {
  724. buttonPlus.hidden = false;
  725. } else {
  726. buttonPlus.hidden = true;
  727. }
  728. }
  729. }
  730. - (void)handleTouchTabbarCenter:(id)sender
  731. {
  732. // Test Maintenance
  733. if (self.maintenanceMode)
  734. return;
  735. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  736. if ([tableDirectory.permissions containsString:@"CK"]) {
  737. (void)[[NCCreateMenuAdd alloc] initWithViewController:self.window.rootViewController view:[(UIButton *)sender superview]];
  738. } else {
  739. [self messageNotification:@"_warning_" description:@"_no_permission_add_file_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  740. }
  741. }
  742. - (void)selectedTabBarController:(NSInteger)index
  743. {
  744. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  745. if (splitViewController.isCollapsed) {
  746. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  747. for (UINavigationController *nvc in tbc.viewControllers) {
  748. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  749. [nvc popToRootViewControllerAnimated:NO];
  750. }
  751. [tbc setSelectedIndex: index];
  752. } else {
  753. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  754. [nvcDetail popToRootViewControllerAnimated:NO];
  755. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  756. [tbc setSelectedIndex: index];
  757. }
  758. }
  759. - (NSString *)getTabBarControllerActiveServerUrl
  760. {
  761. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  762. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  763. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  764. NSInteger index = tabBarController.selectedIndex;
  765. // select active serverUrl
  766. if (index == k_tabBarApplicationIndexFile) {
  767. serverUrl = self.activeMain.serverUrl;
  768. } else if (index == k_tabBarApplicationIndexFavorite) {
  769. if (self.activeFavorites.serverUrl)
  770. serverUrl = self.activeFavorites.serverUrl;
  771. } else if (index == k_tabBarApplicationIndexMedia) {
  772. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  773. }
  774. return serverUrl;
  775. }
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ===== Theming Color =====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (void)settingThemingColorBrand
  780. {
  781. if (self.activeAccount.length == 0 || self.maintenanceMode)
  782. return;
  783. if ([NCBrandOptions sharedInstance].use_themingColor) {
  784. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  785. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  786. } else {
  787. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  788. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  789. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  790. }
  791. [[NCMainCommon sharedInstance] createImagesThemingColor];
  792. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  793. }
  794. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  795. {
  796. // Dark Mode
  797. [NCBrandColor.sharedInstance setDarkMode];
  798. // View
  799. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  800. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  801. // NavigationBar
  802. if (viewController.navigationController.navigationBar) {
  803. viewController.navigationController.navigationBar.translucent = NO;
  804. viewController.navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand;
  805. viewController.navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText;
  806. if ([self.reachability isReachable]) {
  807. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText}];
  808. } else {
  809. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  810. }
  811. viewController.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:NCBrandColor.sharedInstance.brand];
  812. [viewController.navigationController.navigationBar setAlpha:1];
  813. }
  814. //tabBar
  815. if (viewController.tabBarController.tabBar) {
  816. viewController.tabBarController.tabBar.translucent = NO;
  817. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.tabBar;
  818. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  819. [viewController.tabBarController.tabBar setAlpha:1];
  820. }
  821. //tabBar button Plus
  822. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  823. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  824. UIButton *button = [tabBarController.view viewWithTag:99];
  825. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  826. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  827. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  828. // TableView
  829. if (tableView) {
  830. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  831. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  832. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  833. [tableView reloadData];
  834. }
  835. // CollectionView
  836. if (collectionView) {
  837. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  838. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  839. [collectionView reloadData];
  840. }
  841. // Tint Color GLOBAL WINDOW
  842. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  843. }
  844. #pragma --------------------------------------------------------------------------------------------
  845. #pragma mark ===== Manager Passcode =====
  846. #pragma --------------------------------------------------------------------------------------------
  847. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  848. {
  849. // ServerUrl active
  850. NSString *serverUrl = self.activeMain.serverUrl;
  851. BOOL isBlockZone = false;
  852. // fermiamo la data della sessione
  853. self.sessionePasscodeLock = nil;
  854. // se il block code è a zero esci con NON attivare la richiesta password
  855. if ([[CCUtility getBlockCode] length] == 0) return NO;
  856. // se non c'è attivo un account esci con NON attivare la richiesta password
  857. if ([self.activeAccount length] == 0) return NO;
  858. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  859. if (serverUrl && _activeUrl) {
  860. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  861. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  862. if (directory.lock) {
  863. isBlockZone = true;
  864. break;
  865. } else {
  866. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  867. if (serverUrl == self.activeUrl)
  868. break;
  869. }
  870. }
  871. }
  872. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  873. return YES;
  874. }
  875. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  876. {
  877. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  878. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  879. viewController.delegate = self;
  880. viewController.title = [NCBrandOptions sharedInstance].brand;
  881. viewController.fromType = CCBKPasscodeFromLockScreen;
  882. viewController.inputViewTitlePassword = YES;
  883. if ([CCUtility getSimplyBlockCode]) {
  884. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  885. viewController.passcodeInputView.maximumLength = 6;
  886. } else {
  887. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  888. viewController.passcodeInputView.maximumLength = 64;
  889. }
  890. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  891. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  892. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  893. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  894. return navigationController;
  895. }
  896. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  897. {
  898. [aViewController dismissViewControllerAnimated:YES completion:nil];
  899. // is a lock screen
  900. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  901. [aViewController dismissViewControllerAnimated:YES completion:nil];
  902. // start session Passcode Lock
  903. BOOL isBlockZone = false;
  904. NSString *serverUrl = self.activeMain.serverUrl;
  905. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  906. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  907. if (directory.lock) {
  908. isBlockZone = true;
  909. break;
  910. } else {
  911. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  912. if (serverUrl == self.activeUrl)
  913. break;
  914. }
  915. }
  916. if (isBlockZone)
  917. self.sessionePasscodeLock = [NSDate date];
  918. }
  919. }
  920. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  921. {
  922. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  923. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  924. //self.lockUntilDate = nil;
  925. //self.failedAttempts = 0;
  926. aResultHandler(YES);
  927. } else aResultHandler(NO);
  928. } else aResultHandler(YES);
  929. }
  930. #pragma --------------------------------------------------------------------------------------------
  931. #pragma mark ===== reachabilityChanged =====
  932. #pragma --------------------------------------------------------------------------------------------
  933. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  934. {
  935. if ([self.reachability isReachable]) {
  936. if (self.lastReachability == NO) {
  937. NSLog(@"[LOG] Request Service Server Nextcloud");
  938. [[NCService sharedInstance] startRequestServicesServer];
  939. }
  940. NSLog(@"[LOG] Reachability Changed: Reachable");
  941. self.lastReachability = YES;
  942. } else {
  943. if (self.lastReachability == YES) {
  944. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  945. }
  946. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  947. self.lastReachability = NO;
  948. }
  949. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  950. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  951. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  952. }
  953. #pragma --------------------------------------------------------------------------------------------
  954. #pragma mark ===== Fetch =====
  955. #pragma --------------------------------------------------------------------------------------------
  956. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  957. {
  958. // Test Maintenance
  959. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  960. completionHandler(UIBackgroundFetchResultNoData);
  961. return;
  962. }
  963. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  964. // Verify new photo
  965. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  966. // after 20 sec
  967. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  968. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  969. if ([records count] > 0) {
  970. completionHandler(UIBackgroundFetchResultNewData);
  971. } else {
  972. completionHandler(UIBackgroundFetchResultNoData);
  973. }
  974. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  975. });
  976. }
  977. #pragma --------------------------------------------------------------------------------------------
  978. #pragma mark ===== Operation Networking & Session =====
  979. #pragma --------------------------------------------------------------------------------------------
  980. //
  981. // Method called by the system when all the background task has end
  982. //
  983. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  984. {
  985. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  986. // after 20 sec
  987. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  988. self.backgroundSessionCompletionHandler = completionHandler;
  989. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  990. self.backgroundSessionCompletionHandler = nil;
  991. completionHandler();
  992. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  993. });
  994. }
  995. #pragma --------------------------------------------------------------------------------------------
  996. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  997. #pragma --------------------------------------------------------------------------------------------
  998. - (void)loadAutoDownloadUpload
  999. {
  1000. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1001. return;
  1002. tableMetadata *metadataForUpload, *metadataForDownload;
  1003. long counterDownload = 0, counterUpload = 0;
  1004. NSUInteger sizeDownload = 0, sizeUpload = 0;
  1005. BOOL isE2EE = false;
  1006. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  1007. // Detect E2EE
  1008. NSString *saveserverUrl = @"";
  1009. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  1010. for (tableMetadata *metadata in metadatasForE2EE) {
  1011. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  1012. saveserverUrl = metadata.serverUrl;
  1013. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  1014. isE2EE = true;
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. // E2EE : not in background
  1020. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  1021. return;
  1022. }
  1023. // E2EE : only 1 operation
  1024. if (isE2EE) {
  1025. maxConcurrentOperationDownloadUpload = 1;
  1026. }
  1027. // Stop Timer
  1028. [_timerProcessAutoDownloadUpload invalidate];
  1029. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  1030. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  1031. // Counter
  1032. counterDownload = [metadatasDownload count];
  1033. counterUpload = [metadatasUpload count];
  1034. // Size
  1035. for (tableMetadata *metadata in metadatasDownload) {
  1036. sizeDownload = sizeDownload + metadata.size;
  1037. }
  1038. for (tableMetadata *metadata in metadatasUpload) {
  1039. sizeUpload = sizeUpload + metadata.size;
  1040. }
  1041. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  1042. // ------------------------- <selector Download> -------------------------
  1043. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  1044. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"session" ascending:YES];
  1045. if (metadataForDownload) {
  1046. metadataForDownload.status = k_metadataStatusInDownload;
  1047. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  1048. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1049. counterDownload++;
  1050. sizeDownload = sizeDownload + metadata.size;
  1051. } else {
  1052. break;
  1053. }
  1054. }
  1055. // ------------------------- <selector Upload> -------------------------
  1056. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1057. if (sizeUpload > k_maxSizeOperationUpload) {
  1058. break;
  1059. }
  1060. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1061. if (metadataForUpload) {
  1062. metadataForUpload.status = k_metadataStatusInUpload;
  1063. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1064. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1065. counterUpload++;
  1066. sizeUpload = sizeUpload + metadata.size;
  1067. } else {
  1068. break;
  1069. }
  1070. }
  1071. // ------------------------- <selector Auto Upload> -------------------------
  1072. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1073. if (sizeUpload > k_maxSizeOperationUpload) {
  1074. break;
  1075. }
  1076. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1077. if (metadataForUpload) {
  1078. metadataForUpload.status = k_metadataStatusInUpload;
  1079. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1080. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1081. counterUpload++;
  1082. sizeUpload = sizeUpload + metadata.size;
  1083. } else {
  1084. break;
  1085. }
  1086. }
  1087. // ------------------------- <selector Auto Upload All> ----------------------
  1088. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1089. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1090. NSInteger errorCount = [metadatas count];
  1091. if (errorCount >= k_maxErrorAutoUploadAll) {
  1092. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1093. } else {
  1094. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1095. if (sizeUpload > k_maxSizeOperationUpload) {
  1096. break;
  1097. }
  1098. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1099. if (metadataForUpload) {
  1100. metadataForUpload.status = k_metadataStatusInUpload;
  1101. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1102. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1103. counterUpload++;
  1104. sizeUpload = sizeUpload + metadata.size;
  1105. } else {
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. // No Download/upload available ? --> remove errors for retry
  1111. //
  1112. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1113. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1114. for (tableMetadata *metadata in metadatas) {
  1115. if (metadata.status == k_metadataStatusDownloadError)
  1116. metadata.status = k_metadataStatusWaitDownload;
  1117. else if (metadata.status == k_metadataStatusUploadError)
  1118. metadata.status = k_metadataStatusWaitUpload;
  1119. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1120. }
  1121. }
  1122. // Verify internal error download (lost task)
  1123. //
  1124. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1125. for (tableMetadata *metadata in matadatasInDownloading) {
  1126. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1127. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1128. NSURLSessionTask *findTask;
  1129. for (NSURLSessionTask *task in downloadTasks) {
  1130. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1131. findTask = task;
  1132. }
  1133. }
  1134. if (!findTask) {
  1135. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1136. metadata.status = k_metadataStatusWaitDownload;
  1137. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1138. }
  1139. }];
  1140. }
  1141. // Verify internal error upload (lost task)
  1142. //
  1143. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1144. for (tableMetadata *metadata in metadatasUploading) {
  1145. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1146. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1147. NSURLSessionTask *findTask;
  1148. for (NSURLSessionTask *task in uploadTasks) {
  1149. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1150. findTask = task;
  1151. }
  1152. }
  1153. if (!findTask) {
  1154. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1155. metadata.status = k_metadataStatusWaitUpload;
  1156. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1157. }
  1158. }];
  1159. }
  1160. // Upload in pending
  1161. //
  1162. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1163. for (tableMetadata *metadata in metadatasInUpload) {
  1164. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1165. metadata.status = k_metadataStatusWaitUpload;
  1166. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1167. } else {
  1168. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1169. }
  1170. }
  1171. if (metadatasInUpload.count == 0) {
  1172. [self.sessionPendingStatusInUpload removeAllObjects];
  1173. }
  1174. // Start Timer
  1175. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1176. }
  1177. - (void)startLoadAutoDownloadUpload
  1178. {
  1179. if (self.timerProcessAutoDownloadUpload.isValid) {
  1180. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1181. }
  1182. }
  1183. #pragma --------------------------------------------------------------------------------------------
  1184. #pragma mark ===== OpenURL =====
  1185. #pragma --------------------------------------------------------------------------------------------
  1186. // Method called from iOS system to send a file from other app.
  1187. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1188. {
  1189. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1190. return YES;
  1191. NSString *scheme = url.scheme;
  1192. dispatch_time_t timer = 0;
  1193. if (self.activeMain == nil) timer = 1;
  1194. if ([scheme isEqualToString:@"nextcloud"]) {
  1195. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1196. NSString *action = url.host;
  1197. if ([action isEqualToString:@"open-file"]) {
  1198. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1199. NSArray *queryItems = urlComponents.queryItems;
  1200. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1201. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1202. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1203. tableAccount *matchedAccount = nil;
  1204. // verify parameter
  1205. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1206. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1207. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1208. [alertController addAction:okAction];
  1209. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1210. } else {
  1211. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1212. if (account) {
  1213. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1214. NSString *activeAccountUser = account.user;
  1215. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1216. matchedAccount = account;
  1217. } else {
  1218. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1219. for (tableAccount *account in accounts) {
  1220. NSURL *accountURL = [NSURL URLWithString:account.url];
  1221. NSString *accountUser = account.user;
  1222. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1223. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1224. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1225. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1226. }
  1227. }
  1228. }
  1229. if (matchedAccount) {
  1230. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1231. UITabBarController *tbc;
  1232. if (splitViewController.isCollapsed) {
  1233. tbc = splitViewController.viewControllers.firstObject;
  1234. for (UINavigationController *nvc in tbc.viewControllers) {
  1235. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  1236. [nvc popToRootViewControllerAnimated:NO];
  1237. }
  1238. } else {
  1239. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  1240. [nvcDetail popToRootViewControllerAnimated:NO];
  1241. tbc = splitViewController.viewControllers.firstObject;
  1242. }
  1243. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1244. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1245. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1246. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1247. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1248. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1249. if ([path containsString:@"/"]) {
  1250. // Push
  1251. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1252. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1253. 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:@""];
  1254. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1255. } else {
  1256. // Reload folder
  1257. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1258. self.activeMain.blinkFileNamePath = fileNamePath;
  1259. [self.activeMain readFolder:serverUrl];
  1260. }
  1261. });
  1262. });
  1263. });
  1264. } else {
  1265. NSString *domain = [[NSURL URLWithString:link] host];
  1266. NSString *fileName = [path lastPathComponent];
  1267. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1268. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1269. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1270. [alertController addAction:okAction];
  1271. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1272. }
  1273. }
  1274. }
  1275. }
  1276. });
  1277. return YES;
  1278. }
  1279. NSError *error;
  1280. NSLog(@"[LOG] the path is: %@", url.path);
  1281. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1282. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1283. if (self.activeAccount) {
  1284. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1285. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1286. if (error == nil) {
  1287. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1288. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1289. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1290. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1291. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1292. });
  1293. }
  1294. }
  1295. return YES;
  1296. }
  1297. #pragma --------------------------------------------------------------------------------------------
  1298. #pragma mark ===== Maintenance Mode =====
  1299. #pragma --------------------------------------------------------------------------------------------
  1300. - (void)maintenanceMode:(BOOL)mode
  1301. {
  1302. self.maintenanceMode = mode;
  1303. }
  1304. #pragma --------------------------------------------------------------------------------------------
  1305. #pragma mark ===== UPGRADE =====
  1306. #pragma --------------------------------------------------------------------------------------------
  1307. - (BOOL)upgrade
  1308. {
  1309. #ifdef DEBUG
  1310. //self.maintenanceMode = YES;
  1311. #endif
  1312. NSString *actualVersion = [CCUtility getVersion];
  1313. NSString *actualBuild = [CCUtility getBuild];
  1314. /* ---------------------- UPGRADE VERSION ----------------------- */
  1315. // VERSION < 2.17.6
  1316. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1317. // Remove All old Photo Library
  1318. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1319. }
  1320. // VERSION == 2.17.6
  1321. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1322. // Build < 10
  1323. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1324. // Remove All old Photo Library
  1325. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1326. }
  1327. }
  1328. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1329. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1330. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1331. }
  1332. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1333. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1334. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1335. NSString *account = @"";
  1336. NSString *directoryUser = @"";
  1337. NSString *fileName;
  1338. for (tableLocalFile *record in records) {
  1339. if (![account isEqualToString:record.account]) {
  1340. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1341. if (tableAccount) {
  1342. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1343. account = record.account;
  1344. }
  1345. }
  1346. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1347. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1348. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1349. }
  1350. }
  1351. });
  1352. }
  1353. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1354. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1355. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1356. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1357. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1358. }
  1359. }
  1360. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1361. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1362. for (tableAccount *record in records) {
  1363. [CCUtility setPassword:record.account password:record.password];
  1364. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1365. }
  1366. }
  1367. return YES;
  1368. }
  1369. @end