AppDelegate.m 69 KB

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