AppDelegate.m 71 KB

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