AppDelegate.m 62 KB

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