AppDelegate.m 73 KB

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