AppDelegate.m 69 KB

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