AppDelegate.m 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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 "JBroken.h"
  27. #import "CCNetworking.h"
  28. #import "CCCoreData.h"
  29. #import "CCCrypto.h"
  30. #import "CCOffline.h"
  31. #import "CCManageAsset.h"
  32. #import "CCGraphics.h"
  33. #import "CCPhotosCameraUpload.h"
  34. #import "CCOfflineFileFolder.h"
  35. #import "CCMain.h"
  36. #import "CCDetail.h"
  37. #import "Nextcloud-Swift.h"
  38. @interface AppDelegate ()
  39. {
  40. }
  41. @end
  42. @implementation AppDelegate
  43. + (void)initialize
  44. {
  45. [iRate sharedInstance].daysUntilPrompt = 10;
  46. [iRate sharedInstance].usesUntilPrompt = 10;
  47. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  48. //enable preview mode
  49. //[iRate sharedInstance].previewMode = YES;
  50. }
  51. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  52. {
  53. NSString *dir;
  54. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  55. NSLog(@"[LOG] Start program group -----------------");
  56. NSLog(@"%@", dirGroup);
  57. NSLog(@"[LOG] Start program application -----------");
  58. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  59. NSLog(@"[LOG] -------------------------------------");
  60. // create Directory local => Documents
  61. dir = [CCUtility getDirectoryLocal];
  62. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  63. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  64. // create Directory audio => Library, Application Support, audio
  65. dir = [CCUtility getDirectoryAudio];
  66. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  67. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  68. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  69. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  70. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  71. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  72. //[CCCoreData verifyVersionCoreData];
  73. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  74. #ifdef DEBUG
  75. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  76. #else
  77. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  78. #endif
  79. // Verify upgrade
  80. [self upgrade];
  81. // Set account, if no exists clear all
  82. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  83. if (recordAccount == nil) {
  84. // remove all the keys Chain
  85. [CCUtility deleteAllChainStore];
  86. // remove all the App group key
  87. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  88. } else {
  89. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password activeUID:recordAccount.uid activeAccessToken:recordAccount.token typeCloud:recordAccount.typeCloud];
  90. }
  91. // Operation Queue OC-DB Networking
  92. _netQueue = [[NSOperationQueue alloc] init];
  93. _netQueue.name = netQueueName;
  94. _netQueue.maxConcurrentOperationCount = maxConcurrentOperation;
  95. _netQueueDownload = [[NSOperationQueue alloc] init];
  96. _netQueueDownload.name = netQueueDownloadName;
  97. _netQueueDownload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  98. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  99. _netQueueDownloadWWan.name = netQueueDownloadWWanName;
  100. _netQueueDownloadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  101. _netQueueUpload = [[NSOperationQueue alloc] init];
  102. _netQueueUpload.name = netQueueUploadName;
  103. _netQueueUpload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  104. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  105. _netQueueUploadWWan.name = netQueueUploadWWanName;
  106. _netQueueUploadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  107. // Add notification change session
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:networkingSessionNotification object:nil];
  109. // Initialization Share
  110. self.sharesID = [[NSMutableDictionary alloc] init];
  111. self.sharesLink = [[NSMutableDictionary alloc] init];
  112. self.sharesUserAndGroup = [[NSMutableDictionary alloc] init];
  113. // Initialization Notification
  114. self.listOfNotifications = [[NSMutableArray alloc] init];
  115. // Verify Session in progress and Init date task
  116. self.sessionDateLastDownloadTasks = [NSDate date];
  117. self.sessionDateLastUploadTasks = [NSDate date];
  118. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  119. // Background Fetch
  120. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  121. // Initialization List
  122. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  123. self.listChangeTask = [[NSMutableDictionary alloc] init];
  124. self.listMainVC = [[NSMutableDictionary alloc] init];
  125. // Player audio
  126. self.player = [LMMediaPlayerView sharedPlayerView];
  127. self.player.delegate = self;
  128. // ico Image Cache
  129. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  130. // Page Control
  131. /*
  132. UIPageControl *pageControl = [UIPageControl appearance];
  133. pageControl.pageIndicatorTintColor = COLOR_SEPARATOR_TABLE;
  134. pageControl.currentPageIndicatorTintColor = COLOR_NEXTCLOUD;
  135. pageControl.backgroundColor = [UIColor clearColor];
  136. */
  137. // remove tmp & cache
  138. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  139. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  140. for (NSString *file in tmpDirectory) {
  141. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  142. }
  143. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  144. });
  145. // setting Reachable in back
  146. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  147. self.reachability = [Reachability reachabilityForInternetConnection];
  148. self.lastReachability = [self.reachability isReachable];
  149. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  150. [self.reachability startNotifier];
  151. });
  152. //AV Session
  153. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  154. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  155. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  156. // permission request camera roll
  157. ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  158. [lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  159. //NSLog(@"[LOG] %li",(long)[group numberOfAssets]);
  160. } failureBlock:^(NSError *error) {
  161. if (error.code == ALAssetsLibraryAccessUserDeniedError) {
  162. NSLog(@"[LOG] user denied access, code: %li",(long)error.code);
  163. }else{
  164. NSLog(@"[LOG] Other error code: %li",(long)error.code);
  165. }
  166. }];
  167. // permission request notification
  168. if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  169. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
  170. [application registerUserNotificationSettings:settings];
  171. }
  172. // it is a device Jailbroken
  173. self.isDeviceJailbroken = isDeviceJailbroken();
  174. [self.window setTintColor:COLOR_BRAND];
  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. // Settings TabBar
  181. [self createTabBarController];
  182. // passcode
  183. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  184. dispatch_async(dispatch_get_main_queue(), ^{
  185. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  186. });
  187. // Quick Actions
  188. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  189. [self configDynamicShortcutItems];
  190. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  191. if (shortcutItem)
  192. [self handleShortCutItem:shortcutItem];
  193. }
  194. // Start timer Verify Process
  195. self.timerVerifyProcess = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(verifyProcess) userInfo:nil repeats:YES];
  196. // Registration Push Notification
  197. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  198. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  199. [application registerUserNotificationSettings:notificationSettings];
  200. return YES;
  201. }
  202. //
  203. // L' applicazione è diventata attiva
  204. //
  205. - (void)applicationDidBecomeActive:(UIApplication *)application
  206. {
  207. // After 5 sec. for wait load app.activeMain start if exists in Table Automatic Upload + All
  208. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  209. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic] > 0)
  210. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  211. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomaticAll] > 0)
  212. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  213. });
  214. }
  215. //
  216. // L' applicazione si dimetterà dallo stato di attivo
  217. //
  218. - (void)applicationWillResignActive:(UIApplication *)application
  219. {
  220. [self updateApplicationIconBadgeNumber];
  221. }
  222. //
  223. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  224. //
  225. - (void)applicationWillEnterForeground:(UIApplication *)application
  226. {
  227. // facciamo partire il timer per il controllo delle sessioni
  228. [self.timerVerifySessionInProgress invalidate];
  229. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  230. // refresh active Main
  231. if (_activeMain)
  232. [_activeMain getDataSourceWithReloadTableView];
  233. // Initializations
  234. [self applicationInitialized];
  235. }
  236. //
  237. // L' applicazione è entrata nello sfondo
  238. //
  239. - (void)applicationDidEnterBackground:(UIApplication *)application
  240. {
  241. NSLog(@"[LOG] Enter in Background");
  242. [[CCQuickActions quickActionsManager] closeAll];
  243. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  244. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  245. __block UIBackgroundTaskIdentifier background_task;
  246. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  247. //Clean up code. Tell the system that we are done.
  248. [application endBackgroundTask: background_task];
  249. background_task = UIBackgroundTaskInvalid;
  250. }];
  251. }
  252. }
  253. //
  254. // L'applicazione terminerà
  255. //
  256. - (void)applicationWillTerminate:(UIApplication *)application
  257. {
  258. [MagicalRecord cleanUp];
  259. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  260. }
  261. //
  262. // Application Initialized
  263. //
  264. - (void)applicationInitialized
  265. {
  266. // now
  267. dispatch_async(dispatch_get_main_queue(), ^{
  268. //NSLog(@"[LOG] Read Folder for change Rev");
  269. //[[NSNotificationCenter defaultCenter] postNotificationName:@"readFileSelfFolderRev" object:nil];
  270. });
  271. // 0.5 sec.
  272. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  273. //
  274. NSLog(@"[LOG] Request Server Information");
  275. //
  276. if (_activeMain)
  277. [_activeMain requestServerInformation];
  278. });
  279. // 1 sec.
  280. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  281. NSLog(@"[LOG] read file Offline");
  282. [[CCOfflineFileFolder sharedOfflineFileFolder] readFileOffline];
  283. NSLog(@"[LOG] read folder offline");
  284. [[CCOfflineFileFolder sharedOfflineFileFolder] readFolderOffline];
  285. });
  286. // 1.5 sec.
  287. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  288. NSLog(@"[LOG] Initialize Camera Upload");
  289. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  290. });
  291. // Initialize Camera Upload
  292. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  293. }
  294. #pragma --------------------------------------------------------------------------------------------
  295. #pragma mark ===== Verify Process 5 seconds =====
  296. #pragma --------------------------------------------------------------------------------------------
  297. - (void)verifyProcess
  298. {
  299. // BACKGROND & FOREGROUND
  300. /* Active/Disactive Graphics Animation Offline Folders */
  301. NSArray *records = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  302. NSMutableArray *directory = [[NSMutableArray alloc] init];
  303. for (TableDirectory *record in records)
  304. [directory addObject:record.serverUrl];
  305. if ([directory count] > 0)
  306. [[CCOfflineFileFolder sharedOfflineFileFolder] offlineFolderAnimationDirectory:directory callViewController:YES];
  307. // ONLY BACKGROUND
  308. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  309. } else {
  310. // ONLY FOREFROUND
  311. }
  312. }
  313. #pragma --------------------------------------------------------------------------------------------
  314. #pragma mark ===== Setting Active Account =====
  315. #pragma --------------------------------------------------------------------------------------------
  316. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword activeUID:(NSString *)activeUID activeAccessToken:(NSString *)activeAccessToken typeCloud:(NSString *)typeCloud
  317. {
  318. self.activeAccount = activeAccount;
  319. self.activeUrl = activeUrl;
  320. self.activeUser = activeUser;
  321. self.activePassword = activePassword;
  322. self.typeCloud = typeCloud;
  323. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  324. self.activeUID = activeUID;
  325. self.activeAccessToken = activeAccessToken;
  326. }
  327. #pragma --------------------------------------------------------------------------------------------
  328. #pragma mark ===== Push Notification =====
  329. #pragma --------------------------------------------------------------------------------------------
  330. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  331. {
  332. [application registerForRemoteNotifications];
  333. }
  334. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  335. {
  336. NSLog(@"DEVICE TOKEN = %@", deviceToken);
  337. }
  338. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  339. {
  340. NSLog(@"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(@"Receive Notification on Inactive or Background state");
  346. } else {
  347. NSLog(@"Receive Notification on Active state");
  348. }
  349. }
  350. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  351. {
  352. UIApplicationState state = [application applicationState];
  353. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  354. } else if (state == UIApplicationStateInactive) {
  355. // user tapped notification
  356. completionHandler(UIBackgroundFetchResultNewData);
  357. } else {
  358. // app is active
  359. completionHandler(UIBackgroundFetchResultNoData);
  360. }
  361. }
  362. #pragma --------------------------------------------------------------------------------------------
  363. #pragma mark ===== Quick Actions - ShotcutItem =====
  364. #pragma --------------------------------------------------------------------------------------------
  365. - (void)configDynamicShortcutItems
  366. {
  367. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  368. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  369. UIApplicationShortcutIcon *shortcutUploadClearIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadClear];
  370. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  371. UIApplicationShortcutIcon *shortcutIconTypeOffline = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadOffline];
  372. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  373. UIApplicationShortcutItem *shortcutOffline = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.offline", bundleId] localizedTitle:NSLocalizedString(@"_offline_", nil) localizedSubtitle:nil icon:shortcutIconTypeOffline userInfo:nil];
  374. UIApplicationShortcutItem *shortcutUploadClear = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadClear", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadClearIcon userInfo:nil];
  375. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  376. // add all items to an array
  377. NSArray *items = @[shortcutUploadEncrypted, shortcutUploadClear, shortcutPhotos, shortcutOffline];
  378. // add the array to our app
  379. [UIApplication sharedApplication].shortcutItems = items;
  380. }
  381. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  382. {
  383. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  384. completionHandler(handledShortCutItem);
  385. }
  386. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  387. {
  388. BOOL handled = NO;
  389. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  390. NSString *shortcutOffline = [NSString stringWithFormat:@"%@.offline", bundleId];
  391. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  392. NSString *shortcutUploadClear = [NSString stringWithFormat:@"%@.uploadClear", bundleId];
  393. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  394. if ([shortcutItem.type isEqualToString:shortcutUploadClear] && self.activeAccount) {
  395. dispatch_async(dispatch_get_main_queue(), ^{
  396. if (_activeMain) {
  397. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  398. if (splitViewController.isCollapsed) {
  399. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  400. for (UINavigationController *nvc in tbc.viewControllers) {
  401. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  402. [nvc popToRootViewControllerAnimated:NO];
  403. }
  404. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  405. } else {
  406. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  407. [nvcDetail popToRootViewControllerAnimated:NO];
  408. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  409. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  410. }
  411. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  412. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  413. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  414. });
  415. }
  416. });
  417. handled = YES;
  418. }
  419. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  420. dispatch_async(dispatch_get_main_queue(), ^{
  421. if (_activeMain) {
  422. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  423. if (splitViewController.isCollapsed) {
  424. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  425. for (UINavigationController *nvc in tbc.viewControllers) {
  426. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  427. [nvc popToRootViewControllerAnimated:NO];
  428. }
  429. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  430. } else {
  431. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  432. [nvcDetail popToRootViewControllerAnimated:NO];
  433. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  434. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  435. }
  436. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  437. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  438. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  439. });
  440. }
  441. });
  442. handled = YES;
  443. }
  444. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  445. dispatch_async(dispatch_get_main_queue(), ^{
  446. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  447. if (splitViewController.isCollapsed) {
  448. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  449. for (UINavigationController *nvc in tbc.viewControllers) {
  450. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  451. [nvc popToRootViewControllerAnimated:NO];
  452. }
  453. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  454. } else {
  455. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  456. [nvcDetail popToRootViewControllerAnimated:NO];
  457. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  458. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  459. }
  460. });
  461. handled = YES;
  462. }
  463. else if ([shortcutItem.type isEqualToString:shortcutOffline] && self.activeAccount) {
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  466. if (splitViewController.isCollapsed) {
  467. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  468. for (UINavigationController *nvc in tbc.viewControllers) {
  469. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  470. [nvc popToRootViewControllerAnimated:NO];
  471. if ([nvc.topViewController isKindOfClass:[CCOffline class]])
  472. NSLog(@"ERROR");//[(CCOffline *)nvc.topViewController forcedSwitchOffline];
  473. }
  474. [tbc setSelectedIndex:TabBarApplicationIndexOffline];
  475. } else {
  476. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  477. [nvcDetail popToRootViewControllerAnimated:NO];
  478. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  479. UINavigationController *ncOffline = [tbc.viewControllers objectAtIndex:TabBarApplicationIndexOffline];
  480. if ([ncOffline.topViewController isKindOfClass:[CCOffline class]])
  481. NSLog(@"ERROR");//[(CCOffline *)ncOffline.topViewController forcedSwitchOffline];
  482. [tbc setSelectedIndex:TabBarApplicationIndexOffline];
  483. }
  484. });
  485. handled = YES;
  486. }
  487. return handled;
  488. }
  489. #pragma --------------------------------------------------------------------------------------------
  490. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  491. #pragma --------------------------------------------------------------------------------------------
  492. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type
  493. {
  494. title = [NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]];
  495. dispatch_async(dispatch_get_main_queue(), ^{
  496. if (visible) {
  497. [TWMessageBarManager sharedInstance].styleSheet = self;
  498. [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  499. } else {
  500. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  501. }
  502. });
  503. }
  504. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  505. {
  506. UIColor *backgroundColor = nil;
  507. switch (type)
  508. {
  509. case TWMessageBarMessageTypeError:
  510. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  511. break;
  512. case TWMessageBarMessageTypeSuccess:
  513. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  514. break;
  515. case TWMessageBarMessageTypeInfo:
  516. backgroundColor = COLOR_BRAND_MESSAGE;
  517. break;
  518. default:
  519. break;
  520. }
  521. return backgroundColor;
  522. }
  523. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  524. {
  525. UIColor *strokeColor = nil;
  526. switch (type)
  527. {
  528. case TWMessageBarMessageTypeError:
  529. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  530. break;
  531. case TWMessageBarMessageTypeSuccess:
  532. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  533. break;
  534. case TWMessageBarMessageTypeInfo:
  535. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  536. break;
  537. default:
  538. break;
  539. }
  540. return strokeColor;
  541. }
  542. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  543. {
  544. UIImage *iconImage = nil;
  545. switch (type)
  546. {
  547. case TWMessageBarMessageTypeError:
  548. iconImage = [UIImage imageNamed:@"icon-error.png"];
  549. break;
  550. case TWMessageBarMessageTypeSuccess:
  551. iconImage = [UIImage imageNamed:@"icon-success.png"];
  552. break;
  553. case TWMessageBarMessageTypeInfo:
  554. iconImage = [UIImage imageNamed:@"icon-info.png"];
  555. break;
  556. default:
  557. break;
  558. }
  559. return iconImage;
  560. }
  561. #pragma --------------------------------------------------------------------------------------------
  562. #pragma mark ===== TabBarController =====
  563. #pragma --------------------------------------------------------------------------------------------
  564. - (void)createTabBarController
  565. {
  566. UITabBarItem *item;
  567. NSLayoutConstraint *constraint;
  568. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  569. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  570. [CCAspect aspectTabBar:tabBarController.tabBar hidden:NO];
  571. // File
  572. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFile];
  573. [item setTitle:NSLocalizedString(@"_home_", nil)];
  574. item.image = [UIImage imageNamed:image_tabBarFile];
  575. item.selectedImage = [UIImage imageNamed:image_tabBarFile];
  576. // Offline
  577. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexOffline];
  578. [item setTitle:NSLocalizedString(@"_offline_", nil)];
  579. item.image = [UIImage imageNamed:image_tabBarOffline];
  580. item.selectedImage = [UIImage imageNamed:image_tabBarOffline];
  581. // Hide (PLUS)
  582. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexHide];
  583. item.title = nil;
  584. item.image = nil;
  585. item.enabled = false;
  586. // Photos
  587. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexPhotos];
  588. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  589. item.image = [UIImage imageNamed:image_tabBarPhotos];
  590. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  591. // Settings
  592. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexSettings];
  593. [item setTitle:NSLocalizedString(@"_settings_", nil)];
  594. item.image = [UIImage imageNamed:image_tabBarSettings];
  595. item.selectedImage = [UIImage imageNamed:image_tabBarSettings];
  596. // Plus Button
  597. UIImage *buttonImage = [UIImage imageNamed:@"Plus"];
  598. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  599. button.tag = 99;
  600. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  601. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  602. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  603. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  604. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  605. [tabBarController.view addSubview:button];
  606. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  607. [tabBarController.view addConstraint:constraint];
  608. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  609. [tabBarController.view addConstraint:constraint];
  610. }
  611. - (void)plusButtonVisibile:(BOOL)visible
  612. {
  613. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  614. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  615. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  616. if (buttonPlus) {
  617. if (visible) {
  618. buttonPlus.hidden = false;
  619. } else {
  620. buttonPlus.hidden = true;
  621. }
  622. }
  623. }
  624. - (void)handleTouchTabbarCenter:(id)sender
  625. {
  626. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] init];
  627. if ([CCUtility getCreateMenuEncrypted])
  628. [menuAdd createMenuEncryptedWithView:self.window.rootViewController.view];
  629. else
  630. [menuAdd createMenuPlainWithView:self.window.rootViewController.view];
  631. }
  632. - (void)updateApplicationIconBadgeNumber
  633. {
  634. // Core Data
  635. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  636. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  637. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  638. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  639. // netQueueDownload
  640. for (NSOperation *operation in [app.netQueueDownload operations]) {
  641. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  642. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  643. }
  644. // netQueueDownloadWWan
  645. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  646. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  647. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  648. }
  649. // netQueueUpload
  650. for (NSOperation *operation in [app.netQueueUpload operations]) {
  651. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  652. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  653. }
  654. // netQueueUploadWWan
  655. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  656. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  657. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  658. }
  659. // Total
  660. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  661. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  662. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  663. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  664. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  665. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  666. if (total > 0)
  667. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  668. else
  669. [tbItem setBadgeValue:nil];
  670. }
  671. }
  672. #pragma --------------------------------------------------------------------------------------------
  673. #pragma mark ===== Media Player Control =====
  674. #pragma --------------------------------------------------------------------------------------------
  675. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  676. {
  677. switch (event.subtype) {
  678. case UIEventSubtypeRemoteControlPlay:
  679. if (self.player.mediaPlayer) {
  680. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  681. if (self.player.mediaPlayer.nowPlayingItem.title)
  682. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  683. if (self.player.mediaPlayer.nowPlayingItem.artist)
  684. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  685. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  686. [self.player.mediaPlayer play];
  687. }
  688. break;
  689. case UIEventSubtypeRemoteControlPause:
  690. if (self.player.mediaPlayer) {
  691. [self.player.mediaPlayer pause];
  692. }
  693. break;
  694. case UIEventSubtypeRemoteControlNextTrack:
  695. // handle it break;
  696. case UIEventSubtypeRemoteControlPreviousTrack:
  697. // handle it break;
  698. default:
  699. break;
  700. }
  701. }
  702. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  703. {
  704. return YES;
  705. }
  706. #pragma --------------------------------------------------------------------------------------------
  707. #pragma mark ===== Manager Passcode =====
  708. #pragma --------------------------------------------------------------------------------------------
  709. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  710. {
  711. // fermiamo la data della sessione
  712. self.sessionePasscodeLock = nil;
  713. // se il block code è a zero esci con NON attivare la richiesta password
  714. if ([[CCUtility getBlockCode] length] == 0) return NO;
  715. // se non c'è attivo un account esci con NON attivare la richiesta password
  716. if ([self.activeAccount length] == 0) return NO;
  717. // se non c'è il passcode esci con NON attivare la richiesta password
  718. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  719. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  720. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  721. return YES;
  722. }
  723. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  724. {
  725. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  726. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  727. viewController.delegate = self;
  728. viewController.title = _brand_;
  729. viewController.fromType = CCBKPasscodeFromLockScreen;
  730. viewController.inputViewTitlePassword = YES;
  731. if ([CCUtility getSimplyBlockCode]) {
  732. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  733. viewController.passcodeInputView.maximumLength = 6;
  734. } else {
  735. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  736. viewController.passcodeInputView.maximumLength = 64;
  737. }
  738. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  739. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  740. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  741. return navigationController;
  742. }
  743. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  744. {
  745. [aViewController dismissViewControllerAnimated:YES completion:nil];
  746. // is a lock screen
  747. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  748. [aViewController dismissViewControllerAnimated:YES completion:nil];
  749. // start session Passcode Lock
  750. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  751. self.sessionePasscodeLock = [NSDate date];
  752. }
  753. }
  754. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  755. {
  756. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  757. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  758. //self.lockUntilDate = nil;
  759. //self.failedAttempts = 0;
  760. aResultHandler(YES);
  761. } else aResultHandler(NO);
  762. } else aResultHandler(YES);
  763. }
  764. #pragma --------------------------------------------------------------------------------------------
  765. #pragma mark ===== reachabilityChanged =====
  766. #pragma --------------------------------------------------------------------------------------------
  767. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  768. {
  769. if ([self.reachability isReachable]) {
  770. if (self.lastReachability == NO) {
  771. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  772. if (_activeMain)
  773. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  774. }
  775. NSLog(@"[LOG] Reachability Changed: Reachable");
  776. self.lastReachability = YES;
  777. } else {
  778. if (self.lastReachability == YES) {
  779. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  780. }
  781. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  782. self.lastReachability = NO;
  783. }
  784. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  785. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  786. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  787. }
  788. #pragma --------------------------------------------------------------------------------------------
  789. #pragma mark ===== Fetch =====
  790. #pragma --------------------------------------------------------------------------------------------
  791. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  792. {
  793. NSLog(@"[LOG] Start Fetch");
  794. // Verify new photo
  795. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  796. // after 20 sec verify Re
  797. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  798. [[CCNetworking sharedNetworking] automaticDownloadInError];
  799. [[CCNetworking sharedNetworking] automaticUploadInError];
  800. NSLog(@"[LOG] End Fetch 20 sec.");
  801. });
  802. // after 25 sec
  803. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  804. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  805. if ([records count] > 0) {
  806. completionHandler(UIBackgroundFetchResultNewData);
  807. } else {
  808. completionHandler(UIBackgroundFetchResultNoData);
  809. }
  810. NSLog(@"[LOG] End Fetch 25 sec.");
  811. });
  812. }
  813. #pragma --------------------------------------------------------------------------------------------
  814. #pragma mark ===== Operation Networking & Session =====
  815. #pragma --------------------------------------------------------------------------------------------
  816. //
  817. // Method called by the system when all the background task has end
  818. //
  819. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  820. {
  821. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  822. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  823. [[CCNetworking sharedNetworking] automaticDownloadInError];
  824. [[CCNetworking sharedNetworking] automaticUploadInError];
  825. self.backgroundSessionCompletionHandler = completionHandler;
  826. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  827. self.backgroundSessionCompletionHandler = nil;
  828. completionHandler();
  829. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  830. });
  831. }
  832. - (void)cancelAllOperations
  833. {
  834. [_netQueue cancelAllOperations];
  835. [_netQueueDownload cancelAllOperations];
  836. [_netQueueDownloadWWan cancelAllOperations];
  837. [_netQueueUpload cancelAllOperations];
  838. [_netQueueUploadWWan cancelAllOperations];
  839. [self performSelector:@selector(updateApplicationIconBadgeNumber) withObject:nil afterDelay:0.5];
  840. }
  841. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  842. {
  843. id operation;
  844. BOOL activityIndicator = NO;
  845. // Activity Indicator
  846. if (netQueue == _netQueue)
  847. activityIndicator = YES;
  848. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  849. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud activityIndicator:activityIndicator];
  850. [operation setQueuePriority:metadataNet.priority];
  851. [netQueue addOperation:operation];
  852. }
  853. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  854. {
  855. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  856. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  857. for (OCnetworking *operation in [self.netQueueDownload operations])
  858. if ([operation.metadataNet.selector isEqualToString:selector])
  859. [metadatasNet addObject:[operation.metadataNet copy]];
  860. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  861. if ([operation.metadataNet.selector isEqualToString:selector])
  862. [metadatasNet addObject:[operation.metadataNet copy]];
  863. }
  864. return metadatasNet;
  865. }
  866. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  867. {
  868. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  869. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  870. for (OCnetworking *operation in [self.netQueueUpload operations])
  871. if ([operation.metadataNet.selector isEqualToString:selector])
  872. [metadatasNet addObject:[operation.metadataNet copy]];
  873. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  874. if ([operation.metadataNet.selector isEqualToString:selector])
  875. [metadatasNet addObject:[operation.metadataNet copy]];
  876. }
  877. return metadatasNet;
  878. }
  879. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  880. {
  881. // Only one
  882. if ([[self verifyExistsInQueuesUploadSelector:selector] count] > 1)
  883. return;
  884. // Verify num error if selectorUploadAutomaticAll
  885. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  886. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  887. #ifdef DEBUG
  888. NSArray *records = [[NSArray alloc] init];
  889. records = [TableMetadata MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  890. #endif
  891. if (count >= 10) {
  892. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  893. return;
  894. }
  895. }
  896. // Add Network queue
  897. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector context:nil];
  898. if (metadataNet) {
  899. NSOperationQueue *queue;
  900. if ([metadataNet.session containsString:@"wwan"])
  901. queue = app.netQueueUploadWWan;
  902. else
  903. queue = app.netQueueUpload;
  904. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet];
  905. }
  906. }
  907. - (void)verifyDownloadUploadInProgress
  908. {
  909. BOOL callVerifyDownload = NO;
  910. BOOL callVerifyUpload = NO;
  911. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  912. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  913. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  914. callVerifyDownload = YES;
  915. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  916. }
  917. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  918. callVerifyUpload = YES;
  919. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  920. }
  921. if (callVerifyDownload && callVerifyUpload) {
  922. NSLog(@"[LOG] Stop timer verify session");
  923. [self.timerVerifySessionInProgress invalidate];
  924. }
  925. }
  926. }
  927. // Notification change session
  928. - (void)sessionChanged:(NSNotification *)notification
  929. {
  930. NSURLSession *session;
  931. CCMetadata *metadata;
  932. NSURLSessionTask *task;
  933. for (id object in notification.object) {
  934. if ([object isKindOfClass:[NSURLSession class]])
  935. session = object;
  936. if ([object isKindOfClass:[CCMetadata class]])
  937. metadata = object;
  938. if ([object isKindOfClass:[NSURLSessionTask class]])
  939. task = object;
  940. }
  941. /*
  942. Task
  943. */
  944. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  945. app.sessionDateLastDownloadTasks = [NSDate date];
  946. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  947. app.sessionDateLastUploadTasks = [NSDate date];
  948. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  949. dispatch_async(dispatch_get_main_queue(), ^{
  950. [self changeTask:metadata];
  951. });
  952. /*
  953. Session
  954. */
  955. if (session) {
  956. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  957. unsigned long numDownload = [downloadTasks count];
  958. unsigned long numUpload = [uploadTasks count];
  959. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  960. }];
  961. }
  962. }
  963. - (void)changeTask:(CCMetadata *)metadata
  964. {
  965. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  966. // sessionTaskIdentifier on Stop
  967. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  968. }
  969. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  970. // V 1.8 if upload_session_wwan change in upload_session
  971. if ([metadata.session isEqualToString:upload_session_wwan])
  972. metadata.session = upload_session;
  973. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  974. }
  975. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  976. BOOL downloadData = NO, downloadPlist = NO;
  977. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  978. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  979. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  980. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  981. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  982. });
  983. }
  984. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  985. // remove the file
  986. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  987. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  988. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  989. }
  990. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  991. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  992. }
  993. // remove ChangeTask (fileID) from the list
  994. [_listChangeTask removeObjectForKey:metadata.fileID];
  995. // delete progress
  996. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  997. // Detail
  998. if (_activeDetail)
  999. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  1000. // Refresh
  1001. if (_activeMain && [_listChangeTask count] == 0)
  1002. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  1003. }
  1004. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  1005. {
  1006. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  1007. // Update icon badge number
  1008. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1009. [self updateApplicationIconBadgeNumber];
  1010. });
  1011. }
  1012. #pragma --------------------------------------------------------------------------------------------
  1013. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1014. #pragma --------------------------------------------------------------------------------------------
  1015. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1016. {
  1017. return YES;
  1018. }
  1019. // Method called from iOS system to send a file from other app.
  1020. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1021. {
  1022. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1023. NSLog(@"[LOG] the path is: %@", url.path);
  1024. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1025. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1026. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  1027. if (self.activeAccount && [passcode length]) {
  1028. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1029. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1030. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1031. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1032. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1033. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1034. });
  1035. }
  1036. // remove from InBox
  1037. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1038. return YES;
  1039. }
  1040. #pragma --------------------------------------------------------------------------------------------
  1041. #pragma mark ===== UPGRADE =====
  1042. #pragma --------------------------------------------------------------------------------------------
  1043. - (void)upgrade
  1044. {
  1045. #ifdef DEBUG
  1046. // [CCCoreData flushTableGPS];
  1047. // [CCCoreData setGeoInformationLocalNull];
  1048. #endif
  1049. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1050. /* ---------------------- UPGRADE VERSION ----------------------- */
  1051. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1052. [CCCoreData flushTableDirectoryAccount:nil];
  1053. [CCCoreData flushTableLocalFileAccount:nil];
  1054. [CCCoreData flushTableMetadataAccount:nil];
  1055. }
  1056. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1057. [CCCoreData flushTableGPS];
  1058. [CCCoreData setGeoInformationLocalNull];
  1059. }
  1060. if (([actualVersion compare:@"2.17" options:NSNumericSearch] == NSOrderedAscending)) {
  1061. [CCCoreData clearAllDateReadDirectory];
  1062. [CCCoreData flushTableMetadataAccount:nil];
  1063. [CCCoreData localTableCopyFavoriteToOffline];
  1064. [CCCoreData directoryTableCopySynchronizedToOffline];
  1065. }
  1066. }
  1067. @end