AppDelegate.m 70 KB

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