AppDelegate.m 69 KB

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