Advertisement
SweetaAhuja

AppDelegate

Apr 20th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 55.41 KB | None | 0 0
  1. @implementation AppDelegate
  2. {
  3. id _services;
  4. }
  5.  
  6. @synthesize chatServerDelegate;
  7. @synthesize navController;
  8. @synthesize tabBarController;
  9.  
  10. @synthesize xmppStream;
  11. @synthesize xmppReconnect;
  12. @synthesize xmppRoster;
  13. @synthesize xmppRosterStorage;
  14. @synthesize xmppvCardTempModule;
  15. @synthesize xmppvCardAvatarModule;
  16. @synthesize xmppCapabilities;
  17. @synthesize xmppCapabilitiesStorage;
  18. @synthesize xmppLastActivity;
  19. @synthesize xmppMUC;
  20.  
  21. @synthesize hostReach;
  22.  
  23. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  24.  
  25. [GMSServices provideAPIKey:GOOGLE_MAP_API_KEY];
  26. _services = [GMSServices sharedServices];
  27.  
  28. // [ShareObj.sharedDB executeQuery:@"Delete from Groups"];
  29. // [ShareObj.sharedDB executeQuery:@"Delete from Conversation"];
  30. // [ShareObj.sharedDB executeQuery:@"Delete from Message"];
  31.  
  32. {
  33. NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0] stringByAppendingPathComponent:kMediaFolder];
  34.  
  35. BOOL isDir = NO;
  36.  
  37. if(![[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir])
  38. {
  39. NSError *error;
  40.  
  41. if (![[NSFileManager defaultManager] createDirectoryAtPath:dirPath
  42. withIntermediateDirectories:NO
  43. attributes:nil
  44. error:&error])
  45. {
  46. NSLog(@"Create directory error: %@", error);
  47. }
  48. else
  49. {
  50. [Common addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:dirPath] skip:YES];
  51. }
  52. }
  53. }
  54.  
  55.  
  56. // Configure logging framework
  57.  
  58. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  59.  
  60. // Setup the XMPP stream
  61.  
  62. [self setupStream];
  63.  
  64. if (![self connect])
  65. {
  66. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.0 * NSEC_PER_SEC);
  67. dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
  68.  
  69. NSLog(@"Connected...");
  70.  
  71. });
  72. }
  73.  
  74. self.mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
  75.  
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(handleNetworkChange:) name: kReachabilityChangedNotification object: nil];
  77. hostReach = [Reachability reachabilityForInternetConnection];
  78.  
  79. [hostReach startNotifier];
  80.  
  81. NetworkStatus remoteHostStatus = [hostReach currentReachabilityStatus];
  82.  
  83. if(remoteHostStatus == NotReachable)
  84. {
  85. NSLog(@"Internet Disconnected");
  86. ShareObj.isInternetConnected = NO;
  87. }
  88. else if (remoteHostStatus == ReachableViaWiFi)
  89. {
  90. NSLog(@"Connected via WIFI");
  91. ShareObj.isInternetConnected = YES;
  92. }
  93. else if (remoteHostStatus == ReachableViaWWAN)
  94. {
  95. NSLog(@"Connected via WWAN");
  96. ShareObj.isInternetConnected = YES;
  97. }
  98.  
  99. if (![[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]) {
  100.  
  101. if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
  102.  
  103. if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
  104. {
  105. [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
  106. [application registerForRemoteNotifications];
  107. }
  108. }
  109. else
  110. {
  111. [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
  112. }
  113. }
  114. else
  115. {
  116. NSLog(@"device token---%@", [[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]);
  117. [ShareObj setDeviceToken:[[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]];
  118. }
  119.  
  120. if(ShareObj.loginUser.userId > 0)
  121. {
  122. NSLog(@"User Id : %ld",(long)ShareObj.loginUser.userId);
  123. [APP_DELEGATE showTabBarController];
  124. }
  125. else
  126. {
  127. [APP_DELEGATE showNavController];
  128. }
  129.  
  130.  
  131. NSDictionary *pushNotificationPayload = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  132.  
  133. if(pushNotificationPayload)
  134. {
  135. [self performSelector:@selector(handlePushNotification:) withObject:pushNotificationPayload afterDelay:2.0];
  136. }
  137.  
  138.  
  139. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  140.  
  141. return YES;
  142. }
  143.  
  144. #pragma mark-
  145. #pragma mark- MISC
  146.  
  147. -(void)handleNetworkChange:(NSNotification *)notice
  148. {
  149. NetworkStatus remoteHostStatus = [hostReach currentReachabilityStatus];
  150.  
  151. if(remoteHostStatus == NotReachable)
  152. {
  153. [self UpdateOnlineOffline:0];
  154. NSLog(@"Internet Disconnected");
  155. ShareObj.isInternetConnected = NO;
  156. }
  157. else if (remoteHostStatus == ReachableViaWiFi)
  158. {
  159. [self UpdateOnlineOffline:1];
  160. NSLog(@"Connected via WIFI");
  161. ShareObj.isInternetConnected = YES;
  162. }
  163. else if (remoteHostStatus == ReachableViaWWAN)
  164. {
  165. [self UpdateOnlineOffline:1];
  166. NSLog(@"Connected via WWAN");
  167. ShareObj.isInternetConnected = YES;
  168. }
  169. }
  170.  
  171. #pragma mark-
  172. #pragma mark- Navigation Methods
  173.  
  174. - (void)showTabBarController
  175. {
  176. [Common LoadProfileImageAndSaveToLocal];
  177. [self UpdateOnlineOffline:1];
  178.  
  179. self.tabBarController = (TabBarScreen *)[self.mainStoryboard instantiateViewControllerWithIdentifier:@"TabNavigationController"];
  180. [UIView transitionWithView:self.window
  181. duration:0.5
  182. options:UIViewAnimationOptionTransitionCrossDissolve
  183. animations:^(void) {
  184. BOOL oldState = [UIView areAnimationsEnabled];
  185. [UIView setAnimationsEnabled:NO];
  186. [self.window setRootViewController:self.tabBarController];
  187. [UIView setAnimationsEnabled:oldState];
  188. }
  189. completion:^(BOOL finished) {
  190. [ShareObj getCurrentLocation];
  191. }];
  192. }
  193.  
  194. - (void)showNavController
  195. {
  196. self.navController = (UINavigationController *)[self.mainStoryboard instantiateViewControllerWithIdentifier:@"navController"];
  197. ShowHideStatusBarVisible(NO);
  198. [UIView transitionWithView:self.window
  199. duration:0.5
  200. options:UIViewAnimationOptionTransitionCrossDissolve
  201. animations:^(void) {
  202. BOOL oldState = [UIView areAnimationsEnabled];
  203. [UIView setAnimationsEnabled:NO];
  204. [self.window setRootViewController:self.navController];
  205. [UIView setAnimationsEnabled:oldState];
  206. }
  207. completion:^(BOOL finished) {
  208.  
  209. }];
  210. }
  211.  
  212. #pragma mark-
  213. #pragma mark- APNS Metods...
  214.  
  215. -(void)handlePushNotification:(NSDictionary *)pushNotificationPayload
  216. {
  217. [self application:[UIApplication sharedApplication] didReceiveRemoteNotification:pushNotificationPayload];
  218. }
  219.  
  220. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  221. {
  222. NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<> "]];
  223. token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
  224. NSLog(@"device token---%@", token);
  225. [ShareObj setDeviceToken:token];
  226. [[NSUserDefaults standardUserDefaults] setObject:token forKey:kdeviceToken];
  227. [[NSUserDefaults standardUserDefaults] synchronize];
  228. }
  229.  
  230. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  231. {
  232. // NSLog(@"device token failed%s ==> %@",__FUNCTION__,error);
  233. }
  234.  
  235.  
  236. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  237. #pragma mark Core Data
  238. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  239.  
  240. - (NSManagedObjectContext *)managedObjectContext_roster
  241. {
  242. return [xmppRosterStorage mainThreadManagedObjectContext];
  243. }
  244.  
  245. - (NSManagedObjectContext *)managedObjectContext_capabilities
  246. {
  247. return [xmppCapabilitiesStorage mainThreadManagedObjectContext];
  248. }
  249.  
  250. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  251. #pragma mark Private
  252. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  253.  
  254. - (void)setupStream
  255. {
  256. NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
  257.  
  258. // Setup xmpp stream
  259. //
  260. // The XMPPStream is the base class for all activity.
  261. // Everything else plugs into the xmppStream, such as modules/extensions and delegates.
  262.  
  263. xmppStream = [[XMPPStream alloc] init];
  264.  
  265. #if !TARGET_IPHONE_SIMULATOR
  266. {
  267. // Want xmpp to run in the background?
  268. //
  269. // P.S. - The simulator doesn't support backgrounding yet.
  270. // When you try to set the associated property on the simulator, it simply fails.
  271. // And when you background an app on the simulator,
  272. // it just queues network traffic til the app is foregrounded again.
  273. // We are patiently waiting for a fix from Apple.
  274. // If you do enableBackgroundingOnSocket on the simulator,
  275. // you will simply see an error message from the xmpp stack when it fails to set the property.
  276.  
  277. xmppStream.enableBackgroundingOnSocket = YES;
  278. }
  279. #endif
  280.  
  281. // Setup reconnect
  282. //
  283. // The XMPPReconnect module monitors for "accidental disconnections" and
  284. // automatically reconnects the stream for you.
  285. // There's a bunch more information in the XMPPReconnect header file.
  286.  
  287. xmppReconnect = [[XMPPReconnect alloc] init];
  288.  
  289. // Setup roster
  290. //
  291. // The XMPPRoster handles the xmpp protocol stuff related to the roster.
  292. // The storage for the roster is abstracted.
  293. // So you can use any storage mechanism you want.
  294. // You can store it all in memory, or use core data and store it on disk, or use core data with an in-memory store,
  295. // or setup your own using raw SQLite, or create your own storage mechanism.
  296. // You can do it however you like! It's your application.
  297. // But you do need to provide the roster with some storage facility.
  298.  
  299. xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
  300. // xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] initWithInMemoryStore];
  301.  
  302. xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
  303.  
  304. xmppRoster.autoFetchRoster = YES;
  305. xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
  306.  
  307. // Setup vCard support
  308. //
  309. // The vCard Avatar module works in conjuction with the standard vCard Temp module to download user avatars.
  310. // The XMPPRoster will automatically integrate with XMPPvCardAvatarModule to cache roster photos in the roster.
  311.  
  312. xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
  313. xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];
  314.  
  315. xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];
  316.  
  317. // Setup capabilities
  318. //
  319. // The XMPPCapabilities module handles all the complex hashing of the caps protocol (XEP-0115).
  320. // Basically, when other clients broadcast their presence on the network
  321. // they include information about what capabilities their client supports (audio, video, file transfer, etc).
  322. // But as you can imagine, this list starts to get pretty big.
  323. // This is where the hashing stuff comes into play.
  324. // Most people running the same version of the same client are going to have the same list of capabilities.
  325. // So the protocol defines a standardized way to hash the list of capabilities.
  326. // Clients then broadcast the tiny hash instead of the big list.
  327. // The XMPPCapabilities protocol automatically handles figuring out what these hashes mean,
  328. // and also persistently storing the hashes so lookups aren't needed in the future.
  329. //
  330. // Similarly to the roster, the storage of the module is abstracted.
  331. // You are strongly encouraged to persist caps information across sessions.
  332. //
  333. // The XMPPCapabilitiesCoreDataStorage is an ideal solution.
  334. // It can also be shared amongst multiple streams to further reduce hash lookups.
  335.  
  336. xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
  337. xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];
  338.  
  339. xmppCapabilities.autoFetchHashedCapabilities = YES;
  340. xmppCapabilities.autoFetchNonHashedCapabilities = NO;
  341.  
  342. // Activate xmpp modules
  343.  
  344. [xmppReconnect activate:xmppStream];
  345. [xmppRoster activate:xmppStream];
  346. [xmppvCardTempModule activate:xmppStream];
  347. [xmppvCardAvatarModule activate:xmppStream];
  348. [xmppCapabilities activate:xmppStream];
  349.  
  350. // Add ourself as a delegate to anything we may be interested in
  351.  
  352. [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
  353. [xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
  354.  
  355. // Optional:
  356. //
  357. // Replace me with the proper domain and port.
  358. // The example below is setup for a typical google talk account.
  359. //
  360. // If you don't supply a hostName, then it will be automatically resolved using the JID (below).
  361. // For example, if you supply a JID like 'user@quack.com/rsrc'
  362. // then the xmpp framework will follow the xmpp specification, and do a SRV lookup for quack.com.
  363. //
  364. // If you don't specify a hostPort, then the default (5222) will be used.
  365.  
  366. // [xmppStream setHostName:@"talk.google.com"];
  367. // [xmppStream setHostPort:5222];
  368.  
  369.  
  370. // You may need to alter these settings depending on the server you're connecting to
  371. allowSelfSignedCertificates = NO;
  372. allowSSLHostNameMismatch = NO;
  373.  
  374.  
  375. // Last Seen Activity..
  376. xmppLastActivity = [[XMPPLastActivity alloc] initWithDispatchQueue:dispatch_get_main_queue()];
  377. [xmppLastActivity addDelegate:self delegateQueue:dispatch_get_main_queue()];
  378. [xmppLastActivity activate:xmppStream];
  379.  
  380.  
  381. // XMPPMUC..
  382. xmppMUC = [[XMPPMUC alloc] initWithDispatchQueue:dispatch_get_main_queue()];
  383. [xmppMUC addDelegate:self delegateQueue:dispatch_get_main_queue()];
  384. [xmppMUC activate:xmppStream];
  385.  
  386. }
  387.  
  388. - (void)teardownStream
  389. {
  390. [xmppStream removeDelegate:self];
  391. [xmppRoster removeDelegate:self];
  392.  
  393. [xmppReconnect deactivate];
  394. [xmppRoster deactivate];
  395. [xmppvCardTempModule deactivate];
  396. [xmppvCardAvatarModule deactivate];
  397. [xmppCapabilities deactivate];
  398.  
  399. [xmppStream disconnect];
  400.  
  401. xmppStream = nil;
  402. xmppReconnect = nil;
  403. xmppRoster = nil;
  404. xmppRosterStorage = nil;
  405. xmppvCardStorage = nil;
  406. xmppvCardTempModule = nil;
  407. xmppvCardAvatarModule = nil;
  408. xmppCapabilities = nil;
  409. xmppCapabilitiesStorage = nil;
  410. }
  411.  
  412. // It's easy to create XML elments to send and to read received XML elements.
  413. // You have the entire NSXMLElement and NSXMLNode API's.
  414. //
  415. // In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
  416. //
  417. // On the iPhone, Apple chose not to include the full NSXML suite.
  418. // No problem - we use the KissXML library as a drop in replacement.
  419. //
  420. // For more information on working with XML elements, see the Wiki article:
  421. // https://github.com/robbiehanson/XMPPFramework/wiki/WorkingWithElements
  422.  
  423. - (void)goOnline
  424. {
  425. // XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
  426.  
  427. XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"]; // [NSXMLElement elementWithName:@"presence"];
  428. [xmppStream sendElement:presence];
  429.  
  430. {
  431. NSArray *arrGroups = [Groups getAllGroups];
  432.  
  433. for(Groups *objGroup in arrGroups)
  434. {
  435.  
  436. Conversation *objConversation = [Conversation getConversationWithGroup:objGroup];
  437.  
  438. Message *objMessage = [Message getLastMessageForConversation:objConversation];
  439.  
  440.  
  441. NSDateFormatter *df=[[NSDateFormatter alloc] init];
  442. [df setDateFormat:kDefaultDateFormat];
  443. NSDate *date=[df dateFromString:objMessage.msgTime];
  444. [df setDateFormat:kDefaultShortDateFormat];
  445.  
  446. NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
  447. [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // Prevent
  448. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss.sss'Z"];
  449. NSString *hist_date = [dateFormatter stringFromDate:date]; // get your last group date
  450.  
  451. NSXMLElement *history = [NSXMLElement elementWithName:@"history"];
  452. [history addAttributeWithName:@"since" stringValue:hist_date];
  453.  
  454.  
  455. XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
  456. NSLog(@"%@",objGroup.jId);
  457. XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
  458. XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
  459. jid:roomJID
  460. dispatchQueue:dispatch_get_main_queue()];
  461. [xmppRoom activate:self.xmppStream];
  462. [xmppRoom addDelegate:self
  463. delegateQueue:dispatch_get_main_queue()];
  464.  
  465. [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
  466. history:history
  467. password:nil];
  468.  
  469. }
  470. }
  471. }
  472.  
  473. - (void)goOffline
  474. {
  475. XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
  476. [[self xmppStream] sendElement:presence];
  477.  
  478. {
  479. NSArray *arrGroups = [Groups getAllGroups];
  480.  
  481. for(Groups *objGroup in arrGroups)
  482. {
  483. XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
  484. NSLog(@"%@",objGroup.jId);
  485. XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
  486. XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
  487. jid:roomJID
  488. dispatchQueue:dispatch_get_main_queue()];
  489. [xmppRoom leaveRoom];
  490. [xmppRoom deactivate];
  491. [xmppRoom removeDelegate:self];
  492. }
  493. }
  494. }
  495.  
  496. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  497. #pragma mark Connect/disconnect
  498. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  499.  
  500. NSString *const kXMPPmyJID = @"kXMPPmyJID";
  501. NSString *const kXMPPmyPassword = @"kXMPPmyPassword";
  502.  
  503. - (BOOL)connect
  504. {
  505. if(ShareObj.loginUser.userId)
  506. {
  507. if (![xmppStream isDisconnected])
  508. {
  509. return YES;
  510. }
  511.  
  512. NSString *myJID = kOFUser(ShareObj.loginUser.jId);
  513. NSString *myPassword = @"sbahuja_happy";
  514.  
  515. if (myJID == nil || myPassword == nil)
  516. {
  517. return NO;
  518. }
  519.  
  520. [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
  521. password = myPassword;
  522.  
  523.  
  524. NSError *error = nil;
  525. if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
  526. {
  527. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
  528. message:@"See console for error details."
  529. delegate:nil
  530. cancelButtonTitle:@"Ok"
  531. otherButtonTitles:nil];
  532. [alertView show];
  533.  
  534. return NO;
  535. }
  536.  
  537. XMPPMessageDeliveryReceipts* xmppMessageDeliveryRecipts = [[XMPPMessageDeliveryReceipts alloc] initWithDispatchQueue:dispatch_get_main_queue()];
  538. xmppMessageDeliveryRecipts.autoSendMessageDeliveryReceipts = YES;
  539. xmppMessageDeliveryRecipts.autoSendMessageDeliveryRequests = YES;
  540. [xmppMessageDeliveryRecipts activate:self.xmppStream];
  541.  
  542. [self getAllRegisteredUsers];
  543. return YES;
  544.  
  545. }
  546. else
  547. return NO;
  548.  
  549. }
  550.  
  551. - (void)disconnect
  552. {
  553. [self goOffline];
  554. [xmppStream disconnect];
  555. }
  556.  
  557. - (void)getAllRegisteredUsers {
  558.  
  559.  
  560. NSError *error = [[NSError alloc] init];
  561. NSXMLElement *query = [[NSXMLElement alloc] initWithXMLString:@"<query xmlns='http://jabber.org/protocol/disco#items' node='all users'/>"
  562. error:&error];
  563. XMPPIQ *iq = [XMPPIQ iqWithType:@"get"
  564. to:[XMPPJID jidWithString:@"chat.denederlandsewateren.nl"]
  565. elementID:[xmppStream generateUUID] child:query];
  566. [xmppStream sendElement:iq];
  567. }
  568.  
  569. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  570. #pragma mark XMPPStream Delegate
  571. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  572.  
  573. -(void)sendReceiptForReceivedMessage:(Message *)objMessage
  574. to:(NSString *)receiverJId
  575. isGroup:(BOOL)isGroupMessage
  576. {
  577. XMPPJID* recipient = [XMPPJID jidWithString:kOFUser(receiverJId)];
  578.  
  579. XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
  580. [message addAttributeWithName:@"type" stringValue:@"chat"];
  581. [message addAttributeWithName:@"id" stringValue:objMessage.messageId];
  582. [message addDisplayedChatMarkerWithID:objMessage.messageId];
  583. [[APP_DELEGATE xmppStream] sendElement:message];
  584. }
  585.  
  586. -(void)sendReceiptForSeenMessage:(Message *)objMessage
  587. to:(NSString *)receiverJId
  588. isGroup:(BOOL)isGroupMessage
  589. {
  590. XMPPJID* recipient = [XMPPJID jidWithString:kOFUser(receiverJId)];
  591.  
  592. XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
  593. [message addAttributeWithName:@"type" stringValue:@"chat"];
  594. [message addDisplayedChatMarkerWithID:objMessage.messageId];
  595. [[APP_DELEGATE xmppStream] sendElement:message];
  596. }
  597.  
  598.  
  599. -(void)sendGroupMessage:(Message *)objMessage
  600. to:(Groups *)objGroups
  601. {
  602. // Code by sweeta...
  603.  
  604. XMPPJID* recipient = [XMPPJID jidWithString:objGroups.jId];
  605.  
  606. XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"groupchat" to:recipient];
  607. [message addAttributeWithName:@"type" stringValue:@"groupchat"];
  608.  
  609. NSMutableDictionary *msgDic = [[NSMutableDictionary alloc] init];
  610.  
  611. NSMutableDictionary *senderProperty = [[NSMutableDictionary alloc] init];
  612. [senderProperty setObject:objGroups.groupName forKey:kGroupName];
  613. [senderProperty setObject:objGroups.jId forKey:kJId];
  614.  
  615. [msgDic setObject:senderProperty forKey:@"sender"];
  616. [msgDic setObject:[objMessage getDic] forKey:@"message"];
  617.  
  618. NSError *err = nil;
  619.  
  620. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:msgDic options:NSJSONWritingPrettyPrinted error:&err];
  621.  
  622. NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  623. [message addBody:str];
  624.  
  625. XMPPMessage *sent_message = [[XMPPMessage alloc] initWithType:@"groupchat" to:recipient];
  626. [sent_message addAttributeWithName:@"type" stringValue:@"groupchat"];
  627. [sent_message addAttributeWithName:@"to" stringValue:objGroups.jId];
  628. [sent_message addAttributeWithName:@"id" stringValue:objMessage.messageId];
  629. [sent_message addBody:str];
  630.  
  631. // [self.xmppStream sendElement:sent_message];
  632.  
  633. XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
  634.  
  635. XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
  636. jid:recipient
  637. dispatchQueue:dispatch_get_main_queue()];
  638. [xmppRoom changeNickname:objGroups.groupName];
  639. [xmppRoom activate:self.xmppStream];
  640. [xmppRoom addDelegate:self
  641. delegateQueue:dispatch_get_main_queue()];
  642.  
  643. [xmppRoom sendMessage:sent_message];
  644.  
  645. }
  646.  
  647. -(void)sendMessage:(Message *)objMessage
  648. to:(NSString *)receiverJId
  649. isGroup:(BOOL)isGroupMessage
  650. {
  651. XMPPJID* recipient = [XMPPJID jidWithString:receiverJId];
  652.  
  653. XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
  654. [message addAttributeWithName:@"type" stringValue:@"chat"];
  655.  
  656. NSMutableDictionary *msgDic = [[NSMutableDictionary alloc] init];
  657.  
  658. NSMutableDictionary *senderProperty = [[NSMutableDictionary alloc] init];
  659. [senderProperty setObject:[NSString stringWithFormat:@"%@ %@",ShareObj.loginUser.firstName,ShareObj.loginUser.lastName] forKey:kuserName];
  660.  
  661. [senderProperty setObject:[NSString stringWithFormat:@"%ld",(long)ShareObj.loginUser.userId] forKey:kUserId];
  662. [senderProperty setObject:ShareObj.loginUser.mobileNumber forKey:kMobileNumber];
  663.  
  664. [msgDic setObject:senderProperty forKey:@"sender"];
  665. [msgDic setObject:[objMessage getDic] forKey:@"message"];
  666.  
  667. NSError *err = nil;
  668.  
  669. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:msgDic options:NSJSONWritingPrettyPrinted error:&err];
  670.  
  671. NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  672.  
  673. [message addBody:str];
  674.  
  675. // [message addAttributeWithName:@"id" stringValue:objMessage.messageId];
  676. // // User this code to send markable seen message...
  677. // [message addMarkableChatMarker];
  678.  
  679. [[APP_DELEGATE xmppStream] sendElement:message];
  680. }
  681.  
  682. - (NSString *)getLAstSeenDate:(NSInteger)lastSeenSeconds
  683. {
  684. NSDate *today = [[NSDate alloc] init];
  685. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  686. NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
  687.  
  688. [offsetComponents setSecond:-lastSeenSeconds]; // note that I'm setting it to -1
  689.  
  690. NSDate *date = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
  691.  
  692. NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
  693.  
  694. formatter1.timeStyle = NSDateFormatterShortStyle;
  695. formatter1.dateStyle = NSDateFormatterShortStyle;
  696.  
  697. formatter1.doesRelativeDateFormatting = YES;
  698.  
  699. NSString *strLastSeenDateTime = ([formatter1 stringFromDate:date]==nil)?@"offline":[formatter1 stringFromDate:date];
  700.  
  701. return strLastSeenDateTime;
  702. }
  703.  
  704. - (void)xmppLastActivity:(XMPPLastActivity *)sender didReceiveResponse:(XMPPIQ *)response
  705. {
  706.  
  707. NSString *lastSeenFromUser = [[response from] user];
  708.  
  709. if([lastSeenFromUser isEqualToString:@"da4b9237bacccdf19c0760cab7aec4a8359010b0"])
  710. {
  711. NSLog(@"Sweeeee");
  712. }
  713.  
  714. NSInteger lastSeenSeconds = (NSInteger)[response lastActivitySeconds];
  715.  
  716. NSString *strLastSeenDateTime = @"offline";
  717.  
  718. if(lastSeenSeconds != NSNotFound)
  719. {
  720. strLastSeenDateTime = [self getLAstSeenDate:lastSeenSeconds];
  721.  
  722. [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set lastSeenTime = '%@' Where jId Like '%@'",strLastSeenDateTime,lastSeenFromUser]];
  723.  
  724. if(ShareObj.currentConversation)
  725. {
  726. if([[NSString stringWithFormat:@"%ld",ShareObj.currentConversation.userId] isEqualToString:lastSeenFromUser])
  727. {
  728. if([self.chatServerDelegate respondsToSelector:@selector(friendId:lastSeenDate:)])
  729. {
  730. [self.chatServerDelegate friendId:lastSeenFromUser
  731. lastSeenDate:strLastSeenDateTime];
  732. }
  733. }
  734. }
  735. else
  736. {
  737. if([self.chatServerDelegate respondsToSelector:@selector(friendId:lastSeenDate:)])
  738. {
  739. [self.chatServerDelegate friendId:lastSeenFromUser
  740. lastSeenDate:strLastSeenDateTime];
  741. }
  742. }
  743. }
  744. }
  745.  
  746. #pragma mark Groups...
  747.  
  748. - (void)createGroup:(Groups *)objGroup
  749. {
  750. XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
  751.  
  752. XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
  753. XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
  754. jid:roomJID
  755. dispatchQueue:dispatch_get_main_queue()];
  756. [xmppRoom changeNickname:objGroup.groupName];
  757. [xmppRoom activate:self.xmppStream];
  758. [xmppRoom addDelegate:self
  759. delegateQueue:dispatch_get_main_queue()];
  760.  
  761. [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
  762. history:nil
  763. password:nil];
  764.  
  765.  
  766. // NSString *strRoomJId = [[xmppRoom myRoomJID] user];
  767. // NSMutableDictionary *dic = [ShareObj.sharedDB getRecordFromQuery:[NSString stringWithFormat:
  768. // @"Select * from Groups Where jId Like '%@'",kOFGroup(strRoomJId)]];
  769. // Groups *objGroup = [[Groups alloc] initWithObject:dic];
  770.  
  771. if(objGroup.groupOwnerId == ShareObj.loginUser.userId)
  772. {
  773. if(objGroup.groupMembers.length>0)
  774. {
  775. NSArray *arrUsers = [objGroup.groupMembers componentsSeparatedByString:@","];
  776.  
  777. for(NSString *sreMobileNumber in arrUsers)
  778. {
  779. if(![sreMobileNumber isEqualToString:ShareObj.loginUser.mobileNumber])
  780. {
  781. XMPPJID *jId = [XMPPJID jidWithString:kOFUser([sreMobileNumber sha1])];
  782.  
  783. [xmppRoom inviteUser:jId
  784. inGroup:objGroup
  785. withMessage:[NSString stringWithFormat:@"You are added in %@ group.",objGroup.groupName]];
  786. }
  787. }
  788. }
  789. }
  790. }
  791.  
  792. - (void)xmppRoomDidCreate:(XMPPRoom *)sender
  793. {
  794. NSLog(@"Group Created");
  795. }
  796.  
  797. - (void)xmppRoomDidJoin:(XMPPRoom *)sender
  798. {
  799. NSLog(@"xmppRoomDidJoin");
  800. [sender fetchConfigurationForm];
  801. }
  802.  
  803. - (void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
  804. {
  805. //DDLogInfo(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  806.  
  807. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  808.  
  809. // if (check the flag for room and invite) // This has to be done only when we intended
  810. // {
  811. // NSArray* users = list of users we need to invite.
  812. //
  813. // if (users.count > 0)
  814. // {
  815. // for (int i=0; i< users.count; i++)
  816. // {
  817. // NSString *jid = [NSString stringWithFormat:@"%@@xyz.biz", [users objectAtIndex:i]];
  818. // XMPPJID *xmppJID=[XMPPJID jidWithString:jid];
  819. // [sender inviteUser:xmppJID withMessage:@"Join Group."];
  820. // }
  821. // [sender sendMessageWithBody:@"Hi All"];
  822. // }
  823. // }
  824. }
  825.  
  826. - (void)xmppRoomDidLeave:(XMPPRoom *)sender
  827. {
  828. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  829. }
  830.  
  831. - (void)xmppRoomDidDestroy:(XMPPRoom *)sender
  832. {
  833. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  834. }
  835.  
  836. - (void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
  837. {
  838. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  839. }
  840. - (void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
  841. {
  842. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  843. }
  844. - (void)xmppRoom:(XMPPRoom *)sender occupantDidUpdate:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
  845. {
  846. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  847. }
  848.  
  849. /**
  850. * Invoked when a message is received.
  851. * The occupant parameter may be nil if the message came directly from the room, or from a non-occupant.
  852. **/
  853.  
  854. - (void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID
  855. {
  856. NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
  857.  
  858. NSLog(@"%@",[message delayedDeliveryDate]);
  859.  
  860. NSString *messageBody = [message body];
  861.  
  862. NSError *jsonError;
  863. NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
  864. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
  865. options:NSJSONReadingMutableContainers
  866. error:&jsonError];
  867.  
  868. NSMutableDictionary *diccConversation=[json objectForKey:@"sender"];
  869. NSMutableDictionary *diccMsg=[json objectForKey:@"message"];
  870.  
  871. Groups *objGroup = [[Groups alloc] initWithObject:diccConversation];
  872. [objGroup updateInDB];
  873.  
  874. Conversation *objConversation = [Conversation getConversationWithGroup:objGroup];
  875.  
  876. if(objConversation)
  877. {
  878. Message *objMessage = [[Message alloc] initWithObject:diccMsg];
  879. objMessage.conversationId = objConversation.conversationId;
  880. [objMessage setIsMsgRead:0];
  881. [objMessage setMsgStatus:Delivered];
  882. [objMessage updateInDB];
  883. [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
  884.  
  885. if(![objMessage.jId isEqualToString:ShareObj.loginUser.jId])
  886. {
  887. if(ShareObj.currentConversation)
  888. {
  889. if(objConversation.conversationId == ShareObj.currentConversation.conversationId)
  890. {
  891. if([self.chatServerDelegate respondsToSelector:@selector(receivedNewMessage:inConversation:)])
  892. {
  893. [self.chatServerDelegate receivedNewMessage:objMessage inConversation:objConversation];
  894. }
  895. }
  896. }
  897. else
  898. {
  899. [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
  900. object:objConversation];
  901. }
  902.  
  903. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
  904. {
  905.  
  906. }
  907. else
  908. {
  909.  
  910. }
  911. }
  912. }
  913. }
  914.  
  915. - (void)xmppRoom:(XMPPRoom *)sender didFetchConfigurationForm:(NSXMLElement *)configForm
  916. {
  917. NSXMLElement *newConfig = [configForm copy];
  918. NSArray *fields = [newConfig elementsForName:@"field"];
  919.  
  920. for (NSXMLElement *field in fields)
  921. {
  922. NSString *var = [field attributeStringValueForName:@"var"];
  923.  
  924. // Make Room Persistent
  925. if ([var isEqualToString:@"muc#roomconfig_persistentroom"]) {
  926. [field removeChildAtIndex:0];
  927. [field addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];
  928. }
  929. }
  930.  
  931. [sender configureRoomUsingOptions:newConfig];
  932. }
  933.  
  934. - (void)xmppMUC:(XMPPMUC *)sender roomJID:(XMPPJID *) roomJID didReceiveInvitation:(XMPPMessage *)message;
  935. {
  936. NSLog(@"%@",roomJID);
  937.  
  938. NSString *messageBody = [message body];
  939.  
  940. NSError *jsonError;
  941. NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
  942. NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
  943. options:NSJSONReadingMutableContainers
  944. error:&jsonError];
  945.  
  946. Groups *objNewGroup = [[Groups alloc] initWithObject:json];
  947. [objNewGroup updateInDB];
  948.  
  949. NSString *messageFromUser = [[message from] user];
  950.  
  951. Conversation *objConversation = [Conversation getConversationWithGroup:objNewGroup];
  952.  
  953. Message *objMessage = [[Message alloc] init];
  954. objMessage.messageId = [XMPPStream generateUUID];
  955. objMessage.msgType = MsgTypeAlert;
  956. objMessage.jId = messageFromUser;
  957. objMessage.msgContent = [NSString stringWithFormat:@"You are added in %@ Group.",objNewGroup.groupName];
  958. objMessage.conversationId = objConversation.conversationId;
  959. [objMessage setIsMsgRead:0];
  960. [objMessage setMsgStatus:Delivered];
  961. [objMessage updateInDB];
  962. [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
  963.  
  964. [xmppRoster addUser:roomJID withNickname:objNewGroup.groupName];
  965.  
  966. [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
  967. object:objConversation];
  968.  
  969. [self joinMultiUserChatRoom:roomJID];
  970. }
  971.  
  972. - (void) joinMultiUserChatRoom:(XMPPJID *) roomJID
  973. {
  974. XMPPRoomMemoryStorage *roomMemoryStorage = [[XMPPRoomMemoryStorage alloc] init];
  975. XMPPRoom *xmppRoom = [[XMPPRoom alloc]
  976. initWithRoomStorage:roomMemoryStorage
  977. jid:roomJID
  978. dispatchQueue:dispatch_get_main_queue()];
  979.  
  980. [xmppRoom activate:[self xmppStream]];
  981. [xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
  982. [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user history:nil];
  983. }
  984.  
  985. - (void)handlePresence:(XMPPPresence *)presence room:(XMPPRoom *)room;
  986. {
  987. NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
  988. }
  989.  
  990. - (void)handleIncomingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
  991. {
  992. NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
  993. }
  994.  
  995. - (void)handleOutgoingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
  996. {
  997. NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
  998. }
  999.  
  1000. - (void)handleDidLeaveRoom:(XMPPRoom *)room
  1001. {
  1002. NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
  1003. }
  1004. #pragma - - - - -
  1005.  
  1006. - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
  1007. {
  1008. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1009. }
  1010.  
  1011. - (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
  1012. {
  1013. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1014.  
  1015. if (allowSelfSignedCertificates)
  1016. {
  1017. [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
  1018. }
  1019.  
  1020. if (allowSSLHostNameMismatch)
  1021. {
  1022. [settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
  1023. }
  1024. else
  1025. {
  1026. // Google does things incorrectly (does not conform to RFC).
  1027. // Because so many people ask questions about this (assume xmpp framework is broken),
  1028. // I've explicitly added code that shows how other xmpp clients "do the right thing"
  1029. // when connecting to a google server (gmail, or google apps for domains).
  1030.  
  1031. NSString *expectedCertName = nil;
  1032.  
  1033. NSString *serverDomain = xmppStream.hostName;
  1034. NSString *virtualDomain = [xmppStream.myJID domain];
  1035.  
  1036. if ([serverDomain isEqualToString:kOFDomain])
  1037. {
  1038. if ([virtualDomain isEqualToString:kOFDomain])
  1039. {
  1040. expectedCertName = virtualDomain;
  1041. }
  1042. else
  1043. {
  1044. expectedCertName = serverDomain;
  1045. }
  1046. }
  1047. else if (serverDomain == nil)
  1048. {
  1049. expectedCertName = virtualDomain;
  1050. }
  1051. else
  1052. {
  1053. expectedCertName = serverDomain;
  1054. }
  1055.  
  1056. if (expectedCertName)
  1057. {
  1058. [settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
  1059. }
  1060. }
  1061. }
  1062.  
  1063. - (void)xmppStreamDidSecure:(XMPPStream *)sender
  1064. {
  1065. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1066. }
  1067.  
  1068. - (void)xmppStreamDidConnect:(XMPPStream *)sender
  1069. {
  1070. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1071.  
  1072. isXmppConnected = YES;
  1073.  
  1074. NSError *error = nil;
  1075.  
  1076. if (![[self xmppStream] authenticateWithPassword:password error:&error])
  1077. {
  1078. // DDLogError(@"Error authenticating: %@", error);
  1079. }
  1080. }
  1081.  
  1082. - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
  1083. {
  1084. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1085. [self goOnline];
  1086.  
  1087. }
  1088.  
  1089. - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
  1090. {
  1091. NSLog(@"%@",error);
  1092. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1093. }
  1094.  
  1095. - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
  1096. {
  1097. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1098.  
  1099. return NO;
  1100. }
  1101.  
  1102. - (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message
  1103. {
  1104. if([message isChatMessageWithBody]) // New Message...
  1105. {
  1106. NSString *strMessageId = [message receiptResponseID];
  1107.  
  1108. NSLog(@"%@",strMessageId);
  1109.  
  1110. NSInteger status = Success;
  1111.  
  1112. if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
  1113. {
  1114. [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
  1115. }
  1116. else
  1117. {
  1118. [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
  1119. }
  1120. }
  1121. }
  1122. - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
  1123. {
  1124. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1125. // A simple example of inbound message handling.
  1126.  
  1127. if([message hasComposingChatState] || [message hasGoneChatState])
  1128. {
  1129. if(ShareObj.currentConversation && ShareObj.currentConversation.groupId == 0)
  1130. {
  1131. NSString *strJId = ShareObj.currentConversation.jId;
  1132. NSString *messageFromUser = [[message from] user];
  1133.  
  1134. if([strJId isEqualToString:messageFromUser])
  1135. {
  1136. if([self.chatServerDelegate respondsToSelector:@selector(friendId:isTyping:)])
  1137. {
  1138. [self.chatServerDelegate friendId:messageFromUser isTyping:[message hasComposingChatState]];
  1139. }
  1140. }
  1141. }
  1142. }
  1143. else if([message hasActiveChatState])
  1144. {
  1145. NSString *strJId = ShareObj.currentConversation.jId;
  1146. NSString *messageFromUser = [[message from] user];
  1147.  
  1148. if(![ShareObj.arrActiveChatState containsObject:messageFromUser])
  1149. {
  1150. [ShareObj.arrActiveChatState addObject:messageFromUser];
  1151. }
  1152.  
  1153. if(ShareObj.currentConversation)
  1154. {
  1155. if([strJId isEqualToString:messageFromUser])
  1156. {
  1157. if([self.chatServerDelegate respondsToSelector:@selector(chatActiveStatteForfriendId:)])
  1158. {
  1159. [self.chatServerDelegate chatActiveStatteForfriendId:messageFromUser];
  1160. }
  1161. }
  1162. }
  1163. }
  1164. else if([message hasInactiveChatState] || [message hasPausedChatState])
  1165. {
  1166. if(ShareObj.currentConversation)
  1167. {
  1168. NSString *strJId = ShareObj.currentConversation.jId;
  1169. NSString *messageFromUser = [[message from] user];
  1170.  
  1171. if([ShareObj.arrActiveChatState containsObject:messageFromUser])
  1172. {
  1173. [ShareObj.arrActiveChatState removeObject:messageFromUser];
  1174. }
  1175.  
  1176. if([strJId isEqualToString:messageFromUser])
  1177. {
  1178. if([self.chatServerDelegate respondsToSelector:@selector(chatActiveStatteForfriendId:)])
  1179. {
  1180. [self.chatServerDelegate chatActiveStatteForfriendId:messageFromUser];
  1181. }
  1182. }
  1183. }
  1184. }
  1185. else if([message hasReceivedChatMarker]) // Message Received ...
  1186. {
  1187. NSString *strMessageId = [message receiptResponseID];
  1188. NSLog(@"%@",strMessageId);
  1189. }
  1190. else if([message hasDisplayedChatMarker]) // Message Seen ...
  1191. {
  1192. NSString *strMessageId = [message chatMarkerID];
  1193. NSLog(@"%@",strMessageId);
  1194.  
  1195. if(strMessageId)
  1196. {
  1197. NSInteger status = MessageSeen;
  1198.  
  1199. if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
  1200. {
  1201. [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
  1202. }
  1203. else
  1204. {
  1205. [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update Message Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
  1206. }
  1207. }
  1208. }
  1209. else if([message isChatMessageWithBody]) // New Message...
  1210. {
  1211. NSString *messageBody = [message body];
  1212.  
  1213. NSError *jsonError;
  1214. NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
  1215. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
  1216. options:NSJSONReadingMutableContainers
  1217. error:&jsonError];
  1218.  
  1219. NSMutableDictionary *diccConversation=[json objectForKey:@"sender"];
  1220. NSMutableDictionary *diccMsg=[json objectForKey:@"message"];
  1221.  
  1222. Conversation *objConversation;
  1223.  
  1224. if([message isChatMessage])
  1225. {
  1226. User *objUser = [[User alloc] initWithObject:diccConversation];
  1227. objUser.isUsingApp = 1;
  1228. [objUser updateInDB];
  1229.  
  1230. objConversation = [Conversation getConversationWithUser:objUser];
  1231. }
  1232. else if([message isGroupChatMessage])
  1233. {
  1234. Groups *objGroup = [[Groups alloc] initWithObject:diccConversation];
  1235. [objGroup updateInDB];
  1236.  
  1237. objConversation = [Conversation getConversationWithGroup:objGroup];
  1238. }
  1239.  
  1240. if(objConversation)
  1241. {
  1242. Message *objMessage = [[Message alloc] initWithObject:diccMsg];
  1243. objMessage.conversationId = objConversation.conversationId;
  1244. [objMessage setIsMsgRead:0];
  1245. [objMessage setMsgStatus:Delivered];
  1246. [objMessage updateInDB];
  1247. [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
  1248.  
  1249. if(![objMessage.jId isEqualToString:ShareObj.loginUser.jId])
  1250. {
  1251. if(ShareObj.currentConversation)
  1252. {
  1253. if(objConversation.conversationId == ShareObj.currentConversation.conversationId)
  1254. {
  1255. if([self.chatServerDelegate respondsToSelector:@selector(receivedNewMessage:inConversation:)])
  1256. {
  1257. [self.chatServerDelegate receivedNewMessage:objMessage inConversation:objConversation];
  1258. }
  1259. }
  1260. }
  1261. else
  1262. {
  1263. [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
  1264. object:objConversation];
  1265. }
  1266.  
  1267. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
  1268. {
  1269.  
  1270. }
  1271. else
  1272. {
  1273.  
  1274. }
  1275. }
  1276. }
  1277. }
  1278.  
  1279. else if([message hasReceiptResponse]) // Message Delivered ...
  1280. {
  1281. NSString *strMessageId = [message receiptResponseID];
  1282.  
  1283. NSLog(@"%@",strMessageId);
  1284.  
  1285. NSInteger status = Delivered;
  1286.  
  1287. if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
  1288. {
  1289. [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
  1290. }
  1291. else
  1292. {
  1293. [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
  1294. }
  1295. }
  1296. }
  1297.  
  1298. -(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence{
  1299. [sender acceptPresenceSubscriptionRequestFrom:[presence from] andAddToRoster:YES];
  1300. }
  1301.  
  1302. - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
  1303. {
  1304. NSString *presenceType = [presence type]; // online/offline
  1305. NSString *myUsername = [[sender myJID] user];
  1306. NSString *presenceFromUser = [[presence from] user];
  1307.  
  1308. if([presenceType isEqualToString:@"subscribe"])
  1309. {
  1310. [Common LoadProfileImageAndSaveToLocal];
  1311.  
  1312. [self UpdateOnlineOffline:1];
  1313.  
  1314. if(self.tabBarController)
  1315. {
  1316. TabBarScreen *tabScreen = [[self.tabBarController viewControllers] objectAtIndex:0];
  1317. UINavigationController *objNav = [[tabScreen viewControllers] objectAtIndex:0];
  1318. ContactScreen *objContact = [[objNav viewControllers] objectAtIndex:0];
  1319.  
  1320. if(objContact)
  1321. {
  1322. if([objContact respondsToSelector:@selector(friendId:isTyping:)])
  1323. {
  1324.  
  1325. }
  1326. }
  1327. }
  1328.  
  1329. [[self xmppRoster] acceptPresenceSubscriptionRequestFrom:[presence from] andAddToRoster:YES];
  1330. }
  1331. else if (![presenceFromUser isEqualToString:myUsername])
  1332. {
  1333. [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set isOnline = %d Where jId Like '%@'",[presenceType isEqualToString:@"available"]?1:0,presenceFromUser]];
  1334.  
  1335. if(ShareObj.currentConversation)
  1336. {
  1337. NSString *strConversationUserJId = [[NSString stringWithFormat:@"%ld",(long)ShareObj.currentConversation.userId] sha1];
  1338.  
  1339. if([strConversationUserJId isEqualToString:presenceFromUser])
  1340. {
  1341. if([self.chatServerDelegate respondsToSelector:@selector(friendId:GoesOnLineOffLine:)])
  1342. {
  1343. [self.chatServerDelegate friendId:presenceFromUser
  1344. GoesOnLineOffLine:[presenceType isEqualToString:@"available"]?@"Online":@"Offnine"];
  1345. }
  1346. }
  1347. }
  1348. else
  1349. {
  1350. if([self.chatServerDelegate respondsToSelector:@selector(friendId:GoesOnLineOffLine:)])
  1351. {
  1352. [self.chatServerDelegate friendId:presenceFromUser
  1353. GoesOnLineOffLine:[presenceType isEqualToString:@"available"]?@"Online":@"Offnine"];
  1354. }
  1355. }
  1356. }
  1357. }
  1358.  
  1359. - (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
  1360. {
  1361. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1362. }
  1363.  
  1364. - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
  1365. {
  1366. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1367.  
  1368. if (!isXmppConnected)
  1369. {
  1370. // DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
  1371. }
  1372. }
  1373.  
  1374. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1375. #pragma mark XMPPRosterDelegate
  1376. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1377.  
  1378. - (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence
  1379. {
  1380. // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
  1381.  
  1382. XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[presence from]
  1383. xmppStream:xmppStream
  1384. managedObjectContext:[self managedObjectContext_roster]];
  1385.  
  1386. NSString *displayName = [user displayName];
  1387. NSString *jidStrBare = [presence fromStr];
  1388. NSString *body = nil;
  1389.  
  1390. if (![displayName isEqualToString:jidStrBare])
  1391. {
  1392. body = [NSString stringWithFormat:@"Buddy request from %@ <%@>", displayName, jidStrBare];
  1393. }
  1394. else
  1395. {
  1396. body = [NSString stringWithFormat:@"Buddy request from %@", displayName];
  1397. }
  1398.  
  1399. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
  1400. {
  1401. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
  1402. message:body
  1403. delegate:nil
  1404. cancelButtonTitle:@"Not implemented"
  1405. otherButtonTitles:nil];
  1406. [alertView show];
  1407. }
  1408. else
  1409. {
  1410. // We are not active, so use a local notification instead
  1411. UILocalNotification *localNotification = [[UILocalNotification alloc] init];
  1412. localNotification.alertAction = @"Not implemented";
  1413. localNotification.alertBody = body;
  1414.  
  1415. [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
  1416. }
  1417.  
  1418. }
  1419.  
  1420. - (void)applicationWillResignActive:(UIApplication *)application {
  1421.  
  1422. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  1423. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  1424. }
  1425.  
  1426. - (void)applicationDidEnterBackground:(UIApplication *)application {
  1427.  
  1428. [self goOffline];
  1429.  
  1430. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  1431. }
  1432.  
  1433.  
  1434. - (void)applicationDidEnterForeground:(UIApplication *)application
  1435. {
  1436. // [self goOnline];
  1437. }
  1438.  
  1439. - (void)applicationWillEnterForeground:(UIApplication *)application {
  1440.  
  1441. [self goOnline];
  1442. }
  1443.  
  1444. - (void)appStart
  1445. {
  1446. [self ResetBadgeCount];
  1447. [self checkLoginDevice];
  1448. }
  1449.  
  1450. - (void)applicationDidBecomeActive:(UIApplication *)application {
  1451. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  1452. }
  1453.  
  1454.  
  1455. - (void)applicationWillTerminate:(UIApplication *)application {
  1456.  
  1457. }
  1458.  
  1459. -(void)HandleCrash
  1460. {
  1461.  
  1462. }
  1463.  
  1464. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement