AppDelegate.m 68 KB

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