AppDelegate.m 69 KB

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