AppDelegate.m 72 KB

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