AppDelegate.m 70 KB

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