AppDelegate.m 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCNetworking.h"
  25. #import "CCGraphics.h"
  26. #import "CCSynchronize.h"
  27. #import "CCMain.h"
  28. #import "NCBridgeSwift.h"
  29. #import "NCAutoUpload.h"
  30. #import "NCPushNotificationEncryption.h"
  31. #import <QuartzCore/QuartzCore.h>
  32. @class NCViewerRichdocument;
  33. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  34. @end
  35. @implementation AppDelegate
  36. + (void)initialize
  37. {
  38. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  39. }
  40. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  41. {
  42. [CCUtility createDirectoryStandard];
  43. [CCUtility emptyTemporaryDirectory];
  44. // Networking
  45. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking sharedInstance]];
  46. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups];
  47. // Verify upgrade
  48. if ([self upgrade]) {
  49. // Set account, if no exists clear all
  50. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  51. if (tableAccount == nil) {
  52. // remove all the keys Chain
  53. [CCUtility deleteAllChainStore];
  54. // remove all the App group key
  55. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  56. } else {
  57. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  58. }
  59. }
  60. // UserDefaults
  61. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  62. // Background Fetch
  63. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  64. // Initialization List & Array
  65. self.listProgressMetadata = [NSMutableDictionary new];
  66. self.listMainVC = [NSMutableDictionary new];
  67. self.arrayDeleteMetadata = [NSMutableArray new];
  68. self.arrayMoveMetadata = [NSMutableArray new];
  69. self.arrayMoveServerUrlTo = [NSMutableArray new];
  70. self.arrayCopyMetadata = [NSMutableArray new];
  71. self.arrayCopyServerUrlTo = [NSMutableArray new];
  72. self.sessionPendingStatusInUpload = [NSMutableArray new];
  73. // Push Notification
  74. [application registerForRemoteNotifications];
  75. // Display notification (sent via APNS)
  76. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  77. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  78. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  79. }];
  80. // setting Reachable in back
  81. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  82. self.reachability = [Reachability reachabilityForInternetConnection];
  83. self.lastReachability = [self.reachability isReachable];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  85. [self.reachability startNotifier];
  86. });
  87. //AV Session
  88. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  89. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  90. // ProgressView Detail
  91. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  92. // Quick Actions
  93. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  94. [self configDynamicShortcutItems];
  95. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  96. if (shortcutItem)
  97. [self handleShortCutItem:shortcutItem];
  98. }
  99. // Start Timer
  100. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  101. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  102. [self startTimerErrorNetworking];
  103. // Store review
  104. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  105. NCStoreReview *review = [NCStoreReview new];
  106. [review incrementAppRuns];
  107. [review showStoreReview];
  108. }
  109. // Detect Dark mode
  110. if (@available(iOS 13.0, *)) {
  111. if ([CCUtility getDarkModeDetect]) {
  112. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  113. [CCUtility setDarkMode:YES];
  114. } else {
  115. [CCUtility setDarkMode:NO];
  116. }
  117. }
  118. }
  119. if ([NCBrandOptions sharedInstance].disable_intro) {
  120. [CCUtility setIntro:YES];
  121. if (self.activeAccount.length == 0) {
  122. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  123. }
  124. } else {
  125. if ([CCUtility getIntro] == NO) {
  126. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  127. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  128. self.window.rootViewController = navController;
  129. [self.window makeKeyAndVisible];
  130. }
  131. }
  132. // init home
  133. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  134. // Observer
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  136. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  138. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadedFile:) name:k_notificationCenter_uploadedFile object:nil];
  139. // Passcode
  140. dispatch_async(dispatch_get_main_queue(), ^{
  141. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  142. });
  143. return YES;
  144. }
  145. //
  146. // L' applicazione si dimetterà dallo stato di attivo
  147. //
  148. - (void)applicationWillResignActive:(UIApplication *)application
  149. {
  150. // Test Maintenance
  151. if (self.activeAccount.length == 0 || self.maintenanceMode)
  152. return;
  153. [self updateApplicationIconBadgeNumber];
  154. }
  155. //
  156. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  157. //
  158. - (void)applicationWillEnterForeground:(UIApplication *)application
  159. {
  160. // Test Maintenance
  161. if (self.activeAccount.length == 0 || self.maintenanceMode)
  162. return;
  163. NSLog(@"[LOG] Request Passcode");
  164. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  165. NSLog(@"[LOG] Request Service Server Nextcloud");
  166. [[NCService sharedInstance] startRequestServicesServer];
  167. NSLog(@"[LOG] Initialize Auto upload");
  168. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  169. NSLog(@"[LOG] Read active directory");
  170. [self.activeMain readFileReloadFolder];
  171. NSLog(@"[LOG] Required unsubscribing / subscribing");
  172. [self pushNotification];
  173. NSLog(@"[LOG] RichDocument");
  174. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  175. }
  176. //
  177. // L' applicazione entrerà in primo piano (attivo sempre)
  178. //
  179. - (void)applicationDidBecomeActive:(UIApplication *)application
  180. {
  181. // Test Maintenance
  182. if (self.activeAccount.length == 0 || self.maintenanceMode)
  183. return;
  184. // middelware ping
  185. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  186. NSLog(@"[LOG] Middleware Ping");
  187. [[NCService sharedInstance] middlewarePing];
  188. }
  189. // verify task (download/upload) lost
  190. [self verifyTaskLost];
  191. // verify delete Asset Local Identifiers in auto upload
  192. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:self.activeAccount sessionSelector:selectorUploadAutoUpload];
  193. // Brand
  194. #if defined(HC)
  195. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  196. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  197. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  198. vc.account = account;
  199. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  200. }
  201. #endif
  202. }
  203. //
  204. // L' applicazione è entrata nello sfondo
  205. //
  206. - (void)applicationDidEnterBackground:(UIApplication *)application
  207. {
  208. NSLog(@"[LOG] Enter in Background");
  209. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  210. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  211. /*
  212. __block UIBackgroundTaskIdentifier background_task;
  213. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  214. //Clean up code. Tell the system that we are done.
  215. [application endBackgroundTask: background_task];
  216. background_task = UIBackgroundTaskInvalid;
  217. }];
  218. */
  219. }
  220. //
  221. // L'applicazione terminerà
  222. //
  223. - (void)applicationWillTerminate:(UIApplication *)application
  224. {
  225. NSLog(@"[LOG] bye bye, Nextcloud !");
  226. }
  227. #pragma --------------------------------------------------------------------------------------------
  228. #pragma mark ===== Login / checkErrorNetworking =====
  229. #pragma --------------------------------------------------------------------------------------------
  230. - (void)checkErrorNetworking
  231. {
  232. // test
  233. if (self.activeAccount.length == 0 || self.maintenanceMode)
  234. return;
  235. // check unauthorized server (401)
  236. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  237. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  238. }
  239. // check certificate untrusted (-1202)
  240. if ([CCUtility getCertificateError:self.activeAccount]) {
  241. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  242. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  243. [[NCNetworking sharedInstance] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  244. [self startTimerErrorNetworking];
  245. }]];
  246. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  247. [self startTimerErrorNetworking];
  248. }]];
  249. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  250. // Stop timer error network
  251. [self.timerErrorNetworking invalidate];
  252. }];
  253. }
  254. }
  255. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  256. {
  257. // use appConfig [MDM]
  258. if ([NCBrandOptions sharedInstance].use_configuration) {
  259. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  260. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  261. [self showLoginViewController:self.appConfigView forContext:viewController];
  262. }
  263. return;
  264. }
  265. // only for personalized LoginWeb [customer]
  266. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  267. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  268. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  269. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  270. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  271. }
  272. return;
  273. }
  274. // normal login
  275. if (selector == k_intro_signup) {
  276. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  277. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  278. if (selector == k_intro_signup) {
  279. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  280. } else {
  281. self.activeLoginWeb.urlBase = self.activeUrl;
  282. }
  283. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  284. }
  285. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  286. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  287. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  288. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  289. } else if (openLoginWeb) {
  290. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  291. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  292. self.activeLoginWeb.urlBase = self.activeUrl;
  293. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  294. }
  295. } else {
  296. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  297. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  298. [self showLoginViewController:_activeLogin forContext:viewController];
  299. }
  300. }
  301. }
  302. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  303. {
  304. if (contextViewController == NULL) {
  305. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  306. navController.navigationBar.barStyle = UIBarStyleBlack;
  307. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  308. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  309. [navController.navigationBar setTranslucent:false];
  310. self.window.rootViewController = navController;
  311. [self.window makeKeyAndVisible];
  312. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  313. UINavigationController *navController = ((UINavigationController *)contextViewController);
  314. [navController pushViewController:viewController animated:true];
  315. } else {
  316. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  317. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  318. navController.navigationBar.barStyle = UIBarStyleBlack;
  319. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  320. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  321. [navController.navigationBar setTranslucent:false];
  322. [contextViewController presentViewController:navController animated:true completion:nil];
  323. }
  324. }
  325. - (void)startTimerErrorNetworking
  326. {
  327. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  328. }
  329. #pragma --------------------------------------------------------------------------------------------
  330. #pragma mark ===== Account & Communication =====
  331. #pragma --------------------------------------------------------------------------------------------
  332. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  333. {
  334. self.activeAccount = activeAccount;
  335. self.activeUrl = activeUrl;
  336. self.activeUser = activeUser;
  337. self.activeUserID = activeUserID;
  338. self.activePassword = activePassword;
  339. (void)[NCNetworkingNotificationCenter shared];
  340. [[NCCommunicationCommon shared] setupWithUser:activeUser userId:activeUserID password:activePassword url:activeUrl];
  341. [self settingSetupCommunicationCapabilities:activeAccount];
  342. }
  343. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  344. {
  345. [self unsubscribingNextcloudServerPushNotification:account url:self.activeUrl withSubscribing:false];
  346. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  347. /* DELETE ALL FILES LOCAL FS */
  348. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  349. for (tableLocalFile *result in results) {
  350. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  351. }
  352. // Clear database
  353. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  354. [CCUtility clearAllKeysEndToEnd:account];
  355. [CCUtility clearAllKeysPushNotification:account];
  356. [CCUtility setCertificateError:account error:false];
  357. [CCUtility setPassword:account password:nil];
  358. if (wipe) {
  359. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  360. if ([listAccount count] > 0) {
  361. NSString *newAccount = listAccount[0];
  362. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  363. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  364. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  365. } else {
  366. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  367. }
  368. }
  369. }
  370. - (void)settingSetupCommunicationCapabilities:(NSString *)account
  371. {
  372. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  373. if (serverVersionMajor > 0) {
  374. [[OCNetworking sharedManager].sharedOCCommunication setupNextcloudVersion: serverVersionMajor];
  375. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  376. }
  377. NSString *webDavRoot = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:account elements:NCElementsJSON.shared.capabilitiesWebDavRoot];
  378. if (webDavRoot != nil) {
  379. [[NCCommunicationCommon shared] setupWithWebDavRoot:webDavRoot];
  380. }
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== Push Notifications =====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)pushNotification
  386. {
  387. // test
  388. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  389. return;
  390. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  391. NSString *token = [CCUtility getPushNotificationToken:result.account];
  392. if (![token isEqualToString:self.pushKitToken]) {
  393. if (token != nil) {
  394. // unsubscribing + subscribing
  395. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  396. } else {
  397. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  398. }
  399. }
  400. }
  401. }
  402. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  403. {
  404. // test
  405. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  406. return;
  407. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  408. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  409. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  410. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  411. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:account url:url pushToken:self.pushKitToken Hash:pushTokenHash devicePublicKey:pushDevicePublicKey completion:^(NSString *accountCompletion, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  412. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  413. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  414. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  415. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  416. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  417. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  418. } else if (errorCode != 0) {
  419. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  420. } else {
  421. NSLog(@"[LOG] It has been changed user during networking process, error.");
  422. }
  423. }];
  424. }
  425. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  426. {
  427. // test
  428. if (self.activeAccount.length == 0 || self.maintenanceMode)
  429. return;
  430. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  431. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  432. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  433. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  434. if (errorCode == 0) {
  435. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  436. [CCUtility setPushNotificationPublicKey:account data:nil];
  437. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  438. [CCUtility setPushNotificationPrivateKey:account data:nil];
  439. [CCUtility setPushNotificationToken:account token:nil];
  440. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  441. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  442. if (self.pushKitToken != nil && subscribing) {
  443. [self subscribingNextcloudServerPushNotification:account url:url];
  444. }
  445. } else if (errorCode != 0) {
  446. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  447. } else {
  448. NSLog(@"[LOG] It has been changed user during networking process, error.");
  449. }
  450. }];
  451. }
  452. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  453. {
  454. //Called when a notification is delivered to a foreground app.
  455. completionHandler(UNNotificationPresentationOptionAlert);
  456. }
  457. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  458. {
  459. completionHandler();
  460. }
  461. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  462. {
  463. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  464. [self pushNotification];
  465. }
  466. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  467. {
  468. NSString *message = [userInfo objectForKey:@"subject"];
  469. if (message) {
  470. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  471. for (tableAccount *result in results) {
  472. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  473. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  474. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  475. if (decryptedMessage) {
  476. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  477. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  478. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  479. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  480. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  481. if (delete) {
  482. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  483. } else if (deleteAll) {
  484. [self cleanAllNotifications];
  485. }
  486. }
  487. }
  488. }
  489. }
  490. completionHandler(UIBackgroundFetchResultNoData);
  491. }
  492. - (void)cleanAllNotifications
  493. {
  494. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  495. }
  496. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  497. {
  498. // Check in pending notifications
  499. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  500. for (UNNotificationRequest *notificationRequest in requests) {
  501. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  502. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  503. if (decryptedMessage) {
  504. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  505. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  506. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  507. if (nid == notificationId) {
  508. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  509. }
  510. }
  511. }
  512. }];
  513. // Check in delivered notifications
  514. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  515. for (UNNotification *notification in notifications) {
  516. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  517. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  518. if (decryptedMessage) {
  519. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  520. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  521. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  522. if (nid == notificationId) {
  523. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  524. }
  525. }
  526. }
  527. }];
  528. }
  529. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  530. {
  531. const char *data = [deviceToken bytes];
  532. NSMutableString *token = [NSMutableString string];
  533. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  534. [token appendFormat:@"%02.2hhX", data[i]];
  535. }
  536. return [token copy];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ==== NotificationCenter ====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)deleteFile:(NSNotification *)notification
  542. {
  543. if (self.arrayDeleteMetadata.count > 0) {
  544. tableMetadata *metadata = self.arrayDeleteMetadata.firstObject;
  545. [self.arrayDeleteMetadata removeObjectAtIndex:0];
  546. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  547. if (account) {
  548. [[NCNetworking sharedInstance] deleteMetadata:metadata account:metadata.account user:account.user userID:account.userID password:[CCUtility getPassword:metadata.account] url:account.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  549. } else {
  550. [self deleteFile:[NSNotification new]];
  551. }
  552. }
  553. }
  554. - (void)moveFile:(NSNotification *)notification
  555. {
  556. if (self.arrayMoveMetadata.count > 0) {
  557. tableMetadata *metadata = self.arrayMoveMetadata.firstObject;
  558. NSString *serverUrlTo = self.arrayMoveServerUrlTo.firstObject;
  559. [self.arrayMoveMetadata removeObjectAtIndex:0];
  560. [self.arrayMoveServerUrlTo removeObjectAtIndex:0];
  561. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  562. if (account) {
  563. [[NCNetworking sharedInstance] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  564. } else {
  565. [self moveFile:[NSNotification new]];
  566. }
  567. }
  568. }
  569. - (void)copyFile:(NSNotification *)notification
  570. {
  571. if (self.arrayCopyMetadata.count > 0) {
  572. tableMetadata *metadata = self.arrayCopyMetadata.firstObject;
  573. NSString *serverUrlTo = self.arrayCopyServerUrlTo.firstObject;
  574. [self.arrayCopyMetadata removeObjectAtIndex:0];
  575. [self.arrayCopyServerUrlTo removeObjectAtIndex:0];
  576. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  577. if (account) {
  578. [[NCNetworking sharedInstance] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  579. } else {
  580. [self copyFile:[NSNotification new]];
  581. }
  582. }
  583. }
  584. - (void)uploadedFile:(NSNotification *)notification
  585. {
  586. NSDictionary *userInfo = notification.userInfo;
  587. tableMetadata *metadata = userInfo[@"metadata"];
  588. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  589. if (errorCode == 0) {
  590. // verify delete Asset Local Identifiers in auto upload
  591. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:metadata.account sessionSelector:selectorUploadAutoUpload];
  592. }
  593. }
  594. #pragma --------------------------------------------------------------------------------------------
  595. #pragma mark ===== Quick Actions - ShotcutItem =====
  596. #pragma --------------------------------------------------------------------------------------------
  597. - (void)configDynamicShortcutItems
  598. {
  599. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  600. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  601. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  602. // add the array to our app
  603. if (shortcutMedia)
  604. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  605. }
  606. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  607. {
  608. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  609. completionHandler(handledShortCutItem);
  610. }
  611. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  612. {
  613. BOOL handled = NO;
  614. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  615. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  616. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  617. dispatch_async(dispatch_get_main_queue(), ^{
  618. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  619. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  620. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  621. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  622. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  623. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  624. if (splitViewController.isCollapsed) {
  625. [navigationControllerMaster popToRootViewControllerAnimated:false];
  626. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  627. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  628. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  629. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  630. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  631. }
  632. }
  633. } else {
  634. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  635. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  636. }
  637. }
  638. }
  639. }
  640. }
  641. });
  642. handled = YES;
  643. }
  644. return handled;
  645. }
  646. #pragma --------------------------------------------------------------------------------------------
  647. #pragma mark ===== ApplicationIconBadgeNumber =====
  648. #pragma --------------------------------------------------------------------------------------------
  649. - (void)updateApplicationIconBadgeNumber
  650. {
  651. if (self.activeAccount.length == 0 || self.maintenanceMode)
  652. return;
  653. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  654. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  655. NSInteger counterUpload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  656. NSInteger total = counterDownload + counterUpload;
  657. dispatch_async(dispatch_get_main_queue(), ^{
  658. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  659. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  660. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  661. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  662. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  663. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  664. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  665. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  666. if (total > 0) {
  667. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  668. } else {
  669. [tabBarItem setBadgeValue:nil];
  670. }
  671. }
  672. }
  673. }
  674. });
  675. });
  676. }
  677. #pragma --------------------------------------------------------------------------------------------
  678. #pragma mark ===== TabBarController =====
  679. #pragma --------------------------------------------------------------------------------------------
  680. - (void)createTabBarController:(UITabBarController *)tabBarController
  681. {
  682. UITabBarItem *item;
  683. NSLayoutConstraint *constraint;
  684. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  685. // File
  686. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  687. [item setTitle:NSLocalizedString(@"_home_", nil)];
  688. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  689. item.selectedImage = item.image;
  690. // Favorites
  691. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  692. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  693. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  694. item.selectedImage = item.image;
  695. // (PLUS INVISIBLE)
  696. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  697. item.title = @"";
  698. item.image = nil;
  699. item.enabled = false;
  700. // Media
  701. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  702. [item setTitle:NSLocalizedString(@"_media_", nil)];
  703. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  704. item.selectedImage = item.image;
  705. // More
  706. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  707. [item setTitle:NSLocalizedString(@"_more_", nil)];
  708. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  709. item.selectedImage = item.image;
  710. // Plus Button
  711. int buttonSize = 56;
  712. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  713. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  714. buttonPlus.tag = 99;
  715. [buttonPlus setImage:buttonImage forState:UIControlStateNormal];
  716. buttonPlus.backgroundColor = NCBrandColor.sharedInstance.brand;
  717. buttonPlus.layer.cornerRadius = buttonSize / 2;
  718. buttonPlus.layer.masksToBounds = NO;
  719. buttonPlus.layer.shadowOffset = CGSizeMake(0, 0);
  720. buttonPlus.layer.shadowRadius = 3.0f;
  721. buttonPlus.layer.shadowOpacity = 0.5;
  722. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  723. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  724. [tabBarController.tabBar addSubview:buttonPlus];
  725. if (safeAreaBottom > 0) {
  726. // X
  727. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  728. [tabBarController.view addConstraint:constraint];
  729. // Y
  730. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:-(buttonSize / 2)];
  731. [tabBarController.view addConstraint:constraint];
  732. // Width
  733. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  734. [tabBarController.view addConstraint:constraint];
  735. // Height
  736. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  737. [tabBarController.view addConstraint:constraint];
  738. } else {
  739. // X
  740. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  741. [tabBarController.view addConstraint:constraint];
  742. // Y
  743. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-(buttonSize / 2)];
  744. [tabBarController.view addConstraint:constraint];
  745. // Width
  746. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  747. [tabBarController.view addConstraint:constraint];
  748. // Height
  749. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  750. [tabBarController.view addConstraint:constraint];
  751. }
  752. }
  753. - (void)handleTouchTabbarCenter:(id)sender
  754. {
  755. // Test Maintenance
  756. if (self.maintenanceMode)
  757. return;
  758. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  759. if ([tableDirectory.permissions containsString:@"CK"]) {
  760. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  761. [self showMenuInViewController: vc];
  762. } else {
  763. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  764. }
  765. }
  766. - (NSString *)getTabBarControllerActiveServerUrl
  767. {
  768. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  769. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  770. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  771. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  772. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  773. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  774. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  775. NSInteger index = tabBarController.selectedIndex;
  776. // select active serverUrl
  777. if (index == k_tabBarApplicationIndexFile) {
  778. serverUrl = self.activeMain.serverUrl;
  779. } else if (index == k_tabBarApplicationIndexFavorite) {
  780. if (self.activeFavorites.serverUrl)
  781. serverUrl = self.activeFavorites.serverUrl;
  782. } else if (index == k_tabBarApplicationIndexMedia) {
  783. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  784. }
  785. }
  786. }
  787. }
  788. return serverUrl;
  789. }
  790. #pragma --------------------------------------------------------------------------------------------
  791. #pragma mark ===== Theming Color =====
  792. #pragma --------------------------------------------------------------------------------------------
  793. - (void)settingThemingColorBrand
  794. {
  795. if (self.activeAccount.length == 0 || self.maintenanceMode)
  796. return;
  797. if ([NCBrandOptions sharedInstance].use_themingColor) {
  798. NSString *themingColor = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColor];
  799. NSString *themingColorElement = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  800. NSString *themingColorText = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColorText];
  801. [CCGraphics settingThemingColor:themingColor themingColorElement:themingColorElement themingColorText:themingColorText];
  802. UIColor *color = NCBrandColor.sharedInstance.brand;
  803. BOOL isTooLight = NCBrandColor.sharedInstance.brand.isTooLight;
  804. BOOL isTooDark = NCBrandColor.sharedInstance.brand.isTooDark;
  805. if (isTooLight) {
  806. color = [NCBrandColor.sharedInstance.brand darkerBy:10];
  807. } else if (isTooDark) {
  808. color = [NCBrandColor.sharedInstance.brand lighterBy:10];
  809. }
  810. NCBrandColor.sharedInstance.brand = color;
  811. } else {
  812. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  813. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  814. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  815. }
  816. [[NCMainCommon sharedInstance] createImagesThemingColor];
  817. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  818. }
  819. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  820. {
  821. // Dark Mode
  822. [NCBrandColor.sharedInstance setDarkMode];
  823. // View
  824. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  825. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  826. // NavigationBar
  827. if (viewController.navigationController.navigationBar) {
  828. if (![self.reachability isReachable]) {
  829. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  830. }
  831. }
  832. [self configureNavBarForViewController:viewController];
  833. //tabBar
  834. if (viewController.tabBarController.tabBar) {
  835. viewController.tabBarController.tabBar.translucent = NO;
  836. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.backgroundView;
  837. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  838. }
  839. //tabBar button Plus
  840. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  841. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  842. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  843. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  844. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  845. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  846. [tabBarController.tabBar setNeedsDisplay];
  847. UIButton *button = [tabBarController.view viewWithTag:99];
  848. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  849. [button setImage:buttonImage forState:UIControlStateNormal];
  850. button.backgroundColor = NCBrandColor.sharedInstance.brand;
  851. }
  852. }
  853. }
  854. // TableView
  855. if (tableView) {
  856. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  857. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  858. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  859. [tableView reloadData];
  860. }
  861. // CollectionView
  862. if (collectionView) {
  863. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  864. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  865. [collectionView reloadData];
  866. }
  867. // Tint Color GLOBAL WINDOW
  868. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  869. }
  870. #pragma --------------------------------------------------------------------------------------------
  871. #pragma mark ===== reachabilityChanged =====
  872. #pragma --------------------------------------------------------------------------------------------
  873. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  874. {
  875. if ([self.reachability isReachable]) {
  876. if (self.lastReachability == NO) {
  877. NSLog(@"[LOG] Request Service Server Nextcloud");
  878. [[NCService sharedInstance] startRequestServicesServer];
  879. }
  880. NSLog(@"[LOG] Reachability Changed: Reachable");
  881. self.lastReachability = YES;
  882. } else {
  883. if (self.lastReachability == YES) {
  884. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  885. }
  886. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  887. self.lastReachability = NO;
  888. }
  889. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  890. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  891. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_setTitleMain object:nil];
  892. }
  893. #pragma --------------------------------------------------------------------------------------------
  894. #pragma mark ===== Fetch =====
  895. #pragma --------------------------------------------------------------------------------------------
  896. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  897. {
  898. // Test Maintenance
  899. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  900. completionHandler(UIBackgroundFetchResultNoData);
  901. return;
  902. }
  903. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  904. // Verify new photo
  905. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  906. // after 20 sec
  907. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  908. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  909. if ([records count] > 0) {
  910. completionHandler(UIBackgroundFetchResultNewData);
  911. } else {
  912. completionHandler(UIBackgroundFetchResultNoData);
  913. }
  914. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  915. });
  916. }
  917. #pragma --------------------------------------------------------------------------------------------
  918. #pragma mark ===== Operation Networking & Session =====
  919. #pragma --------------------------------------------------------------------------------------------
  920. //
  921. // Method called by the system when all the background task has end
  922. //
  923. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  924. {
  925. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  926. // after 20 sec
  927. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  928. self.backgroundSessionCompletionHandler = completionHandler;
  929. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  930. self.backgroundSessionCompletionHandler = nil;
  931. completionHandler();
  932. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  933. });
  934. }
  935. #pragma --------------------------------------------------------------------------------------------
  936. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  937. #pragma --------------------------------------------------------------------------------------------
  938. - (void)loadAutoDownloadUpload
  939. {
  940. if (self.activeAccount.length == 0 || self.maintenanceMode)
  941. return;
  942. tableMetadata *metadataForUpload, *metadataForDownload;
  943. long counterDownload = 0, counterUpload = 0;
  944. NSUInteger sizeDownload = 0, sizeUpload = 0;
  945. NSMutableArray *uploaded = [NSMutableArray new];
  946. NSPredicate *predicate;
  947. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  948. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  949. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  950. // E2EE only 1
  951. for(tableMetadata *metadata in metadatasDownload) {
  952. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  953. }
  954. for(tableMetadata *metadata in metadatasUpload) {
  955. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  956. }
  957. // Counter
  958. counterDownload = [metadatasDownload count];
  959. counterUpload = [metadatasUpload count];
  960. // Size
  961. for (tableMetadata *metadata in metadatasDownload) {
  962. sizeDownload = sizeDownload + metadata.size;
  963. }
  964. for (tableMetadata *metadata in metadatasUpload) {
  965. sizeUpload = sizeUpload + metadata.size;
  966. }
  967. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  968. // Stop Timer
  969. [_timerProcessAutoDownloadUpload invalidate];
  970. // ------------------------- <selector Download> -------------------------
  971. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  972. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  973. if (metadataForDownload) {
  974. if ([CCUtility isFolderEncrypted:metadataForDownload.serverUrl e2eEncrypted:metadataForDownload.e2eEncrypted account:metadataForDownload.account]) {
  975. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  976. maxConcurrentOperationDownloadUpload = 1;
  977. metadataForDownload.status = k_metadataStatusInDownload;
  978. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  979. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  980. break;
  981. } else {
  982. metadataForDownload.status = k_metadataStatusInDownload;
  983. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  984. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  985. counterDownload++;
  986. sizeDownload = sizeDownload + metadata.size;
  987. }
  988. } else {
  989. break;
  990. }
  991. }
  992. // ------------------------- <selector Upload> -------------------------
  993. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  994. if (sizeUpload > k_maxSizeOperationUpload) {
  995. break;
  996. }
  997. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  998. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadFile, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  999. } else {
  1000. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload];
  1001. }
  1002. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1003. // Verify modify file
  1004. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  1005. break;
  1006. }
  1007. if (metadataForUpload) {
  1008. // Verify modify file
  1009. BOOL isAleadyInUpload = false;
  1010. for (tableMetadata *metadata in metadatasUpload) {
  1011. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  1012. isAleadyInUpload = true;
  1013. }
  1014. }
  1015. if (isAleadyInUpload == false) {
  1016. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1017. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1018. maxConcurrentOperationDownloadUpload = 1;
  1019. metadataForUpload.status = k_metadataStatusInUpload;
  1020. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1021. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1022. break;
  1023. } else {
  1024. metadataForUpload.status = k_metadataStatusInUpload;
  1025. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1026. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1027. counterUpload++;
  1028. sizeUpload = sizeUpload + metadata.size;
  1029. // For verify modify file
  1030. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1031. }
  1032. } else {
  1033. break;
  1034. }
  1035. } else {
  1036. break;
  1037. }
  1038. }
  1039. // ------------------------- <selector Auto Upload> -------------------------
  1040. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1041. if (sizeUpload > k_maxSizeOperationUpload) {
  1042. break;
  1043. }
  1044. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1045. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUpload, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1046. } else {
  1047. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload];
  1048. }
  1049. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1050. if (metadataForUpload) {
  1051. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1052. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1053. maxConcurrentOperationDownloadUpload = 1;
  1054. metadataForUpload.status = k_metadataStatusInUpload;
  1055. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1056. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1057. break;
  1058. } else {
  1059. metadataForUpload.status = k_metadataStatusInUpload;
  1060. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1061. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1062. counterUpload++;
  1063. sizeUpload = sizeUpload + metadata.size;
  1064. }
  1065. } else {
  1066. break;
  1067. }
  1068. }
  1069. // ------------------------- <selector Auto Upload All> ----------------------
  1070. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1071. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1072. NSInteger errorCount = [metadatas count];
  1073. if (errorCount >= k_maxErrorAutoUploadAll) {
  1074. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1075. } else {
  1076. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1077. if (sizeUpload > k_maxSizeOperationUpload) {
  1078. break;
  1079. }
  1080. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1081. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1082. } else {
  1083. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload];
  1084. }
  1085. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"session" ascending:YES];
  1086. if (metadataForUpload) {
  1087. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1088. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1089. maxConcurrentOperationDownloadUpload = 1;
  1090. metadataForUpload.status = k_metadataStatusInUpload;
  1091. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1092. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1093. break;
  1094. } else {
  1095. metadataForUpload.status = k_metadataStatusInUpload;
  1096. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1097. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1098. counterUpload++;
  1099. sizeUpload = sizeUpload + metadata.size;
  1100. }
  1101. } else {
  1102. break;
  1103. }
  1104. }
  1105. }
  1106. // No Download/upload available ? --> remove errors for retry
  1107. //
  1108. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1109. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1110. for (tableMetadata *metadata in metadatas) {
  1111. if (metadata.status == k_metadataStatusDownloadError)
  1112. metadata.status = k_metadataStatusWaitDownload;
  1113. else if (metadata.status == k_metadataStatusUploadError)
  1114. metadata.status = k_metadataStatusWaitUpload;
  1115. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1116. }
  1117. }
  1118. // Upload in pending
  1119. //
  1120. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1121. for (tableMetadata *metadata in metadatasInUpload) {
  1122. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1123. metadata.status = k_metadataStatusWaitUpload;
  1124. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1125. } else {
  1126. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1127. }
  1128. }
  1129. if (metadatasInUpload.count == 0) {
  1130. [self.sessionPendingStatusInUpload removeAllObjects];
  1131. }
  1132. // Start Timer
  1133. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1134. }
  1135. - (void)startLoadAutoDownloadUpload
  1136. {
  1137. if (self.timerProcessAutoDownloadUpload.isValid) {
  1138. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1139. }
  1140. }
  1141. - (void)verifyTaskLost
  1142. {
  1143. // DOWNLOAD
  1144. //
  1145. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1146. for (tableMetadata *metadata in matadatasInDownloading) {
  1147. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1148. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1149. NSURLSessionTask *findTask;
  1150. for (NSURLSessionTask *task in downloadTasks) {
  1151. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1152. findTask = task;
  1153. }
  1154. }
  1155. if (!findTask) {
  1156. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1157. metadata.status = k_metadataStatusWaitDownload;
  1158. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1159. }
  1160. }];
  1161. }
  1162. // UPLOAD
  1163. //
  1164. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1165. for (tableMetadata *metadata in metadatasUploading) {
  1166. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1167. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1168. NSURLSessionTask *findTask;
  1169. for (NSURLSessionTask *task in uploadTasks) {
  1170. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1171. findTask = task;
  1172. }
  1173. }
  1174. if (!findTask) {
  1175. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1176. metadata.status = k_metadataStatusWaitUpload;
  1177. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1178. }
  1179. }];
  1180. }
  1181. }
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. #pragma mark ===== OpenURL =====
  1184. #pragma --------------------------------------------------------------------------------------------
  1185. // Method called from iOS system to send a file from other app.
  1186. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1187. {
  1188. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1189. return YES;
  1190. NSString *scheme = url.scheme;
  1191. dispatch_time_t timer = 0;
  1192. if (self.activeMain == nil) timer = 1;
  1193. if ([scheme isEqualToString:@"nextcloud"]) {
  1194. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1195. NSString *action = url.host;
  1196. if ([action isEqualToString:@"open-file"]) {
  1197. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1198. NSArray *queryItems = urlComponents.queryItems;
  1199. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1200. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1201. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1202. tableAccount *matchedAccount = nil;
  1203. // verify parameter
  1204. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1205. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1206. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1207. [alertController addAction:okAction];
  1208. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1209. } else {
  1210. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1211. if (account) {
  1212. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1213. NSString *activeAccountUser = account.user;
  1214. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1215. matchedAccount = account;
  1216. } else {
  1217. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1218. for (tableAccount *account in accounts) {
  1219. NSURL *accountURL = [NSURL URLWithString:account.url];
  1220. NSString *accountUser = account.user;
  1221. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1222. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1223. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1224. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1225. }
  1226. }
  1227. }
  1228. if (matchedAccount) {
  1229. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1230. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1231. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1232. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1233. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1234. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1235. if (splitViewController.isCollapsed) {
  1236. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1237. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1238. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1239. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1240. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1241. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1242. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1243. }
  1244. }
  1245. }
  1246. } else {
  1247. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1248. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1249. }
  1250. }
  1251. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1252. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1253. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1254. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1255. if ([path containsString:@"/"]) {
  1256. // Push
  1257. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1258. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1259. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  1260. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  1261. } else {
  1262. // Reload folder
  1263. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1264. self.activeMain.blinkFileNamePath = fileNamePath;
  1265. [self.activeMain readFolder:serverUrl];
  1266. }
  1267. });
  1268. });
  1269. }
  1270. }
  1271. }
  1272. } else {
  1273. NSString *domain = [[NSURL URLWithString:link] host];
  1274. NSString *fileName = [path lastPathComponent];
  1275. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1276. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1277. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1278. [alertController addAction:okAction];
  1279. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1280. }
  1281. }
  1282. }
  1283. }
  1284. });
  1285. return YES;
  1286. }
  1287. NSError *error;
  1288. NSLog(@"[LOG] the path is: %@", url.path);
  1289. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1290. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1291. if (self.activeAccount) {
  1292. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1293. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1294. if (error == nil) {
  1295. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1296. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1297. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1298. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1299. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1300. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1301. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1302. });
  1303. }
  1304. }
  1305. }
  1306. }
  1307. return YES;
  1308. }
  1309. #pragma --------------------------------------------------------------------------------------------
  1310. #pragma mark ===== Passcode + Delegate =====
  1311. #pragma --------------------------------------------------------------------------------------------
  1312. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  1313. {
  1314. LAContext *laContext = [LAContext new];
  1315. NSError *error;
  1316. BOOL isBiometryAvailable = false;
  1317. if ([[CCUtility getPasscode] length] == 0 || [self.activeAccount length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  1318. if (!self.passcodeViewController.view.window) {
  1319. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  1320. if (@available(iOS 13.0, *)) {
  1321. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  1322. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  1323. }
  1324. }
  1325. self.passcodeViewController.delegate = self;
  1326. self.passcodeViewController.allowCancel = false;
  1327. self.passcodeViewController.keypadButtonShowLettering = false;
  1328. if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  1329. if (error == NULL) {
  1330. if (laContext.biometryType == LABiometryTypeFaceID) {
  1331. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  1332. self.passcodeViewController.allowBiometricValidation = true;
  1333. isBiometryAvailable = true;
  1334. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  1335. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  1336. self.passcodeViewController.allowBiometricValidation = true;
  1337. isBiometryAvailable = true;
  1338. } else {
  1339. isBiometryAvailable = false;
  1340. NSLog(@"No Biometric support");
  1341. }
  1342. }
  1343. }
  1344. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  1345. }
  1346. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1347. if (automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  1348. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1349. if (success) {
  1350. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1351. [self.passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1352. });
  1353. }
  1354. }];
  1355. }
  1356. });
  1357. }
  1358. - (void)didTapCancelInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1359. {
  1360. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1361. }
  1362. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1363. {
  1364. return [code isEqualToString:[CCUtility getPasscode]];
  1365. }
  1366. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1367. {
  1368. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1369. if (success) {
  1370. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1371. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1372. });
  1373. }
  1374. }];
  1375. }
  1376. #pragma --------------------------------------------------------------------------------------------
  1377. #pragma mark ===== Maintenance Mode =====
  1378. #pragma --------------------------------------------------------------------------------------------
  1379. - (void)maintenanceMode:(BOOL)mode
  1380. {
  1381. self.maintenanceMode = mode;
  1382. }
  1383. #pragma --------------------------------------------------------------------------------------------
  1384. #pragma mark ===== UPGRADE =====
  1385. #pragma --------------------------------------------------------------------------------------------
  1386. - (BOOL)upgrade
  1387. {
  1388. #ifdef DEBUG
  1389. //self.maintenanceMode = YES;
  1390. #endif
  1391. NSString *actualVersion = [CCUtility getVersion];
  1392. NSString *actualBuild = [CCUtility getBuild];
  1393. /* ---------------------- UPGRADE VERSION ----------------------- */
  1394. // VERSION < 2.17.6
  1395. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1396. // Remove All old Photo Library
  1397. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1398. }
  1399. // VERSION == 2.17.6
  1400. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1401. // Build < 10
  1402. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1403. // Remove All old Photo Library
  1404. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1405. }
  1406. }
  1407. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1408. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1409. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1410. }
  1411. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1412. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1413. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1414. NSString *account = @"";
  1415. NSString *directoryUser = @"";
  1416. NSString *fileName;
  1417. for (tableLocalFile *record in records) {
  1418. if (![account isEqualToString:record.account]) {
  1419. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1420. if (tableAccount) {
  1421. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1422. account = record.account;
  1423. }
  1424. }
  1425. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1426. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1427. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1428. }
  1429. }
  1430. });
  1431. }
  1432. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1433. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1434. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1435. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1436. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1437. }
  1438. }
  1439. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1440. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1441. for (tableAccount *record in records) {
  1442. [CCUtility setPassword:record.account password:record.password];
  1443. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1444. }
  1445. }
  1446. return YES;
  1447. }
  1448. @end