AppDelegate.m 68 KB

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