AppDelegate.m 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. //
  2. // AppDelegate.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. 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 <MagicalRecord/MagicalRecord.h>
  25. #import "CCCoreData.h"
  26. #import "iRate.h"
  27. #import "AFURLSessionManager.h"
  28. #import "CCNetworking.h"
  29. #import "CCCrypto.h"
  30. #import "CCGraphics.h"
  31. #import "CCPhotos.h"
  32. #import "CCSynchronize.h"
  33. #import "CCMain.h"
  34. #import "CCDetail.h"
  35. #import "Firebase.h"
  36. #import <Fabric/Fabric.h>
  37. #import <Crashlytics/Crashlytics.h>
  38. #import "JDStatusBarNotification.h"
  39. #import "NCBridgeSwift.h"
  40. #import "NCAutoUpload.h"
  41. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  42. {
  43. }
  44. @end
  45. @implementation AppDelegate
  46. + (void)initialize
  47. {
  48. [iRate sharedInstance].daysUntilPrompt = 10;
  49. [iRate sharedInstance].usesUntilPrompt = 10;
  50. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  51. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  52. //enable preview mode
  53. //[iRate sharedInstance].previewMode = YES;
  54. }
  55. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  56. {
  57. // Brand
  58. if ([NCBrandOptions sharedInstance].use_firebase) {
  59. /*
  60. In order for this to work, proper GoogleService-Info.plist must be included
  61. */
  62. @try {
  63. [FIRApp configure];
  64. } @catch (NSException *exception) {
  65. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  66. }
  67. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  68. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  69. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  70. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  71. } else {
  72. // iOS 10 or later
  73. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  74. // For iOS 10 display notification (sent via APNS)
  75. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  76. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  77. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  78. }];
  79. // For iOS 10 data message (sent via FCM)
  80. [FIRMessaging messaging].remoteMessageDelegate = self;
  81. #endif
  82. }
  83. }
  84. NSString *dir;
  85. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  86. NSLog(@"[LOG] Start program group -----------------");
  87. NSLog(@"%@", dirGroup);
  88. NSLog(@"[LOG] Start program application -----------");
  89. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  90. NSLog(@"[LOG] -------------------------------------");
  91. // create Directory local => Documents
  92. dir = [CCUtility getDirectoryLocal];
  93. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  94. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  95. // create Directory audio => Library, Application Support, audio
  96. dir = [CCUtility getDirectoryAudio];
  97. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  98. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  99. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  100. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  101. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  102. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  103. // create dir Database Nextcloud
  104. dir = [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path];
  105. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  106. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  107. NSError *error = nil;
  108. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:dir error:&error];
  109. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  110. #ifdef DEBUG
  111. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  112. #else
  113. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  114. #endif
  115. // Verify upgrade
  116. if ([self upgrade]) {
  117. // Set account, if no exists clear all
  118. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  119. if (account == nil) {
  120. // remove all the keys Chain
  121. [CCUtility deleteAllChainStore];
  122. // remove all the App group key
  123. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  124. } else {
  125. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activePassword:account.password];
  126. }
  127. }
  128. // Operation Queue OC Networking
  129. _netQueue = [[NSOperationQueue alloc] init];
  130. _netQueue.name = k_queue;
  131. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  132. // Add notification change session
  133. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  134. // Initialization Share
  135. self.sharesID = [NSMutableDictionary new];
  136. self.sharesLink = [NSMutableDictionary new];
  137. self.sharesUserAndGroup = [NSMutableDictionary new];
  138. // Initialization Notification
  139. self.listOfNotifications = [NSMutableArray new];
  140. // Background Fetch
  141. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  142. // Initialization List
  143. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  144. self.listChangeTask = [[NSMutableDictionary alloc] init];
  145. self.listMainVC = [[NSMutableDictionary alloc] init];
  146. // Player audio
  147. self.player = [LMMediaPlayerView sharedPlayerView];
  148. self.player.delegate = self;
  149. // setting Reachable in back
  150. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  151. self.reachability = [Reachability reachabilityForInternetConnection];
  152. self.lastReachability = [self.reachability isReachable];
  153. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  154. [self.reachability startNotifier];
  155. });
  156. //AV Session
  157. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  158. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  159. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  160. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  161. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  162. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  163. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  164. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  165. [app aspectNavigationControllerBar:navigationController.navigationBar encrypted:NO online:YES hidden:NO];
  166. // Settings TabBar
  167. [self createTabBarController];
  168. // passcode
  169. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  170. dispatch_async(dispatch_get_main_queue(), ^{
  171. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  172. });
  173. // Quick Actions
  174. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  175. [self configDynamicShortcutItems];
  176. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  177. if (shortcutItem)
  178. [self handleShortCutItem:shortcutItem];
  179. }
  180. // Start Timer
  181. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  182. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  183. // Registration Push Notification
  184. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  185. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  186. [application registerUserNotificationSettings:notificationSettings];
  187. // Fabric
  188. [Fabric with:@[[Crashlytics class]]];
  189. [self logUser];
  190. return YES;
  191. }
  192. //
  193. // L' applicazione si dimetterà dallo stato di attivo
  194. //
  195. - (void)applicationWillResignActive:(UIApplication *)application
  196. {
  197. [_activeMain closeAllMenu];
  198. [self updateApplicationIconBadgeNumber];
  199. }
  200. //
  201. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  202. //
  203. - (void)applicationWillEnterForeground:(UIApplication *)application
  204. {
  205. // refresh active Main
  206. if (_activeMain) {
  207. [_activeMain reloadDatasource];
  208. [_activeMain readFileReloadFolder];
  209. }
  210. // refresh Photos tab
  211. if (_activePhotos) {
  212. [_activePhotos reloadDatasourceForced];
  213. }
  214. // Initializations
  215. [self applicationInitialized];
  216. }
  217. //
  218. // L' applicazione è entrata nello sfondo
  219. //
  220. - (void)applicationDidEnterBackground:(UIApplication *)application
  221. {
  222. NSLog(@"[LOG] Enter in Background");
  223. [[CCQuickActions quickActionsManager] closeAll];
  224. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  225. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  226. __block UIBackgroundTaskIdentifier background_task;
  227. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  228. //Clean up code. Tell the system that we are done.
  229. [application endBackgroundTask: background_task];
  230. background_task = UIBackgroundTaskInvalid;
  231. }];
  232. }
  233. }
  234. //
  235. // L'applicazione terminerà
  236. //
  237. - (void)applicationWillTerminate:(UIApplication *)application
  238. {
  239. [MagicalRecord cleanUp];
  240. NSLog(@"[LOG] bye bye, Nextcloud !");
  241. }
  242. //
  243. // Application Initialized
  244. //
  245. - (void)applicationInitialized
  246. {
  247. // Test Maintenance
  248. if (self.maintenanceMode)
  249. return;
  250. // Execute : now
  251. NSLog(@"[LOG] Update Folder Photo");
  252. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:_activeUrl];
  253. if ([autoUploadPath length] > 0)
  254. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  255. // Execute : after 1 sec.
  256. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  257. // verify Download
  258. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  259. if (_activeMain)
  260. [[CCNetworking sharedNetworking] verifyDownloadInError:self.activeMain];
  261. // verify Upload
  262. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  263. [[CCNetworking sharedNetworking] verifyUploadInErrorOrWait];
  264. if (_activeMain) {
  265. NSLog(@"[LOG] Request Server Capabilities");
  266. [_activeMain requestServerCapabilities];
  267. }
  268. if (_activeMain && [[NCBrandOptions sharedInstance] use_middlewarePing]) {
  269. NSLog(@"[LOG] Middleware Ping");
  270. [_activeMain middlewarePing];
  271. }
  272. NSLog(@"[LOG] Initialize Auto upload");
  273. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  274. NSLog(@"[LOG] Listning Favorites");
  275. [_activeFavorites readListingFavorites];
  276. });
  277. }
  278. #pragma --------------------------------------------------------------------------------------------
  279. #pragma mark ===== Login =====
  280. #pragma --------------------------------------------------------------------------------------------
  281. - (void)openLoginView:(id)delegate loginType:(enumLoginType)loginType
  282. {
  283. if ([NCBrandOptions sharedInstance].use_login_web) {
  284. if (!_activeLoginWeb.isViewLoaded || !_activeLoginWeb.view.window) {
  285. _activeLoginWeb = [CCLoginWeb new];
  286. _activeLoginWeb.delegate = delegate;
  287. _activeLoginWeb.loginType = loginType;
  288. dispatch_async(dispatch_get_main_queue(), ^ {
  289. [_activeLoginWeb presentModalWithDefaultTheme:delegate];
  290. });
  291. }
  292. } else {
  293. if (!_activeLogin.isViewLoaded || !_activeLogin.view.window) {
  294. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  295. _activeLogin.delegate = delegate;
  296. _activeLogin.loginType = loginType;
  297. dispatch_async(dispatch_get_main_queue(), ^ {
  298. [self.window makeKeyAndVisible];
  299. [self.window.rootViewController presentViewController:_activeLogin animated:YES completion:nil];
  300. });
  301. }
  302. }
  303. }
  304. #pragma --------------------------------------------------------------------------------------------
  305. #pragma mark ===== Setting Active Account for all APP =====
  306. #pragma --------------------------------------------------------------------------------------------
  307. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword
  308. {
  309. self.activeAccount = activeAccount;
  310. self.activeUrl = activeUrl;
  311. self.activeUser = activeUser;
  312. self.activePassword = activePassword;
  313. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  314. // Setting Account to CCNetworking
  315. [[CCNetworking sharedNetworking] settingAccount];
  316. }
  317. #pragma --------------------------------------------------------------------------------------------
  318. #pragma mark ===== Push Notification =====
  319. #pragma --------------------------------------------------------------------------------------------
  320. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  321. {
  322. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  323. }
  324. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  325. {
  326. [application registerForRemoteNotifications];
  327. }
  328. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  329. {
  330. // test
  331. if (self.activeAccount.length == 0)
  332. return;
  333. // FIREBASE registered token
  334. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  335. NSString *pushToken = [[FIRInstanceID instanceID] token];
  336. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  337. NSString *pushTokenHash = [[CCCrypto sharedManager] createSHA512:pushToken];
  338. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  339. #ifdef DEBUG
  340. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  341. #else
  342. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  343. #endif
  344. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  345. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  346. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  347. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  348. metadataNet.action = actionSubscribingNextcloudServer;
  349. metadataNet.options = options;
  350. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  351. }
  352. }
  353. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  354. {
  355. NSLog(@"[LOG] Error register remote notification %@", error);
  356. }
  357. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  358. UIApplicationState state = [application applicationState];
  359. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  360. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  361. } else {
  362. NSLog(@"[LOG] Receive Notification on Active state");
  363. }
  364. // If you are receiving a notification message while your app is in the background,
  365. // this callback will not be fired till the user taps on the notification launching the application.
  366. // TODO: Handle data of notification
  367. // Print message ID.
  368. //if (userInfo[kGCMMessageIDKey]) {
  369. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  370. //}
  371. // Print full message.
  372. NSLog(@"[LOG] %@", userInfo);
  373. }
  374. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  375. {
  376. UIApplicationState state = [application applicationState];
  377. // Print message ID.
  378. //if (userInfo[kGCMMessageIDKey]) {
  379. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  380. //}
  381. // Print full message.
  382. NSLog(@"[LOG] %@", userInfo);
  383. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  384. } else if (state == UIApplicationStateInactive) {
  385. // user tapped notification
  386. completionHandler(UIBackgroundFetchResultNewData);
  387. } else {
  388. // app is active
  389. completionHandler(UIBackgroundFetchResultNoData);
  390. }
  391. }
  392. #pragma FIREBASE
  393. - (void)tokenRefreshNotification:(NSNotification *)notification {
  394. // Note that this callback will be fired everytime a new token is generated, including the first
  395. // time. So if you need to retrieve the token as soon as it is available this is where that
  396. // should be done.
  397. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  398. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  399. // Connect to FCM since connection may have failed when attempted before having a token.
  400. [self connectToFcm];
  401. // TODO: If necessary send token to application server.
  402. }
  403. - (void)connectToFcm {
  404. // Won't connect since there is no token
  405. if (![[FIRInstanceID instanceID] token]) {
  406. return;
  407. }
  408. // Disconnect previous FCM connection if it exists.
  409. [[FIRMessaging messaging] disconnect];
  410. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  411. if (error != nil) {
  412. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  413. } else {
  414. NSLog(@"[LOG] Connected to FCM.");
  415. }
  416. }];
  417. }
  418. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  419. // Receive data message on iOS 10 devices while app is in the foreground.
  420. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  421. // Print full message
  422. NSLog(@"[LOG] %@", remoteMessage.appData);
  423. }
  424. #endif
  425. #pragma --------------------------------------------------------------------------------------------
  426. #pragma mark ===== Quick Actions - ShotcutItem =====
  427. #pragma --------------------------------------------------------------------------------------------
  428. - (void)configDynamicShortcutItems
  429. {
  430. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  431. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  432. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  433. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUploadEncrypted"];
  434. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  435. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  436. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  437. if (app.isCryptoCloudMode) {
  438. // add the array to our app
  439. if (shortcutUploadEncrypted && shortcutUpload && shortcutPhotos)
  440. [UIApplication sharedApplication].shortcutItems = @[shortcutUploadEncrypted, shortcutUpload, shortcutPhotos];
  441. } else {
  442. // add the array to our app
  443. if (shortcutUpload && shortcutPhotos)
  444. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  445. }
  446. }
  447. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  448. {
  449. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  450. completionHandler(handledShortCutItem);
  451. }
  452. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  453. {
  454. BOOL handled = NO;
  455. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  456. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  457. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  458. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  459. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  460. dispatch_async(dispatch_get_main_queue(), ^{
  461. if (_activeMain) {
  462. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  463. if (splitViewController.isCollapsed) {
  464. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  465. for (UINavigationController *nvc in tbc.viewControllers) {
  466. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  467. [nvc popToRootViewControllerAnimated:NO];
  468. }
  469. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  470. } else {
  471. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  472. [nvcDetail popToRootViewControllerAnimated:NO];
  473. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  474. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  475. }
  476. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  477. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  478. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  479. });
  480. }
  481. });
  482. handled = YES;
  483. }
  484. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  485. dispatch_async(dispatch_get_main_queue(), ^{
  486. if (_activeMain) {
  487. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  488. if (splitViewController.isCollapsed) {
  489. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  490. for (UINavigationController *nvc in tbc.viewControllers) {
  491. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  492. [nvc popToRootViewControllerAnimated:NO];
  493. }
  494. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  495. } else {
  496. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  497. [nvcDetail popToRootViewControllerAnimated:NO];
  498. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  499. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  500. }
  501. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  502. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  503. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  504. });
  505. }
  506. });
  507. handled = YES;
  508. }
  509. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  510. dispatch_async(dispatch_get_main_queue(), ^{
  511. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  512. if (splitViewController.isCollapsed) {
  513. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  514. for (UINavigationController *nvc in tbc.viewControllers) {
  515. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  516. [nvc popToRootViewControllerAnimated:NO];
  517. }
  518. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  519. } else {
  520. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  521. [nvcDetail popToRootViewControllerAnimated:NO];
  522. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  523. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  524. }
  525. });
  526. handled = YES;
  527. }
  528. return handled;
  529. }
  530. #pragma --------------------------------------------------------------------------------------------
  531. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  532. #pragma --------------------------------------------------------------------------------------------
  533. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  534. {
  535. static NSInteger errorCodePrev = 0;
  536. dispatch_async(dispatch_get_main_queue(), ^{
  537. if (visible) {
  538. if (errorcode == kCFURLErrorNotConnectedToInternet || errorcode == k_CCErrorNetworkNowAvailable) {
  539. if (errorCodePrev != errorcode)
  540. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  541. errorCodePrev = errorcode;
  542. } else {
  543. if (description.length > 0) {
  544. [TWMessageBarManager sharedInstance].styleSheet = self;
  545. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  546. }
  547. }
  548. } else {
  549. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  550. }
  551. });
  552. }
  553. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  554. {
  555. UIColor *backgroundColor = nil;
  556. switch (type)
  557. {
  558. case TWMessageBarMessageTypeError:
  559. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  560. break;
  561. case TWMessageBarMessageTypeSuccess:
  562. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  563. break;
  564. case TWMessageBarMessageTypeInfo:
  565. backgroundColor = [NCBrandColor sharedInstance].brand;
  566. break;
  567. default:
  568. break;
  569. }
  570. return backgroundColor;
  571. }
  572. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  573. {
  574. UIColor *strokeColor = nil;
  575. switch (type)
  576. {
  577. case TWMessageBarMessageTypeError:
  578. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  579. break;
  580. case TWMessageBarMessageTypeSuccess:
  581. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  582. break;
  583. case TWMessageBarMessageTypeInfo:
  584. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  585. break;
  586. default:
  587. break;
  588. }
  589. return strokeColor;
  590. }
  591. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  592. {
  593. UIImage *iconImage = nil;
  594. switch (type)
  595. {
  596. case TWMessageBarMessageTypeError:
  597. iconImage = [UIImage imageNamed:@"icon-error.png"];
  598. break;
  599. case TWMessageBarMessageTypeSuccess:
  600. iconImage = [UIImage imageNamed:@"icon-success.png"];
  601. break;
  602. case TWMessageBarMessageTypeInfo:
  603. iconImage = [UIImage imageNamed:@"icon-info.png"];
  604. break;
  605. default:
  606. break;
  607. }
  608. return iconImage;
  609. }
  610. - (void)updateApplicationIconBadgeNumber
  611. {
  612. // Test Maintenance
  613. if (self.maintenanceMode)
  614. return;
  615. NSInteger queueDownload = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  616. NSInteger queueUpload = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  617. // Total
  618. NSInteger total = queueDownload + queueUpload + [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:nil] + [[NCManageDatabase sharedInstance] countQueueUploadWithSession:nil];
  619. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  620. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  621. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  622. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  623. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  624. if (total > 0) {
  625. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  626. } else {
  627. [tbItem setBadgeValue:nil];
  628. NSDictionary* userInfo = @{@"fileID": @"", @"serverUrl": @"", @"cryptated": [NSNumber numberWithFloat:0], @"progress": [NSNumber numberWithFloat:0]};
  629. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  630. }
  631. }
  632. }
  633. #pragma --------------------------------------------------------------------------------------------
  634. #pragma mark ===== TabBarController =====
  635. #pragma --------------------------------------------------------------------------------------------
  636. - (void)createTabBarController
  637. {
  638. UITabBarItem *item;
  639. NSLayoutConstraint *constraint;
  640. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  641. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  642. [app aspectTabBar:tabBarController.tabBar hidden:NO];
  643. // File
  644. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  645. [item setTitle:NSLocalizedString(@"_home_", nil)];
  646. item.image = [UIImage imageNamed:@"tabBarFiles"];
  647. item.selectedImage = [UIImage imageNamed:@"tabBarFiles"];
  648. // Favorites
  649. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  650. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  651. item.image = [UIImage imageNamed:@"tabBarFavorite"];
  652. item.selectedImage = [UIImage imageNamed:@"tabBarFavorite"];
  653. // (PLUS)
  654. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  655. item.title = nil;
  656. item.image = nil;
  657. item.enabled = false;
  658. // Photos
  659. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  660. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  661. item.image = [UIImage imageNamed:@"tabBarPhotos"];
  662. item.selectedImage = [UIImage imageNamed:@"tabBarPhotos"];
  663. // More
  664. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  665. [item setTitle:NSLocalizedString(@"_more_", nil)];
  666. item.image = [UIImage imageNamed:@"tabBarMore"];
  667. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  668. // Plus Button
  669. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  670. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  671. button.tag = 99;
  672. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  673. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  674. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  675. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  676. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  677. [tabBarController.view addSubview:button];
  678. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  679. [tabBarController.view addConstraint:constraint];
  680. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  681. [tabBarController.view addConstraint:constraint];
  682. }
  683. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav encrypted:(BOOL)encrypted online:(BOOL)online hidden:(BOOL)hidden
  684. {
  685. nav.translucent = NO;
  686. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  687. nav.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  688. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  689. if (encrypted)
  690. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].cryptocloud}];
  691. if (!online)
  692. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  693. nav.hidden = hidden;
  694. [nav setAlpha:1];
  695. }
  696. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  697. {
  698. tab.translucent = NO;
  699. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  700. tab.tintColor = [NCBrandColor sharedInstance].brand;
  701. tab.hidden = hidden;
  702. [tab setAlpha:1];
  703. }
  704. - (void)plusButtonVisibile:(BOOL)visible
  705. {
  706. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  707. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  708. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  709. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  710. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  711. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  712. if (buttonPlus) {
  713. if (visible) {
  714. buttonPlus.hidden = false;
  715. } else {
  716. buttonPlus.hidden = true;
  717. }
  718. }
  719. }
  720. - (void)handleTouchTabbarCenter:(id)sender
  721. {
  722. // Test Maintenance
  723. if (self.maintenanceMode)
  724. return;
  725. UIView *view = [(UIButton *)sender superview];
  726. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  727. if ([CCUtility getCreateMenuEncrypted])
  728. [menuAdd createMenuEncryptedWithView:view];
  729. else
  730. [menuAdd createMenuPlainWithView:view];
  731. }
  732. - (void)selectedTabBarController:(NSInteger)index
  733. {
  734. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  735. if (splitViewController.isCollapsed) {
  736. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  737. for (UINavigationController *nvc in tbc.viewControllers) {
  738. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  739. [nvc popToRootViewControllerAnimated:NO];
  740. }
  741. [tbc setSelectedIndex: index];
  742. } else {
  743. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  744. [nvcDetail popToRootViewControllerAnimated:NO];
  745. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  746. [tbc setSelectedIndex: index];
  747. }
  748. }
  749. - (NSString *)getTabBarControllerActiveServerUrl
  750. {
  751. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  752. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  753. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  754. NSInteger index = tabBarController.selectedIndex;
  755. // select active serverUrl
  756. if (index == k_tabBarApplicationIndexFile) {
  757. serverUrl = app.activeMain.serverUrl;
  758. } else if (index == k_tabBarApplicationIndexFavorite) {
  759. if (app.activeFavorites.serverUrl)
  760. serverUrl = app.activeFavorites.serverUrl;
  761. } else if (index == k_tabBarApplicationIndexPhotos) {
  762. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  763. }
  764. return serverUrl;
  765. }
  766. #pragma --------------------------------------------------------------------------------------------
  767. #pragma mark ===== Theming Color =====
  768. #pragma --------------------------------------------------------------------------------------------
  769. - (void)settingThemingColorBrand
  770. {
  771. UIColor* newColor;
  772. if (self.activeAccount.length > 0) {
  773. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  774. if ([NCBrandOptions sharedInstance].use_themingColor && capabilities.themingColor.length == 7) {
  775. BOOL isLight = [CCGraphics isLight:[CCGraphics colorFromHexString:capabilities.themingColor]];
  776. if (isLight) {
  777. // Activity
  778. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Server Theming" note:NSLocalizedString(@"_theming_is_light_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  779. newColor = [NCBrandColor sharedInstance].customer;
  780. } else {
  781. newColor = [CCGraphics colorFromHexString:capabilities.themingColor];
  782. }
  783. } else {
  784. newColor = [NCBrandColor sharedInstance].customer;
  785. }
  786. } else {
  787. newColor = [NCBrandColor sharedInstance].customer;
  788. }
  789. if (self.activeAccount.length > 0 && ![newColor isEqual:[NCBrandColor sharedInstance].brand] && newColor) {
  790. [NCBrandColor sharedInstance].brand = newColor;
  791. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  792. }
  793. }
  794. - (void)changeTheming:(UIViewController *)vc
  795. {
  796. UIColor *color = [NCBrandColor sharedInstance].brand;
  797. // Change Navigation & TabBar color
  798. vc.navigationController.navigationBar.barTintColor = color;
  799. vc.tabBarController.tabBar.tintColor = color;
  800. // Change button Plus
  801. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  802. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  803. UIButton *button = [tabBarController.view viewWithTag:99];
  804. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  805. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  806. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  807. // Tint Color GLOBAL WINDOW
  808. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  809. }
  810. #pragma --------------------------------------------------------------------------------------------
  811. #pragma mark ===== Media Player Control =====
  812. #pragma --------------------------------------------------------------------------------------------
  813. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  814. {
  815. switch (event.subtype) {
  816. case UIEventSubtypeRemoteControlPlay:
  817. if (self.player.mediaPlayer) {
  818. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  819. if (self.player.mediaPlayer.nowPlayingItem.title)
  820. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  821. if (self.player.mediaPlayer.nowPlayingItem.artist)
  822. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  823. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  824. [self.player.mediaPlayer play];
  825. }
  826. break;
  827. case UIEventSubtypeRemoteControlPause:
  828. if (self.player.mediaPlayer) {
  829. [self.player.mediaPlayer pause];
  830. }
  831. break;
  832. case UIEventSubtypeRemoteControlNextTrack:
  833. // handle it break;
  834. case UIEventSubtypeRemoteControlPreviousTrack:
  835. // handle it break;
  836. default:
  837. break;
  838. }
  839. }
  840. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  841. {
  842. return YES;
  843. }
  844. #pragma --------------------------------------------------------------------------------------------
  845. #pragma mark ===== Manager Passcode =====
  846. #pragma --------------------------------------------------------------------------------------------
  847. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  848. {
  849. // ServerUrl active
  850. NSString *serverUrl = self.activeMain.serverUrl;
  851. BOOL isBlockZone = false;
  852. // fermiamo la data della sessione
  853. self.sessionePasscodeLock = nil;
  854. // se il block code è a zero esci con NON attivare la richiesta password
  855. if ([[CCUtility getBlockCode] length] == 0) return NO;
  856. // se non c'è attivo un account esci con NON attivare la richiesta password
  857. if ([self.activeAccount length] == 0) return NO;
  858. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  859. if (serverUrl && _activeUrl) {
  860. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  861. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  862. if (directory.lock) {
  863. isBlockZone = true;
  864. break;
  865. } else {
  866. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  867. if (serverUrl == self.activeUrl)
  868. break;
  869. }
  870. }
  871. }
  872. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  873. return YES;
  874. }
  875. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  876. {
  877. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  878. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  879. viewController.delegate = self;
  880. viewController.title = [NCBrandOptions sharedInstance].brand;
  881. viewController.fromType = CCBKPasscodeFromLockScreen;
  882. viewController.inputViewTitlePassword = YES;
  883. if ([CCUtility getSimplyBlockCode]) {
  884. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  885. viewController.passcodeInputView.maximumLength = 6;
  886. } else {
  887. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  888. viewController.passcodeInputView.maximumLength = 64;
  889. }
  890. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  891. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  892. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  893. return navigationController;
  894. }
  895. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  896. {
  897. [aViewController dismissViewControllerAnimated:YES completion:nil];
  898. // is a lock screen
  899. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  900. [aViewController dismissViewControllerAnimated:YES completion:nil];
  901. // start session Passcode Lock
  902. BOOL isBlockZone = false;
  903. NSString *serverUrl = self.activeMain.serverUrl;
  904. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  905. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  906. if (directory.lock) {
  907. isBlockZone = true;
  908. break;
  909. } else {
  910. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  911. if (serverUrl == self.activeUrl)
  912. break;
  913. }
  914. }
  915. if (isBlockZone)
  916. self.sessionePasscodeLock = [NSDate date];
  917. }
  918. }
  919. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  920. {
  921. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  922. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  923. //self.lockUntilDate = nil;
  924. //self.failedAttempts = 0;
  925. aResultHandler(YES);
  926. } else aResultHandler(NO);
  927. } else aResultHandler(YES);
  928. }
  929. #pragma --------------------------------------------------------------------------------------------
  930. #pragma mark ===== reachabilityChanged =====
  931. #pragma --------------------------------------------------------------------------------------------
  932. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  933. {
  934. if ([self.reachability isReachable]) {
  935. if (self.lastReachability == NO) {
  936. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorNetworkNowAvailable];
  937. if (_activeMain)
  938. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  939. }
  940. NSLog(@"[LOG] Reachability Changed: Reachable");
  941. self.lastReachability = YES;
  942. } else {
  943. if (self.lastReachability == YES) {
  944. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  945. }
  946. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  947. self.lastReachability = NO;
  948. }
  949. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  950. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  951. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  952. }
  953. #pragma --------------------------------------------------------------------------------------------
  954. #pragma mark ===== Fetch =====
  955. #pragma --------------------------------------------------------------------------------------------
  956. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  957. {
  958. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  959. // Verify new photo
  960. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  961. // after 20 sec
  962. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  963. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  964. if ([records count] > 0) {
  965. completionHandler(UIBackgroundFetchResultNewData);
  966. } else {
  967. completionHandler(UIBackgroundFetchResultNoData);
  968. }
  969. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  970. });
  971. }
  972. #pragma --------------------------------------------------------------------------------------------
  973. #pragma mark ===== Operation Networking & Session =====
  974. #pragma --------------------------------------------------------------------------------------------
  975. //
  976. // Method called by the system when all the background task has end
  977. //
  978. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  979. {
  980. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  981. // after 20 sec
  982. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  983. self.backgroundSessionCompletionHandler = completionHandler;
  984. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  985. self.backgroundSessionCompletionHandler = nil;
  986. completionHandler();
  987. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  988. });
  989. }
  990. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  991. {
  992. id operation;
  993. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl isCryptoCloudMode:_isCryptoCloudMode];
  994. [operation setQueuePriority:metadataNet.priority];
  995. [netQueue addOperation:operation];
  996. }
  997. // Notification change session
  998. - (void)sessionChanged:(NSNotification *)notification
  999. {
  1000. NSURLSession *session;
  1001. NSString *fileID;
  1002. NSURLSessionTask *task;
  1003. for (id object in notification.object) {
  1004. if ([object isKindOfClass:[NSURLSession class]])
  1005. session = object;
  1006. if ([object isKindOfClass:[NSString class]])
  1007. fileID = object;
  1008. if ([object isKindOfClass:[NSURLSessionTask class]])
  1009. task = object;
  1010. }
  1011. /*
  1012. Task
  1013. */
  1014. if (fileID && [_listChangeTask objectForKey:fileID])
  1015. dispatch_async(dispatch_get_main_queue(), ^{
  1016. [self changeTask:fileID];
  1017. });
  1018. /*
  1019. Session
  1020. */
  1021. if (session) {
  1022. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1023. unsigned long numDownload = [downloadTasks count];
  1024. unsigned long numUpload = [uploadTasks count];
  1025. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  1026. }];
  1027. }
  1028. }
  1029. - (void)changeTask:(NSString *)fileID
  1030. {
  1031. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1032. if (!metadata) return;
  1033. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1034. if (!serverUrl) return;
  1035. if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"stopUpload"]) {
  1036. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1037. }
  1038. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadUpload"]) {
  1039. // V 1.8 if upload_session_wwan change in upload_session
  1040. if ([metadata.session isEqualToString:k_upload_session_wwan])
  1041. metadata.session = k_upload_session;
  1042. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1043. }
  1044. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadDownload"]) {
  1045. BOOL downloadData = NO, downloadPlist = NO;
  1046. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) downloadData = YES;
  1047. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) downloadPlist = YES;
  1048. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1049. [[CCNetworking sharedNetworking] downloadFile:fileID serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:self.activeMain];
  1050. });
  1051. }
  1052. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1053. // remove the file
  1054. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1055. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1056. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1057. }
  1058. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"cancelDownload"]) {
  1059. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1060. }
  1061. // remove ChangeTask (fileID) from the list
  1062. [_listChangeTask removeObjectForKey:fileID];
  1063. // delete progress
  1064. [_listProgressMetadata removeObjectForKey:fileID];
  1065. // Progress Task
  1066. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1067. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1068. // Refresh
  1069. if (_activeMain && [_listChangeTask count] == 0) {
  1070. [_activeMain reloadDatasource:serverUrl];
  1071. }
  1072. }
  1073. #pragma --------------------------------------------------------------------------------------------
  1074. #pragma mark ===== Process Auto Upload < k_timerProcess seconds > =====
  1075. #pragma --------------------------------------------------------------------------------------------
  1076. - (void)processAutoDownloadUpload
  1077. {
  1078. // Test Maintenance
  1079. if (self.maintenanceMode)
  1080. return;
  1081. // BACKGROND & FOREGROUND
  1082. NSLog(@"-PROCESS-AUTO-UPLOAD-");
  1083. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1084. // ONLY BACKGROUND
  1085. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1086. } else {
  1087. // ONLY FOREFROUND
  1088. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1089. }
  1090. }
  1091. - (void)loadAutoDownloadUpload:(NSNumber *)maxConcurrent
  1092. {
  1093. CCMetadataNet *metadataNet;
  1094. // Stop Timer
  1095. [_timerProcessAutoDownloadUpload invalidate];
  1096. NSInteger maxConcurrentDownloadUpload = [maxConcurrent integerValue];
  1097. NSInteger counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1098. NSInteger counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1099. NSInteger counterNewUpload = 0;
  1100. // ------------------------- <selector Auto Download> -------------------------
  1101. while (counterDownloadInSession < maxConcurrentDownloadUpload) {
  1102. metadataNet = [[NCManageDatabase sharedInstance] getQueueDownload];
  1103. if (metadataNet) {
  1104. [[CCNetworking sharedNetworking] downloadFile:metadataNet.fileID serverUrl:metadataNet.serverUrl downloadData:metadataNet.downloadData downloadPlist:metadataNet.downloadPlist selector:metadataNet.selector selectorPost:metadataNet.selectorPost session:metadataNet.session taskStatus:metadataNet.taskStatus delegate:app.activeMain];
  1105. } else
  1106. break;
  1107. counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1108. }
  1109. // ------------------------- <selector Auto Upload> -------------------------
  1110. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1111. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUpload];
  1112. if (metadataNet) {
  1113. // Priority Error only in Foreground
  1114. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1115. continue;
  1116. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1117. counterNewUpload++;
  1118. } else
  1119. break;
  1120. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1121. }
  1122. // ------------------------- <selector Auto Upload All> ----------------------
  1123. // Verify num error MAX 10 after STOP
  1124. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionSelector = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", _activeAccount, selectorUploadAutoUploadAll, k_taskIdentifierError, k_taskIdentifierError] sorted:nil ascending:NO];
  1125. NSInteger errorCount = [metadatas count];
  1126. if (errorCount >= 10) {
  1127. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1128. } else {
  1129. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1130. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUploadAll];
  1131. if (metadataNet) {
  1132. // Priority Error only in Foreground
  1133. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1134. continue;
  1135. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1136. counterNewUpload++;
  1137. } else
  1138. break;
  1139. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1140. }
  1141. }
  1142. // ------------------------- <selector Upload File> -------------------------
  1143. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1144. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadFile];
  1145. if (metadataNet) {
  1146. // Priority Error only in Foreground
  1147. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1148. continue;
  1149. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1150. counterNewUpload++;
  1151. } else
  1152. break;
  1153. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1154. }
  1155. // Verify Lock
  1156. NSInteger counterUploadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  1157. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockQueueUpload];
  1158. if (counterNewUpload == 0 && counterUploadInSession == 0 && [tableMetadatasInLock count] > 0) {
  1159. // Unlock
  1160. for (tableMetadata *metadata in tableMetadatasInLock) {
  1161. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  1162. [[NCManageDatabase sharedInstance] unlockQueueUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  1163. }
  1164. }
  1165. // In background verify Upload in error
  1166. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1167. [[CCNetworking sharedNetworking] verifyUploadInErrorOrWait];
  1168. }
  1169. // Start Timer
  1170. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:app selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  1171. }
  1172. #pragma --------------------------------------------------------------------------------------------
  1173. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1174. #pragma --------------------------------------------------------------------------------------------
  1175. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1176. {
  1177. return YES;
  1178. }
  1179. // Method called from iOS system to send a file from other app.
  1180. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1181. {
  1182. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1183. NSLog(@"[LOG] the path is: %@", url.path);
  1184. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1185. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1186. if (self.activeAccount) {
  1187. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1188. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1189. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1190. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1191. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1192. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1193. });
  1194. }
  1195. // remove from InBox
  1196. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1197. return YES;
  1198. }
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. #pragma mark ===== Crashlytics =====
  1201. #pragma --------------------------------------------------------------------------------------------
  1202. - (void) logUser
  1203. {
  1204. if (self.activeAccount.length > 0)
  1205. [CrashlyticsKit setUserName:self.activeAccount];
  1206. }
  1207. #pragma --------------------------------------------------------------------------------------------
  1208. #pragma mark ===== Maintenance Mode =====
  1209. #pragma --------------------------------------------------------------------------------------------
  1210. - (void)maintenanceMode:(BOOL)mode
  1211. {
  1212. self.maintenanceMode = mode;
  1213. }
  1214. #pragma --------------------------------------------------------------------------------------------
  1215. #pragma mark ===== UPGRADE =====
  1216. #pragma --------------------------------------------------------------------------------------------
  1217. - (BOOL)upgrade
  1218. {
  1219. #ifdef DEBUG
  1220. //self.maintenanceMode = YES;
  1221. #endif
  1222. NSString *actualVersion = [CCUtility getVersion];
  1223. //NSString *actualBuild = [CCUtility getBuild];
  1224. /* ---------------------- UPGRADE VERSION ----------------------- */
  1225. if (([actualVersion compare:@"2.17.3" options:NSNumericSearch] == NSOrderedAscending)) {
  1226. // Migrate Certificates Table From CoreData to Realm
  1227. NSArray *listCertificateLocation = [CCCoreData migrateCertificatesLocation];
  1228. for (NSString *certificateLocation in listCertificateLocation)
  1229. [[NCManageDatabase sharedInstance] addCertificates:certificateLocation];
  1230. }
  1231. // VERSION < 2.17.4
  1232. if (([actualVersion compare:@"2.17.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1233. [self maintenanceMode:YES];
  1234. // Change type order
  1235. [CCUtility setOrderSettings:@"fileName"];
  1236. // Migrate Account Table From CoreData to Realm
  1237. NSArray *listAccount = [CCCoreData migrateAccount];
  1238. for (TableAccount *account in listAccount)
  1239. [[NCManageDatabase sharedInstance] addTableAccountFromCoredata:account];
  1240. // Align Photo Library
  1241. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  1242. // Most important is done
  1243. [CCUtility setVersion];
  1244. [CCUtility setBuild];
  1245. // Directories + LocalFile
  1246. NSArray *listDirectories = [CCCoreData migrateDirectories];
  1247. for (TableDirectory *directory in listDirectories)
  1248. [[NCManageDatabase sharedInstance] addTableDirectoryFromCoredata:directory];
  1249. NSArray *listLocalFile = [CCCoreData migrateLocalFile];
  1250. for (TableLocalFile *localFile in listLocalFile)
  1251. [[NCManageDatabase sharedInstance] addTableLocalFileFromCoredata:localFile];
  1252. [self maintenanceMode:NO];
  1253. }
  1254. // VERSION == 2.17.4
  1255. if ([actualVersion isEqualToString:@"2.17.4"]) {
  1256. // Build < 37 (example)
  1257. /*
  1258. if (([actualBuild compare:@"37" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1259. [CCUtility setOrderSettings:@"fileName"];
  1260. [CCUtility setBuild];
  1261. }
  1262. */
  1263. }
  1264. return YES;
  1265. }
  1266. @end