AppDelegate.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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. #import "JDStatusBarNotification.h"
  39. #ifdef CUSTOM_BUILD
  40. #import "CustomSwift.h"
  41. #else
  42. #import "Nextcloud-Swift.h"
  43. #endif
  44. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  45. {
  46. }
  47. @end
  48. @implementation AppDelegate
  49. + (void)initialize
  50. {
  51. [iRate sharedInstance].daysUntilPrompt = 10;
  52. [iRate sharedInstance].usesUntilPrompt = 10;
  53. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  54. //enable preview mode
  55. //[iRate sharedInstance].previewMode = YES;
  56. }
  57. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  58. {
  59. // Brand
  60. if (k_option_use_firebase) {
  61. /*
  62. In order for this to work, proper GoogleService-Info.plist must be included
  63. */
  64. @try {
  65. [FIRApp configure];
  66. } @catch (NSException *exception) {
  67. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  68. }
  69. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  70. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  71. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  72. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  73. } else {
  74. // iOS 10 or later
  75. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  76. // For iOS 10 display notification (sent via APNS)
  77. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  78. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  79. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  80. }];
  81. // For iOS 10 data message (sent via FCM)
  82. [FIRMessaging messaging].remoteMessageDelegate = self;
  83. #endif
  84. }
  85. }
  86. NSString *dir;
  87. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:k_capabilitiesGroups];
  88. NSLog(@"[LOG] Start program group -----------------");
  89. NSLog(@"%@", dirGroup);
  90. NSLog(@"[LOG] Start program application -----------");
  91. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  92. NSLog(@"[LOG] -------------------------------------");
  93. // create Directory local => Documents
  94. dir = [CCUtility getDirectoryLocal];
  95. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  96. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  97. // create Directory audio => Library, Application Support, audio
  98. dir = [CCUtility getDirectoryAudio];
  99. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  100. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  101. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  102. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  103. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  104. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  105. // create dir Database Nextcloud
  106. dir = [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path];
  107. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  108. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  109. //[CCCoreData verifyVersionCoreData];
  110. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  111. #ifdef DEBUG
  112. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  113. #else
  114. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  115. #endif
  116. // Verify upgrade
  117. [self upgrade];
  118. // Set account, if no exists clear all
  119. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  120. if (recordAccount == nil) {
  121. // remove all the keys Chain
  122. [CCUtility deleteAllChainStore];
  123. // remove all the App group key
  124. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  125. } else {
  126. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password];
  127. }
  128. // Operation Queue OC Networking
  129. _netQueue = [[NSOperationQueue alloc] init];
  130. _netQueue.name = k_queue;
  131. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  132. _netQueueDownload = [[NSOperationQueue alloc] init];
  133. _netQueueDownload.name = k_download_queue;
  134. _netQueueDownload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  135. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  136. _netQueueDownloadWWan.name = k_download_queuewwan;
  137. _netQueueDownloadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  138. _netQueueUpload = [[NSOperationQueue alloc] init];
  139. _netQueueUpload.name = k_upload_queue;
  140. _netQueueUpload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  141. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  142. _netQueueUploadWWan.name = k_upload_queuewwan;
  143. _netQueueUploadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  144. // Check new Asset Photos/Video in progress
  145. _automaticCheckAssetInProgress = NO;
  146. _automaticUploadInProgress = NO;
  147. // Add notification change session
  148. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  149. // Initialization Share
  150. self.sharesID = [NSMutableDictionary new];
  151. self.sharesLink = [NSMutableDictionary new];
  152. self.sharesUserAndGroup = [NSMutableDictionary new];
  153. // Initialization Notification
  154. self.listOfNotifications = [NSMutableArray new];
  155. // Verify Session in progress and Init date task
  156. self.sessionDateLastDownloadTasks = [NSDate date];
  157. self.sessionDateLastUploadTasks = [NSDate date];
  158. // Background Fetch
  159. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  160. // Initialization List
  161. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  162. self.listChangeTask = [[NSMutableDictionary alloc] init];
  163. self.listMainVC = [[NSMutableDictionary alloc] init];
  164. // Player audio
  165. self.player = [LMMediaPlayerView sharedPlayerView];
  166. self.player.delegate = self;
  167. // ico Image Cache
  168. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  169. // setting Reachable in back
  170. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  171. self.reachability = [Reachability reachabilityForInternetConnection];
  172. self.lastReachability = [self.reachability isReachable];
  173. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  174. [self.reachability startNotifier];
  175. });
  176. //AV Session
  177. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  178. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  179. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  180. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  181. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  182. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  183. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  184. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  185. [app aspectNavigationControllerBar:navigationController.navigationBar encrypted:NO online:YES hidden:NO];
  186. // Settings TabBar
  187. [self createTabBarController];
  188. // passcode
  189. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  190. dispatch_async(dispatch_get_main_queue(), ^{
  191. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  192. });
  193. // Quick Actions
  194. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  195. [self configDynamicShortcutItems];
  196. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  197. if (shortcutItem)
  198. [self handleShortCutItem:shortcutItem];
  199. }
  200. // Start Timer
  201. self.timerProcess = [NSTimer scheduledTimerWithTimeInterval:k_timerProcess target:self selector:@selector(process) userInfo:nil repeats:YES];
  202. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:k_timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  203. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  204. // Registration Push Notification
  205. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  206. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  207. [application registerUserNotificationSettings:notificationSettings];
  208. // Fabric
  209. [Fabric with:@[[Crashlytics class]]];
  210. return YES;
  211. }
  212. //
  213. // L' applicazione si dimetterà dallo stato di attivo
  214. //
  215. - (void)applicationWillResignActive:(UIApplication *)application
  216. {
  217. [_activeMain closeAllMenu];
  218. [self updateApplicationIconBadgeNumber];
  219. }
  220. //
  221. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  222. //
  223. - (void)applicationWillEnterForeground:(UIApplication *)application
  224. {
  225. // facciamo partire il timer per il controllo delle sessioni e dei Lock
  226. [self.timerVerifySessionInProgress invalidate];
  227. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:k_timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  228. // refresh active Main
  229. if (_activeMain)
  230. [_activeMain reloadDatasource];
  231. // Initializations
  232. [self applicationInitialized];
  233. }
  234. //
  235. // L' applicazione è entrata nello sfondo
  236. //
  237. - (void)applicationDidEnterBackground:(UIApplication *)application
  238. {
  239. NSLog(@"[LOG] Enter in Background");
  240. [[CCQuickActions quickActionsManager] closeAll];
  241. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  242. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  243. __block UIBackgroundTaskIdentifier background_task;
  244. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  245. //Clean up code. Tell the system that we are done.
  246. [application endBackgroundTask: background_task];
  247. background_task = UIBackgroundTaskInvalid;
  248. }];
  249. }
  250. }
  251. //
  252. // L'applicazione terminerà
  253. //
  254. - (void)applicationWillTerminate:(UIApplication *)application
  255. {
  256. [MagicalRecord cleanUp];
  257. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  258. }
  259. //
  260. // Application Initialized
  261. //
  262. - (void)applicationInitialized
  263. {
  264. // Execute : now
  265. NSLog(@"[LOG] Update Folder Photo");
  266. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:self.activeAccount activeUrl:self.activeUrl];
  267. if ([folderCameraUpload length] > 0)
  268. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:self.activeAccount] selector:selectorReadFolder];
  269. // Execute : after 0.5 sec.
  270. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  271. NSLog(@"[LOG] Request Server Capabilities");
  272. if (_activeMain)
  273. [_activeMain requestServerCapabilities];
  274. NSLog(@"[LOG] Initialize Camera Upload");
  275. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  276. NSLog(@"[LOG] Listning Favorites");
  277. [[CCSynchronize sharedSynchronize] readListingFavorites];
  278. });
  279. // Initialize Camera Upload
  280. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  281. }
  282. #pragma --------------------------------------------------------------------------------------------
  283. #pragma mark ===== Process k_timerProcess seconds =====
  284. #pragma --------------------------------------------------------------------------------------------
  285. - (void)process
  286. {
  287. // BACKGROND & FOREGROUND
  288. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  289. // ONLY BACKGROUND
  290. } else {
  291. // ONLY FOREFROUND
  292. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  293. }
  294. }
  295. #pragma --------------------------------------------------------------------------------------------
  296. #pragma mark ===== Setting Active Account =====
  297. #pragma --------------------------------------------------------------------------------------------
  298. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword
  299. {
  300. self.activeAccount = activeAccount;
  301. self.activeUrl = activeUrl;
  302. self.activeUser = activeUser;
  303. self.activePassword = activePassword;
  304. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  305. }
  306. #pragma --------------------------------------------------------------------------------------------
  307. #pragma mark ===== Push Notification =====
  308. #pragma --------------------------------------------------------------------------------------------
  309. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  310. {
  311. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  312. }
  313. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  314. {
  315. [application registerForRemoteNotifications];
  316. }
  317. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  318. {
  319. // test
  320. if (self.activeAccount.length == 0)
  321. return;
  322. // FIREBASE registered token
  323. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  324. NSString *pushToken = [[FIRInstanceID instanceID] token];
  325. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  326. NSString *pushTokenHash = [[CCCrypto sharedManager] createSHA512:pushToken];
  327. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  328. #ifdef DEBUG
  329. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  330. #else
  331. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  332. #endif
  333. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  334. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  335. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  336. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  337. metadataNet.action = actionSubscribingNextcloudServer;
  338. metadataNet.options = options;
  339. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  340. }
  341. }
  342. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  343. {
  344. NSLog(@"[LOG] Error register remote notification %@", error);
  345. }
  346. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  347. UIApplicationState state = [application applicationState];
  348. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  349. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  350. } else {
  351. NSLog(@"[LOG] Receive Notification on Active state");
  352. }
  353. // If you are receiving a notification message while your app is in the background,
  354. // this callback will not be fired till the user taps on the notification launching the application.
  355. // TODO: Handle data of notification
  356. // Print message ID.
  357. //if (userInfo[kGCMMessageIDKey]) {
  358. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  359. //}
  360. // Print full message.
  361. NSLog(@"[LOG] %@", userInfo);
  362. }
  363. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  364. {
  365. UIApplicationState state = [application applicationState];
  366. // Print message ID.
  367. //if (userInfo[kGCMMessageIDKey]) {
  368. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  369. //}
  370. // Print full message.
  371. NSLog(@"[LOG] %@", userInfo);
  372. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  373. } else if (state == UIApplicationStateInactive) {
  374. // user tapped notification
  375. completionHandler(UIBackgroundFetchResultNewData);
  376. } else {
  377. // app is active
  378. completionHandler(UIBackgroundFetchResultNoData);
  379. }
  380. }
  381. #pragma FIREBASE
  382. - (void)tokenRefreshNotification:(NSNotification *)notification {
  383. // Note that this callback will be fired everytime a new token is generated, including the first
  384. // time. So if you need to retrieve the token as soon as it is available this is where that
  385. // should be done.
  386. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  387. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  388. // Connect to FCM since connection may have failed when attempted before having a token.
  389. [self connectToFcm];
  390. // TODO: If necessary send token to application server.
  391. }
  392. - (void)connectToFcm {
  393. // Won't connect since there is no token
  394. if (![[FIRInstanceID instanceID] token]) {
  395. return;
  396. }
  397. // Disconnect previous FCM connection if it exists.
  398. [[FIRMessaging messaging] disconnect];
  399. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  400. if (error != nil) {
  401. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  402. } else {
  403. NSLog(@"[LOG] Connected to FCM.");
  404. }
  405. }];
  406. }
  407. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  408. // Receive data message on iOS 10 devices while app is in the foreground.
  409. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  410. // Print full message
  411. NSLog(@"[LOG] %@", remoteMessage.appData);
  412. }
  413. #endif
  414. #pragma --------------------------------------------------------------------------------------------
  415. #pragma mark ===== Quick Actions - ShotcutItem =====
  416. #pragma --------------------------------------------------------------------------------------------
  417. - (void)configDynamicShortcutItems
  418. {
  419. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  420. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  421. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUpload];
  422. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  423. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  424. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  425. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  426. if (app.isCryptoCloudMode) {
  427. // add the array to our app
  428. [UIApplication sharedApplication].shortcutItems = @[shortcutUploadEncrypted, shortcutUpload, shortcutPhotos];
  429. } else {
  430. // add the array to our app
  431. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  432. }
  433. }
  434. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  435. {
  436. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  437. completionHandler(handledShortCutItem);
  438. }
  439. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  440. {
  441. BOOL handled = NO;
  442. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  443. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  444. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  445. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  446. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  447. dispatch_async(dispatch_get_main_queue(), ^{
  448. if (_activeMain) {
  449. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  450. if (splitViewController.isCollapsed) {
  451. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  452. for (UINavigationController *nvc in tbc.viewControllers) {
  453. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  454. [nvc popToRootViewControllerAnimated:NO];
  455. }
  456. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  457. } else {
  458. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  459. [nvcDetail popToRootViewControllerAnimated:NO];
  460. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  461. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  462. }
  463. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  464. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  465. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  466. });
  467. }
  468. });
  469. handled = YES;
  470. }
  471. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  472. dispatch_async(dispatch_get_main_queue(), ^{
  473. if (_activeMain) {
  474. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  475. if (splitViewController.isCollapsed) {
  476. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  477. for (UINavigationController *nvc in tbc.viewControllers) {
  478. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  479. [nvc popToRootViewControllerAnimated:NO];
  480. }
  481. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  482. } else {
  483. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  484. [nvcDetail popToRootViewControllerAnimated:NO];
  485. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  486. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  487. }
  488. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  489. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  490. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  491. });
  492. }
  493. });
  494. handled = YES;
  495. }
  496. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  497. dispatch_async(dispatch_get_main_queue(), ^{
  498. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  499. if (splitViewController.isCollapsed) {
  500. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  501. for (UINavigationController *nvc in tbc.viewControllers) {
  502. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  503. [nvc popToRootViewControllerAnimated:NO];
  504. }
  505. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  506. } else {
  507. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  508. [nvcDetail popToRootViewControllerAnimated:NO];
  509. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  510. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  511. }
  512. });
  513. handled = YES;
  514. }
  515. return handled;
  516. }
  517. #pragma --------------------------------------------------------------------------------------------
  518. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  519. #pragma --------------------------------------------------------------------------------------------
  520. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  521. {
  522. static NSInteger errorCodePrev = 0;
  523. dispatch_async(dispatch_get_main_queue(), ^{
  524. if (visible) {
  525. if (errorcode == kCFURLErrorNotConnectedToInternet || errorcode == k_CCErrorNetworkNowAvailable) {
  526. if (errorCodePrev != errorcode)
  527. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  528. errorCodePrev = errorcode;
  529. } else {
  530. [TWMessageBarManager sharedInstance].styleSheet = self;
  531. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]] description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  532. }
  533. } else {
  534. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  535. }
  536. });
  537. }
  538. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  539. {
  540. UIColor *backgroundColor = nil;
  541. switch (type)
  542. {
  543. case TWMessageBarMessageTypeError:
  544. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  545. break;
  546. case TWMessageBarMessageTypeSuccess:
  547. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  548. break;
  549. case TWMessageBarMessageTypeInfo:
  550. backgroundColor = [NCBrandColor sharedInstance].brand;
  551. break;
  552. default:
  553. break;
  554. }
  555. return backgroundColor;
  556. }
  557. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  558. {
  559. UIColor *strokeColor = nil;
  560. switch (type)
  561. {
  562. case TWMessageBarMessageTypeError:
  563. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  564. break;
  565. case TWMessageBarMessageTypeSuccess:
  566. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  567. break;
  568. case TWMessageBarMessageTypeInfo:
  569. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  570. break;
  571. default:
  572. break;
  573. }
  574. return strokeColor;
  575. }
  576. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  577. {
  578. UIImage *iconImage = nil;
  579. switch (type)
  580. {
  581. case TWMessageBarMessageTypeError:
  582. iconImage = [UIImage imageNamed:@"icon-error.png"];
  583. break;
  584. case TWMessageBarMessageTypeSuccess:
  585. iconImage = [UIImage imageNamed:@"icon-success.png"];
  586. break;
  587. case TWMessageBarMessageTypeInfo:
  588. iconImage = [UIImage imageNamed:@"icon-info.png"];
  589. break;
  590. default:
  591. break;
  592. }
  593. return iconImage;
  594. }
  595. #pragma --------------------------------------------------------------------------------------------
  596. #pragma mark ===== TabBarController =====
  597. #pragma --------------------------------------------------------------------------------------------
  598. - (void)createTabBarController
  599. {
  600. UITabBarItem *item;
  601. NSLayoutConstraint *constraint;
  602. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  603. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  604. [app aspectTabBar:tabBarController.tabBar hidden:NO];
  605. // File
  606. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  607. [item setTitle:NSLocalizedString(@"_home_", nil)];
  608. item.image = [UIImage imageNamed:image_tabBarFiles];
  609. item.selectedImage = [UIImage imageNamed:image_tabBarFiles];
  610. // Favorites
  611. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexOffline];
  612. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  613. item.image = [UIImage imageNamed:image_tabBarFavorite];
  614. item.selectedImage = [UIImage imageNamed:image_tabBarFavorite];
  615. // Hide (PLUS)
  616. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexHide];
  617. item.title = nil;
  618. item.image = nil;
  619. item.enabled = false;
  620. // Photos
  621. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  622. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  623. item.image = [UIImage imageNamed:image_tabBarPhotos];
  624. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  625. // More
  626. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  627. [item setTitle:NSLocalizedString(@"_more_", nil)];
  628. item.image = [UIImage imageNamed:image_tabBarMore];
  629. item.selectedImage = [UIImage imageNamed:image_tabBarMore];
  630. // Plus Button
  631. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  632. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  633. button.tag = 99;
  634. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  635. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  636. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  637. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  638. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  639. [tabBarController.view addSubview:button];
  640. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  641. [tabBarController.view addConstraint:constraint];
  642. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  643. [tabBarController.view addConstraint:constraint];
  644. }
  645. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav encrypted:(BOOL)encrypted online:(BOOL)online hidden:(BOOL)hidden
  646. {
  647. nav.translucent = NO;
  648. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  649. nav.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  650. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  651. if (encrypted)
  652. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].cryptocloud}];
  653. if (!online)
  654. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  655. nav.hidden = hidden;
  656. [nav setAlpha:1];
  657. }
  658. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  659. {
  660. tab.translucent = NO;
  661. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  662. tab.tintColor = [NCBrandColor sharedInstance].brand;
  663. tab.hidden = hidden;
  664. [tab setAlpha:1];
  665. }
  666. - (void)plusButtonVisibile:(BOOL)visible
  667. {
  668. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  669. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  670. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  671. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  672. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  673. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  674. if (buttonPlus) {
  675. if (visible) {
  676. buttonPlus.hidden = false;
  677. } else {
  678. buttonPlus.hidden = true;
  679. }
  680. }
  681. }
  682. - (void)handleTouchTabbarCenter:(id)sender
  683. {
  684. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  685. if ([CCUtility getCreateMenuEncrypted])
  686. [menuAdd createMenuEncryptedWithView:self.window.rootViewController.view];
  687. else
  688. [menuAdd createMenuPlainWithView:self.window.rootViewController.view];
  689. }
  690. - (void)updateApplicationIconBadgeNumber
  691. {
  692. // Core Data
  693. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  694. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  695. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  696. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  697. // netQueueDownload
  698. for (NSOperation *operation in [app.netQueueDownload operations])
  699. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  700. // netQueueDownloadWWan
  701. for (NSOperation *operation in [app.netQueueDownloadWWan operations])
  702. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  703. // netQueueUpload
  704. for (NSOperation *operation in [app.netQueueUpload operations])
  705. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  706. // netQueueUploadWWan
  707. for (NSOperation *operation in [app.netQueueUploadWWan operations])
  708. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  709. // Total
  710. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [[NCManageDatabase sharedInstance] countAutomaticUploadForAccount:app.activeAccount selector:nil];
  711. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  712. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  713. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  714. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  715. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  716. if (total > 0)
  717. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  718. else
  719. [tbItem setBadgeValue:nil];
  720. }
  721. }
  722. #pragma --------------------------------------------------------------------------------------------
  723. #pragma mark ===== Theming Color =====
  724. #pragma --------------------------------------------------------------------------------------------
  725. - (void)settingThemingColorBrand
  726. {
  727. if (self.activeAccount.length > 0) {
  728. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesForAccount:self.activeAccount];
  729. if (k_option_use_themingColor && capabilities.themingColor.length > 0) {
  730. [NCBrandColor sharedInstance].brand = [CCGraphics colorFromHexString:capabilities.themingColor];
  731. } else {
  732. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  733. }
  734. } else {
  735. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  736. }
  737. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTheming" object:nil];
  738. }
  739. - (void)changeTheming:(UIViewController *)vc
  740. {
  741. UIColor *color = [NCBrandColor sharedInstance].brand;
  742. // Change Navigation & TabBar color
  743. vc.navigationController.navigationBar.barTintColor = color;
  744. vc.tabBarController.tabBar.tintColor = color;
  745. // Change button Plus
  746. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  747. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  748. UIButton *button = [tabBarController.view viewWithTag:99];
  749. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  750. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  751. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  752. // Tint Color GLOBAL WINDOW
  753. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  754. }
  755. #pragma --------------------------------------------------------------------------------------------
  756. #pragma mark ===== Media Player Control =====
  757. #pragma --------------------------------------------------------------------------------------------
  758. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  759. {
  760. switch (event.subtype) {
  761. case UIEventSubtypeRemoteControlPlay:
  762. if (self.player.mediaPlayer) {
  763. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  764. if (self.player.mediaPlayer.nowPlayingItem.title)
  765. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  766. if (self.player.mediaPlayer.nowPlayingItem.artist)
  767. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  768. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  769. [self.player.mediaPlayer play];
  770. }
  771. break;
  772. case UIEventSubtypeRemoteControlPause:
  773. if (self.player.mediaPlayer) {
  774. [self.player.mediaPlayer pause];
  775. }
  776. break;
  777. case UIEventSubtypeRemoteControlNextTrack:
  778. // handle it break;
  779. case UIEventSubtypeRemoteControlPreviousTrack:
  780. // handle it break;
  781. default:
  782. break;
  783. }
  784. }
  785. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  786. {
  787. return YES;
  788. }
  789. #pragma --------------------------------------------------------------------------------------------
  790. #pragma mark ===== Manager Passcode =====
  791. #pragma --------------------------------------------------------------------------------------------
  792. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  793. {
  794. // ServerUrl active
  795. NSString *serverUrl = self.activeMain.serverUrl;
  796. // fermiamo la data della sessione
  797. self.sessionePasscodeLock = nil;
  798. // se il block code è a zero esci con NON attivare la richiesta password
  799. if ([[CCUtility getBlockCode] length] == 0) return NO;
  800. // se non c'è attivo un account esci con NON attivare la richiesta password
  801. if ([self.activeAccount length] == 0) return NO;
  802. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  803. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:serverUrl activeAccount:self.activeAccount]) return NO;
  804. return YES;
  805. }
  806. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  807. {
  808. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  809. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  810. viewController.delegate = self;
  811. viewController.title = k_brand;
  812. viewController.fromType = CCBKPasscodeFromLockScreen;
  813. viewController.inputViewTitlePassword = YES;
  814. if ([CCUtility getSimplyBlockCode]) {
  815. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  816. viewController.passcodeInputView.maximumLength = 6;
  817. } else {
  818. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  819. viewController.passcodeInputView.maximumLength = 64;
  820. }
  821. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  822. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  823. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  824. return navigationController;
  825. }
  826. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  827. {
  828. [aViewController dismissViewControllerAnimated:YES completion:nil];
  829. // is a lock screen
  830. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  831. [aViewController dismissViewControllerAnimated:YES completion:nil];
  832. // start session Passcode Lock
  833. NSString *serverUrl = self.activeMain.serverUrl;
  834. if ([CCCoreData isBlockZone:serverUrl activeAccount:self.activeAccount])
  835. self.sessionePasscodeLock = [NSDate date];
  836. }
  837. }
  838. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  839. {
  840. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  841. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  842. //self.lockUntilDate = nil;
  843. //self.failedAttempts = 0;
  844. aResultHandler(YES);
  845. } else aResultHandler(NO);
  846. } else aResultHandler(YES);
  847. }
  848. #pragma --------------------------------------------------------------------------------------------
  849. #pragma mark ===== reachabilityChanged =====
  850. #pragma --------------------------------------------------------------------------------------------
  851. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  852. {
  853. if ([self.reachability isReachable]) {
  854. if (self.lastReachability == NO) {
  855. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorNetworkNowAvailable];
  856. if (_activeMain)
  857. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  858. }
  859. NSLog(@"[LOG] Reachability Changed: Reachable");
  860. self.lastReachability = YES;
  861. } else {
  862. if (self.lastReachability == YES) {
  863. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  864. }
  865. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  866. self.lastReachability = NO;
  867. }
  868. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  869. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  870. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleMain" object:nil];
  871. }
  872. #pragma --------------------------------------------------------------------------------------------
  873. #pragma mark ===== Fetch =====
  874. #pragma --------------------------------------------------------------------------------------------
  875. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  876. {
  877. NSLog(@"[LOG] Start Fetch");
  878. // Verify new photo
  879. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  880. // after 20 sec verify Re
  881. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  882. [[CCNetworking sharedNetworking] automaticDownloadInError];
  883. [[CCNetworking sharedNetworking] automaticUploadInError];
  884. NSLog(@"[LOG] End Fetch 20 sec.");
  885. });
  886. // after 25 sec
  887. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  888. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  889. if ([records count] > 0) {
  890. completionHandler(UIBackgroundFetchResultNewData);
  891. } else {
  892. completionHandler(UIBackgroundFetchResultNoData);
  893. }
  894. NSLog(@"[LOG] End Fetch 25 sec.");
  895. });
  896. }
  897. #pragma --------------------------------------------------------------------------------------------
  898. #pragma mark ===== Operation Networking & Session =====
  899. #pragma --------------------------------------------------------------------------------------------
  900. //
  901. // Method called by the system when all the background task has end
  902. //
  903. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  904. {
  905. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  906. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  907. [[CCNetworking sharedNetworking] automaticDownloadInError];
  908. [[CCNetworking sharedNetworking] automaticUploadInError];
  909. self.backgroundSessionCompletionHandler = completionHandler;
  910. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  911. self.backgroundSessionCompletionHandler = nil;
  912. completionHandler();
  913. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  914. });
  915. }
  916. - (void)cancelAllOperations
  917. {
  918. [_netQueue cancelAllOperations];
  919. [_netQueueDownload cancelAllOperations];
  920. [_netQueueDownloadWWan cancelAllOperations];
  921. [_netQueueUpload cancelAllOperations];
  922. [_netQueueUploadWWan cancelAllOperations];
  923. }
  924. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  925. {
  926. id operation;
  927. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl isCryptoCloudMode:_isCryptoCloudMode];
  928. [operation setQueuePriority:metadataNet.priority];
  929. [netQueue addOperation:operation];
  930. }
  931. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  932. {
  933. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  934. for (OCnetworking *operation in [self.netQueueDownload operations])
  935. if ([operation.metadataNet.selector isEqualToString:selector])
  936. [metadatasNet addObject:[operation.metadataNet copy]];
  937. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  938. if ([operation.metadataNet.selector isEqualToString:selector])
  939. [metadatasNet addObject:[operation.metadataNet copy]];
  940. return metadatasNet;
  941. }
  942. - (void)loadAutomaticUpload
  943. {
  944. CCMetadataNet *metadataNet;
  945. // Is loading new Asset or this ?
  946. if (_automaticCheckAssetInProgress || _automaticUploadInProgress)
  947. return;
  948. // START Automatic Upload in progress
  949. _automaticUploadInProgress = YES;
  950. NSArray *uploadInQueue = [CCCoreData getTableMetadataUploadAccount:app.activeAccount];
  951. NSArray *recordAutomaticUploadInLock = [[NCManageDatabase sharedInstance] getAllLockAutomaticUploadForAccount:_activeAccount];
  952. for (tableAutomaticUpload *tableAutomaticUpload in recordAutomaticUploadInLock) {
  953. BOOL recordFound = NO;
  954. for (CCMetadataNet *metadataNet in uploadInQueue) {
  955. if (metadataNet.assetLocalIdentifier == tableAutomaticUpload.assetLocalIdentifier)
  956. recordFound = YES;
  957. }
  958. if (!recordFound)
  959. [[NCManageDatabase sharedInstance] unlockAutomaticUploadForAccount:_activeAccount assetLocalIdentifier:tableAutomaticUpload.assetLocalIdentifier];
  960. }
  961. // ------------------------- <selectorUploadAutomatic> -------------------------
  962. metadataNet = [[NCManageDatabase sharedInstance] getAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic];
  963. while (metadataNet) {
  964. [[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];
  965. metadataNet = [[NCManageDatabase sharedInstance] getAutomaticUploadForAccount: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 = [[NCManageDatabase sharedInstance] getAutomaticUploadForAccount: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. [[NCManageDatabase sharedInstance] 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. [[NCManageDatabase sharedInstance] deleteAutomaticUploadForAccount:_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. [[NCManageDatabase sharedInstance] 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. [[NCManageDatabase sharedInstance] 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 ===== UPGRADE =====
  1142. #pragma --------------------------------------------------------------------------------------------
  1143. - (void)upgrade
  1144. {
  1145. #ifdef DEBUG
  1146. #endif
  1147. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1148. /* ---------------------- UPGRADE VERSION ----------------------- */
  1149. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1150. [CCCoreData flushTableDirectoryAccount:nil];
  1151. [CCCoreData flushTableLocalFileAccount:nil];
  1152. [CCCoreData flushTableMetadataAccount:nil];
  1153. }
  1154. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1155. [CCCoreData setGeoInformationLocalNull];
  1156. }
  1157. if (([actualVersion compare:@"2.17" options:NSNumericSearch] == NSOrderedAscending)) {
  1158. [CCCoreData clearAllDateReadDirectory];
  1159. [CCCoreData flushTableMetadataAccount:nil];
  1160. }
  1161. if (([actualVersion compare:@"2.17.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1162. }
  1163. if (([actualVersion compare:@"2.17.2" options:NSNumericSearch] == NSOrderedAscending)) {
  1164. }
  1165. if (([actualVersion compare:@"2.17.3" options:NSNumericSearch] == NSOrderedAscending)) {
  1166. }
  1167. }
  1168. @end