JDFacade.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. //
  2. // JDFacade.m
  3. // kneet2
  4. //
  5. // Created by Created by Jason Lee on 10/1/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. @import ObjectiveC.runtime;
  9. #import "JDFacade.h"
  10. #import "JDUserDefaults.h"
  11. #import "CypherUtil.h"
  12. #import "JDUUID.h"
  13. #import "CustomLoadingView.h"
  14. #import "CustomImageView.h"
  15. #import "RequestHandler.h"
  16. //OpenSource
  17. #ifndef PRODUCT_MODE
  18. #import "FLEXManager.h"
  19. #endif
  20. #import "UIView+Toast.h"
  21. #import "JDProgressHUD.h"
  22. #import "Valet.h"
  23. #import "VALValet.h"
  24. #import "LoginViewController.h"
  25. #import "MainViewController.h"
  26. #import "DeviceModel.h"
  27. #import "HomeHubViewController.h"
  28. @interface JDFacade () {
  29. VALValet *_valet;
  30. JDProgressHUD *_HUD;
  31. NSTimer *_homehubBackgroundTimer;
  32. }
  33. @end
  34. @implementation JDFacade
  35. @synthesize tmpEmailId = _tmpEmailId;
  36. #pragma mark - Properties
  37. - (NSString *)deviceUUID {
  38. if (!_deviceUUID) {
  39. _deviceUUID = [[JDUUID UUIDHandler] getUUID];
  40. }
  41. return _deviceUUID;
  42. }
  43. - (NSString *)APNSToken {
  44. return _APNSToken ? _APNSToken : ksEmptyString;
  45. }
  46. - (NSString *)tmpEmailId {
  47. NSString *enTmpEmailId = [self objectForKeyFromUserDefaults:USDEF_APP_TMP_EMAIL];
  48. _tmpEmailId = [CypherUtil AES128Decrypt:enTmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  49. return _tmpEmailId ? _tmpEmailId : ksEmptyString;
  50. }
  51. - (void)setTmpEmailId:(NSString *)tmpEmailId {
  52. NSString *enTmpEmailId = [CypherUtil AES128Encrypt:tmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  53. [self storeObjectToUserDefaults:enTmpEmailId forKey:USDEF_APP_TMP_EMAIL];
  54. }
  55. - (void)setCurrentOperation:(NSOperation *)currentOperation {
  56. [CustomLoadingView loadingView].operation = currentOperation;
  57. }
  58. - (NSString *)deviceHostName {
  59. return [self hostnameOfDevice];
  60. }
  61. - (void)setLoginUser:(LoginModel *)loginUser {
  62. _loginUser = loginUser;
  63. if (!_loginUser) {
  64. if (_homehubBackgroundTimer) {
  65. [_homehubBackgroundTimer invalidate];
  66. _homehubBackgroundTimer = nil;
  67. }
  68. }
  69. }
  70. - (NSString *)hostnameOfDevice {
  71. char baseHostName[256];
  72. int success = gethostname(baseHostName, 255);
  73. if (success != 0) return nil;
  74. baseHostName[255] = '\0';
  75. #if !TARGET_IPHONE_SIMULATOR
  76. NSLog(@"%s\n %@, %s", __PRETTY_FUNCTION__, @"!TARGET_IPHONE_SIMULATOR", baseHostName);
  77. NSString *hostname = [NSString stringWithFormat:@"%s", baseHostName];
  78. if (![hostname hasSuffix:@"local"]) {
  79. hostname = [NSString stringWithFormat:@"%s.local", baseHostName];
  80. }
  81. return hostname;
  82. #else
  83. return [NSString stringWithFormat:@"%s", baseHostName];
  84. #endif
  85. }
  86. #pragma mark - View Facade
  87. - (AppDelegate *)appDelegate {
  88. return (AppDelegate *)[UIApplication sharedApplication].delegate;
  89. }
  90. #pragma mark - 화면 제어
  91. - (UIViewController *)currentViewController {
  92. id appDelegate = [UIApplication sharedApplication].delegate;
  93. UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
  94. if (vc.presentedViewController) {
  95. while (vc.presentedViewController) {
  96. vc = vc.presentedViewController;
  97. }
  98. if ([vc isKindOfClass:[UINavigationController class]]) {
  99. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  100. vc = [vcArray objectAtIndex:vcArray.count - 1];
  101. }
  102. return vc;
  103. }
  104. if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
  105. vc = vc.presentingViewController;
  106. }
  107. if ([vc isKindOfClass:[UINavigationController class]]) {
  108. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  109. vc = [vcArray objectAtIndex:vcArray.count - 1];
  110. }
  111. return vc;
  112. }
  113. - (id)viewControllerOnNaviationController:(Class)viewControllerClass {
  114. UIViewController *targetVc = nil;
  115. UINavigationController *navigationController = self.currentViewController.navigationController;
  116. if (!navigationController) {
  117. navigationController = (UINavigationController *)self.currentViewController.presentingViewController;
  118. }
  119. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  120. for (UIViewController *vc in navigationController.viewControllers) {
  121. if ([vc isKindOfClass:viewControllerClass]) {
  122. targetVc = vc;
  123. break;
  124. }
  125. }
  126. }
  127. return targetVc;
  128. }
  129. - (id)viewControllerOnPresentingViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass {
  130. return [self viewControllerOnPresentingViewController:pvc viewControllerClass:viewControllerClass tryTimes:10];
  131. }
  132. - (id)viewControllerOnPresentingViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass tryTimes:(NSInteger)tryTimes {
  133. UIViewController *vc = pvc.presentingViewController;
  134. if (![vc isKindOfClass:viewControllerClass] && tryTimes > 0) {
  135. vc = [self viewControllerOnPresentingViewController:vc viewControllerClass:viewControllerClass tryTimes:tryTimes-1];
  136. }
  137. return vc;
  138. }
  139. - (id)viewControllerOnPresentedViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass {
  140. return [self viewControllerOnPresentedViewController:pvc viewControllerClass:viewControllerClass tryTimes:10];
  141. }
  142. - (id)viewControllerOnPresentedViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass tryTimes:(NSInteger)tryTimes {
  143. UIViewController *vc = pvc.presentedViewController;
  144. if (![vc isKindOfClass:viewControllerClass] && tryTimes > 0) {
  145. vc = [self viewControllerOnPresentedViewController:vc viewControllerClass:viewControllerClass tryTimes:tryTimes-1];
  146. }
  147. return vc;
  148. }
  149. #pragma mark - KeychainItem Wrapper
  150. static NSString *const ksKeychainIdentifier = @"OneCableACCOUNT";
  151. static NSString *const ksKeychainArchiveData = @"_archiveData";
  152. - (void)storeObjectToKeychain:(id)object forKey:(NSString *)aKey {
  153. if (!_valet) {
  154. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  155. }
  156. NSMutableDictionary *dict = nil;
  157. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  158. if (archiveData) {
  159. dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  160. }
  161. if (!dict) {
  162. dict = [[NSMutableDictionary alloc] init];
  163. }
  164. [dict setObject:object forKey:aKey];
  165. archiveData = [NSKeyedArchiver archivedDataWithRootObject:dict];
  166. [_valet setObject:archiveData forKey:ksKeychainArchiveData];
  167. }
  168. - (id)objectForKeyFromKeychain:(NSString *)aKey {
  169. if (!_valet) {
  170. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  171. }
  172. NSMutableDictionary *dict = nil;
  173. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  174. id obj = nil;
  175. if (archiveData) {
  176. dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  177. obj = [dict objectForKey:aKey];
  178. }
  179. return obj;
  180. }
  181. - (void)removeObjectAtKeychain:(NSString *)aKey {
  182. if (!_valet) {
  183. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  184. }
  185. NSMutableDictionary *dict = nil;
  186. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  187. if (archiveData) {
  188. NSMutableDictionary *dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  189. [dict removeObjectForKey:aKey];
  190. }
  191. archiveData = [NSKeyedArchiver archivedDataWithRootObject:dict];
  192. [_valet setObject:archiveData forKey:ksKeychainArchiveData];
  193. }
  194. #pragma mark - UserDefautls - Local Store
  195. - (void)storeObjectToUserDefaults:(id)object forKey:(NSString *)aKey {
  196. [[JDUserDefaults defaults] syncronizeObject:object forKey:aKey];
  197. }
  198. - (id)objectForKeyFromUserDefaults:(NSString *)aKey {
  199. return [[JDUserDefaults defaults] objectForKey:aKey];
  200. }
  201. #pragma mark - Alert & Loading
  202. - (void)loadIndicator:(BOOL)showIndicator allowUserInteraction:(BOOL)allowUserInteracton {
  203. //로딩시 터치 방지
  204. if(showIndicator) {
  205. dispatch_async(dispatch_get_main_queue(), ^{
  206. [[JDFacade facade].currentViewController.view endEditing:YES];
  207. UIView *topView = [CommonUtil topView];
  208. [[CustomLoadingView loadingView] showInView:topView];
  209. });
  210. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  211. } else {
  212. dispatch_async(dispatch_get_main_queue(), ^{
  213. [[CustomLoadingView loadingView] hide];
  214. });
  215. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  216. }
  217. }
  218. - (void)showLoadingWhileExecutingBlock:(dispatch_block_t)block completionHandler:(JDFacadeCompletionCallBackHandler)completion {
  219. [[CustomLoadingView loadingView] showInView:[CommonUtil topView] whileExecutingBlock:block completionHandler:completion];
  220. }
  221. #pragma mark - Alert UI
  222. - (void)alert:(NSString *)message {
  223. [self alertTitle:@"알림" message:message];
  224. }
  225. - (void)alertTitle:(NSString *)title message:(NSString *)message {
  226. [self.currentViewController.view endEditing:YES];
  227. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  228. [alert show];
  229. }
  230. - (void)alert:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)completion {
  231. [self alertTitle:@"알림" message:message completionHander:completion];
  232. }
  233. - (void)alertTitle:(NSString *)title message:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)completion {
  234. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  235. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  236. if (completion) {
  237. completion();
  238. }
  239. }];
  240. }
  241. - (void)confirm:(NSString *)message completion:(CustomAlertViewCallBackHandler)completion {
  242. [self confirmTitle:@"알림" message:message completion:completion];
  243. }
  244. - (void)confirmTitle:(NSString *)title message:(NSString *)message completion:(CustomAlertViewCallBackHandler)completion {
  245. [self confirmTitle:title message:message btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:completion];
  246. }
  247. - (void)confirmTitle:(NSString *)title message:(NSString *)message btnOKLabel:(NSString *)btnOKLabel btnCancelLabel:(NSString *)btnCancelLabel completion:(CustomAlertViewCallBackHandler)completion {
  248. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:btnOKLabel cancelButtonTitle:btnCancelLabel];
  249. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  250. if (completion) {
  251. completion(alertView, buttonIndex);
  252. }
  253. }];
  254. }
  255. - (void)retryAlert:(NSString *)message target:(id)target selector:(SEL)selector {
  256. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  257. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  258. if (buttonIndex == 1) {
  259. if ([target respondsToSelector:selector]) {
  260. [target performSelector:selector withObject:nil afterDelay:0.0f];
  261. }
  262. }
  263. }];
  264. }
  265. - (void)retryAlert:(NSString *)message target:(id)target selector:(SEL)selector arguments:(id)arguments,... {
  266. va_list args;
  267. va_start(args, arguments);
  268. NSInteger i = 0;
  269. NSMutableArray *argsArray = [[NSMutableArray alloc] init];
  270. [argsArray addObject:arguments];
  271. while ((arguments = va_arg(args, id)) != nil) {//루프 - 입력된 메시지를 받아옴.
  272. [argsArray addObject:arguments];
  273. i++;
  274. }
  275. va_end(args);
  276. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  277. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  278. if (buttonIndex == 0) {
  279. if (target && selector) {
  280. NSMethodSignature *sig = [target methodSignatureForSelector:selector];
  281. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
  282. NSInteger index = 2;
  283. [invocation setTarget:target]; // index 0 (hidden)
  284. [invocation setSelector:selector]; //index 1 (hidden)
  285. for (id argument in argsArray) {
  286. [invocation setArgument:(void *)&argument atIndex:index++];
  287. }
  288. [invocation invoke];
  289. }
  290. }
  291. }];
  292. }
  293. - (void)retryAlert:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)handler {
  294. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  295. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  296. if (buttonIndex == 1) {//재시도
  297. if (handler) {
  298. handler();
  299. }
  300. }
  301. }];
  302. }
  303. - (void)fireLocalNotification:(NSString *)message {
  304. NSLog(@"fireLocalNotification %@", message);
  305. NSDate *now = [NSDate date];
  306. UILocalNotification *localNotif = [[UILocalNotification alloc] init];
  307. localNotif.fireDate = now;
  308. NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
  309. localNotif.timeZone = timezone;
  310. localNotif.hasAction = YES;
  311. localNotif.alertBody = message;
  312. localNotif.alertAction = @"View";
  313. localNotif.soundName = UILocalNotificationDefaultSoundName;
  314. localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
  315. [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
  316. }
  317. - (void)toast:(NSString *)message {
  318. [[CommonUtil topView] makeToast:message];
  319. }
  320. #pragma mark - CheckBox && Radiobutton Status
  321. - (id)getRadioButtonStatus:(id)object {
  322. if (!object)
  323. return @NO;
  324. return objc_getAssociatedObject(object, ksCustomRadioButtonStatus);
  325. }
  326. - (void)setRadioButtonStatus:(id)status object:(id)object {
  327. if (!object)
  328. return;
  329. objc_setAssociatedObject(object, ksCustomRadioButtonStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for radio box
  330. }
  331. - (id)getCheckBoxStatus:(id)object {
  332. if (!object)
  333. return @NO;
  334. return objc_getAssociatedObject(object, ksCustomCheckBoxStatus);
  335. }
  336. - (void)setCheckBoxStatus:(id)status object:(id)object {
  337. if (!object)
  338. return;
  339. objc_setAssociatedObject(object, ksCustomCheckBoxStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for check box
  340. }
  341. #pragma mark - 화면이동 제어
  342. - (void)dismissModalStack:(BOOL)animated completion:(JDFacadeCompletionCallBackHandler)completion {
  343. UIViewController *vc = self.currentViewController;
  344. while (vc.presentingViewController) {
  345. vc = vc.presentingViewController;
  346. }
  347. CATransition *transition = [CATransition animation];
  348. transition.duration = kfTransitionRightDur;
  349. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  350. transition.type = kCATransitionMoveIn;
  351. transition.subtype = kCATransitionFromBottom;
  352. [vc.view.window.layer addAnimation:transition forKey:nil];
  353. [vc dismissViewControllerAnimated:NO completion:^{
  354. if (completion) {
  355. completion();
  356. }
  357. }];
  358. }
  359. - (void)presentViewControllerByPush:(UIViewController *)vc {
  360. CATransition *transition = [CATransition animation];
  361. transition.duration = kfTransitionRightDur;
  362. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  363. transition.type = kCATransitionPush;
  364. transition.subtype = kCATransitionFromRight;
  365. [self.currentViewController.view.window.layer addAnimation:transition forKey:nil];
  366. [self.currentViewController presentViewController:vc animated:NO completion:nil];
  367. }
  368. - (void)presentViewControllerByPush:(UIViewController *)vc pvc:(UIViewController *)pvc {
  369. CATransition *transition = [CATransition animation];
  370. transition.duration = kfTransitionRightDur;
  371. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  372. transition.type = kCATransitionPush;
  373. transition.subtype = kCATransitionFromRight;
  374. [pvc.view.window.layer addAnimation:transition forKey:nil];
  375. [pvc presentViewController:vc animated:NO completion:nil];
  376. }
  377. - (UIViewController *)presentedViewController:(UIViewController *)vc {
  378. UIViewController *presentedViewController = vc.presentedViewController;
  379. if (presentedViewController) {
  380. return [self presentedViewController:presentedViewController];
  381. }
  382. return vc;
  383. }
  384. - (void)dismissViewControllerByPush:(UIViewController *)vc {
  385. CATransition *transition = [CATransition animation];
  386. transition.duration = kfTransitionRightDur;
  387. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  388. transition.type = kCATransitionPush;
  389. transition.subtype = kCATransitionFromBottom;
  390. UIViewController *presentedViewController = [self presentedViewController:vc];
  391. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  392. [vc dismissViewControllerAnimated:NO completion:nil];
  393. }
  394. - (void)dismissViewControllerByPush:(UIViewController *)vc completion:(JDFacadeCompletionCallBackHandler)completion {
  395. CATransition *transition = [CATransition animation];
  396. transition.duration = kfTransitionRightDur;
  397. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  398. transition.type = kCATransitionPush;
  399. transition.subtype = kCATransitionFromLeft;
  400. UIViewController *presentedViewController = [self presentedViewController:vc];
  401. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  402. [vc dismissViewControllerAnimated:NO completion:^{
  403. if (completion) {
  404. completion();
  405. }
  406. }];
  407. }
  408. - (void)dismissAllViewControllers {
  409. UIViewController *vc = self.currentViewController;
  410. if (vc.presentingViewController) {
  411. [vc dismissViewControllerAnimated:NO completion:^{
  412. [self dismissAllViewControllers];
  413. }];
  414. }
  415. }
  416. #pragma mark - Biz Logic
  417. - (void)requestPollingHomeHubStatusInBackground {
  418. //schedul timer.
  419. if (!_homehubBackgroundTimer) {
  420. [self requestPollingHomeHubStatus:^{
  421. _homehubBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestPollingHomeHubStatus) userInfo:nil repeats:YES];
  422. }];
  423. }
  424. }
  425. - (void)requestPollingHomeHubStatus {
  426. [self requestPollingHomeHubStatus:nil];
  427. }
  428. - (void)requestPollingHomeHubStatus:(JDFacadeCompletionCallBackHandler)completion {
  429. NSString *path = API_GET_DEVICE_HOMEHUB_STATUS;
  430. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  431. DeviceModel *homehub = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  432. modelClass:[DeviceModel class] showLoadingView:NO];
  433. if (homehub && homehub.onlineState && ![homehub.onlineState isEmptyString]) {
  434. [JDFacade facade].loginUser.homehubOnlineState = homehub.onlineState;
  435. [JDFacade facade].loginUser.homehubCreateDatetime = homehub.createDatetime;
  436. } else {
  437. [JDFacade facade].loginUser.homehubDeviceId = nil;
  438. [JDFacade facade].loginUser.homehubOnlineState = nil;
  439. [JDFacade facade].loginUser.homehubCreateDatetime = nil;
  440. }
  441. [_mainViewController updateHomeHubStatusToChildViewController];
  442. //update global - homehub state
  443. if ([[JDFacade facade].currentViewController isKindOfClass:[HomeHubViewController class]]) {
  444. HomeHubViewController *vc = (HomeHubViewController *)[JDFacade facade].currentViewController;
  445. [vc updateHomeHubStatus];
  446. }
  447. #ifdef DEBUG_MODE
  448. NSLogInfo(@"==########== homehub state = %@ ==########==", [JDFacade facade].loginUser.homehubOnlineState);
  449. #endif
  450. if (completion) {
  451. completion();
  452. }
  453. });
  454. }
  455. #pragma mark - UI Flow
  456. - (void)gotoLoginView {
  457. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  458. [[JDFacade facade].appDelegate.window setRootViewController:vc];
  459. }
  460. //- (void)gotoLoginViewWithExpiring {
  461. // LoginViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  462. // [vc actionAfterLogout];
  463. //}
  464. //
  465. - (void)logout {
  466. LoginViewController *lvc = (LoginViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  467. [lvc requestLogout];
  468. }
  469. - (void)loadInvitationView {
  470. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"InvitationListViewController" storyboardName:@"Main"];
  471. [self.currentViewController presentViewController:vc animated:YES completion:nil];
  472. }
  473. //- (void)checkDefaultHome {
  474. // if (!self.loginUser) {//로그인이 안된 경우, 불필요함.
  475. // return;
  476. // }
  477. //
  478. // [self updateHomegrpListForLoginUser:^{
  479. // //1. 다른 홈이 있는지 확인 - 정렬순서대로 기본홈을 설정 - currentHome
  480. // if (self.loginUser.homegrpList && self.loginUser.homegrpList.count) {
  481. // self.loginHomeGroup = self.loginUser.homegrpList[0];
  482. // [self gotoWishMenu:KNMenuIdDashboard];
  483. // return;
  484. // }
  485. //
  486. // //2. 다른 홈이 없는 경우, - 홈만들기로 이동함.
  487. // CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:NSLocalizedString(@"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?", @"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?") delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  488. // [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  489. // if (buttonIndex == 0) {//OK
  490. // [self gotoStartHome:NO];
  491. // } else {
  492. // [self logout];
  493. // }
  494. // }];
  495. // }];
  496. //}
  497. - (void)gotoStartHome:(BOOL)canGoBack {
  498. // StartHomeViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"StartHomeViewController" storyboardName:@"SignUp"];
  499. // vc.canGoBack = canGoBack;
  500. // [[JDFacade facade] presentViewControllerByPush:vc pvc:self.currentViewController];
  501. }
  502. - (void)gotoWishMenu:(KNMenuId)menuId {
  503. [self gotoWishMenu:menuId completion:nil];
  504. }
  505. - (void)gotoWishMenu:(KNMenuId)menuId completion:(JDFacadeCompletionCallBackHandler)completion {
  506. self.wishMenuId = menuId;
  507. switch (self.wishMenuId) {
  508. case KNMenuIdDashboard: {
  509. [_mainViewController btnCollapseTouched:nil];
  510. [[JDFacade facade] requestPollingHomeHubStatus:^{
  511. [[JDFacade facade] dismissModalStack:YES completion:nil];
  512. }];
  513. }
  514. break;
  515. case KNMenuIdThings: {
  516. [[JDFacade facade] dismissModalStack:YES completion:^{
  517. [_mainViewController loadThingsViewController];
  518. }];
  519. }
  520. break;
  521. case KNMenuIdRules: {
  522. [[JDFacade facade] dismissModalStack:YES completion:^{
  523. [_mainViewController loadRulesViewController];
  524. }];
  525. }
  526. break;
  527. case KNMenuIdHomeMember: {
  528. [[JDFacade facade] dismissModalStack:YES completion:^{
  529. [_mainViewController loadMembersViewController];
  530. }];
  531. }
  532. break;
  533. default:
  534. break;
  535. }
  536. }
  537. - (void)gotoHomeHubRegistration {
  538. // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubStartViewController" storyboardName:@"HomeHub"];
  539. //
  540. // vc.providesPresentationContextTransitionStyle = YES;
  541. // vc.definesPresentationContext = YES;
  542. //
  543. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  544. //
  545. // [self.currentViewController presentViewController:vc animated:NO completion:nil];
  546. }
  547. //- (void)updateHomegrpListForLoginUser:(JDFacadeCompletionCallBackHandler)completion {
  548. //
  549. // NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID};
  550. //
  551. // dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  552. // HomeGroupListModel *homegrpList = [[RequestHandler handler] sendSyncGetRequestAPIPath:API_GET_HOMEGROUP parameters:parameter
  553. // modelClass:[HomeGroupListModel class] showLoadingView:YES];
  554. //
  555. //
  556. // // NSLog(@"%s\n %@", __PRETTY_FUNCTION__, homegrpList);
  557. // //홈그룹을 설정함.
  558. // self.loginUser.homegrpList = homegrpList && homegrpList.homegrpList ? homegrpList.homegrpList : nil;
  559. //
  560. // //로그인 홈을 지정함.
  561. // for (HomeGroupModel *homegrp in self.loginUser.homegrpList) {
  562. // if ([self.loginUser.homegrpId isEqualToString:homegrp.homegrpId]) {
  563. // self.loginHomeGroup = homegrp;
  564. // break;
  565. // }
  566. // }
  567. //
  568. //// [[LocationHandler handler] resetAllMonitoredRegions]; //현재 앱이 구동 중이면, 위치 센서를 다시 등록해야함.
  569. //// [[LocationHandler handler] registerGeofencingForHomeGroupIndex:0]; //모든 홈 그룹을 다시 모니터링 등록 - 루프
  570. //
  571. // if (completion) {
  572. // completion();
  573. // }
  574. // });
  575. //}
  576. - (void)updateLoginInfo:(JDFacadeCompletionCallBackHandler)completion {
  577. NSLog(@"%s\n %@", __PRETTY_FUNCTION__, [JDFacade facade].deviceUUID);
  578. NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID,
  579. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  580. @"os_type": MOBILE_DEVICE_TYPE};
  581. NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];
  582. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  583. LoginModel *loginInfo = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:parameter
  584. modelClass:[LoginModel class] showLoadingView:YES];
  585. if (loginInfo) {
  586. [JDFacade facade].loginUser = loginInfo;
  587. }
  588. if (completion) {
  589. completion();
  590. }
  591. });
  592. }
  593. - (void)updateMainViewController {
  594. [self.mainViewController updateCurrentViewController];
  595. }
  596. - (void)loadURLExternalBrowser:(NSString *)URLString {
  597. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
  598. }
  599. - (void)alertCameraPermissionDisabled {
  600. NSString *message = MSG_CAMERA_DISABLE;
  601. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:message delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  602. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  603. if (buttonIndex == 0) {//OK
  604. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  605. [[UIApplication sharedApplication]openURL:settingsURL];
  606. }
  607. }];
  608. }
  609. #pragma mark - Debug
  610. - (void)showFlex {
  611. #ifndef PRODUCT_MODE
  612. [[FLEXManager sharedManager] showExplorer];
  613. #endif
  614. }
  615. - (BOOL)redirectNSLog {
  616. // Create log file
  617. NSDate *date = [NSDate date];
  618. NSDateFormatter *df = [CommonUtil dateFormatter];
  619. [df setDateFormat:@"yyyyMMddHHmmss"];
  620. NSString *sdate = [df stringFromDate:date];
  621. NSString *logPath = [NSString stringWithFormat:@"%@/log_%@.txt", NSTemporaryDirectory(), sdate];
  622. [@"" writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  623. id fileHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
  624. if (!fileHandle) {
  625. NSLog(@"Opening log failed");
  626. return NO;
  627. }
  628. // Redirect stderr
  629. int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
  630. if (!err) {
  631. NSLog(@"Couldn't redirect stderr");
  632. return NO;
  633. }
  634. return YES;
  635. }
  636. - (void)observeKeyboardRect {
  637. if (CGRectEqualToRect(gKeyboardRect, CGRectZero)) {
  638. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  639. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  640. }
  641. }
  642. - (void)keyboardWillShow:(NSNotification *)notification {
  643. NSDictionary *info = [notification userInfo];
  644. gKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  645. }
  646. - (void)keyboardWillHide:(NSNotification*)notification {
  647. gKeyboardRect = CGRectZero;
  648. }
  649. #pragma mark - Singleton
  650. + (JDFacade *)facade {
  651. static JDFacade *sharedJSFacade = nil;
  652. static dispatch_once_t onceToken;
  653. dispatch_once(&onceToken, ^{
  654. sharedJSFacade = [[self alloc] init];
  655. [sharedJSFacade observeKeyboardRect];
  656. });
  657. return sharedJSFacade;
  658. }
  659. - (id)init {
  660. if (self = [super init]) {
  661. }
  662. return self;
  663. }
  664. -(NSString *)getUrlWithCustID:(NSString *)str aditional:(NSString *)aditional {
  665. NSString *result = @"";
  666. if ([aditional isEmptyString]) {
  667. result = [NSString stringWithFormat:str, _loginUser.custId, aditional];
  668. }
  669. else {
  670. result = [NSString stringWithFormat:str, _loginUser.custId];
  671. }
  672. return result;
  673. }
  674. -(NSString *)getUrlWithCustAndGroupID:(NSString *)str aditional:(NSString *)aditional {
  675. NSString *result = @"";
  676. if ([aditional isEmptyString]) {
  677. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, aditional];
  678. }
  679. else {
  680. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId];
  681. }
  682. return result;
  683. }
  684. -(NSString *)getUrlWithCustGroupIDAndMemberID:(NSString *)str {
  685. return [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, _loginUser.memberId];
  686. }
  687. @end