AppDelegate.m 71 KB

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