AppDelegate.m 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. //
  2. // AppDelegate.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "iRate.h"
  25. #import "AFURLSessionManager.h"
  26. #import "CCNetworking.h"
  27. #import "CCCoreData.h"
  28. #import "CCCrypto.h"
  29. #import "CCManageAsset.h"
  30. #import "CCGraphics.h"
  31. #import "CCPhotosCameraUpload.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. #ifdef CUSTOM_BUILD
  39. #import "CustomSwift.h"
  40. #else
  41. #import "Nextcloud-Swift.h"
  42. #endif
  43. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  44. {
  45. }
  46. @end
  47. @implementation AppDelegate
  48. + (void)initialize
  49. {
  50. [iRate sharedInstance].daysUntilPrompt = 10;
  51. [iRate sharedInstance].usesUntilPrompt = 10;
  52. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  53. //enable preview mode
  54. //[iRate sharedInstance].previewMode = YES;
  55. }
  56. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  57. {
  58. // Brand
  59. if (k_option_use_firebase) {
  60. /*
  61. In order for this to work, proper GoogleService-Info.plist must be included
  62. */
  63. @try {
  64. [FIRApp configure];
  65. } @catch (NSException *exception) {
  66. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  67. }
  68. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  69. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  70. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  71. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  72. } else {
  73. // iOS 10 or later
  74. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  75. // For iOS 10 display notification (sent via APNS)
  76. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  77. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  78. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  79. }];
  80. // For iOS 10 data message (sent via FCM)
  81. [FIRMessaging messaging].remoteMessageDelegate = self;
  82. #endif
  83. }
  84. }
  85. NSString *dir;
  86. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:k_capabilitiesGroups];
  87. NSLog(@"[LOG] Start program group -----------------");
  88. NSLog(@"%@", dirGroup);
  89. NSLog(@"[LOG] Start program application -----------");
  90. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  91. NSLog(@"[LOG] -------------------------------------");
  92. // create Directory local => Documents
  93. dir = [CCUtility getDirectoryLocal];
  94. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  95. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  96. // create Directory audio => Library, Application Support, audio
  97. dir = [CCUtility getDirectoryAudio];
  98. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  99. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  100. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  101. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  102. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  103. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  104. //[CCCoreData verifyVersionCoreData];
  105. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  106. #ifdef DEBUG
  107. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  108. #else
  109. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  110. #endif
  111. // Verify upgrade
  112. [self upgrade];
  113. // Set account, if no exists clear all
  114. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  115. if (recordAccount == nil) {
  116. // remove all the keys Chain
  117. [CCUtility deleteAllChainStore];
  118. // remove all the App group key
  119. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  120. } else {
  121. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password];
  122. }
  123. // Operation Queue OC Networking
  124. _netQueue = [[NSOperationQueue alloc] init];
  125. _netQueue.name = k_queue;
  126. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  127. _netQueueDownload = [[NSOperationQueue alloc] init];
  128. _netQueueDownload.name = k_download_queue;
  129. _netQueueDownload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  130. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  131. _netQueueDownloadWWan.name = k_download_queuewwan;
  132. _netQueueDownloadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  133. _netQueueUpload = [[NSOperationQueue alloc] init];
  134. _netQueueUpload.name = k_upload_queue;
  135. _netQueueUpload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  136. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  137. _netQueueUploadWWan.name = k_upload_queuewwan;
  138. _netQueueUploadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  139. // Check new Asset Photos/Video in progress
  140. _automaticCheckAssetInProgress = NO;
  141. _automaticUploadInProgress = NO;
  142. // Add notification change session
  143. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  144. // Initialization Share
  145. self.sharesID = [NSMutableDictionary new];
  146. self.sharesLink = [NSMutableDictionary new];
  147. self.sharesUserAndGroup = [NSMutableDictionary new];
  148. // Initialization Notification
  149. self.listOfNotifications = [NSMutableArray new];
  150. // Verify Session in progress and Init date task
  151. self.sessionDateLastDownloadTasks = [NSDate date];
  152. self.sessionDateLastUploadTasks = [NSDate date];
  153. // Background Fetch
  154. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  155. // Initialization List
  156. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  157. self.listChangeTask = [[NSMutableDictionary alloc] init];
  158. self.listMainVC = [[NSMutableDictionary alloc] init];
  159. // Player audio
  160. self.player = [LMMediaPlayerView sharedPlayerView];
  161. self.player.delegate = self;
  162. // ico Image Cache
  163. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  164. // setting Reachable in back
  165. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  166. self.reachability = [Reachability reachabilityForInternetConnection];
  167. self.lastReachability = [self.reachability isReachable];
  168. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  169. [self.reachability startNotifier];
  170. });
  171. //AV Session
  172. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  173. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  174. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  175. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  176. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  177. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  178. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  179. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  180. [app aspectNavigationControllerBar:navigationController.navigationBar encrypted:NO online:YES hidden:NO];
  181. // Settings TabBar
  182. [self createTabBarController];
  183. // passcode
  184. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  185. dispatch_async(dispatch_get_main_queue(), ^{
  186. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  187. });
  188. // Quick Actions
  189. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  190. [self configDynamicShortcutItems];
  191. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  192. if (shortcutItem)
  193. [self handleShortCutItem:shortcutItem];
  194. }
  195. // Start Timer
  196. self.timerProcess = [NSTimer scheduledTimerWithTimeInterval:k_timerProcess target:self selector:@selector(process) userInfo:nil repeats:YES];
  197. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:k_timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  198. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  199. // Registration Push Notification
  200. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  201. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  202. [application registerUserNotificationSettings:notificationSettings];
  203. // Fabric
  204. [Fabric with:@[[Crashlytics class]]];
  205. [self logUserCrashlytics];
  206. return YES;
  207. }
  208. //
  209. // L' applicazione si dimetterà dallo stato di attivo
  210. //
  211. - (void)applicationWillResignActive:(UIApplication *)application
  212. {
  213. [_activeMain closeAllMenu];
  214. [self updateApplicationIconBadgeNumber];
  215. }
  216. //
  217. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  218. //
  219. - (void)applicationWillEnterForeground:(UIApplication *)application
  220. {
  221. // facciamo partire il timer per il controllo delle sessioni e dei Lock
  222. [self.timerVerifySessionInProgress invalidate];
  223. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:k_timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  224. // refresh active Main
  225. if (_activeMain)
  226. [_activeMain reloadDatasource];
  227. // Initializations
  228. [self applicationInitialized];
  229. }
  230. //
  231. // L' applicazione è entrata nello sfondo
  232. //
  233. - (void)applicationDidEnterBackground:(UIApplication *)application
  234. {
  235. NSLog(@"[LOG] Enter in Background");
  236. [[CCQuickActions quickActionsManager] closeAll];
  237. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  238. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  239. __block UIBackgroundTaskIdentifier background_task;
  240. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  241. //Clean up code. Tell the system that we are done.
  242. [application endBackgroundTask: background_task];
  243. background_task = UIBackgroundTaskInvalid;
  244. }];
  245. }
  246. }
  247. //
  248. // L'applicazione terminerà
  249. //
  250. - (void)applicationWillTerminate:(UIApplication *)application
  251. {
  252. [MagicalRecord cleanUp];
  253. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  254. }
  255. //
  256. // Application Initialized
  257. //
  258. - (void)applicationInitialized
  259. {
  260. // Execute : now
  261. NSLog(@"[LOG] Update Folder Photo");
  262. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:self.activeAccount activeUrl:self.activeUrl];
  263. if ([folderCameraUpload length] > 0)
  264. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:self.activeAccount] selector:selectorReadFolder];
  265. // Execute : after 0.5 sec.
  266. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  267. NSLog(@"[LOG] Request Server Capabilities");
  268. if (_activeMain)
  269. [_activeMain requestServerCapabilities];
  270. NSLog(@"[LOG] Initialize Camera Upload");
  271. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  272. NSLog(@"[LOG] Listning Favorites");
  273. [[CCSynchronize sharedSynchronize] readListingFavorites];
  274. });
  275. // Initialize Camera Upload
  276. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  277. }
  278. #pragma --------------------------------------------------------------------------------------------
  279. #pragma mark ===== Process k_timerProcess seconds =====
  280. #pragma --------------------------------------------------------------------------------------------
  281. - (void)process
  282. {
  283. // BACKGROND & FOREGROUND
  284. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  285. // ONLY BACKGROUND
  286. } else {
  287. // ONLY FOREFROUND
  288. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  289. }
  290. }
  291. #pragma --------------------------------------------------------------------------------------------
  292. #pragma mark ===== Setting Active Account =====
  293. #pragma --------------------------------------------------------------------------------------------
  294. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword
  295. {
  296. self.activeAccount = activeAccount;
  297. self.activeUrl = activeUrl;
  298. self.activeUser = activeUser;
  299. self.activePassword = activePassword;
  300. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  301. }
  302. #pragma --------------------------------------------------------------------------------------------
  303. #pragma mark ===== Push Notification =====
  304. #pragma --------------------------------------------------------------------------------------------
  305. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  306. {
  307. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  308. }
  309. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  310. {
  311. [application registerForRemoteNotifications];
  312. }
  313. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  314. {
  315. // test
  316. if (self.activeAccount.length == 0)
  317. return;
  318. // FIREBASE registered token
  319. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  320. NSString *pushToken = [[FIRInstanceID instanceID] token];
  321. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  322. NSString *pushTokenHash = [[CCCrypto sharedManager] createSHA512:pushToken];
  323. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  324. #ifdef DEBUG
  325. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  326. #else
  327. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  328. #endif
  329. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  330. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  331. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  332. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  333. metadataNet.action = actionSubscribingNextcloudServer;
  334. metadataNet.options = options;
  335. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  336. }
  337. }
  338. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  339. {
  340. NSLog(@"[LOG] Error register remote notification %@", error);
  341. }
  342. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  343. UIApplicationState state = [application applicationState];
  344. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  345. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  346. } else {
  347. NSLog(@"[LOG] Receive Notification on Active state");
  348. }
  349. // If you are receiving a notification message while your app is in the background,
  350. // this callback will not be fired till the user taps on the notification launching the application.
  351. // TODO: Handle data of notification
  352. // Print message ID.
  353. //if (userInfo[kGCMMessageIDKey]) {
  354. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  355. //}
  356. // Print full message.
  357. NSLog(@"[LOG] %@", userInfo);
  358. }
  359. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  360. {
  361. UIApplicationState state = [application applicationState];
  362. // Print message ID.
  363. //if (userInfo[kGCMMessageIDKey]) {
  364. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  365. //}
  366. // Print full message.
  367. NSLog(@"[LOG] %@", userInfo);
  368. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  369. } else if (state == UIApplicationStateInactive) {
  370. // user tapped notification
  371. completionHandler(UIBackgroundFetchResultNewData);
  372. } else {
  373. // app is active
  374. completionHandler(UIBackgroundFetchResultNoData);
  375. }
  376. }
  377. #pragma FIREBASE
  378. - (void)tokenRefreshNotification:(NSNotification *)notification {
  379. // Note that this callback will be fired everytime a new token is generated, including the first
  380. // time. So if you need to retrieve the token as soon as it is available this is where that
  381. // should be done.
  382. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  383. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  384. // Connect to FCM since connection may have failed when attempted before having a token.
  385. [self connectToFcm];
  386. // TODO: If necessary send token to application server.
  387. }
  388. - (void)connectToFcm {
  389. // Won't connect since there is no token
  390. if (![[FIRInstanceID instanceID] token]) {
  391. return;
  392. }
  393. // Disconnect previous FCM connection if it exists.
  394. [[FIRMessaging messaging] disconnect];
  395. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  396. if (error != nil) {
  397. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  398. } else {
  399. NSLog(@"[LOG] Connected to FCM.");
  400. }
  401. }];
  402. }
  403. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  404. // Receive data message on iOS 10 devices while app is in the foreground.
  405. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  406. // Print full message
  407. NSLog(@"[LOG] %@", remoteMessage.appData);
  408. }
  409. #endif
  410. #pragma --------------------------------------------------------------------------------------------
  411. #pragma mark ===== Quick Actions - ShotcutItem =====
  412. #pragma --------------------------------------------------------------------------------------------
  413. - (void)configDynamicShortcutItems
  414. {
  415. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  416. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  417. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUpload];
  418. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  419. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  420. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  421. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  422. if (app.isCryptoCloudMode) {
  423. // add the array to our app
  424. [UIApplication sharedApplication].shortcutItems = @[shortcutUploadEncrypted, shortcutUpload, shortcutPhotos];
  425. } else {
  426. // add the array to our app
  427. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  428. }
  429. }
  430. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  431. {
  432. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  433. completionHandler(handledShortCutItem);
  434. }
  435. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  436. {
  437. BOOL handled = NO;
  438. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  439. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  440. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  441. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  442. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  443. dispatch_async(dispatch_get_main_queue(), ^{
  444. if (_activeMain) {
  445. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  446. if (splitViewController.isCollapsed) {
  447. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  448. for (UINavigationController *nvc in tbc.viewControllers) {
  449. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  450. [nvc popToRootViewControllerAnimated:NO];
  451. }
  452. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  453. } else {
  454. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  455. [nvcDetail popToRootViewControllerAnimated:NO];
  456. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  457. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  458. }
  459. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  460. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  461. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  462. });
  463. }
  464. });
  465. handled = YES;
  466. }
  467. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  468. dispatch_async(dispatch_get_main_queue(), ^{
  469. if (_activeMain) {
  470. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  471. if (splitViewController.isCollapsed) {
  472. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  473. for (UINavigationController *nvc in tbc.viewControllers) {
  474. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  475. [nvc popToRootViewControllerAnimated:NO];
  476. }
  477. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  478. } else {
  479. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  480. [nvcDetail popToRootViewControllerAnimated:NO];
  481. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  482. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  483. }
  484. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  485. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  486. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  487. });
  488. }
  489. });
  490. handled = YES;
  491. }
  492. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  493. dispatch_async(dispatch_get_main_queue(), ^{
  494. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  495. if (splitViewController.isCollapsed) {
  496. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  497. for (UINavigationController *nvc in tbc.viewControllers) {
  498. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  499. [nvc popToRootViewControllerAnimated:NO];
  500. }
  501. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  502. } else {
  503. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  504. [nvcDetail popToRootViewControllerAnimated:NO];
  505. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  506. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  507. }
  508. });
  509. handled = YES;
  510. }
  511. return handled;
  512. }
  513. #pragma --------------------------------------------------------------------------------------------
  514. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  515. #pragma --------------------------------------------------------------------------------------------
  516. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  517. {
  518. title = [NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]];
  519. dispatch_async(dispatch_get_main_queue(), ^{
  520. if (visible) {
  521. if (errorcode == kCFURLErrorNotConnectedToInternet) {
  522. NSLog(@"[LOG] No internet connection");
  523. } else {
  524. [TWMessageBarManager sharedInstance].styleSheet = self;
  525. [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  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:image_tabBarFiles];
  603. item.selectedImage = [UIImage imageNamed:image_tabBarFiles];
  604. // Favorites
  605. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexOffline];
  606. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  607. item.image = [UIImage imageNamed:image_tabBarFavorite];
  608. item.selectedImage = [UIImage imageNamed:image_tabBarFavorite];
  609. // Hide (PLUS)
  610. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexHide];
  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:image_tabBarPhotos];
  618. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  619. // More
  620. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  621. [item setTitle:NSLocalizedString(@"_more_", nil)];
  622. item.image = [UIImage imageNamed:image_tabBarMore];
  623. item.selectedImage = [UIImage imageNamed:image_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. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  679. if ([CCUtility getCreateMenuEncrypted])
  680. [menuAdd createMenuEncryptedWithView:self.window.rootViewController.view];
  681. else
  682. [menuAdd createMenuPlainWithView:self.window.rootViewController.view];
  683. }
  684. - (void)updateApplicationIconBadgeNumber
  685. {
  686. // Core Data
  687. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  688. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  689. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  690. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  691. // netQueueDownload
  692. for (NSOperation *operation in [app.netQueueDownload operations])
  693. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  694. // netQueueDownloadWWan
  695. for (NSOperation *operation in [app.netQueueDownloadWWan operations])
  696. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  697. // netQueueUpload
  698. for (NSOperation *operation in [app.netQueueUpload operations])
  699. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  700. // netQueueUploadWWan
  701. for (NSOperation *operation in [app.netQueueUploadWWan operations])
  702. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  703. // Total
  704. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  705. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  706. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  707. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  708. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  709. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  710. if (total > 0)
  711. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  712. else
  713. [tbItem setBadgeValue:nil];
  714. }
  715. }
  716. #pragma --------------------------------------------------------------------------------------------
  717. #pragma mark ===== Theming Color =====
  718. #pragma --------------------------------------------------------------------------------------------
  719. - (void)settingThemingColorBrand
  720. {
  721. if (self.activeAccount.length > 0) {
  722. TableCapabilities *tableCapabilities = [CCCoreData getCapabilitesForAccount:self.activeAccount];
  723. if (k_option_use_themingColor && tableCapabilities.themingColor.length > 0) {
  724. [NCBrandColor sharedInstance].brand = [CCGraphics colorFromHexString:tableCapabilities.themingColor];
  725. } else {
  726. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  727. }
  728. } else {
  729. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  730. }
  731. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTheming" object:nil];
  732. }
  733. - (void)changeTheming:(UIViewController *)vc
  734. {
  735. UIColor *color = [NCBrandColor sharedInstance].brand;
  736. // Change Navigation & TabBar color
  737. vc.navigationController.navigationBar.barTintColor = color;
  738. vc.tabBarController.tabBar.tintColor = color;
  739. // Change button Plus
  740. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  741. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  742. UIButton *button = [tabBarController.view viewWithTag:99];
  743. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  744. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  745. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  746. // Tint Color GLOBAL WINDOW
  747. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  748. }
  749. #pragma --------------------------------------------------------------------------------------------
  750. #pragma mark ===== Media Player Control =====
  751. #pragma --------------------------------------------------------------------------------------------
  752. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  753. {
  754. switch (event.subtype) {
  755. case UIEventSubtypeRemoteControlPlay:
  756. if (self.player.mediaPlayer) {
  757. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  758. if (self.player.mediaPlayer.nowPlayingItem.title)
  759. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  760. if (self.player.mediaPlayer.nowPlayingItem.artist)
  761. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  762. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  763. [self.player.mediaPlayer play];
  764. }
  765. break;
  766. case UIEventSubtypeRemoteControlPause:
  767. if (self.player.mediaPlayer) {
  768. [self.player.mediaPlayer pause];
  769. }
  770. break;
  771. case UIEventSubtypeRemoteControlNextTrack:
  772. // handle it break;
  773. case UIEventSubtypeRemoteControlPreviousTrack:
  774. // handle it break;
  775. default:
  776. break;
  777. }
  778. }
  779. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  780. {
  781. return YES;
  782. }
  783. #pragma --------------------------------------------------------------------------------------------
  784. #pragma mark ===== Manager Passcode =====
  785. #pragma --------------------------------------------------------------------------------------------
  786. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  787. {
  788. // ServerUrl active
  789. NSString *serverUrl = self.activeMain.serverUrl;
  790. // fermiamo la data della sessione
  791. self.sessionePasscodeLock = nil;
  792. // se il block code è a zero esci con NON attivare la richiesta password
  793. if ([[CCUtility getBlockCode] length] == 0) return NO;
  794. // se non c'è attivo un account esci con NON attivare la richiesta password
  795. if ([self.activeAccount length] == 0) return NO;
  796. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  797. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:serverUrl activeAccount:self.activeAccount]) return NO;
  798. return YES;
  799. }
  800. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  801. {
  802. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  803. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  804. viewController.delegate = self;
  805. viewController.title = k_brand;
  806. viewController.fromType = CCBKPasscodeFromLockScreen;
  807. viewController.inputViewTitlePassword = YES;
  808. if ([CCUtility getSimplyBlockCode]) {
  809. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  810. viewController.passcodeInputView.maximumLength = 6;
  811. } else {
  812. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  813. viewController.passcodeInputView.maximumLength = 64;
  814. }
  815. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  816. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  817. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  818. return navigationController;
  819. }
  820. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  821. {
  822. [aViewController dismissViewControllerAnimated:YES completion:nil];
  823. // is a lock screen
  824. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  825. [aViewController dismissViewControllerAnimated:YES completion:nil];
  826. // start session Passcode Lock
  827. NSString *serverUrl = self.activeMain.serverUrl;
  828. if ([CCCoreData isBlockZone:serverUrl activeAccount:self.activeAccount])
  829. self.sessionePasscodeLock = [NSDate date];
  830. }
  831. }
  832. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  833. {
  834. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  835. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  836. //self.lockUntilDate = nil;
  837. //self.failedAttempts = 0;
  838. aResultHandler(YES);
  839. } else aResultHandler(NO);
  840. } else aResultHandler(YES);
  841. }
  842. #pragma --------------------------------------------------------------------------------------------
  843. #pragma mark ===== reachabilityChanged =====
  844. #pragma --------------------------------------------------------------------------------------------
  845. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  846. {
  847. if ([self.reachability isReachable]) {
  848. if (self.lastReachability == NO) {
  849. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  850. if (_activeMain)
  851. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  852. }
  853. NSLog(@"[LOG] Reachability Changed: Reachable");
  854. self.lastReachability = YES;
  855. } else {
  856. if (self.lastReachability == YES) {
  857. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  858. }
  859. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  860. self.lastReachability = NO;
  861. }
  862. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  863. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  864. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleMain" object:nil];
  865. }
  866. #pragma --------------------------------------------------------------------------------------------
  867. #pragma mark ===== Fetch =====
  868. #pragma --------------------------------------------------------------------------------------------
  869. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  870. {
  871. NSLog(@"[LOG] Start Fetch");
  872. // Verify new photo
  873. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  874. // after 20 sec verify Re
  875. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  876. [[CCNetworking sharedNetworking] automaticDownloadInError];
  877. [[CCNetworking sharedNetworking] automaticUploadInError];
  878. NSLog(@"[LOG] End Fetch 20 sec.");
  879. });
  880. // after 25 sec
  881. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  882. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  883. if ([records count] > 0) {
  884. completionHandler(UIBackgroundFetchResultNewData);
  885. } else {
  886. completionHandler(UIBackgroundFetchResultNoData);
  887. }
  888. NSLog(@"[LOG] End Fetch 25 sec.");
  889. });
  890. }
  891. #pragma --------------------------------------------------------------------------------------------
  892. #pragma mark ===== Operation Networking & Session =====
  893. #pragma --------------------------------------------------------------------------------------------
  894. //
  895. // Method called by the system when all the background task has end
  896. //
  897. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  898. {
  899. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  900. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  901. [[CCNetworking sharedNetworking] automaticDownloadInError];
  902. [[CCNetworking sharedNetworking] automaticUploadInError];
  903. self.backgroundSessionCompletionHandler = completionHandler;
  904. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  905. self.backgroundSessionCompletionHandler = nil;
  906. completionHandler();
  907. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  908. });
  909. }
  910. - (void)cancelAllOperations
  911. {
  912. [_netQueue cancelAllOperations];
  913. [_netQueueDownload cancelAllOperations];
  914. [_netQueueDownloadWWan cancelAllOperations];
  915. [_netQueueUpload cancelAllOperations];
  916. [_netQueueUploadWWan cancelAllOperations];
  917. }
  918. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  919. {
  920. id operation;
  921. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl isCryptoCloudMode:_isCryptoCloudMode];
  922. [operation setQueuePriority:metadataNet.priority];
  923. [netQueue addOperation:operation];
  924. }
  925. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  926. {
  927. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  928. for (OCnetworking *operation in [self.netQueueDownload operations])
  929. if ([operation.metadataNet.selector isEqualToString:selector])
  930. [metadatasNet addObject:[operation.metadataNet copy]];
  931. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  932. if ([operation.metadataNet.selector isEqualToString:selector])
  933. [metadatasNet addObject:[operation.metadataNet copy]];
  934. return metadatasNet;
  935. }
  936. - (void)loadAutomaticUpload
  937. {
  938. CCMetadataNet *metadataNet;
  939. // Is loading new Asset or this ?
  940. if (_automaticCheckAssetInProgress || _automaticUploadInProgress)
  941. return;
  942. // START Automatic Upload in progress
  943. _automaticUploadInProgress = YES;
  944. NSArray *uploadInQueue = [CCCoreData getTableMetadataUploadAccount:app.activeAccount];
  945. NSArray *recordAutomaticUploadInLock = [CCCoreData getAllLockTableAutomaticUploadForAccount:_activeAccount];
  946. for (TableAutomaticUpload *tableAutomaticUpload in recordAutomaticUploadInLock) {
  947. BOOL recordFound = NO;
  948. for (CCMetadataNet *metadataNet in uploadInQueue) {
  949. if (metadataNet.assetLocalIdentifier == tableAutomaticUpload.assetLocalIdentifier)
  950. recordFound = YES;
  951. }
  952. if (!recordFound)
  953. [CCCoreData unlockTableAutomaticUploadForAccount:_activeAccount assetLocalIdentifier:tableAutomaticUpload.assetLocalIdentifier];
  954. }
  955. // ------------------------- <selectorUploadAutomatic> -------------------------
  956. metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic];
  957. while (metadataNet) {
  958. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  959. if (result.count) {
  960. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet.assetLocalIdentifier fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:app.activeMain];
  961. } else {
  962. [CCCoreData addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selectorUploadAutomatic note:@"Internal error image/video not found [0]" type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_activeAccount activeUrl:_activeUrl];
  963. [CCCoreData deleteTableAutomaticUploadForAccount:_activeAccount assetLocalIdentifier:metadataNet.assetLocalIdentifier];
  964. }
  965. metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic];
  966. }
  967. // ------------------------- <selectorUploadAutomaticAll> -------------------------
  968. // Verify num error MAX 10 after STOP
  969. NSUInteger errorCount = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,k_taskIdentifierError, k_taskIdentifierError]];
  970. if (errorCount >= 10) {
  971. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  972. // STOP Im progress
  973. _automaticUploadInProgress = NO;
  974. return;
  975. }
  976. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier > 0) OR (sessionTaskIdentifierPlist > 0))", app.activeAccount, selectorUploadAutomaticAll]];
  977. if (count >= k_maxConcurrentOperationDownloadUpload) {
  978. // STOP Im progress
  979. _automaticUploadInProgress = NO;
  980. return;
  981. }
  982. metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomaticAll];
  983. if (metadataNet) {
  984. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  985. if (result.count) {
  986. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet.assetLocalIdentifier fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:app.activeMain];
  987. } else {
  988. [CCCoreData addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selectorUploadAutomatic note:@"Internal error image/video not found [0]" type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_activeAccount activeUrl:_activeUrl];
  989. [CCCoreData deleteTableAutomaticUploadForAccount:_activeAccount assetLocalIdentifier:metadataNet.assetLocalIdentifier];
  990. }
  991. }
  992. // STOP Im progress
  993. _automaticUploadInProgress = NO;
  994. }
  995. - (void)verifyDownloadUploadInProgress
  996. {
  997. BOOL callVerifyDownload = NO;
  998. BOOL callVerifyUpload = NO;
  999. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  1000. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:k_timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:k_timerVerifySession]);
  1001. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:k_timerVerifySession]] == NSOrderedDescending) {
  1002. callVerifyDownload = YES;
  1003. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  1004. }
  1005. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:k_timerVerifySession]] == NSOrderedDescending) {
  1006. callVerifyUpload = YES;
  1007. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  1008. }
  1009. if (callVerifyDownload && callVerifyUpload) {
  1010. NSLog(@"[LOG] Stop timer verify session");
  1011. [self.timerVerifySessionInProgress invalidate];
  1012. }
  1013. }
  1014. }
  1015. // Notification change session
  1016. - (void)sessionChanged:(NSNotification *)notification
  1017. {
  1018. NSURLSession *session;
  1019. CCMetadata *metadata;
  1020. NSURLSessionTask *task;
  1021. for (id object in notification.object) {
  1022. if ([object isKindOfClass:[NSURLSession class]])
  1023. session = object;
  1024. if ([object isKindOfClass:[CCMetadata class]])
  1025. metadata = object;
  1026. if ([object isKindOfClass:[NSURLSessionTask class]])
  1027. task = object;
  1028. }
  1029. /*
  1030. Task
  1031. */
  1032. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  1033. app.sessionDateLastDownloadTasks = [NSDate date];
  1034. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  1035. app.sessionDateLastUploadTasks = [NSDate date];
  1036. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  1037. dispatch_async(dispatch_get_main_queue(), ^{
  1038. [self changeTask:metadata];
  1039. });
  1040. /*
  1041. Session
  1042. */
  1043. if (session) {
  1044. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1045. unsigned long numDownload = [downloadTasks count];
  1046. unsigned long numUpload = [uploadTasks count];
  1047. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  1048. }];
  1049. }
  1050. }
  1051. - (void)changeTask:(CCMetadata *)metadata
  1052. {
  1053. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1054. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  1055. // sessionTaskIdentifier on Stop
  1056. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1057. }
  1058. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  1059. // V 1.8 if upload_session_wwan change in upload_session
  1060. if ([metadata.session isEqualToString:k_upload_session_wwan])
  1061. metadata.session = k_upload_session;
  1062. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1063. }
  1064. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  1065. BOOL downloadData = NO, downloadPlist = NO;
  1066. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) downloadData = YES;
  1067. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) downloadPlist = YES;
  1068. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1069. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:nil];
  1070. });
  1071. }
  1072. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1073. // remove the file
  1074. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  1075. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  1076. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  1077. }
  1078. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  1079. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1080. }
  1081. // remove ChangeTask (fileID) from the list
  1082. [_listChangeTask removeObjectForKey:metadata.fileID];
  1083. // delete progress
  1084. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  1085. // Progress Task
  1086. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1087. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1088. // Refresh
  1089. if (_activeMain && [_listChangeTask count] == 0) {
  1090. [_activeMain reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:nil selector:nil];
  1091. }
  1092. }
  1093. - (BOOL)createFolderSubFolderAutomaticUploadFolderPhotos:(NSString *)folderPhotos useSubFolder:(BOOL)useSubFolder assets:(NSArray *)assets selector:(NSString *)selector
  1094. {
  1095. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl isCryptoCloudMode:NO];
  1096. if(![ocNetworking automaticCreateFolderSync:folderPhotos]) {
  1097. // Activity
  1098. [CCCoreData addActivityClient:folderPhotos fileID:@"" action:k_activityDebugActionAutomaticUpload selector:selector note:NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  1099. return false;
  1100. }
  1101. // Create if request the subfolders
  1102. if (useSubFolder) {
  1103. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  1104. if(![ocNetworking automaticCreateFolderSync:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  1105. // Activity
  1106. [CCCoreData addActivityClient:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] fileID:@"" action:k_activityDebugActionAutomaticUpload selector:selector note:NSLocalizedString(@"_error_createsubfolders_upload_",nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  1107. return false;
  1108. }
  1109. }
  1110. }
  1111. return true;
  1112. }
  1113. #pragma --------------------------------------------------------------------------------------------
  1114. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1115. #pragma --------------------------------------------------------------------------------------------
  1116. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1117. {
  1118. return YES;
  1119. }
  1120. // Method called from iOS system to send a file from other app.
  1121. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1122. {
  1123. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1124. NSLog(@"[LOG] the path is: %@", url.path);
  1125. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1126. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1127. if (self.activeAccount) {
  1128. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1129. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1130. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1131. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1132. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1133. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1134. });
  1135. }
  1136. // remove from InBox
  1137. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1138. return YES;
  1139. }
  1140. #pragma --------------------------------------------------------------------------------------------
  1141. #pragma mark ===== Crashlytics =====
  1142. #pragma --------------------------------------------------------------------------------------------
  1143. - (void)logUserCrashlytics
  1144. {
  1145. TableAccount *tableAccount = [CCCoreData getActiveAccount];
  1146. if (tableAccount) {
  1147. if (tableAccount.email && tableAccount.email.length > 0)
  1148. [CrashlyticsKit setUserEmail:tableAccount.email];
  1149. }
  1150. }
  1151. #pragma --------------------------------------------------------------------------------------------
  1152. #pragma mark ===== UPGRADE =====
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. - (void)upgrade
  1155. {
  1156. #ifdef DEBUG
  1157. // [CCCoreData flushTableGPS];
  1158. // [CCCoreData setGeoInformationLocalNull];
  1159. #endif
  1160. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1161. /* ---------------------- UPGRADE VERSION ----------------------- */
  1162. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1163. [CCCoreData flushTableDirectoryAccount:nil];
  1164. [CCCoreData flushTableLocalFileAccount:nil];
  1165. [CCCoreData flushTableMetadataAccount:nil];
  1166. }
  1167. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1168. [CCCoreData flushTableGPS];
  1169. [CCCoreData setGeoInformationLocalNull];
  1170. }
  1171. if (([actualVersion compare:@"2.17" options:NSNumericSearch] == NSOrderedAscending)) {
  1172. [CCCoreData clearAllDateReadDirectory];
  1173. [CCCoreData flushTableMetadataAccount:nil];
  1174. }
  1175. if (([actualVersion compare:@"2.17.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1176. }
  1177. if (([actualVersion compare:@"2.17.2" options:NSNumericSearch] == NSOrderedAscending)) {
  1178. }
  1179. }
  1180. @end