Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @implementation AppDelegate
- {
- id _services;
- }
- @synthesize chatServerDelegate;
- @synthesize navController;
- @synthesize tabBarController;
- @synthesize xmppStream;
- @synthesize xmppReconnect;
- @synthesize xmppRoster;
- @synthesize xmppRosterStorage;
- @synthesize xmppvCardTempModule;
- @synthesize xmppvCardAvatarModule;
- @synthesize xmppCapabilities;
- @synthesize xmppCapabilitiesStorage;
- @synthesize xmppLastActivity;
- @synthesize xmppMUC;
- @synthesize hostReach;
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- [GMSServices provideAPIKey:GOOGLE_MAP_API_KEY];
- _services = [GMSServices sharedServices];
- // [ShareObj.sharedDB executeQuery:@"Delete from Groups"];
- // [ShareObj.sharedDB executeQuery:@"Delete from Conversation"];
- // [ShareObj.sharedDB executeQuery:@"Delete from Message"];
- {
- NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0] stringByAppendingPathComponent:kMediaFolder];
- BOOL isDir = NO;
- if(![[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir])
- {
- NSError *error;
- if (![[NSFileManager defaultManager] createDirectoryAtPath:dirPath
- withIntermediateDirectories:NO
- attributes:nil
- error:&error])
- {
- NSLog(@"Create directory error: %@", error);
- }
- else
- {
- [Common addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:dirPath] skip:YES];
- }
- }
- }
- // Configure logging framework
- [DDLog addLogger:[DDTTYLogger sharedInstance]];
- // Setup the XMPP stream
- [self setupStream];
- if (![self connect])
- {
- dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.0 * NSEC_PER_SEC);
- dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
- NSLog(@"Connected...");
- });
- }
- self.mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(handleNetworkChange:) name: kReachabilityChangedNotification object: nil];
- hostReach = [Reachability reachabilityForInternetConnection];
- [hostReach startNotifier];
- NetworkStatus remoteHostStatus = [hostReach currentReachabilityStatus];
- if(remoteHostStatus == NotReachable)
- {
- NSLog(@"Internet Disconnected");
- ShareObj.isInternetConnected = NO;
- }
- else if (remoteHostStatus == ReachableViaWiFi)
- {
- NSLog(@"Connected via WIFI");
- ShareObj.isInternetConnected = YES;
- }
- else if (remoteHostStatus == ReachableViaWWAN)
- {
- NSLog(@"Connected via WWAN");
- ShareObj.isInternetConnected = YES;
- }
- if (![[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]) {
- if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
- if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
- {
- [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
- [application registerForRemoteNotifications];
- }
- }
- else
- {
- [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
- }
- }
- else
- {
- NSLog(@"device token---%@", [[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]);
- [ShareObj setDeviceToken:[[NSUserDefaults standardUserDefaults] objectForKey:kdeviceToken]];
- }
- if(ShareObj.loginUser.userId > 0)
- {
- NSLog(@"User Id : %ld",(long)ShareObj.loginUser.userId);
- [APP_DELEGATE showTabBarController];
- }
- else
- {
- [APP_DELEGATE showNavController];
- }
- NSDictionary *pushNotificationPayload = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
- if(pushNotificationPayload)
- {
- [self performSelector:@selector(handlePushNotification:) withObject:pushNotificationPayload afterDelay:2.0];
- }
- [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
- return YES;
- }
- #pragma mark-
- #pragma mark- MISC
- -(void)handleNetworkChange:(NSNotification *)notice
- {
- NetworkStatus remoteHostStatus = [hostReach currentReachabilityStatus];
- if(remoteHostStatus == NotReachable)
- {
- [self UpdateOnlineOffline:0];
- NSLog(@"Internet Disconnected");
- ShareObj.isInternetConnected = NO;
- }
- else if (remoteHostStatus == ReachableViaWiFi)
- {
- [self UpdateOnlineOffline:1];
- NSLog(@"Connected via WIFI");
- ShareObj.isInternetConnected = YES;
- }
- else if (remoteHostStatus == ReachableViaWWAN)
- {
- [self UpdateOnlineOffline:1];
- NSLog(@"Connected via WWAN");
- ShareObj.isInternetConnected = YES;
- }
- }
- #pragma mark-
- #pragma mark- Navigation Methods
- - (void)showTabBarController
- {
- [Common LoadProfileImageAndSaveToLocal];
- [self UpdateOnlineOffline:1];
- self.tabBarController = (TabBarScreen *)[self.mainStoryboard instantiateViewControllerWithIdentifier:@"TabNavigationController"];
- [UIView transitionWithView:self.window
- duration:0.5
- options:UIViewAnimationOptionTransitionCrossDissolve
- animations:^(void) {
- BOOL oldState = [UIView areAnimationsEnabled];
- [UIView setAnimationsEnabled:NO];
- [self.window setRootViewController:self.tabBarController];
- [UIView setAnimationsEnabled:oldState];
- }
- completion:^(BOOL finished) {
- [ShareObj getCurrentLocation];
- }];
- }
- - (void)showNavController
- {
- self.navController = (UINavigationController *)[self.mainStoryboard instantiateViewControllerWithIdentifier:@"navController"];
- ShowHideStatusBarVisible(NO);
- [UIView transitionWithView:self.window
- duration:0.5
- options:UIViewAnimationOptionTransitionCrossDissolve
- animations:^(void) {
- BOOL oldState = [UIView areAnimationsEnabled];
- [UIView setAnimationsEnabled:NO];
- [self.window setRootViewController:self.navController];
- [UIView setAnimationsEnabled:oldState];
- }
- completion:^(BOOL finished) {
- }];
- }
- #pragma mark-
- #pragma mark- APNS Metods...
- -(void)handlePushNotification:(NSDictionary *)pushNotificationPayload
- {
- [self application:[UIApplication sharedApplication] didReceiveRemoteNotification:pushNotificationPayload];
- }
- - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
- {
- NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<> "]];
- token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
- NSLog(@"device token---%@", token);
- [ShareObj setDeviceToken:token];
- [[NSUserDefaults standardUserDefaults] setObject:token forKey:kdeviceToken];
- [[NSUserDefaults standardUserDefaults] synchronize];
- }
- - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
- {
- // NSLog(@"device token failed%s ==> %@",__FUNCTION__,error);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Core Data
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (NSManagedObjectContext *)managedObjectContext_roster
- {
- return [xmppRosterStorage mainThreadManagedObjectContext];
- }
- - (NSManagedObjectContext *)managedObjectContext_capabilities
- {
- return [xmppCapabilitiesStorage mainThreadManagedObjectContext];
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Private
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (void)setupStream
- {
- NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
- // Setup xmpp stream
- //
- // The XMPPStream is the base class for all activity.
- // Everything else plugs into the xmppStream, such as modules/extensions and delegates.
- xmppStream = [[XMPPStream alloc] init];
- #if !TARGET_IPHONE_SIMULATOR
- {
- // Want xmpp to run in the background?
- //
- // P.S. - The simulator doesn't support backgrounding yet.
- // When you try to set the associated property on the simulator, it simply fails.
- // And when you background an app on the simulator,
- // it just queues network traffic til the app is foregrounded again.
- // We are patiently waiting for a fix from Apple.
- // If you do enableBackgroundingOnSocket on the simulator,
- // you will simply see an error message from the xmpp stack when it fails to set the property.
- xmppStream.enableBackgroundingOnSocket = YES;
- }
- #endif
- // Setup reconnect
- //
- // The XMPPReconnect module monitors for "accidental disconnections" and
- // automatically reconnects the stream for you.
- // There's a bunch more information in the XMPPReconnect header file.
- xmppReconnect = [[XMPPReconnect alloc] init];
- // Setup roster
- //
- // The XMPPRoster handles the xmpp protocol stuff related to the roster.
- // The storage for the roster is abstracted.
- // So you can use any storage mechanism you want.
- // 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,
- // or setup your own using raw SQLite, or create your own storage mechanism.
- // You can do it however you like! It's your application.
- // But you do need to provide the roster with some storage facility.
- xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
- // xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] initWithInMemoryStore];
- xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
- xmppRoster.autoFetchRoster = YES;
- xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
- // Setup vCard support
- //
- // The vCard Avatar module works in conjuction with the standard vCard Temp module to download user avatars.
- // The XMPPRoster will automatically integrate with XMPPvCardAvatarModule to cache roster photos in the roster.
- xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
- xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];
- xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];
- // Setup capabilities
- //
- // The XMPPCapabilities module handles all the complex hashing of the caps protocol (XEP-0115).
- // Basically, when other clients broadcast their presence on the network
- // they include information about what capabilities their client supports (audio, video, file transfer, etc).
- // But as you can imagine, this list starts to get pretty big.
- // This is where the hashing stuff comes into play.
- // Most people running the same version of the same client are going to have the same list of capabilities.
- // So the protocol defines a standardized way to hash the list of capabilities.
- // Clients then broadcast the tiny hash instead of the big list.
- // The XMPPCapabilities protocol automatically handles figuring out what these hashes mean,
- // and also persistently storing the hashes so lookups aren't needed in the future.
- //
- // Similarly to the roster, the storage of the module is abstracted.
- // You are strongly encouraged to persist caps information across sessions.
- //
- // The XMPPCapabilitiesCoreDataStorage is an ideal solution.
- // It can also be shared amongst multiple streams to further reduce hash lookups.
- xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
- xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];
- xmppCapabilities.autoFetchHashedCapabilities = YES;
- xmppCapabilities.autoFetchNonHashedCapabilities = NO;
- // Activate xmpp modules
- [xmppReconnect activate:xmppStream];
- [xmppRoster activate:xmppStream];
- [xmppvCardTempModule activate:xmppStream];
- [xmppvCardAvatarModule activate:xmppStream];
- [xmppCapabilities activate:xmppStream];
- // Add ourself as a delegate to anything we may be interested in
- [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
- [xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
- // Optional:
- //
- // Replace me with the proper domain and port.
- // The example below is setup for a typical google talk account.
- //
- // If you don't supply a hostName, then it will be automatically resolved using the JID (below).
- // For example, if you supply a JID like 'user@quack.com/rsrc'
- // then the xmpp framework will follow the xmpp specification, and do a SRV lookup for quack.com.
- //
- // If you don't specify a hostPort, then the default (5222) will be used.
- // [xmppStream setHostName:@"talk.google.com"];
- // [xmppStream setHostPort:5222];
- // You may need to alter these settings depending on the server you're connecting to
- allowSelfSignedCertificates = NO;
- allowSSLHostNameMismatch = NO;
- // Last Seen Activity..
- xmppLastActivity = [[XMPPLastActivity alloc] initWithDispatchQueue:dispatch_get_main_queue()];
- [xmppLastActivity addDelegate:self delegateQueue:dispatch_get_main_queue()];
- [xmppLastActivity activate:xmppStream];
- // XMPPMUC..
- xmppMUC = [[XMPPMUC alloc] initWithDispatchQueue:dispatch_get_main_queue()];
- [xmppMUC addDelegate:self delegateQueue:dispatch_get_main_queue()];
- [xmppMUC activate:xmppStream];
- }
- - (void)teardownStream
- {
- [xmppStream removeDelegate:self];
- [xmppRoster removeDelegate:self];
- [xmppReconnect deactivate];
- [xmppRoster deactivate];
- [xmppvCardTempModule deactivate];
- [xmppvCardAvatarModule deactivate];
- [xmppCapabilities deactivate];
- [xmppStream disconnect];
- xmppStream = nil;
- xmppReconnect = nil;
- xmppRoster = nil;
- xmppRosterStorage = nil;
- xmppvCardStorage = nil;
- xmppvCardTempModule = nil;
- xmppvCardAvatarModule = nil;
- xmppCapabilities = nil;
- xmppCapabilitiesStorage = nil;
- }
- // It's easy to create XML elments to send and to read received XML elements.
- // You have the entire NSXMLElement and NSXMLNode API's.
- //
- // In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
- //
- // On the iPhone, Apple chose not to include the full NSXML suite.
- // No problem - we use the KissXML library as a drop in replacement.
- //
- // For more information on working with XML elements, see the Wiki article:
- // https://github.com/robbiehanson/XMPPFramework/wiki/WorkingWithElements
- - (void)goOnline
- {
- // XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
- XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"]; // [NSXMLElement elementWithName:@"presence"];
- [xmppStream sendElement:presence];
- {
- NSArray *arrGroups = [Groups getAllGroups];
- for(Groups *objGroup in arrGroups)
- {
- Conversation *objConversation = [Conversation getConversationWithGroup:objGroup];
- Message *objMessage = [Message getLastMessageForConversation:objConversation];
- NSDateFormatter *df=[[NSDateFormatter alloc] init];
- [df setDateFormat:kDefaultDateFormat];
- NSDate *date=[df dateFromString:objMessage.msgTime];
- [df setDateFormat:kDefaultShortDateFormat];
- NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // Prevent
- [dateFormatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss.sss'Z"];
- NSString *hist_date = [dateFormatter stringFromDate:date]; // get your last group date
- NSXMLElement *history = [NSXMLElement elementWithName:@"history"];
- [history addAttributeWithName:@"since" stringValue:hist_date];
- XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
- NSLog(@"%@",objGroup.jId);
- XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
- XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
- jid:roomJID
- dispatchQueue:dispatch_get_main_queue()];
- [xmppRoom activate:self.xmppStream];
- [xmppRoom addDelegate:self
- delegateQueue:dispatch_get_main_queue()];
- [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
- history:history
- password:nil];
- }
- }
- }
- - (void)goOffline
- {
- XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
- [[self xmppStream] sendElement:presence];
- {
- NSArray *arrGroups = [Groups getAllGroups];
- for(Groups *objGroup in arrGroups)
- {
- XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
- NSLog(@"%@",objGroup.jId);
- XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
- XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
- jid:roomJID
- dispatchQueue:dispatch_get_main_queue()];
- [xmppRoom leaveRoom];
- [xmppRoom deactivate];
- [xmppRoom removeDelegate:self];
- }
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Connect/disconnect
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- NSString *const kXMPPmyJID = @"kXMPPmyJID";
- NSString *const kXMPPmyPassword = @"kXMPPmyPassword";
- - (BOOL)connect
- {
- if(ShareObj.loginUser.userId)
- {
- if (![xmppStream isDisconnected])
- {
- return YES;
- }
- NSString *myJID = kOFUser(ShareObj.loginUser.jId);
- NSString *myPassword = @"sbahuja_happy";
- if (myJID == nil || myPassword == nil)
- {
- return NO;
- }
- [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
- password = myPassword;
- NSError *error = nil;
- if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
- {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
- message:@"See console for error details."
- delegate:nil
- cancelButtonTitle:@"Ok"
- otherButtonTitles:nil];
- [alertView show];
- return NO;
- }
- XMPPMessageDeliveryReceipts* xmppMessageDeliveryRecipts = [[XMPPMessageDeliveryReceipts alloc] initWithDispatchQueue:dispatch_get_main_queue()];
- xmppMessageDeliveryRecipts.autoSendMessageDeliveryReceipts = YES;
- xmppMessageDeliveryRecipts.autoSendMessageDeliveryRequests = YES;
- [xmppMessageDeliveryRecipts activate:self.xmppStream];
- [self getAllRegisteredUsers];
- return YES;
- }
- else
- return NO;
- }
- - (void)disconnect
- {
- [self goOffline];
- [xmppStream disconnect];
- }
- - (void)getAllRegisteredUsers {
- NSError *error = [[NSError alloc] init];
- NSXMLElement *query = [[NSXMLElement alloc] initWithXMLString:@"<query xmlns='http://jabber.org/protocol/disco#items' node='all users'/>"
- error:&error];
- XMPPIQ *iq = [XMPPIQ iqWithType:@"get"
- to:[XMPPJID jidWithString:@"chat.denederlandsewateren.nl"]
- elementID:[xmppStream generateUUID] child:query];
- [xmppStream sendElement:iq];
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark XMPPStream Delegate
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- -(void)sendReceiptForReceivedMessage:(Message *)objMessage
- to:(NSString *)receiverJId
- isGroup:(BOOL)isGroupMessage
- {
- XMPPJID* recipient = [XMPPJID jidWithString:kOFUser(receiverJId)];
- XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
- [message addAttributeWithName:@"type" stringValue:@"chat"];
- [message addAttributeWithName:@"id" stringValue:objMessage.messageId];
- [message addDisplayedChatMarkerWithID:objMessage.messageId];
- [[APP_DELEGATE xmppStream] sendElement:message];
- }
- -(void)sendReceiptForSeenMessage:(Message *)objMessage
- to:(NSString *)receiverJId
- isGroup:(BOOL)isGroupMessage
- {
- XMPPJID* recipient = [XMPPJID jidWithString:kOFUser(receiverJId)];
- XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
- [message addAttributeWithName:@"type" stringValue:@"chat"];
- [message addDisplayedChatMarkerWithID:objMessage.messageId];
- [[APP_DELEGATE xmppStream] sendElement:message];
- }
- -(void)sendGroupMessage:(Message *)objMessage
- to:(Groups *)objGroups
- {
- // Code by sweeta...
- XMPPJID* recipient = [XMPPJID jidWithString:objGroups.jId];
- XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"groupchat" to:recipient];
- [message addAttributeWithName:@"type" stringValue:@"groupchat"];
- NSMutableDictionary *msgDic = [[NSMutableDictionary alloc] init];
- NSMutableDictionary *senderProperty = [[NSMutableDictionary alloc] init];
- [senderProperty setObject:objGroups.groupName forKey:kGroupName];
- [senderProperty setObject:objGroups.jId forKey:kJId];
- [msgDic setObject:senderProperty forKey:@"sender"];
- [msgDic setObject:[objMessage getDic] forKey:@"message"];
- NSError *err = nil;
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:msgDic options:NSJSONWritingPrettyPrinted error:&err];
- NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
- [message addBody:str];
- XMPPMessage *sent_message = [[XMPPMessage alloc] initWithType:@"groupchat" to:recipient];
- [sent_message addAttributeWithName:@"type" stringValue:@"groupchat"];
- [sent_message addAttributeWithName:@"to" stringValue:objGroups.jId];
- [sent_message addAttributeWithName:@"id" stringValue:objMessage.messageId];
- [sent_message addBody:str];
- // [self.xmppStream sendElement:sent_message];
- XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
- XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
- jid:recipient
- dispatchQueue:dispatch_get_main_queue()];
- [xmppRoom changeNickname:objGroups.groupName];
- [xmppRoom activate:self.xmppStream];
- [xmppRoom addDelegate:self
- delegateQueue:dispatch_get_main_queue()];
- [xmppRoom sendMessage:sent_message];
- }
- -(void)sendMessage:(Message *)objMessage
- to:(NSString *)receiverJId
- isGroup:(BOOL)isGroupMessage
- {
- XMPPJID* recipient = [XMPPJID jidWithString:receiverJId];
- XMPPMessage* message = [[XMPPMessage alloc] initWithType:@"chat" to:recipient];
- [message addAttributeWithName:@"type" stringValue:@"chat"];
- NSMutableDictionary *msgDic = [[NSMutableDictionary alloc] init];
- NSMutableDictionary *senderProperty = [[NSMutableDictionary alloc] init];
- [senderProperty setObject:[NSString stringWithFormat:@"%@ %@",ShareObj.loginUser.firstName,ShareObj.loginUser.lastName] forKey:kuserName];
- [senderProperty setObject:[NSString stringWithFormat:@"%ld",(long)ShareObj.loginUser.userId] forKey:kUserId];
- [senderProperty setObject:ShareObj.loginUser.mobileNumber forKey:kMobileNumber];
- [msgDic setObject:senderProperty forKey:@"sender"];
- [msgDic setObject:[objMessage getDic] forKey:@"message"];
- NSError *err = nil;
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:msgDic options:NSJSONWritingPrettyPrinted error:&err];
- NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
- [message addBody:str];
- // [message addAttributeWithName:@"id" stringValue:objMessage.messageId];
- // // User this code to send markable seen message...
- // [message addMarkableChatMarker];
- [[APP_DELEGATE xmppStream] sendElement:message];
- }
- - (NSString *)getLAstSeenDate:(NSInteger)lastSeenSeconds
- {
- NSDate *today = [[NSDate alloc] init];
- NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
- NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
- [offsetComponents setSecond:-lastSeenSeconds]; // note that I'm setting it to -1
- NSDate *date = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
- NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
- formatter1.timeStyle = NSDateFormatterShortStyle;
- formatter1.dateStyle = NSDateFormatterShortStyle;
- formatter1.doesRelativeDateFormatting = YES;
- NSString *strLastSeenDateTime = ([formatter1 stringFromDate:date]==nil)?@"offline":[formatter1 stringFromDate:date];
- return strLastSeenDateTime;
- }
- - (void)xmppLastActivity:(XMPPLastActivity *)sender didReceiveResponse:(XMPPIQ *)response
- {
- NSString *lastSeenFromUser = [[response from] user];
- if([lastSeenFromUser isEqualToString:@"da4b9237bacccdf19c0760cab7aec4a8359010b0"])
- {
- NSLog(@"Sweeeee");
- }
- NSInteger lastSeenSeconds = (NSInteger)[response lastActivitySeconds];
- NSString *strLastSeenDateTime = @"offline";
- if(lastSeenSeconds != NSNotFound)
- {
- strLastSeenDateTime = [self getLAstSeenDate:lastSeenSeconds];
- [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set lastSeenTime = '%@' Where jId Like '%@'",strLastSeenDateTime,lastSeenFromUser]];
- if(ShareObj.currentConversation)
- {
- if([[NSString stringWithFormat:@"%ld",ShareObj.currentConversation.userId] isEqualToString:lastSeenFromUser])
- {
- if([self.chatServerDelegate respondsToSelector:@selector(friendId:lastSeenDate:)])
- {
- [self.chatServerDelegate friendId:lastSeenFromUser
- lastSeenDate:strLastSeenDateTime];
- }
- }
- }
- else
- {
- if([self.chatServerDelegate respondsToSelector:@selector(friendId:lastSeenDate:)])
- {
- [self.chatServerDelegate friendId:lastSeenFromUser
- lastSeenDate:strLastSeenDateTime];
- }
- }
- }
- }
- #pragma mark Groups...
- - (void)createGroup:(Groups *)objGroup
- {
- XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
- XMPPJID *roomJID = [XMPPJID jidWithString:objGroup.jId];
- XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
- jid:roomJID
- dispatchQueue:dispatch_get_main_queue()];
- [xmppRoom changeNickname:objGroup.groupName];
- [xmppRoom activate:self.xmppStream];
- [xmppRoom addDelegate:self
- delegateQueue:dispatch_get_main_queue()];
- [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
- history:nil
- password:nil];
- // NSString *strRoomJId = [[xmppRoom myRoomJID] user];
- // NSMutableDictionary *dic = [ShareObj.sharedDB getRecordFromQuery:[NSString stringWithFormat:
- // @"Select * from Groups Where jId Like '%@'",kOFGroup(strRoomJId)]];
- // Groups *objGroup = [[Groups alloc] initWithObject:dic];
- if(objGroup.groupOwnerId == ShareObj.loginUser.userId)
- {
- if(objGroup.groupMembers.length>0)
- {
- NSArray *arrUsers = [objGroup.groupMembers componentsSeparatedByString:@","];
- for(NSString *sreMobileNumber in arrUsers)
- {
- if(![sreMobileNumber isEqualToString:ShareObj.loginUser.mobileNumber])
- {
- XMPPJID *jId = [XMPPJID jidWithString:kOFUser([sreMobileNumber sha1])];
- [xmppRoom inviteUser:jId
- inGroup:objGroup
- withMessage:[NSString stringWithFormat:@"You are added in %@ group.",objGroup.groupName]];
- }
- }
- }
- }
- }
- - (void)xmppRoomDidCreate:(XMPPRoom *)sender
- {
- NSLog(@"Group Created");
- }
- - (void)xmppRoomDidJoin:(XMPPRoom *)sender
- {
- NSLog(@"xmppRoomDidJoin");
- [sender fetchConfigurationForm];
- }
- - (void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
- {
- //DDLogInfo(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- // if (check the flag for room and invite) // This has to be done only when we intended
- // {
- // NSArray* users = list of users we need to invite.
- //
- // if (users.count > 0)
- // {
- // for (int i=0; i< users.count; i++)
- // {
- // NSString *jid = [NSString stringWithFormat:@"%@@xyz.biz", [users objectAtIndex:i]];
- // XMPPJID *xmppJID=[XMPPJID jidWithString:jid];
- // [sender inviteUser:xmppJID withMessage:@"Join Group."];
- // }
- // [sender sendMessageWithBody:@"Hi All"];
- // }
- // }
- }
- - (void)xmppRoomDidLeave:(XMPPRoom *)sender
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- }
- - (void)xmppRoomDidDestroy:(XMPPRoom *)sender
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- }
- - (void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- }
- - (void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- }
- - (void)xmppRoom:(XMPPRoom *)sender occupantDidUpdate:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- }
- /**
- * Invoked when a message is received.
- * The occupant parameter may be nil if the message came directly from the room, or from a non-occupant.
- **/
- - (void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID
- {
- NSLog(@"%@: %@ --- %@", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
- NSLog(@"%@",[message delayedDeliveryDate]);
- NSString *messageBody = [message body];
- NSError *jsonError;
- NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
- options:NSJSONReadingMutableContainers
- error:&jsonError];
- NSMutableDictionary *diccConversation=[json objectForKey:@"sender"];
- NSMutableDictionary *diccMsg=[json objectForKey:@"message"];
- Groups *objGroup = [[Groups alloc] initWithObject:diccConversation];
- [objGroup updateInDB];
- Conversation *objConversation = [Conversation getConversationWithGroup:objGroup];
- if(objConversation)
- {
- Message *objMessage = [[Message alloc] initWithObject:diccMsg];
- objMessage.conversationId = objConversation.conversationId;
- [objMessage setIsMsgRead:0];
- [objMessage setMsgStatus:Delivered];
- [objMessage updateInDB];
- [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
- if(![objMessage.jId isEqualToString:ShareObj.loginUser.jId])
- {
- if(ShareObj.currentConversation)
- {
- if(objConversation.conversationId == ShareObj.currentConversation.conversationId)
- {
- if([self.chatServerDelegate respondsToSelector:@selector(receivedNewMessage:inConversation:)])
- {
- [self.chatServerDelegate receivedNewMessage:objMessage inConversation:objConversation];
- }
- }
- }
- else
- {
- [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
- object:objConversation];
- }
- if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
- {
- }
- else
- {
- }
- }
- }
- }
- - (void)xmppRoom:(XMPPRoom *)sender didFetchConfigurationForm:(NSXMLElement *)configForm
- {
- NSXMLElement *newConfig = [configForm copy];
- NSArray *fields = [newConfig elementsForName:@"field"];
- for (NSXMLElement *field in fields)
- {
- NSString *var = [field attributeStringValueForName:@"var"];
- // Make Room Persistent
- if ([var isEqualToString:@"muc#roomconfig_persistentroom"]) {
- [field removeChildAtIndex:0];
- [field addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];
- }
- }
- [sender configureRoomUsingOptions:newConfig];
- }
- - (void)xmppMUC:(XMPPMUC *)sender roomJID:(XMPPJID *) roomJID didReceiveInvitation:(XMPPMessage *)message;
- {
- NSLog(@"%@",roomJID);
- NSString *messageBody = [message body];
- NSError *jsonError;
- NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
- NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
- options:NSJSONReadingMutableContainers
- error:&jsonError];
- Groups *objNewGroup = [[Groups alloc] initWithObject:json];
- [objNewGroup updateInDB];
- NSString *messageFromUser = [[message from] user];
- Conversation *objConversation = [Conversation getConversationWithGroup:objNewGroup];
- Message *objMessage = [[Message alloc] init];
- objMessage.messageId = [XMPPStream generateUUID];
- objMessage.msgType = MsgTypeAlert;
- objMessage.jId = messageFromUser;
- objMessage.msgContent = [NSString stringWithFormat:@"You are added in %@ Group.",objNewGroup.groupName];
- objMessage.conversationId = objConversation.conversationId;
- [objMessage setIsMsgRead:0];
- [objMessage setMsgStatus:Delivered];
- [objMessage updateInDB];
- [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
- [xmppRoster addUser:roomJID withNickname:objNewGroup.groupName];
- [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
- object:objConversation];
- [self joinMultiUserChatRoom:roomJID];
- }
- - (void) joinMultiUserChatRoom:(XMPPJID *) roomJID
- {
- XMPPRoomMemoryStorage *roomMemoryStorage = [[XMPPRoomMemoryStorage alloc] init];
- XMPPRoom *xmppRoom = [[XMPPRoom alloc]
- initWithRoomStorage:roomMemoryStorage
- jid:roomJID
- dispatchQueue:dispatch_get_main_queue()];
- [xmppRoom activate:[self xmppStream]];
- [xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
- [xmppRoom joinRoomUsingNickname:xmppStream.myJID.user history:nil];
- }
- - (void)handlePresence:(XMPPPresence *)presence room:(XMPPRoom *)room;
- {
- NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)handleIncomingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
- {
- NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)handleOutgoingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
- {
- NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)handleDidLeaveRoom:(XMPPRoom *)room
- {
- NSLog(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- #pragma - - - - -
- - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- if (allowSelfSignedCertificates)
- {
- [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
- }
- if (allowSSLHostNameMismatch)
- {
- [settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
- }
- else
- {
- // Google does things incorrectly (does not conform to RFC).
- // Because so many people ask questions about this (assume xmpp framework is broken),
- // I've explicitly added code that shows how other xmpp clients "do the right thing"
- // when connecting to a google server (gmail, or google apps for domains).
- NSString *expectedCertName = nil;
- NSString *serverDomain = xmppStream.hostName;
- NSString *virtualDomain = [xmppStream.myJID domain];
- if ([serverDomain isEqualToString:kOFDomain])
- {
- if ([virtualDomain isEqualToString:kOFDomain])
- {
- expectedCertName = virtualDomain;
- }
- else
- {
- expectedCertName = serverDomain;
- }
- }
- else if (serverDomain == nil)
- {
- expectedCertName = virtualDomain;
- }
- else
- {
- expectedCertName = serverDomain;
- }
- if (expectedCertName)
- {
- [settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
- }
- }
- }
- - (void)xmppStreamDidSecure:(XMPPStream *)sender
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)xmppStreamDidConnect:(XMPPStream *)sender
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- isXmppConnected = YES;
- NSError *error = nil;
- if (![[self xmppStream] authenticateWithPassword:password error:&error])
- {
- // DDLogError(@"Error authenticating: %@", error);
- }
- }
- - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- [self goOnline];
- }
- - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
- {
- NSLog(@"%@",error);
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- return NO;
- }
- - (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message
- {
- if([message isChatMessageWithBody]) // New Message...
- {
- NSString *strMessageId = [message receiptResponseID];
- NSLog(@"%@",strMessageId);
- NSInteger status = Success;
- if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
- {
- [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
- }
- else
- {
- [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
- }
- }
- }
- - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- // A simple example of inbound message handling.
- if([message hasComposingChatState] || [message hasGoneChatState])
- {
- if(ShareObj.currentConversation && ShareObj.currentConversation.groupId == 0)
- {
- NSString *strJId = ShareObj.currentConversation.jId;
- NSString *messageFromUser = [[message from] user];
- if([strJId isEqualToString:messageFromUser])
- {
- if([self.chatServerDelegate respondsToSelector:@selector(friendId:isTyping:)])
- {
- [self.chatServerDelegate friendId:messageFromUser isTyping:[message hasComposingChatState]];
- }
- }
- }
- }
- else if([message hasActiveChatState])
- {
- NSString *strJId = ShareObj.currentConversation.jId;
- NSString *messageFromUser = [[message from] user];
- if(![ShareObj.arrActiveChatState containsObject:messageFromUser])
- {
- [ShareObj.arrActiveChatState addObject:messageFromUser];
- }
- if(ShareObj.currentConversation)
- {
- if([strJId isEqualToString:messageFromUser])
- {
- if([self.chatServerDelegate respondsToSelector:@selector(chatActiveStatteForfriendId:)])
- {
- [self.chatServerDelegate chatActiveStatteForfriendId:messageFromUser];
- }
- }
- }
- }
- else if([message hasInactiveChatState] || [message hasPausedChatState])
- {
- if(ShareObj.currentConversation)
- {
- NSString *strJId = ShareObj.currentConversation.jId;
- NSString *messageFromUser = [[message from] user];
- if([ShareObj.arrActiveChatState containsObject:messageFromUser])
- {
- [ShareObj.arrActiveChatState removeObject:messageFromUser];
- }
- if([strJId isEqualToString:messageFromUser])
- {
- if([self.chatServerDelegate respondsToSelector:@selector(chatActiveStatteForfriendId:)])
- {
- [self.chatServerDelegate chatActiveStatteForfriendId:messageFromUser];
- }
- }
- }
- }
- else if([message hasReceivedChatMarker]) // Message Received ...
- {
- NSString *strMessageId = [message receiptResponseID];
- NSLog(@"%@",strMessageId);
- }
- else if([message hasDisplayedChatMarker]) // Message Seen ...
- {
- NSString *strMessageId = [message chatMarkerID];
- NSLog(@"%@",strMessageId);
- if(strMessageId)
- {
- NSInteger status = MessageSeen;
- if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
- {
- [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
- }
- else
- {
- [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update Message Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
- }
- }
- }
- else if([message isChatMessageWithBody]) // New Message...
- {
- NSString *messageBody = [message body];
- NSError *jsonError;
- NSData *objectData = [messageBody dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
- options:NSJSONReadingMutableContainers
- error:&jsonError];
- NSMutableDictionary *diccConversation=[json objectForKey:@"sender"];
- NSMutableDictionary *diccMsg=[json objectForKey:@"message"];
- Conversation *objConversation;
- if([message isChatMessage])
- {
- User *objUser = [[User alloc] initWithObject:diccConversation];
- objUser.isUsingApp = 1;
- [objUser updateInDB];
- objConversation = [Conversation getConversationWithUser:objUser];
- }
- else if([message isGroupChatMessage])
- {
- Groups *objGroup = [[Groups alloc] initWithObject:diccConversation];
- [objGroup updateInDB];
- objConversation = [Conversation getConversationWithGroup:objGroup];
- }
- if(objConversation)
- {
- Message *objMessage = [[Message alloc] initWithObject:diccMsg];
- objMessage.conversationId = objConversation.conversationId;
- [objMessage setIsMsgRead:0];
- [objMessage setMsgStatus:Delivered];
- [objMessage updateInDB];
- [objConversation updateKey:kMsgId value:@(objMessage.msgId)];
- if(![objMessage.jId isEqualToString:ShareObj.loginUser.jId])
- {
- if(ShareObj.currentConversation)
- {
- if(objConversation.conversationId == ShareObj.currentConversation.conversationId)
- {
- if([self.chatServerDelegate respondsToSelector:@selector(receivedNewMessage:inConversation:)])
- {
- [self.chatServerDelegate receivedNewMessage:objMessage inConversation:objConversation];
- }
- }
- }
- else
- {
- [[NSNotificationCenter defaultCenter] postNotificationName:kReceivedMessageInConversationNotification
- object:objConversation];
- }
- if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
- {
- }
- else
- {
- }
- }
- }
- }
- else if([message hasReceiptResponse]) // Message Delivered ...
- {
- NSString *strMessageId = [message receiptResponseID];
- NSLog(@"%@",strMessageId);
- NSInteger status = Delivered;
- if([self.chatServerDelegate respondsToSelector:@selector(receivedReceiptForMessageId:status:)])
- {
- [self.chatServerDelegate receivedReceiptForMessageId:strMessageId status:status];
- }
- else
- {
- [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set msgStatus = %ld Where messageId == '%@'",(long)status,strMessageId]];
- }
- }
- }
- -(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence{
- [sender acceptPresenceSubscriptionRequestFrom:[presence from] andAddToRoster:YES];
- }
- - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
- {
- NSString *presenceType = [presence type]; // online/offline
- NSString *myUsername = [[sender myJID] user];
- NSString *presenceFromUser = [[presence from] user];
- if([presenceType isEqualToString:@"subscribe"])
- {
- [Common LoadProfileImageAndSaveToLocal];
- [self UpdateOnlineOffline:1];
- if(self.tabBarController)
- {
- TabBarScreen *tabScreen = [[self.tabBarController viewControllers] objectAtIndex:0];
- UINavigationController *objNav = [[tabScreen viewControllers] objectAtIndex:0];
- ContactScreen *objContact = [[objNav viewControllers] objectAtIndex:0];
- if(objContact)
- {
- if([objContact respondsToSelector:@selector(friendId:isTyping:)])
- {
- }
- }
- }
- [[self xmppRoster] acceptPresenceSubscriptionRequestFrom:[presence from] andAddToRoster:YES];
- }
- else if (![presenceFromUser isEqualToString:myUsername])
- {
- [ShareObj.sharedDB executeCreateQuery:[NSString stringWithFormat:@"Update User Set isOnline = %d Where jId Like '%@'",[presenceType isEqualToString:@"available"]?1:0,presenceFromUser]];
- if(ShareObj.currentConversation)
- {
- NSString *strConversationUserJId = [[NSString stringWithFormat:@"%ld",(long)ShareObj.currentConversation.userId] sha1];
- if([strConversationUserJId isEqualToString:presenceFromUser])
- {
- if([self.chatServerDelegate respondsToSelector:@selector(friendId:GoesOnLineOffLine:)])
- {
- [self.chatServerDelegate friendId:presenceFromUser
- GoesOnLineOffLine:[presenceType isEqualToString:@"available"]?@"Online":@"Offnine"];
- }
- }
- }
- else
- {
- if([self.chatServerDelegate respondsToSelector:@selector(friendId:GoesOnLineOffLine:)])
- {
- [self.chatServerDelegate friendId:presenceFromUser
- GoesOnLineOffLine:[presenceType isEqualToString:@"available"]?@"Online":@"Offnine"];
- }
- }
- }
- }
- - (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- }
- - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- if (!isXmppConnected)
- {
- // DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark XMPPRosterDelegate
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence
- {
- // DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
- XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[presence from]
- xmppStream:xmppStream
- managedObjectContext:[self managedObjectContext_roster]];
- NSString *displayName = [user displayName];
- NSString *jidStrBare = [presence fromStr];
- NSString *body = nil;
- if (![displayName isEqualToString:jidStrBare])
- {
- body = [NSString stringWithFormat:@"Buddy request from %@ <%@>", displayName, jidStrBare];
- }
- else
- {
- body = [NSString stringWithFormat:@"Buddy request from %@", displayName];
- }
- if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
- {
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
- message:body
- delegate:nil
- cancelButtonTitle:@"Not implemented"
- otherButtonTitles:nil];
- [alertView show];
- }
- else
- {
- // We are not active, so use a local notification instead
- UILocalNotification *localNotification = [[UILocalNotification alloc] init];
- localNotification.alertAction = @"Not implemented";
- localNotification.alertBody = body;
- [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
- }
- }
- - (void)applicationWillResignActive:(UIApplication *)application {
- // 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.
- // 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.
- }
- - (void)applicationDidEnterBackground:(UIApplication *)application {
- [self goOffline];
- [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
- }
- - (void)applicationDidEnterForeground:(UIApplication *)application
- {
- // [self goOnline];
- }
- - (void)applicationWillEnterForeground:(UIApplication *)application {
- [self goOnline];
- }
- - (void)appStart
- {
- [self ResetBadgeCount];
- [self checkLoginDevice];
- }
- - (void)applicationDidBecomeActive:(UIApplication *)application {
- // 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.
- }
- - (void)applicationWillTerminate:(UIApplication *)application {
- }
- -(void)HandleCrash
- {
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement