AppDelegate.m 71 KB

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