Esempio n. 1
0
 public static SentChatBubble getSplitChatBubbles(ConvMessage cm, bool readFromDB)
 {
     try
     {
         SentChatBubble sentChatBubble;
         if (cm.Message.Length < HikeConstants.MAX_CHATBUBBLE_SIZE)
         {
             sentChatBubble = new SentChatBubble(cm, readFromDB, cm.Message);
             return(sentChatBubble);
         }
         sentChatBubble = new SentChatBubble(cm, readFromDB, cm.Message.Substring(0, HikeConstants.MAX_CHATBUBBLE_SIZE));
         sentChatBubble.splitChatBubbles = new List <MyChatBubble>();
         int lengthOfNextBubble = 1400;
         for (int i = 1; i <= (cm.Message.Length / HikeConstants.MAX_CHATBUBBLE_SIZE); i++)
         {
             if ((cm.Message.Length - (i) * HikeConstants.MAX_CHATBUBBLE_SIZE) / HikeConstants.MAX_CHATBUBBLE_SIZE > 0)
             {
                 lengthOfNextBubble = HikeConstants.MAX_CHATBUBBLE_SIZE;
             }
             else
             {
                 lengthOfNextBubble = (cm.Message.Length - (i) * HikeConstants.MAX_CHATBUBBLE_SIZE) % HikeConstants.MAX_CHATBUBBLE_SIZE;
             }
             SentChatBubble splitBubble = new SentChatBubble(cm, readFromDB, cm.Message.Substring(i * HikeConstants.MAX_CHATBUBBLE_SIZE,
                                                                                                  lengthOfNextBubble));
             sentChatBubble.splitChatBubbles.Add(splitBubble);
         }
         return(sentChatBubble);
     }
     catch (Exception e)
     {
         Debug.WriteLine("Sent chat bubble :: " + e.StackTrace);
         return(null);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Thread safe function to update msg status
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static string updateAllMsgStatus(string fromUser, long[] ids, int status)
        {
            bool   shouldSubmit = false;
            string msisdn       = null;

            using (HikeChatsDb context = new HikeChatsDb(App.MsgsDBConnectionstring + ";Max Buffer Size = 1024"))
            {
                for (int i = 0; i < ids.Length; i++)
                {
                    ConvMessage message = DbCompiledQueries.GetMessagesForMsgId(context, ids[i]).FirstOrDefault <ConvMessage>();
                    if (message != null)
                    {
                        if ((int)message.MessageStatus < status)
                        {
                            if (fromUser == null || fromUser == message.Msisdn)
                            {
                                message.MessageStatus = (ConvMessage.State)status;
                                msisdn       = message.Msisdn;
                                shouldSubmit = true;
                            }
                        }
                    }
                }
                if (shouldSubmit)
                {
                    SubmitWithConflictResolve(context);
                }
                shouldSubmit = false;
                return(msisdn);
            }
        }
Esempio n. 3
0
 public MyChatBubble(ConvMessage cm)
 {
     this.Text            = cm.Message;
     this.TimeStamp       = TimeUtils.getTimeStringForChatThread(cm.Timestamp);
     this._messageId      = cm.MessageId;
     this._timeStampLong  = cm.Timestamp;
     this._messageState   = cm.MessageStatus;
     this._metaDataString = cm.MetaDataString;
     if (cm.FileAttachment != null)
     {
         this.FileAttachment = cm.FileAttachment;
         setAttachmentState(cm.FileAttachment.FileState);
     }
     else if (!cm.HasAttachment)
     {
         var currentPage = ((App)Application.Current).RootFrame.Content as NewChatThread;
         if (currentPage != null)
         {
             ContextMenu contextMenu = null;
             if (String.IsNullOrEmpty(cm.MetaDataString) || !cm.MetaDataString.Contains("poke"))
             {
                 contextMenu = currentPage.createAttachmentContextMenu(Attachment.AttachmentState.COMPLETED,
                                                                       false, true); //since it is not an attachment message this bool won't make difference
             }
             else
             {
                 contextMenu = currentPage.createAttachmentContextMenu(Attachment.AttachmentState.CANCELED,
                                                                       true, true); //set to tru to have only delete option for nudge bubbles
             }
             ContextMenuService.SetContextMenu(this, contextMenu);
         }
     }
 }
Esempio n. 4
0
        private void Invite_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Button btn = sender as Button;

            if (!btn.IsEnabled)
            {
                return;
            }
            btn.Content = AppResources.Invited;
            ContactInfo ci = btn.DataContext as ContactInfo;

            if (ci == null)
            {
                return;
            }
            long   time        = TimeUtils.getCurrentTimeStamp();
            string inviteToken = "";
            //App.appSettings.TryGetValue<string>(HikeConstants.INVITE_TOKEN, out inviteToken);
            ConvMessage convMessage = new ConvMessage(string.Format(AppResources.sms_invite_message, inviteToken), ci.Msisdn, time, ConvMessage.State.SENT_UNCONFIRMED);

            convMessage.IsSms    = true;
            convMessage.IsInvite = true;
            App.HikePubSubInstance.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(convMessage.IsSms ? false : true));
            btn.IsEnabled = false;
        }
Esempio n. 5
0
        public static ConversationListObject addGroupConversation(ConvMessage convMessage, string groupName)
        {
            /*
             * Msisdn : GroupId
             * Contactname : GroupOwner
             */
            byte[] avatar = MiscDBUtil.getThumbNailForMsisdn(convMessage.Msisdn);
            ConversationListObject obj = new ConversationListObject(convMessage.Msisdn, groupName, convMessage.Message,
                                                                    true, convMessage.Timestamp, avatar, convMessage.MessageStatus, convMessage.MessageId);

            if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.MEMBERS_JOINED)
            {
                string[] vals = convMessage.Message.Split(';');
                if (vals.Length == 2)
                {
                    obj.LastMessage = vals[1];
                }
                else
                {
                    obj.LastMessage = convMessage.Message;
                }
            }
            string msisdn = obj.Msisdn.Replace(":", "_");

            saveConvObject(obj, msisdn);
            int convs = 0;

            App.appSettings.TryGetValue <int>(HikeViewModel.NUMBER_OF_CONVERSATIONS, out convs);
            App.WriteToIsoStorageSettings(HikeViewModel.NUMBER_OF_CONVERSATIONS, convs + 1);
            //saveNewConv(obj);
            return(obj);
        }
Esempio n. 6
0
 public static string updateMsgStatus(string fromUser, long msgID, int val)
 {
     using (HikeChatsDb context = new HikeChatsDb(App.MsgsDBConnectionstring + ";Max Buffer Size = 1024"))
     {
         ConvMessage message = DbCompiledQueries.GetMessagesForMsgId(context, msgID).FirstOrDefault <ConvMessage>();
         if (message != null)
         {
             if ((int)message.MessageStatus < val)
             {
                 if (fromUser == null || fromUser == message.Msisdn)
                 {
                     message.MessageStatus = (ConvMessage.State)val;
                     SubmitWithConflictResolve(context);
                     return(message.Msisdn);
                 }
                 else
                 {
                     return(null);
                 }
             }
         }
         else
         {
             return(null);
         }
     }
     return(null);
 }
        public static ReceivedChatBubble getSplitChatBubbles(ConvMessage cm, bool isGroupChat, string userName)
        {
            ReceivedChatBubble receivedChatBubble;

            if (cm.Message.Length < HikeConstants.MAX_CHATBUBBLE_SIZE)
            {
                receivedChatBubble = new ReceivedChatBubble(cm, isGroupChat, userName, cm.Message);
                return(receivedChatBubble);
            }
            receivedChatBubble = new ReceivedChatBubble(cm, isGroupChat, userName, cm.Message.Substring(0, HikeConstants.MAX_CHATBUBBLE_SIZE));
            receivedChatBubble.splitChatBubbles = new List <MyChatBubble>();
            int lengthOfNextBubble = 1400;

            for (int i = 1; i <= (cm.Message.Length / HikeConstants.MAX_CHATBUBBLE_SIZE); i++)
            {
                if ((cm.Message.Length - (i) * HikeConstants.MAX_CHATBUBBLE_SIZE) / HikeConstants.MAX_CHATBUBBLE_SIZE > 0)
                {
                    lengthOfNextBubble = HikeConstants.MAX_CHATBUBBLE_SIZE;
                }
                else
                {
                    lengthOfNextBubble = (cm.Message.Length - (i) * HikeConstants.MAX_CHATBUBBLE_SIZE) % HikeConstants.MAX_CHATBUBBLE_SIZE;
                }
                ReceivedChatBubble splitBubble = new ReceivedChatBubble(cm, isGroupChat, userName, cm.Message.Substring
                                                                            (i * HikeConstants.MAX_CHATBUBBLE_SIZE, lengthOfNextBubble));
                receivedChatBubble.splitChatBubbles.Add(splitBubble);
            }
            return(receivedChatBubble);
        }
        public void uploadFileCallback(JObject obj, ConvMessage convMessage, SentChatBubble chatBubble)
        {
            if (obj != null && chatBubble.FileAttachment.FileState != Attachment.AttachmentState.CANCELED &&
                chatBubble.FileAttachment.FileState != Attachment.AttachmentState.FAILED_OR_NOT_STARTED)
            {
                JObject data        = obj[HikeConstants.FILE_RESPONSE_DATA].ToObject <JObject>();
                string  fileKey     = data[HikeConstants.FILE_KEY].ToString();
                string  fileName    = data[HikeConstants.FILE_NAME].ToString();
                string  contentType = data[HikeConstants.FILE_CONTENT_TYPE].ToString();

                chatBubble.updateProgress(110);
                //DO NOT Update message text in db. We sent the below line, but we save content type as message.
                //here message status should be updated in db, as on event listener message state should be unknown

                if (contentType.Contains(HikeConstants.IMAGE))
                {
                    convMessage.Message = String.Format(AppResources.FILES_MESSAGE_PREFIX, AppResources.Photo_Txt) + HikeConstants.FILE_TRANSFER_BASE_URL +
                                          "/" + fileKey;
                }
                else if (contentType.Contains(HikeConstants.AUDIO))
                {
                    convMessage.Message = String.Format(AppResources.FILES_MESSAGE_PREFIX, AppResources.Voice_msg_Txt) + HikeConstants.FILE_TRANSFER_BASE_URL +
                                          "/" + fileKey;
                }
                else if (contentType.Contains(HikeConstants.LOCATION))
                {
                    convMessage.Message = String.Format(AppResources.FILES_MESSAGE_PREFIX, AppResources.Location_Txt) + HikeConstants.FILE_TRANSFER_BASE_URL +
                                          "/" + fileKey;
                }
                else if (contentType.Contains(HikeConstants.VIDEO))
                {
                    convMessage.Message = String.Format(AppResources.FILES_MESSAGE_PREFIX, AppResources.Video_Txt) + HikeConstants.FILE_TRANSFER_BASE_URL +
                                          "/" + fileKey;
                }
                else if (contentType.Contains(HikeConstants.CT_CONTACT))
                {
                    convMessage.Message = String.Format(AppResources.FILES_MESSAGE_PREFIX, AppResources.ContactTransfer_Text) + HikeConstants.FILE_TRANSFER_BASE_URL +
                                          "/" + fileKey;
                }
                convMessage.MessageStatus = ConvMessage.State.SENT_UNCONFIRMED;
                chatBubble.scheduleTryingImage();
                convMessage.FileAttachment.FileKey     = fileKey;
                convMessage.FileAttachment.ContentType = contentType;
                mPubSub.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(true));
                chatBubble.setAttachmentState(Attachment.AttachmentState.COMPLETED);
                MiscDBUtil.saveAttachmentObject(convMessage.FileAttachment, convMessage.Msisdn, convMessage.MessageId);
            }
            else
            {
                chatBubble.SetSentMessageStatus(ConvMessage.State.SENT_FAILED);
                chatBubble.setAttachmentState(Attachment.AttachmentState.FAILED_OR_NOT_STARTED);
            }
        }
Esempio n. 9
0
        /* Adds a chat message to message Table.*/
        public static bool addMessage(ConvMessage convMessage)
        {
            using (HikeChatsDb context = new HikeChatsDb(App.MsgsDBConnectionstring + ";Max Buffer Size = 1024;"))
            {
                if (convMessage.MappedMessageId > 0)
                {
                    IQueryable <ConvMessage> qq = DbCompiledQueries.GetMessageForMappedMsgIdMsisdn(context, convMessage.Msisdn, convMessage.MappedMessageId, convMessage.Message);
                    ConvMessage cm = qq.FirstOrDefault();
                    if (cm != null)
                    {
                        return(false);
                    }
                }
                long currentMessageId = convMessage.MessageId;
                context.messages.InsertOnSubmit(convMessage);
                try
                {
                    context.SubmitChanges();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception while inserting msg in CHATS DB : " + ex.StackTrace);
                    return(false);
                }
                //if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.NO_INFO)
                //{
                //    long msgId = convMessage.MessageId;
                //    Deployment.Current.Dispatcher.BeginInvoke(() =>
                //    {

                //        NewChatThread currentPage = App.newChatThreadPage;

                //        if (currentPage != null)
                //        {
                //            if (convMessage.IsSent)
                //            {
                //                SentChatBubble sentChatBubble;
                //                currentPage.OutgoingMsgsMap.TryGetValue(currentMessageId, out sentChatBubble);
                //                if (sentChatBubble != null)
                //                {
                //                    currentPage.OutgoingMsgsMap.Remove(currentMessageId);
                //                    currentPage.OutgoingMsgsMap.Add(convMessage.MessageId, sentChatBubble);
                //                    sentChatBubble.MessageId = convMessage.MessageId;
                //                }
                //            }
                //        }
                //    });
                //}
            }
            return(true);
        }
Esempio n. 10
0
 private void inviteSMSUsers_Tap(object sender, System.Windows.Input.GestureEventArgs e)
 {
     App.AnalyticsInstance.addEvent(Analytics.INVITE_SMS_PARTICIPANTS);
     //TODO start this loop from end, after sorting is done on onHike status
     for (int i = 0; i < GroupManager.Instance.GroupCache[groupId].Count; i++)
     {
         GroupParticipant gp = GroupManager.Instance.GroupCache[groupId][i];
         if (!gp.IsOnHike)
         {
             long        time        = utils.TimeUtils.getCurrentTimeStamp();
             ConvMessage convMessage = new ConvMessage(AppResources.sms_invite_message, gp.Msisdn, time, ConvMessage.State.SENT_UNCONFIRMED);
             convMessage.IsInvite = true;
             App.HikePubSubInstance.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(false));
         }
     }
     MessageBoxResult result = MessageBox.Show(AppResources.GroupInfo_InviteSent_MsgBoxText_Txt, AppResources.GroupInfo_InviteSent_MsgBoxHeader_Txt, MessageBoxButton.OK);
 }
Esempio n. 11
0
        public void updateProfile_Callback(JObject obj)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (obj != null && HikeConstants.OK == (string)obj[HikeConstants.STAT])
                {
                    App.ViewModel.ConvMap[groupId].Avatar = fullViewImageBytes;
                    groupImage.Source = grpImage;
                    groupImage.Height = 83;
                    groupImage.Width  = 83;

                    string msg                  = string.Format(AppResources.GroupImgChangedByGrpMember_Txt, AppResources.You_Txt);
                    ConvMessage cm              = new ConvMessage(msg, groupId, TimeUtils.getCurrentTimeStamp(), ConvMessage.State.RECEIVED_READ, -1, -1);
                    cm.GrpParticipantState      = ConvMessage.ParticipantInfoState.GROUP_PIC_CHANGED;
                    cm.GroupParticipant         = App.MSISDN;
                    JObject jo                  = new JObject();
                    jo[HikeConstants.TYPE]      = HikeConstants.MqttMessageTypes.GROUP_DISPLAY_PIC;
                    cm.MetaDataString           = jo.ToString(Newtonsoft.Json.Formatting.None);
                    ConversationListObject cobj = MessagesTableUtils.addChatMessage(cm, false);
                    if (cobj == null)
                    {
                        return;
                    }

                    // handle msgs
                    object[] vs = new object[2];
                    vs[0]       = cm;
                    vs[1]       = cobj;
                    mPubSub.publish(HikePubSub.MESSAGE_RECEIVED, vs);

                    // handle saving image
                    object[] vals = new object[3];
                    vals[0]       = groupId;
                    vals[1]       = fullViewImageBytes;
                    vals[2]       = thumbnailBytes;
                    mPubSub.publish(HikePubSub.ADD_OR_UPDATE_PROFILE, vals);
                }
                else
                {
                    MessageBox.Show(AppResources.CannotChangeGrpImg_Txt, AppResources.Something_Wrong_Txt, MessageBoxButton.OK);
                }
                //progressBar.IsEnabled = false;
                shellProgress.IsVisible = false;
                isProfilePicTapped      = false;
            });
        }
Esempio n. 12
0
 public SentChatBubble(ConvMessage cm, byte[] thumbnailsBytes)
     : base(cm)
 {
     // Required to initialize variables
     InitializeComponent();
     initializeBasedOnState(cm, cm.Message);
     this.BubblePoint.Fill = bubbleColor;
     this.BubbleBg.Fill    = bubbleColor;
     if (thumbnailsBytes != null && thumbnailsBytes.Length > 0)
     {
         using (var memStream = new MemoryStream(thumbnailsBytes))
         {
             memStream.Seek(0, SeekOrigin.Begin);
             BitmapImage fileThumbnail = new BitmapImage();
             fileThumbnail.SetSource(memStream);
             this.MessageImage.Source = fileThumbnail;
         }
     }
 }
        private void LoadMessages()
        {
            List <Conversation> conversationList = ConversationTableUtils.getAllConversations();

            if (conversationList == null)
            {
                return;
            }
            for (int i = 0; i < conversationList.Count; i++)
            {
                Conversation conv        = conversationList[i];
                ConvMessage  lastMessage = MessagesTableUtils.getLastMessageForMsisdn(conv.Msisdn); // why we are not getting only lastmsg as string
                ContactInfo  contact     = UsersTableUtils.getContactInfoFromMSISDN(conv.Msisdn);

                Thumbnails             thumbnail = MiscDBUtil.getThumbNailForMSisdn(conv.Msisdn);
                ConversationListObject mObj      = new ConversationListObject((contact == null) ? conv.Msisdn : contact.Msisdn, (contact == null) ? conv.Msisdn : contact.Name, lastMessage.Message, (contact == null) ? conv.OnHike : contact.OnHike,
                                                                              TimeUtils.getTimeString(lastMessage.Timestamp), thumbnail == null ? null : thumbnail.Avatar);
                convMap.Add(conv.Msisdn, mObj);
                App.ViewModel.MessageListPageCollection.Add(mObj);
            }
        }
        public ReceivedChatBubble(ConvMessage cm, bool isGroupChat, string userName, string messageString)
            : base(cm)
        {
            // Required to initialize variables
            InitializeComponent();
            string contentType  = cm.FileAttachment == null ? "" : cm.FileAttachment.ContentType;
            bool   showDownload = cm.FileAttachment != null && (cm.FileAttachment.FileState == Attachment.AttachmentState.CANCELED ||
                                                                cm.FileAttachment.FileState == Attachment.AttachmentState.FAILED_OR_NOT_STARTED);

            initializeBasedOnState(cm, isGroupChat, userName, messageString);

            if (cm.FileAttachment != null && cm.FileAttachment.Thumbnail != null && cm.FileAttachment.Thumbnail.Length != 0)
            {
                using (var memStream = new MemoryStream(cm.FileAttachment.Thumbnail))
                {
                    memStream.Seek(0, SeekOrigin.Begin);
                    BitmapImage fileThumbnail = new BitmapImage();
                    fileThumbnail.SetSource(memStream);
                    this.MessageImage.Source = fileThumbnail;
                }
            }
        }
Esempio n. 15
0
        // this is called in case of gcj from Network manager
        public static ConversationListObject addGroupChatMessage(ConvMessage convMsg, JObject jsonObj)
        {
            ConversationListObject obj = null;

            if (!App.ViewModel.ConvMap.ContainsKey(convMsg.Msisdn)) // represents group is new
            {
                bool success = addMessage(convMsg);
                if (!success)
                {
                    return(null);
                }
                string groupName = GroupManager.Instance.defaultGroupName(convMsg.Msisdn);
                obj = ConversationTableUtils.addGroupConversation(convMsg, groupName);
                App.ViewModel.ConvMap[convMsg.Msisdn] = obj;
                GroupInfo gi = new GroupInfo(convMsg.Msisdn, null, convMsg.GroupParticipant, true);
                GroupTableUtils.addGroupInfo(gi);
            }
            else // add a member to a group
            {
                List <GroupParticipant> existingMembers = null;
                GroupManager.Instance.GroupCache.TryGetValue(convMsg.Msisdn, out existingMembers);
                if (existingMembers == null)
                {
                    return(null);
                }

                obj = App.ViewModel.ConvMap[convMsg.Msisdn];
                GroupInfo gi = GroupTableUtils.getGroupInfoForId(convMsg.Msisdn);

                if (string.IsNullOrEmpty(gi.GroupName)) // no group name is set
                {
                    obj.ContactName = GroupManager.Instance.defaultGroupName(obj.Msisdn);
                }

                if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.MEMBERS_JOINED)
                {
                    string[] vals = convMsg.Message.Split(';');
                    if (vals.Length == 2)
                    {
                        obj.LastMessage = vals[1];
                    }
                    else
                    {
                        obj.LastMessage = convMsg.Message;
                    }
                }
                else
                {
                    obj.LastMessage = convMsg.Message;
                }

                bool success = addMessage(convMsg);
                if (!success)
                {
                    return(null);
                }

                obj.MessageStatus = convMsg.MessageStatus;
                obj.TimeStamp     = convMsg.Timestamp;
                obj.LastMsgId     = convMsg.MessageId;
                ConversationTableUtils.updateConversation(obj);
            }

            return(obj);
        }
Esempio n. 16
0
        public static ConversationListObject addChatMessage(ConvMessage convMsg, bool isNewGroup)
        {
            if (convMsg == null)
            {
                return(null);
            }
            ConversationListObject obj = null;

            if (!App.ViewModel.ConvMap.ContainsKey(convMsg.Msisdn))
            {
                if (Utils.isGroupConversation(convMsg.Msisdn) && !isNewGroup) // if its a group chat msg and group does not exist , simply ignore msg.
                {
                    return(null);
                }

                obj = ConversationTableUtils.addConversation(convMsg, isNewGroup);
                App.ViewModel.ConvMap.Add(convMsg.Msisdn, obj);
            }
            else
            {
                obj = App.ViewModel.ConvMap[convMsg.Msisdn];
                #region PARTICIPANT_JOINED
                if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.PARTICIPANT_JOINED)
                {
                    obj.LastMessage = convMsg.Message;

                    GroupInfo gi = GroupTableUtils.getGroupInfoForId(convMsg.Msisdn);
                    if (gi == null)
                    {
                        return(null);
                    }
                    if (string.IsNullOrEmpty(gi.GroupName)) // no group name is set
                    {
                        obj.ContactName = GroupManager.Instance.defaultGroupName(convMsg.Msisdn);
                    }
                }
                #endregion
                #region PARTICIPANT_LEFT
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.PARTICIPANT_LEFT || convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.INTERNATIONAL_GROUP_USER)
                {
                    obj.LastMessage = convMsg.Message;
                    GroupInfo gi = GroupTableUtils.getGroupInfoForId(convMsg.Msisdn);
                    if (gi == null)
                    {
                        return(null);
                    }
                    if (string.IsNullOrEmpty(gi.GroupName)) // no group name is set
                    {
                        obj.ContactName = GroupManager.Instance.defaultGroupName(convMsg.Msisdn);
                    }
                }
                #endregion
                #region GROUP_JOINED_OR_WAITING
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.GROUP_JOINED_OR_WAITING) // shows invite msg
                {
                    string[]      vals = Utils.splitUserJoinedMessage(convMsg.Message);
                    List <string> waitingParticipants = null;
                    for (int i = 0; i < vals.Length; i++)
                    {
                        string[] vars = vals[i].Split(HikeConstants.DELIMITERS, StringSplitOptions.RemoveEmptyEntries); // msisdn:0 or msisdn:1

                        // every participant is either on DND or not on DND
                        GroupParticipant gp = GroupManager.Instance.getGroupParticipant(null, vars[0], convMsg.Msisdn);
                        if (vars[1] == "0") // DND USER and not OPTED IN
                        {
                            if (waitingParticipants == null)
                            {
                                waitingParticipants = new List <string>();
                            }
                            waitingParticipants.Add(gp.FirstName);
                        }
                    }
                    if (waitingParticipants != null && waitingParticipants.Count > 0) // show waiting msg
                    {
                        StringBuilder msgText = new StringBuilder();
                        if (waitingParticipants.Count == 1)
                        {
                            msgText.Append(waitingParticipants[0]);
                        }
                        else if (waitingParticipants.Count == 2)
                        {
                            msgText.Append(waitingParticipants[0] + AppResources.And_txt + waitingParticipants[1]);
                        }
                        else
                        {
                            for (int i = 0; i < waitingParticipants.Count; i++)
                            {
                                msgText.Append(waitingParticipants[0]);
                                if (i == waitingParticipants.Count - 2)
                                {
                                    msgText.Append(AppResources.And_txt);
                                }
                                else if (i < waitingParticipants.Count - 2)
                                {
                                    msgText.Append(",");
                                }
                            }
                        }
                        obj.LastMessage = string.Format(AppResources.WAITING_TO_JOIN, msgText.ToString());
                    }
                    else
                    {
                        string[]         vars = vals[vals.Length - 1].Split(':');
                        GroupParticipant gp   = GroupManager.Instance.getGroupParticipant(null, vars[0], convMsg.Msisdn);
                        string           text = AppResources.USER_JOINED_GROUP_CHAT;
                        obj.LastMessage = gp.FirstName + text;
                    }
                }
                #endregion
                #region USER_OPT_IN
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.USER_OPT_IN)
                {
                    if (Utils.isGroupConversation(obj.Msisdn))
                    {
                        GroupParticipant gp = GroupManager.Instance.getGroupParticipant(null, convMsg.Message, obj.Msisdn);
                        obj.LastMessage = gp.FirstName + AppResources.USER_JOINED_GROUP_CHAT;
                    }
                    else
                    {
                        obj.LastMessage = obj.NameToShow + AppResources.USER_OPTED_IN_MSG;
                    }
                    convMsg.Message = obj.LastMessage;
                }
                #endregion
                #region CREDITS_GAINED
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.CREDITS_GAINED)
                {
                    obj.LastMessage = convMsg.Message;
                }
                #endregion
                #region DND_USER
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.DND_USER)
                {
                    obj.LastMessage = string.Format(AppResources.DND_USER, obj.NameToShow);
                    convMsg.Message = obj.LastMessage;
                }
                #endregion
                #region USER_JOINED
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.USER_JOINED)
                {
                    if (Utils.isGroupConversation(obj.Msisdn))
                    {
                        GroupParticipant gp = GroupManager.Instance.getGroupParticipant(null, convMsg.Message, obj.Msisdn);
                        obj.LastMessage = string.Format(AppResources.USER_JOINED_HIKE, gp.FirstName);
                    }
                    else // 1-1 chat
                    {
                        obj.LastMessage = string.Format(AppResources.USER_JOINED_HIKE, obj.NameToShow);
                    }
                    convMsg.Message = obj.LastMessage;
                }
                #endregion \
                #region GROUP NAME/PIC CHANGED
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.GROUP_NAME_CHANGE || convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.GROUP_PIC_CHANGED)
                {
                    obj.LastMessage = convMsg.Message;
                }
                #endregion
                #region NO_INFO
                else if (convMsg.GrpParticipantState == ConvMessage.ParticipantInfoState.NO_INFO)
                {
                    //convMsg.GroupParticipant is null means message sent by urself
                    if (convMsg.GroupParticipant != null && Utils.isGroupConversation(convMsg.Msisdn))
                    {
                        GroupParticipant gp = GroupManager.Instance.getGroupParticipant(null, convMsg.GroupParticipant, convMsg.Msisdn);
                        obj.LastMessage = gp != null ? (gp.FirstName + "- " + convMsg.Message) : convMsg.Message;
                    }
                    else
                    {
                        obj.LastMessage = convMsg.Message;
                    }
                }
                #endregion
                #region OTHER MSGS
                else
                {
                    obj.LastMessage = convMsg.Message;
                }
                #endregion

                Stopwatch st1     = Stopwatch.StartNew();
                bool      success = addMessage(convMsg);
                if (!success)
                {
                    return(null);
                }
                st1.Stop();
                long msec1 = st1.ElapsedMilliseconds;
                Debug.WriteLine("Time to add chat msg : {0}", msec1);

                obj.MessageStatus = convMsg.MessageStatus;
                obj.TimeStamp     = convMsg.Timestamp;
                obj.LastMsgId     = convMsg.MessageId;
                Stopwatch st = Stopwatch.StartNew();
                ConversationTableUtils.updateConversation(obj);
                st.Stop();
                long msec = st.ElapsedMilliseconds;
                Debug.WriteLine("Time to update conversation  : {0}", msec);
            }

            return(obj);
        }
        public void onEventReceived(string type, object obj)
        {
            #region MESSAGE_SENT
            if (HikePubSub.MESSAGE_SENT == type)
            {
                object[]    vals        = (object[])obj;
                ConvMessage convMessage = (ConvMessage)vals[0];

                bool                   isNewGroup = (bool)vals[1];
                SentChatBubble         chatBubble = (SentChatBubble)vals[2];
                ConversationListObject convObj    = MessagesTableUtils.addChatMessage(convMessage, isNewGroup);
                if (convObj == null)
                {
                    return;
                }
                if (chatBubble != null)
                {
                    chatBubble.MessageId = convMessage.MessageId;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (chatBubble != null)
                    {
                        addSentMessageToMsgMap(chatBubble);
                    }

                    if (convObj.ConvBoxObj == null)
                    {
                        convObj.ConvBoxObj = new ConversationBox(convObj);
                        if (App.ViewModel.ConversationListPage != null)
                        {
                            ContextMenuService.SetContextMenu(convObj.ConvBoxObj, App.ViewModel.ConversationListPage.createConversationContextMenu(convObj));
                        }
                    }
                    else if (App.ViewModel.MessageListPageCollection.Contains(convObj.ConvBoxObj))//cannot use convMap here because object has pushed to map but not to ui
                    {
                        App.ViewModel.MessageListPageCollection.Remove(convObj.ConvBoxObj);
                    }

                    App.ViewModel.MessageListPageCollection.Insert(0, convObj.ConvBoxObj);

                    if (!isNewGroup)
                    {
                        mPubSub.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(convMessage.IsSms ? false : true));
                    }
                });
                //if (!isNewGroup)
                //    mPubSub.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(convMessage.IsSms ? false : true));
            }
            #endregion
            #region FORWARD_ATTACHMENT
            else if (HikePubSub.FORWARD_ATTACHMENT == type)
            {
                object[]       vals           = (object[])obj;
                ConvMessage    convMessage    = (ConvMessage)vals[0];
                string         sourceFilePath = (string)vals[1];
                SentChatBubble chatBubble     = (SentChatBubble)vals[2];

                ConversationListObject convObj = MessagesTableUtils.addChatMessage(convMessage, false);
                chatBubble.MessageId = convMessage.MessageId;

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    addSentMessageToMsgMap(chatBubble);

                    if (convObj.ConvBoxObj == null)
                    {
                        convObj.ConvBoxObj = new ConversationBox(convObj);
                        if (App.ViewModel.ConversationListPage != null)
                        {
                            ContextMenuService.SetContextMenu(convObj.ConvBoxObj, App.ViewModel.ConversationListPage.createConversationContextMenu(convObj));
                        }
                    }
                    else if (App.ViewModel.MessageListPageCollection.Contains(convObj.ConvBoxObj))//cannot use convMap here because object has pushed to map but not to ui
                    {
                        App.ViewModel.MessageListPageCollection.Remove(convObj.ConvBoxObj);
                    }

                    App.ViewModel.MessageListPageCollection.Insert(0, convObj.ConvBoxObj);
                    //forward attachment message
                    string destinationFilePath = HikeConstants.FILES_BYTE_LOCATION + "/" + convMessage.Msisdn + "/" + convMessage.MessageId;
                    //while writing in iso, we write it as failed and then revert to started
                    MiscDBUtil.saveAttachmentObject(convMessage.FileAttachment, convMessage.Msisdn, convMessage.MessageId);

                    //since, Location & Contact has required info in metadata string, no need to use raw files
                    if (!convMessage.FileAttachment.ContentType.Contains(HikeConstants.CT_CONTACT) &&
                        !convMessage.FileAttachment.ContentType.Contains(HikeConstants.LOCATION))
                    {
                        MiscDBUtil.copyFileInIsolatedStorage(sourceFilePath, destinationFilePath);
                    }
                    mPubSub.publish(HikePubSub.MQTT_PUBLISH, convMessage.serialize(true));
                });
            }
            #endregion
            #region ATTACHMENT_SEND
            else if (HikePubSub.ATTACHMENT_SENT == type)
            {
                object[]       vals        = (object[])obj;
                ConvMessage    convMessage = (ConvMessage)vals[0];
                byte[]         fileBytes   = (byte[])vals[1];
                SentChatBubble chatBubble  = (SentChatBubble)vals[2];

                //In case of sending attachments, here message state should be unknown instead of sent_unconfirmed
                //convMessage.MessageStatus = ConvMessage.State.SENT_UNCONFIRMED;
                ConversationListObject convObj = MessagesTableUtils.addChatMessage(convMessage, false);

                // in case of db failure convObj returned will be null
                if (convObj == null)
                {
                    return;
                }
                chatBubble.MessageId = convMessage.MessageId;

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    addSentMessageToMsgMap(chatBubble);
                    if (convObj.ConvBoxObj == null)
                    {
                        convObj.ConvBoxObj = new ConversationBox(convObj);
                        if (App.ViewModel.ConversationListPage != null)
                        {
                            ContextMenuService.SetContextMenu(convObj.ConvBoxObj, App.ViewModel.ConversationListPage.createConversationContextMenu(convObj));
                        }
                    }
                    else if (App.ViewModel.MessageListPageCollection.Contains(convObj.ConvBoxObj))
                    {
                        App.ViewModel.MessageListPageCollection.Remove(convObj.ConvBoxObj);
                    }
                    App.ViewModel.MessageListPageCollection.Insert(0, convObj.ConvBoxObj);
                    //send attachment message (new attachment - upload case)
                    MessagesTableUtils.addUploadingOrDownloadingMessage(convMessage.MessageId, chatBubble);
                    convMessage.FileAttachment.FileState = Attachment.AttachmentState.FAILED_OR_NOT_STARTED;
                    MiscDBUtil.saveAttachmentObject(convMessage.FileAttachment, convMessage.Msisdn, convMessage.MessageId);
                    convMessage.FileAttachment.FileState = Attachment.AttachmentState.STARTED;

                    AccountUtils.postUploadPhotoFunction finalCallbackForUploadFile = new AccountUtils.postUploadPhotoFunction(uploadFileCallback);
                    if (!convMessage.FileAttachment.ContentType.Contains(HikeConstants.CT_CONTACT))
                    {
                        MiscDBUtil.storeFileInIsolatedStorage(HikeConstants.FILES_BYTE_LOCATION + "/" + convMessage.Msisdn + "/" +
                                                              Convert.ToString(convMessage.MessageId), fileBytes);
                    }
                    AccountUtils.uploadFile(fileBytes, finalCallbackForUploadFile, convMessage, chatBubble);
                });
            }
            #endregion
            #region ATTACHMENT_RESEND_OR_FORWARD
            else if (HikePubSub.ATTACHMENT_RESEND == type)
            {
                object[]       vals        = (object[])obj;
                ConvMessage    convMessage = (ConvMessage)vals[0];
                SentChatBubble chatBubble  = (SentChatBubble)vals[1];
                byte[]         fileBytes;
                if (convMessage.FileAttachment.ContentType.Contains(HikeConstants.CT_CONTACT))
                {
                    fileBytes = Encoding.UTF8.GetBytes(convMessage.MetaDataString);
                }
                else
                {
                    MiscDBUtil.readFileFromIsolatedStorage(HikeConstants.FILES_BYTE_LOCATION + "/" + convMessage.Msisdn + "/" +
                                                           Convert.ToString(convMessage.MessageId), out fileBytes);
                }
                AccountUtils.postUploadPhotoFunction finalCallbackForUploadFile = new AccountUtils.postUploadPhotoFunction(uploadFileCallback);
                AccountUtils.uploadFile(fileBytes, finalCallbackForUploadFile, convMessage, chatBubble);
            }
            #endregion
            #region MESSAGE_RECEIVED_READ
            else if (HikePubSub.MESSAGE_RECEIVED_READ == type)  // represents event when a msg is read by this user
            {
                long[] ids = (long[])obj;
                updateDbBatch(ids, (int)ConvMessage.State.RECEIVED_READ);
            }
            #endregion
            #region MESSAGE_DELETED
            else if (HikePubSub.MESSAGE_DELETED == type)
            {
                object[] o = (object[])obj;

                long msgId = (long)o[0];
                MessagesTableUtils.deleteMessage(msgId); // delete msg with given msgId from messages table

                ConversationListObject c = (ConversationListObject)o[1];
                bool delConv             = (bool)o[2];
                if (delConv)
                {
                    // delete the conversation from DB.
                    ConversationTableUtils.deleteConversation(c.Msisdn);
                    //ConversationTableUtils.saveConvObjectList();
                }
                else
                {
                    //update conversation
                    ConversationTableUtils.updateConversation(c);
                }
                // TODO :: persistence.removeMessage(msgId);
            }
            #endregion
            #region BLOCK_USER
            else if (HikePubSub.BLOCK_USER == type)
            {
                string msisdn = (string)obj;
                UsersTableUtils.block(msisdn);
                JObject blockObj = blockUnblockSerialize("b", msisdn);
                mPubSub.publish(HikePubSub.MQTT_PUBLISH, blockObj);
            }
            #endregion
            #region UNBLOCK_USER
            else if (HikePubSub.UNBLOCK_USER == type)
            {
                string msisdn = (string)obj;
                UsersTableUtils.unblock(msisdn);
                JObject unblockObj = blockUnblockSerialize("ub", msisdn);
                mPubSub.publish(HikePubSub.MQTT_PUBLISH, unblockObj);
            }
            #endregion
            #region ADD_OR_UPDATE_PROFILE
            else if (HikePubSub.ADD_OR_UPDATE_PROFILE == type)
            {
                object[] vals           = (object[])obj;
                string   msisdn         = (string)vals[0];
                byte[]   fullViewBytes  = (byte[])vals[1];
                byte[]   thumbnailBytes = (byte[])vals[2];
                if (Utils.isGroupConversation(msisdn))
                {
                    string grpId = msisdn.Replace(":", "_");
                    MiscDBUtil.saveAvatarImage(grpId + HikeConstants.FULL_VIEW_IMAGE_PREFIX, fullViewBytes, false);
                    MiscDBUtil.saveAvatarImage(grpId, thumbnailBytes, false);
                }
                else
                {
                    MiscDBUtil.saveAvatarImage(HikeConstants.MY_PROFILE_PIC, thumbnailBytes, false);
                }
            }
            #endregion
            #region GROUP LEFT
            else if (HikePubSub.GROUP_LEFT == type)
            {
                /*
                 * 1. Delete conversation with this groupId
                 * 2. Delete ConvMessages
                 * 3. Delete GroupInfo
                 * 4. Delete GroupMembers
                 */
                string groupId = (string)obj;
                ConversationTableUtils.deleteConversation(groupId);
                //ConversationTableUtils.saveConvObjectList();
                MessagesTableUtils.deleteAllMessagesForMsisdn(groupId);
                GroupTableUtils.deleteGroupWithId(groupId);
                GroupManager.Instance.GroupCache.Remove(groupId);
                GroupManager.Instance.DeleteGroup(groupId);
            }
            #endregion
            #region BLOCK GROUP OWNER
            else if (HikePubSub.BLOCK_GROUPOWNER == type)
            {
                string groupOwner = (string)obj;
                UsersTableUtils.block(groupOwner);
                JObject blockObj = blockUnblockSerialize("b", groupOwner);
                mPubSub.publish(HikePubSub.MQTT_PUBLISH, blockObj);
            }
            #endregion
            #region UNBLOCK GROUP OWNER
            else if (HikePubSub.UNBLOCK_GROUPOWNER == type)
            {
                string groupOwner = (string)obj;
                UsersTableUtils.unblock(groupOwner);
                JObject unblockObj = blockUnblockSerialize("ub", groupOwner);
                mPubSub.publish(HikePubSub.MQTT_PUBLISH, unblockObj);
            }
            #endregion
            #region DELETE CONVERSATION
            else if (HikePubSub.DELETE_CONVERSATION == type)
            {
                string convMsisdn = (string)obj;
                if (Utils.isGroupConversation(convMsisdn))                 // if Group Conversation delete groups too
                {
                    GroupTableUtils.deleteGroupWithId(convMsisdn);         // remove entry from Group Table
                    GroupManager.Instance.GroupCache.Remove(convMsisdn);
                    GroupManager.Instance.DeleteGroup(convMsisdn);         // delete the group file
                }
                MessagesTableUtils.deleteAllMessagesForMsisdn(convMsisdn); //removed all chat messages for this msisdn
                ConversationTableUtils.deleteConversation(convMsisdn);     // removed entry from conversation table
                //ConversationTableUtils.saveConvObjectList();
                MiscDBUtil.deleteMsisdnData(convMsisdn);
            }
            #endregion
        }
Esempio n. 18
0
        private static void setParams_Callback(IAsyncResult result)
        {
            object[]             vars                  = (object[])result.AsyncState;
            JObject              data                  = new JObject();
            HttpWebRequest       req                   = vars[0] as HttpWebRequest;
            Stream               postStream            = req.EndGetRequestStream(result);
            postResponseFunction finalCallbackFunction = null;
            RequestType          type                  = (RequestType)vars[1];

            switch (type)
            {
                #region REGISTER ACCOUNT
            case RequestType.REGISTER_ACCOUNT:
                string pin          = vars[2] as string;
                string unAuthMSISDN = vars[3] as string;
                finalCallbackFunction = vars[4] as postResponseFunction;
                data.Add("set_cookie", "0");
                data.Add("devicetype", "windows");
                data[HikeConstants.DEVICE_ID] = Utils.getHashedDeviceId();
                //data[HikeConstants.DEVICE_TOKEN] = Utils.getDeviceId();//for push notifications
                data[HikeConstants.DEVICE_VERSION] = Utils.getDeviceModel();
                data[HikeConstants.APP_VERSION]    = Utils.getAppVersion();
                string inviteToken = "";
                if (!string.IsNullOrEmpty(inviteToken))
                {
                    data[HikeConstants.INVITE_TOKEN_KEY] = inviteToken;
                }
                if (pin != null)
                {
                    data.Add("msisdn", unAuthMSISDN);
                    data.Add("pin", pin);
                }
                Compress4(data.ToString(Formatting.None), postStream);
                postStream.Close();
                req.BeginGetResponse(json_Callback, new object[] { req, type, finalCallbackFunction });
                return;

                #endregion
                #region INVITE
            case RequestType.INVITE:
                string phoneNo = vars[2] as string;
                data.Add("to", phoneNo);
                break;

                #endregion
                #region VALIDATE NUMBER
            case RequestType.VALIDATE_NUMBER:
                string numberToValidate = vars[2] as string;
                finalCallbackFunction = vars[3] as postResponseFunction;
                data.Add("phone_no", numberToValidate);
                break;

                #endregion
                #region CALL ME
            case RequestType.CALL_ME:
                string msisdn = vars[2] as string;
                finalCallbackFunction = vars[3] as postResponseFunction;
                data.Add("msisdn", msisdn);
                break;

                #endregion
                #region SET NAME
            case RequestType.SET_NAME:
                string nameToSet = vars[2] as string;
                finalCallbackFunction = vars[3] as postResponseFunction;
                data.Add("name", nameToSet);
                break;

                #endregion
                #region SET PROFILE
            case RequestType.SET_PROFILE:
                JObject jo = vars[2] as JObject;
                data = jo;
                finalCallbackFunction = vars[3] as postResponseFunction;
                break;

                #endregion
                #region POST ADDRESSBOOK
            case RequestType.POST_ADDRESSBOOK:
                Dictionary <string, List <ContactInfo> > contactListMap = vars[2] as Dictionary <string, List <ContactInfo> >;
                finalCallbackFunction = vars[3] as postResponseFunction;
                data = getJsonContactList(contactListMap);
                string x = data.ToString(Newtonsoft.Json.Formatting.None);
                Compress4(x, postStream);
                postStream.Close();
                req.BeginGetResponse(json_Callback, new object[] { req, type, finalCallbackFunction });
                ContactUtils.ContactState = ContactUtils.ContactScanState.ADDBOOK_POSTED;
                return;

                #endregion
                #region SOCIAL POST
            case RequestType.SOCIAL_POST:
                data = vars[2] as JObject;
                finalCallbackFunction = vars[3] as postResponseFunction;
                break;

                #endregion
                #region SOCIAL DELETE
            case RequestType.SOCIAL_DELETE:
                finalCallbackFunction = vars[2] as postResponseFunction;
                break;

                #endregion
                #region UPDATE ADDRESSBOOK
            case RequestType.UPDATE_ADDRESSBOOK:
                Dictionary <string, List <ContactInfo> > contacts_to_update = vars[2] as Dictionary <string, List <ContactInfo> >;
                JArray ids_json = vars[3] as JArray;
                finalCallbackFunction = vars[4] as postResponseFunction;
                if (ids_json != null)
                {
                    data.Add("remove", ids_json);
                }
                JObject ids_to_update = getJsonContactList(contacts_to_update);
                if (ids_to_update != null)
                {
                    data.Add("update", ids_to_update);
                }
                break;

                #endregion
                #region DELETE ACCOUNT
            case RequestType.DELETE_ACCOUNT:
                finalCallbackFunction = vars[2] as postResponseFunction;
                break;

                #endregion
                #region POST PROFILE ICON
            case RequestType.POST_PROFILE_ICON:
                byte[] imageBytes = (byte[])vars[2];
                finalCallbackFunction = vars[3] as postResponseFunction;
                postStream.Write(imageBytes, 0, imageBytes.Length);
                postStream.Close();
                req.BeginGetResponse(json_Callback, new object[] { req, type, finalCallbackFunction });
                return;

                #endregion
                #region POST PUSH NOTIFICATION DATA
            case RequestType.POST_PUSHNOTIFICATION_DATA:
                string uri = (string)vars[2];
                finalCallbackFunction = vars[3] as postResponseFunction;
                data.Add("dev_token", uri);
                data.Add("dev_type", "windows");
                break;

                #endregion
            case RequestType.POST_INFO_ON_APP_UPDATE:
                finalCallbackFunction = vars[2] as postResponseFunction;
                if (Utils.IsWP8)
                {
                    data["_os"] = "win8";
                }
                else
                {
                    data["_os"] = "win7";
                }
                data["_os_version"]   = Utils.getOSVersion();
                data["deviceversion"] = Utils.getDeviceModel();
                data["app_version"]   = Utils.getAppVersion();
                data["dev_type"]      = "windows";
                break;

                #region UPLOAD FILE
            case RequestType.UPLOAD_FILE:
                byte[] dataBytes = (byte[])vars[2];
                postUploadPhotoFunction finalCallbackForUploadFile = vars[3] as postUploadPhotoFunction;
                ConvMessage             convMessage = vars[4] as ConvMessage;
                SentChatBubble          chatBubble  = vars[5] as SentChatBubble;
                int    bufferSize       = 2048;
                int    startIndex       = 0;
                int    noOfBytesToWrite = 0;
                double progressValue    = 0;
                while (startIndex < dataBytes.Length)
                {
                    Thread.Sleep(5);
                    noOfBytesToWrite = dataBytes.Length - startIndex;
                    noOfBytesToWrite = noOfBytesToWrite < bufferSize ? noOfBytesToWrite : bufferSize;
                    postStream.Write(dataBytes, startIndex, noOfBytesToWrite);
                    progressValue = ((double)(startIndex + noOfBytesToWrite) / dataBytes.Length) * 100;
                    bool updated = chatBubble.updateProgress(progressValue);
                    if (!updated)
                    {
                        chatBubble.setAttachmentState(Attachment.AttachmentState.CANCELED);
                        break;
                    }
                    startIndex += noOfBytesToWrite;
                }

                postStream.Close();
                req.BeginGetResponse(json_Callback, new object[] { req, type, finalCallbackForUploadFile, convMessage, chatBubble });
                return;

                #endregion
                #region DEFAULT
            default:
                break;
                #endregion
            }

            using (StreamWriter sw = new StreamWriter(postStream))
            {
                string json = data.ToString(Newtonsoft.Json.Formatting.None);
                sw.Write(json);
            }
            postStream.Close();
            req.BeginGetResponse(json_Callback, new object[] { req, type, finalCallbackFunction });
        }
Esempio n. 19
0
        public static void uploadFile(byte[] dataBytes, postUploadPhotoFunction finalCallbackFunction, ConvMessage convMessage,
                                      SentChatBubble chatbubble)
        {
            HttpWebRequest req = HttpWebRequest.Create(new Uri(HikeConstants.FILE_TRANSFER_BASE_URL)) as HttpWebRequest;

            addToken(req);
            req.Method      = "PUT";
            req.ContentType = convMessage.FileAttachment.ContentType.Contains(HikeConstants.IMAGE) ||
                              convMessage.FileAttachment.ContentType.Contains(HikeConstants.VIDEO) ? "" : convMessage.FileAttachment.ContentType;
            req.Headers["Connection"]           = "Keep-Alive";
            req.Headers["Content-Name"]         = convMessage.FileAttachment.FileName;
            req.Headers["X-Thumbnail-Required"] = "0";

            req.BeginGetRequestStream(setParams_Callback, new object[] { req, RequestType.UPLOAD_FILE, dataBytes, finalCallbackFunction, convMessage,
                                                                         chatbubble });
        }
Esempio n. 20
0
        public void onEventReceived(string type, object obj)
        {
            #region UPDATE_UI
            if (HikePubSub.UPDATE_UI == type)
            {
                string msisdn = (string)obj;
                if (msisdn != groupId)
                {
                    return;
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    groupImage.Source = App.ViewModel.ConvMap[msisdn].AvatarImage;
                });
            }
            #endregion
            #region PARTICIPANT_JOINED_GROUP
            else if (HikePubSub.PARTICIPANT_JOINED_GROUP == type)
            {
                JObject json         = (JObject)obj;
                string  eventGroupId = (string)json[HikeConstants.TO];
                if (eventGroupId != groupId)
                {
                    return;
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    groupMembersOC.Clear();
                    for (int i = 0; i < GroupManager.Instance.GroupCache[groupId].Count; i++)
                    {
                        GroupParticipant gp = GroupManager.Instance.GroupCache[groupId][i];
                        if (!gp.HasLeft)
                        {
                            groupMembersOC.Add(gp);
                        }
                        if (!gp.IsOnHike && !EnableInviteBtn)
                        {
                            smsUsers++;
                            this.inviteBtn.IsEnabled = true;
                        }
                    }
                    groupName            = App.ViewModel.ConvMap[groupId].NameToShow;
                    groupNameTxtBox.Text = groupName;
                    PhoneApplicationService.Current.State[HikeConstants.GROUP_NAME_FROM_CHATTHREAD] = groupName;
                });
            }
            #endregion
            #region PARTICIPANT_LEFT_GROUP
            else if (HikePubSub.PARTICIPANT_LEFT_GROUP == type)
            {
                ConvMessage cm           = (ConvMessage)obj;
                string      eventGroupId = cm.Msisdn;
                if (eventGroupId != groupId)
                {
                    return;
                }
                string           leaveMsisdn = cm.GroupParticipant;
                GroupParticipant gp          = GroupManager.Instance.getGroupParticipant(null, leaveMsisdn, eventGroupId);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    for (int i = 0; i < groupMembersOC.Count; i++)
                    {
                        if (groupMembersOC[i].Msisdn == leaveMsisdn)
                        {
                            groupMembersOC.RemoveAt(i);
                            groupName            = App.ViewModel.ConvMap[groupId].NameToShow; // change name of group
                            groupNameTxtBox.Text = groupName;
                            PhoneApplicationService.Current.State[HikeConstants.GROUP_NAME_FROM_CHATTHREAD] = groupName;
                            if (!gp.IsOnHike)
                            {
                                smsUsers--;
                                if (smsUsers <= 0)
                                {
                                    inviteBtn.IsEnabled = false;
                                }
                            }
                            return;
                        }
                    }
                });
            }
            #endregion
            #region GROUP_NAME_CHANGED
            else if (HikePubSub.GROUP_NAME_CHANGED == type)
            {
                if (isgroupNameSelfChanged)
                {
                    return;
                }
                string grpId = (string)obj;
                if (grpId == groupId)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        this.groupNameTxtBox.Text = App.ViewModel.ConvMap[groupId].ContactName;
                    });
                }
            }
            #endregion
            #region GROUP PIC CHANGED
            else if (HikePubSub.UPDATE_GRP_PIC == type)
            {
                string grpId = (string)obj;
                if (grpId == groupId)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        this.groupImage.Source = App.ViewModel.ConvMap[groupId].AvatarImage;
                    });
                }
            }
            #endregion
            #region GROUP_END
            else if (HikePubSub.GROUP_END == type)
            {
                string gId = (string)obj;
                if (gId == groupId)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.GoBack();
                    });
                }
            }
            #endregion
            #region USER JOINED HIKE
            else if (HikePubSub.USER_JOINED == type)
            {
                string ms = (string)obj;
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    for (int i = 0; i < groupMembersOC.Count; i++)
                    {
                        if (groupMembersOC[i].Msisdn == ms)
                        {
                            groupMembersOC[i].IsOnHike = true;
                            smsUsers--;
                            if (smsUsers == 0)
                            {
                                this.inviteBtn.IsEnabled = false;
                            }
                            return;
                        }
                    }
                });
            }
            #endregion
            #region USER LEFT HIKE
            else if (HikePubSub.USER_LEFT == type)
            {
                string ms = (string)obj;
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    for (int i = 0; i < groupMembersOC.Count; i++)
                    {
                        if (groupMembersOC[i].Msisdn == ms)
                        {
                            smsUsers++;
                            groupMembersOC[i].IsOnHike = false;
                            this.inviteBtn.IsEnabled   = true;
                            return;
                        }
                    }
                });
            }

            #endregion
        }
Esempio n. 21
0
        public static ConversationListObject addConversation(ConvMessage convMessage, bool isNewGroup)
        {
            ConversationListObject obj = null;

            if (isNewGroup)
            {
                string groupName = convMessage.Msisdn;
                if (PhoneApplicationService.Current.State.ContainsKey(convMessage.Msisdn))
                {
                    groupName = (string)PhoneApplicationService.Current.State[convMessage.Msisdn];
                    PhoneApplicationService.Current.State.Remove(convMessage.Msisdn);
                }
                obj = new ConversationListObject(convMessage.Msisdn, groupName, convMessage.Message, true, convMessage.Timestamp, null, convMessage.MessageStatus, convMessage.MessageId);
            }
            else
            {
                ContactInfo contactInfo = UsersTableUtils.getContactInfoFromMSISDN(convMessage.Msisdn);
                byte[]      avatar      = MiscDBUtil.getThumbNailForMsisdn(convMessage.Msisdn);
                obj = new ConversationListObject(convMessage.Msisdn, contactInfo == null ? null : contactInfo.Name, convMessage.Message,
                                                 contactInfo == null ? !convMessage.IsSms : contactInfo.OnHike, convMessage.Timestamp, avatar, convMessage.MessageStatus, convMessage.MessageId);
                if (App.ViewModel.Isfavourite(convMessage.Msisdn))
                {
                    obj.IsFav = true;
                }
            }

            /*If ABCD join grp chat convObj should show D joined grp chat as D is last in sorted order*/
            if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.PARTICIPANT_JOINED)
            {
                obj.LastMessage = convMessage.Message;
            }
            else if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.USER_OPT_IN)
            {
                obj.LastMessage     = obj.NameToShow + AppResources.USER_OPTED_IN_MSG;
                convMessage.Message = obj.LastMessage;
            }
            else if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.CREDITS_GAINED)
            {
                obj.LastMessage = convMessage.Message;
            }
            else if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.DND_USER)
            {
                obj.LastMessage     = string.Format(AppResources.DND_USER, obj.NameToShow);
                convMessage.Message = obj.LastMessage;
            }
            else if (convMessage.GrpParticipantState == ConvMessage.ParticipantInfoState.USER_JOINED)
            {
                obj.LastMessage     = string.Format(AppResources.USER_JOINED_HIKE, obj.NameToShow);
                convMessage.Message = obj.LastMessage;
            }

            Stopwatch st1     = Stopwatch.StartNew();
            bool      success = MessagesTableUtils.addMessage(convMessage);

            if (!success)
            {
                return(null);
            }
            obj.LastMsgId = convMessage.MessageId;
            st1.Stop();
            long msec1 = st1.ElapsedMilliseconds;

            Debug.WriteLine("Time to add chat msg : {0}", msec1);

            Stopwatch st = Stopwatch.StartNew();

            //saveNewConv(obj);
            saveConvObject(obj, obj.Msisdn.Replace(":", "_"));
            int convs = 0;

            App.appSettings.TryGetValue <int>(HikeViewModel.NUMBER_OF_CONVERSATIONS, out convs);
            App.WriteToIsoStorageSettings(HikeViewModel.NUMBER_OF_CONVERSATIONS, convs + 1);
            st.Stop();
            long msec = st.ElapsedMilliseconds;

            Debug.WriteLine("Time to write conversation to iso storage {0}", msec);

            return(obj);
        }
        private void initializeBasedOnState(ConvMessage cm, bool isGroupChat, string userName, string messageString)
        {
            bool   hasAttachment = cm.HasAttachment;
            string contentType   = cm.FileAttachment == null ? "" : cm.FileAttachment.ContentType;
            bool   isContact     = hasAttachment && contentType.Contains(HikeConstants.CT_CONTACT);

            if (isContact)
            {
                messageString = string.IsNullOrEmpty(cm.FileAttachment.FileName) ? "contact" : cm.FileAttachment.FileName;
            }
            bool showDownload = cm.FileAttachment != null && (cm.FileAttachment.FileState == Attachment.AttachmentState.CANCELED ||
                                                              cm.FileAttachment.FileState == Attachment.AttachmentState.FAILED_OR_NOT_STARTED);
            bool isNudge = cm.MetaDataString != null && cm.MetaDataString.Contains("poke");

            Rectangle BubbleBg = new Rectangle();

            if (!isNudge)
            {
                BubbleBg.Fill      = UI_Utils.Instance.ReceivedChatBubbleColor;
                bubblePointer.Fill = UI_Utils.Instance.ReceivedChatBubbleColor;
            }
            else
            {
                BubbleBg.Fill      = UI_Utils.Instance.PhoneThemeColor;
                bubblePointer.Fill = UI_Utils.Instance.PhoneThemeColor;
            }
            Grid.SetRowSpan(BubbleBg, 2 + (isGroupChat ? 1 : 0));
            wrapperGrid.Children.Add(BubbleBg);

            int rowNumber = 0;

            if (isGroupChat)
            {
                TextBlock textBlck = new TextBlock();
                textBlck.Text       = userName + " -";
                textBlck.FontSize   = 22;
                textBlck.FontFamily = UI_Utils.Instance.SemiBoldFont;
                textBlck.Foreground = UI_Utils.Instance.GroupChatHeaderColor;
                textBlck.Margin     = userNameMargin;
                Grid.SetRow(textBlck, 0);
                wrapperGrid.Children.Add(textBlck);
                rowNumber = 1;
            }

            if (hasAttachment || isNudge)
            {
                attachment = new Grid();
                RowDefinition r1 = new RowDefinition();
                r1.Height = GridLength.Auto;
                RowDefinition r2 = new RowDefinition();
                r2.Height = GridLength.Auto;
                attachment.RowDefinitions.Add(r1);
                attachment.RowDefinitions.Add(r2);
                Grid.SetRow(attachment, rowNumber);
                Grid.SetColumn(attachment, 1);
                wrapperGrid.Children.Add(attachment);

                MessageImage                     = new Image();
                MessageImage.MaxWidth            = 180;
                MessageImage.MaxHeight           = 180;
                MessageImage.HorizontalAlignment = HorizontalAlignment.Left;
                MessageImage.Margin              = imgMargin;
                if (contentType.Contains(HikeConstants.AUDIO))
                {
                    this.MessageImage.Source = UI_Utils.Instance.AudioAttachmentReceive;
                }
                else if (isNudge)
                {
                    this.MessageImage.Source = UI_Utils.Instance.NudgeReceived;
                    this.MessageImage.Height = 35;
                    this.MessageImage.Width  = 46;
                    this.MessageImage.Margin = nudgeMargin;
                }
                else if (isContact)
                {
                    this.MessageImage.Source = UI_Utils.Instance.ContactIcon;
                    this.MessageImage.Height = 20;
                    this.MessageImage.Width  = 30;
                    TextBlock textBlck = new TextBlock();
                    textBlck.Text         = messageString;
                    textBlck.FontSize     = 22;
                    textBlck.Foreground   = UI_Utils.Instance.ReceiveMessageForeground;
                    textBlck.Margin       = contactMessageTextMargin;
                    textBlck.TextWrapping = TextWrapping.Wrap;
                    textBlck.FontFamily   = UI_Utils.Instance.SemiLightFont;
                    textBlck.MinWidth     = 150;
                    textBlck.MaxWidth     = 330;
                    Grid.SetRow(textBlck, 0);
                    Grid.SetColumn(textBlck, 1);
                    attachment.Children.Add(textBlck);
                }
                Grid.SetRow(MessageImage, 0);
                attachment.Children.Add(MessageImage);

                if ((contentType.Contains(HikeConstants.VIDEO) || contentType.Contains(HikeConstants.AUDIO) || showDownload) && !contentType.Contains(HikeConstants.LOCATION) &&
                    !contentType.Contains(HikeConstants.CT_CONTACT))
                {
                    PlayIcon           = new Image();
                    PlayIcon.MaxWidth  = 43;
                    PlayIcon.MaxHeight = 42;
                    if (contentType.Contains(HikeConstants.IMAGE))
                    {
                        PlayIcon.Source = UI_Utils.Instance.DownloadIcon;
                    }
                    else
                    {
                        PlayIcon.Source = UI_Utils.Instance.PlayIcon;
                    }
                    PlayIcon.HorizontalAlignment = HorizontalAlignment.Center;
                    PlayIcon.VerticalAlignment   = VerticalAlignment.Center;

                    PlayIcon.Margin = imgMargin;
                    Grid.SetRow(PlayIcon, 0);
                    attachment.Children.Add(PlayIcon);
                }
                if (!isNudge)
                {
                    downloadProgress            = new ProgressBar();
                    downloadProgress.Height     = 10;
                    downloadProgress.Background = new SolidColorBrush(Color.FromArgb(255, 0x99, 0x99, 0x99));
                    downloadProgress.Foreground = UI_Utils.Instance.ReceivedChatBubbleProgress;
                    downloadProgress.Minimum    = 0;
                    downloadProgress.MaxHeight  = 100;
                    downloadProgress.Opacity    = 0;
                    if (showDownload)
                    {
                        temporaryProgressBar        = new PerformanceProgressBar();
                        temporaryProgressBar.Height = 10;
                        //                    temporaryProgressBar.Background = UI_Utils.Instance.TextBoxBackground;
                        temporaryProgressBar.Foreground = UI_Utils.Instance.ReceivedChatBubbleProgress;
                        temporaryProgressBar.IsEnabled  = false;
                        temporaryProgressBar.Opacity    = 1;
                        downloadProgress.Visibility     = Visibility.Collapsed;
                        downloadProgress.Opacity        = 1;
                        Grid.SetRow(temporaryProgressBar, 1);
                        attachment.Children.Add(temporaryProgressBar);
                    }
                    Grid.SetRow(downloadProgress, 1);
                    attachment.Children.Add(downloadProgress);
                }
            }
            else
            {
                MessageText       = new LinkifiedTextBox(UI_Utils.Instance.ReceiveMessageForeground, 22, messageString);
                MessageText.Width = 330;
                if (!isGroupChat)
                {
                    MessageText.Margin = messageTextMargin;
                }
                MessageText.FontFamily = UI_Utils.Instance.SemiLightFont;
                Grid.SetRow(MessageText, rowNumber);
                wrapperGrid.Children.Add(MessageText);
            }
            if (!isNudge)
            {
                TimeStampBlock = new TextBlock();
                TimeStampBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                TimeStampBlock.FontSize            = 18;
                TimeStampBlock.Foreground          = UI_Utils.Instance.ReceivedChatBubbleTimestamp;
                TimeStampBlock.Text   = TimeStamp;
                TimeStampBlock.Margin = timeStampBlockMargin;
                Grid.SetRow(TimeStampBlock, rowNumber + 1);
                wrapperGrid.Children.Add(TimeStampBlock);
            }
        }
Esempio n. 23
0
        public SentChatBubble(ConvMessage cm, bool readFromDB, string messageText)
            : base(cm)
        {
            InitializeComponent();
            initializeBasedOnState(cm, messageText);
            //IsSms is false for group chat
            switch (cm.MessageStatus)
            {
            case ConvMessage.State.SENT_CONFIRMED:
                this.SDRImage.Source = UI_Utils.Instance.Sent;
                break;

            case ConvMessage.State.SENT_DELIVERED:
                this.SDRImage.Source = UI_Utils.Instance.Delivered;
                break;

            case ConvMessage.State.SENT_DELIVERED_READ:
                this.SDRImage.Source = UI_Utils.Instance.Read;
                break;

            case ConvMessage.State.UNKNOWN:
                if (cm.HasAttachment)
                {
                    this.SDRImage.Source = UI_Utils.Instance.HttpFailed;
                }
                break;

            case ConvMessage.State.SENT_UNCONFIRMED:
                if (this.FileAttachment != null)
                {
                    if (string.IsNullOrEmpty(this.FileAttachment.FileKey))
                    {
                        this.SDRImage.Source = UI_Utils.Instance.HttpFailed;
                    }
                    else
                    {
                        this.SDRImage.Source = UI_Utils.Instance.Trying;
                    }
                }
                else if (readFromDB)
                {
                    this.SDRImage.Source = UI_Utils.Instance.Trying;
                }
                else
                {
                    scheduleTryingImage();
                }
                break;

            default:
                break;
            }
            if (cm.FileAttachment != null && cm.FileAttachment.Thumbnail != null)
            {
                using (var memStream = new MemoryStream(cm.FileAttachment.Thumbnail))
                {
                    memStream.Seek(0, SeekOrigin.Begin);
                    BitmapImage fileThumbnail = new BitmapImage();
                    fileThumbnail.SetSource(memStream);
                    this.MessageImage.Source = fileThumbnail;
                }
            }
            this.BubblePoint.Fill = bubbleColor;
            this.BubbleBg.Fill    = bubbleColor;
        }
        public void onEventReceived(string type, object obj)
        {
            if (HikePubSub.MESSAGE_RECEIVED == type || HikePubSub.SEND_NEW_MSG == type)
            {
                ConvMessage            convMessage = (ConvMessage)obj;
                ConversationListObject mObj;
                bool isNewConversation = false;

                /*This is used to avoid cross thread invokation exception*/

                if (convMap.ContainsKey(convMessage.Msisdn))
                {
                    mObj             = convMap[convMessage.Msisdn];
                    mObj.LastMessage = convMessage.Message;
                    mObj.TimeStamp   = TimeUtils.getTimeString(convMessage.Timestamp);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        App.ViewModel.MessageListPageCollection.Remove(mObj);
                    });
                }
                else
                {
                    ContactInfo contact   = UsersTableUtils.getContactInfoFromMSISDN(convMessage.Msisdn);
                    Thumbnails  thumbnail = MiscDBUtil.getThumbNailForMSisdn(convMessage.Msisdn);
                    mObj = new ConversationListObject(convMessage.Msisdn, contact == null ? convMessage.Msisdn : contact.Name, convMessage.Message,
                                                      contact == null ? !convMessage.IsSms : contact.OnHike, TimeUtils.getTimeString(convMessage.Timestamp),
                                                      thumbnail == null ? null : thumbnail.Avatar);

                    convMap.Add(convMessage.Msisdn, mObj);
                    isNewConversation = true;
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (App.ViewModel.MessageListPageCollection == null)
                    {
                        App.ViewModel.MessageListPageCollection = new ObservableCollection <ConversationListObject>();
                    }
                    App.ViewModel.MessageListPageCollection.Insert(0, mObj);
                });
                object[] vals = new object[2];
                vals[0] = convMessage;
                vals[1] = isNewConversation;
                if (HikePubSub.SEND_NEW_MSG == type)
                {
                    mPubSub.publish(HikePubSub.MESSAGE_SENT, vals);
                }
            }
            else if (HikePubSub.MSG_READ == type)
            {
                string msisdn = (string)obj;
                try
                {
                    ConversationListObject convObj = convMap[msisdn];
                    convObj.MessageStatus = ConvMessage.State.RECEIVED_READ;
                    //TODO : update the UI here also.
                }
                catch (KeyNotFoundException)
                {
                }
            }
            else if ((HikePubSub.USER_LEFT == type) || (HikePubSub.USER_JOINED == type))
            {
                string msisdn = (string)obj;
                try
                {
                    ConversationListObject convObj = convMap[msisdn];
                    convObj.IsOnhike = HikePubSub.USER_JOINED == type;
                }
                catch (KeyNotFoundException)
                {
                }
            }
            else if (HikePubSub.UPDATE_UI == type)
            {
                string msisdn = (string)obj;
                try
                {
                    ConversationListObject convObj = convMap[msisdn];
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        convObj.NotifyPropertyChanged("Msisdn");
                    });
                }
                catch (KeyNotFoundException)
                {
                }
            }
            else if (HikePubSub.SMS_CREDIT_CHANGED == type)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    creditsTxtBlck.Text = Convert.ToString((int)obj);
                });
            }
        }
Esempio n. 25
0
        //private static Thickness textBubbleMargin = new Thickness(74, 12, 0, 10);
        //private static Thickness nudgeBubbleMargin = new Thickness(348, 12, 0, 10);
        //private static Thickness attachmentBubbleMargin = new Thickness(200, 12, 0, 10);

        private void initializeBasedOnState(ConvMessage cm, string messageString)
        {
            bool   hasAttachment = cm.HasAttachment;
            string contentType   = cm.FileAttachment == null ? "" : cm.FileAttachment.ContentType;
            //string messageString = cm.Message;
            bool isSMS   = cm.IsSms;
            bool isNudge = cm.MetaDataString != null && cm.MetaDataString.Contains("poke");

            bool isContact = hasAttachment && contentType.Contains(HikeConstants.CT_CONTACT);

            if (isContact)
            {
                messageString = cm.FileAttachment.FileName;
            }
            BubbleBg = new Rectangle();
            Grid.SetRowSpan(BubbleBg, 2);
            Grid.SetColumn(BubbleBg, 1);
            wrapperGrid.Children.Add(BubbleBg);

            if (hasAttachment || isNudge)
            {
                attachment = new Grid();
                RowDefinition r1 = new RowDefinition();
                r1.Height = GridLength.Auto;
                RowDefinition r2 = new RowDefinition();
                r2.Height = GridLength.Auto;
                attachment.RowDefinitions.Add(r1);
                attachment.RowDefinitions.Add(r2);
                Grid.SetRow(attachment, 0);
                Grid.SetColumn(attachment, 1);
                wrapperGrid.Children.Add(attachment);

                MessageImage                     = new Image();
                MessageImage.MaxWidth            = 180;
                MessageImage.MaxHeight           = 180;
                MessageImage.HorizontalAlignment = HorizontalAlignment.Right;
                MessageImage.Margin              = imgMargin;
                if (contentType.Contains(HikeConstants.AUDIO))
                {
                    this.MessageImage.Source = UI_Utils.Instance.AudioAttachmentSend;
                }
                else if (isNudge)
                {
                    this.MessageImage.Source = UI_Utils.Instance.NudgeSent;
                    this.MessageImage.Height = 35;
                    this.MessageImage.Width  = 48;
                    this.MessageImage.Margin = nudgeMargin;
                    //this.Margin = nudgeBubbleMargin;
                }
                else if (isContact)
                {
                    this.MessageImage.Source = UI_Utils.Instance.ContactIcon;
                    this.MessageImage.Height = 20;
                    this.MessageImage.Width  = 30;
                    this.MessageImage.HorizontalAlignment = HorizontalAlignment.Left;
                    TextBlock textBlck = new TextBlock();
                    textBlck.Text         = messageString;
                    textBlck.FontSize     = 22;
                    textBlck.MinWidth     = 150;
                    textBlck.MaxWidth     = 330;
                    textBlck.Foreground   = UI_Utils.Instance.White;
                    textBlck.Margin       = contactMessageTextMargin;
                    textBlck.TextWrapping = TextWrapping.Wrap;
                    Grid.SetRow(textBlck, 0);
                    Grid.SetColumn(textBlck, 1);
                    attachment.Children.Add(textBlck);
                    textBlck.FontFamily = UI_Utils.Instance.SemiLightFont;
                }
                Grid.SetRow(MessageImage, 0);

                attachment.Children.Add(MessageImage);

                if (contentType.Contains(HikeConstants.VIDEO) || contentType.Contains(HikeConstants.AUDIO))
                {
                    PlayIcon                     = new Image();
                    PlayIcon.MaxWidth            = 43;
                    PlayIcon.MaxHeight           = 42;
                    PlayIcon.Source              = UI_Utils.Instance.PlayIcon;
                    PlayIcon.HorizontalAlignment = HorizontalAlignment.Center;
                    PlayIcon.VerticalAlignment   = VerticalAlignment.Center;
                    PlayIcon.Margin              = imgMargin;
                    Grid.SetRow(PlayIcon, 0);
                    attachment.Children.Add(PlayIcon);
                }
                if (!isNudge)
                {
                    uploadProgress        = new ProgressBar();
                    uploadProgress.Height = 10;
                    if (isSMS)
                    {
                        uploadProgress.Background = UI_Utils.Instance.SmsBackground;
                    }
                    else
                    {
                        uploadProgress.Background = UI_Utils.Instance.HikeMsgBackground;
                    }
                    uploadProgress.Opacity    = 0;
                    uploadProgress.Foreground = progressColor;
                    uploadProgress.Value      = 0;
                    uploadProgress.Minimum    = 0;
                    uploadProgress.MaxHeight  = 100;
                    Grid.SetRow(uploadProgress, 1);
                    attachment.Children.Add(uploadProgress);
                    //this.Margin = attachmentBubbleMargin;
                }
            }
            else
            {
                MessageText            = new LinkifiedTextBox(UI_Utils.Instance.White, 22, messageString);
                MessageText.Width      = 330;
                MessageText.Foreground = progressColor;
                MessageText.Margin     = messageTextMargin;
                MessageText.FontFamily = UI_Utils.Instance.SemiLightFont;
                Grid.SetRow(MessageText, 0);
                Grid.SetColumn(MessageText, 1);
                wrapperGrid.Children.Add(MessageText);
                //this.Margin = textBubbleMargin;
            }

            SDRImage        = new Image();
            SDRImage.Margin = sdrImageMargin;
            SDRImage.Height = 20;
            Grid.SetRowSpan(SDRImage, 2);
            Grid.SetColumn(SDRImage, 0);
            wrapperGrid.Children.Add(SDRImage);
            if (!isNudge)
            {
                TimeStampBlock = new TextBlock();
                TimeStampBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                TimeStampBlock.FontSize            = 18;
                if (isSMS)
                {
                    TimeStampBlock.Foreground = UI_Utils.Instance.SMSSentChatBubbleTimestamp;
                }
                else
                {
                    TimeStampBlock.Foreground = UI_Utils.Instance.HikeSentChatBubbleTimestamp;
                }
                TimeStampBlock.Text   = TimeStamp;
                TimeStampBlock.Margin = timeStampBlockMargin;
                Grid.SetRow(TimeStampBlock, 1);
                Grid.SetColumn(TimeStampBlock, 1);
                wrapperGrid.Children.Add(TimeStampBlock);
            }

            if (isNudge)
            {
                bubbleColor = UI_Utils.Instance.PhoneThemeColor;
            }
            else if (isSMS)
            {
                bubbleColor = UI_Utils.Instance.SmsBackground;
            }
            else
            {
                bubbleColor = UI_Utils.Instance.HikeMsgBackground;
            }
        }