AppDelegate.m 70 KB

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