protected internal virtual void OnMessageReceived(ConversationMessage message)
 {
 }
示例#2
0
 public void UpdateConversationMessage(ConversationMessage currentConversationMessage)
 {
     this.ObjectContext.ConversationMessages.AttachAsModified(currentConversationMessage, this.ChangeSet.GetOriginal(currentConversationMessage));
 }
示例#3
0
 public async Task<ConversationMessage> WriteMessageToChat(User user, Guid chatId, ConversationMessage message)
 {
     var conversationMember =
         await this.databaseContext.ConversationMembers.FirstOrDefaultAsync(x =>
             x.UserId == user.Id && x.ConversationId == chatId);
     if (conversationMember == null) return null;
     message.Sender = conversationMember;
     message.SentOn = DateTime.UtcNow;
     await this.databaseContext.ConversationMessages.AddAsync(message);
     await this.databaseContext.SaveChangesAsync();
     return message;
 }
示例#4
0
 public async Task <ConversationMessage> WriteMessageToChat(Guid chatId, ConversationMessage message)
 {
     return(await this.repository.WriteMessageToChat(this.identityService.AuthenticatedUser, chatId, message));
 }
        protected internal override void OnMessageReceived(ConversationMessage message)
        {
            if (message is CancelItemMessage)
            {
                CancelItemMessage msg = message as CancelItemMessage;
                msg.Items.ForEach((o) =>
                {
                    var cutItem = Items.FirstOrDefault(d => d.ID == o.ID);
                    if (cutItem != null)
                    {
                        cutItem.TransferState = TransferState.Canceled;
                    }
                });

                holder.Remove(msg.Items);
            }
            else if (message is ConfirmItemMessage)
            {
                Debug.WriteLine("ConfirmedItem msg count=" + (confirmMsgCount++));
                var cm = message as ConfirmItemMessage;
                //若不复制,Confirmed中的移除动作报错。测试确认一下。
                var tmpProcessingList = new List <Item>(ProcessingItems);
                //Console.WriteLine("Received a confirm message itemid=" + cm.ItemID);
                var item = tmpProcessingList.Find(i => i.ID == cm.ItemID);
                if (item != null)
                {
                    //这个状态改变,会导致item从ProcessingItems中移除。
                    item.ForceComplete(TransferState.Confirmed);
                    //移除动作是在同一线程中,移除完毕会进入这里。
                    if (ProcessingItems.Count() == 0)
                    {
                        //应该还需要做这个检查,有可能存在没有正在处理的文件,但其他也没法送,或者状态不对的情况。
                        if (Items.All(o => o.TransferState == TransferState.Confirmed))
                        {
                            //所有文件成功发送完毕
                            Completed?.Invoke(this);
                        }
                        else
                        {
                            //该做什么?没有正在处理的Item,但也不是所有的Item状态都是Confirmed。出错了..., 如果给对方发了列表,对方马上就回复Confirm,也是0
                        }
                    }
                    else
                    {
                        if (tmpProcessingList.All(o => o.TransferState == TransferState.WaitConfirmTimeouted || o.TransferState == TransferState.Error))
                        {
                            //处理列表中的东西,都是出错 / 等待确认超时的,没办法再处理了。报告错误。上层如果要重新发送,可以到ProcessingItem里面去取。
                            //TODO 只需检查ProcessingItems即可。需要确认一个文件出错,或者等待确认超时,传递到父目录没有?
                            Errored?.Invoke(this);
                        }
                    }
                }
            }
            else if (message is ReceiveItemErrorMessage)
            {
                var rie  = message as ReceiveItemErrorMessage;
                var item = ProcessingItems.FirstOrDefault(i => i.ID == rie.ItemID);
                if (item == null)
                {
                    item = Items.Find(i => i.ID == rie.ID);
                }
                if (item != null)
                {
                    item.ErrorCode     = rie.ErrorCode;
                    item.TransferState = TransferState.Error;
                }
            }
        }
示例#6
0
    private void BindMessages()
    {
        if (SelectedConversation != null)
        {
            var           messages = SelectedConversation.AllMessages;
            StringBuilder sb       = new StringBuilder();
            int           otherId  = SelectedConversation.GetOtherUserId(Member.CurrentId);

            var otherMember = new Member(otherId);
            var avatarImg   = string.Format("<a href=\"javascript:;\" class=\"image\"><img src='{0}' /></a>", ResolveUrl(otherMember.AvatarUrl));

            int lastMemberId = 0;

            ConversationMessage.SetConversationMessagesAsRead(SelectedConversation.Id, Member.CurrentId);

            foreach (var m in messages)
            {
                var isMyMessage = m.UserId == Member.CurrentId;
                sb.AppendFormat("<li class='{0}'>", isMyMessage ? "right" : "left");

                StringBuilder messageText = new StringBuilder();

                if (m.MessageType == MessageType.RepresentativeDepositRequest || m.MessageType == MessageType.RepresentativeWithdrawalRequest)
                {
                    //If action is pending and escrow time finished, change action status
                    if (ConversationManager.GetEscrowTimeLeft(m.DateTime) <= 0 && m.RepresentativeRequestStatus == RepresentativeRequestStatus.Pending)
                    {
                        m.RepresentativeRequestStatus = RepresentativeRequestStatus.InDispute;
                        m.Save();
                    }

                    string commandText = m.MessageType == MessageType.RepresentativeDepositRequest ? U6010.DEPOSITVIAREPRESENTATIVE : U6010.WITHDRAWVIAREPRESENTATIVE;
                    messageText.AppendFormat("<div class=\"alert alert-warning fade in m-b-15 text-center w-100\">{0}.<br/>{1}: <b>{2}</b> ({5} - {6})<br/>{3}: <b>{4}</b>",
                                             commandText, L1.AMOUNT, m.RepresentativeTransferAmount, L1.STATUS, m.RepresentativeRequestStatus.ToString(), U6010.WITHDRAWALFEE,
                                             NumberUtils.FormatPercents(AppSettings.Representatives.RepresentativesHelpWithdrawalFee));

                    if (m.RepresentativeRequestStatus == RepresentativeRequestStatus.Pending)
                    {
                        messageText.AppendFormat("<br/><br/>{0}: {1}", U4200.TIMELEFT, ConversationManager.GetHtmlEscrowTimeLeft(m.DateTime));
                    }

                    if (m.RepresentativeRequestStatus == RepresentativeRequestStatus.Pending)
                    {
                        if (m.UserId != Member.CurrentId)
                        {
                            messageText.AppendFormat("<br/><br/>");
                            messageText.AppendFormat("<a href=\"user/network/messenger.aspx?action=confirm&id={1}\" class='btn btn-primary btn-xs m-r-5 btn-success'><i class='fa fa-check'></i> {0}</a>", L1.CONFIRM, m.Id);

                            if (m.MessageType == MessageType.RepresentativeDepositRequest)
                            {
                                messageText.AppendFormat("<a href=\"user/network/messenger.aspx?action=dispute&id={1}\" class='btn btn-primary btn-xs m-r-5 btn-danger'><i class='fa fa-exclamation'></i> {0}</a>", U6010.DISPUTE, m.Id);
                            }

                            if (m.MessageType == MessageType.RepresentativeWithdrawalRequest)
                            {
                                messageText.AppendFormat("<a href=\"user/network/messenger.aspx?action=reject&id={1}\" class='btn btn-primary btn-xs m-r-5 btn-danger'><i class='fa fa-exclamation'></i> {0}</a>", U6010.REJECT, m.Id);
                            }
                        }
                        else if (m.MessageType == MessageType.RepresentativeDepositRequest)
                        {
                            messageText.AppendFormat("<br /><a href=\"user/network/messenger.aspx?action=cancel&id={1}\" class='btn btn-primary btn-xs m-r-5 btn-warning'><i class='fa fa-ban'></i> {0}</a>", U4000.CANCEL, m.Id);
                        }
                    }

                    messageText.AppendFormat("</div>");
                }

                messageText.Append(m.Text);

                if (lastMemberId == m.UserId)
                {
                    sb.AppendFormat("<div class=\"row\"><div class=\"col-md-12\"><div class=\"message p-20 no-direction {0}\">{1}</div></div></div>", isMyMessage ? "my-message" : "", messageText);
                }
                else
                {
                    sb.AppendFormat("<div class=\"row\"><div class=\"col-md-12\"><a href=\"javascript:;\" class=\"name\">{0}</a>", isMyMessage ? Member.CurrentName : otherMember.Name);
                    sb.AppendFormat("<span class=\"date-time\">{0}</span></div></div>", m.DateTime.ToLongDateString() + " " + m.DateTime.ToLongTimeString());
                    sb.AppendFormat("<div class=\"row\"><div class=\"col-md-12\">{0}<div class=\"message p-20 {1}\">{2}</div></div></div>", isMyMessage ? "" : avatarImg, isMyMessage ? "my-message" : "", messageText);
                }
                sb.Append("</li>");

                lastMemberId = m.UserId;
            }

            MessagesLiteral.Text        = sb.ToString();
            OtherMemberNameLiteral.Text = otherMember.Name;
        }
    }
示例#7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        AccessManager.RedirectIfDisabled(AppSettings.TitanFeatures.PeopleMessagesEnabled);
        user = Member.CurrentInCache;
        StatusPlaceHolder.Visible = false;

        if (Request.QueryString["recipientId"] != null)
        {
            int recipientId = Convert.ToInt32(Request.QueryString["recipientId"]);
            if (recipientId == user.Id)
            {
                Response.Redirect("messenger.aspx");
            }
            try
            {
                Recipient = new Member(recipientId);
            }
            catch
            {
                Response.Redirect("messenger.aspx");
            }
        }

        if (Request.QueryString["cid"] != null)
        {
            try
            {
                var conversation = new Conversation(Convert.ToInt32(Request.QueryString["cid"]));

                if (conversation.UserIdOne == Member.CurrentId || conversation.UserIdTwo == Member.CurrentId)
                {
                    SelectedConversation = conversation;
                }

                ConversationMessage.SetConversationMessagesAsRead(Convert.ToInt32(Request.QueryString["cid"]), Member.CurrentId);
            }
            catch (Exception ex) { }
        }

        if (!IsPostBack)
        {
            SendButton.Text = L1.SEND;

            #region Actions

            try
            {
                if (Request.QueryString["action"] != null && Request.QueryString["id"] != null)
                {
                    ErrorMessagePanel.Visible = false;
                    SuccMessagePanel.Visible  = false;
                    StatusPlaceHolder.Visible = true;

                    //Perform actions
                    ConversationMessage conversationMessage = new ConversationMessage(Convert.ToInt32(Request.QueryString["id"]));

                    SuccMessage.Text = String.Empty;

                    if (Request.QueryString["action"] == "confirm")
                    {
                        SuccMessage.Text = conversationMessage.TryConfirmTransaction(Member.CurrentId);
                    }

                    if (Request.QueryString["action"] == "dispute")
                    {
                        conversationMessage.TryDisputeTransaction(Member.CurrentId);
                        SuccMessage.Text = U6010.DEPOSITDISPUTEINFO;
                    }

                    if (Request.QueryString["action"] == "reject")
                    {
                        conversationMessage.TryRejectTransaction(Member.CurrentId);
                    }

                    if (Request.QueryString["action"] == "cancel")
                    {
                        conversationMessage.TryCancelTransaction(Member.CurrentId);
                        SuccMessage.Text = String.Format(U6010.DEPOSITCANCELEDINFO);
                    }

                    NotificationManager.Refresh(NotificationType.PendingRepresentativePaymentRequest);
                    SuccMessagePanel.Visible = true;
                }
            }
            catch (MsgException ex)
            {
                ErrorMessagePanel.Visible = true;
                ErrorMessage.Text         = ex.Message;
            }
            catch (Exception) { }

            #endregion
        }

        BindConversations();
        BindMessages();

        OtherMemberNameLiteral.Text = U5004.MESSAGE;
        MessageTextBox.Attributes.Add("placeholder", U6000.ENTERYOURMESSAGEHERE);
    }
示例#8
0
 private void AddCaptureToExportList()
 {
     ConversationMessage.SendConversationMessage(this.CurrentConversation, ConversationMessage.MessageType.AddConversationToExport, false);
 }
示例#9
0
    private static int RefreshAndGetValue(NotificationType type, Member user = null)
    {
        if (!Member.IsLogged)
        {
            return(0);
        }

        if (user == null)
        {
            user = Member.CurrentInCache;
        }

        switch (type)
        {
        case NotificationType.NewAds:

            List <PtcAdvert> AvailableAdList = PtcAdvert.GetActiveAdsForUser(user);
            int newAdsCounter = 0;

            foreach (PtcAdvert Ad in AvailableAdList)
            {
                if (!user.AdsViewed.Contains(Ad.Id))
                {
                    newAdsCounter++;
                }
            }
            return(newAdsCounter);

        case NotificationType.NewMessages:
            return(ConversationMessage.GetNumberOfUnreadMessages(Member.CurrentId));

        case NotificationType.NewDirectReferrals:

            using (var bridge = ParserPool.Acquire(Database.Client))
            {
                return((int)bridge.Instance.ExecuteRawCommandScalar("SELECT COUNT (*) FROM Users WHERE IsSpotted = 0 AND ReferrerId = "
                                                                    + Member.CurrentId));
            }

        case NotificationType.NewAchievements:

            return(user.UnspottedAchievements);

        case NotificationType.NewCPAOffers:
            //CPAOFfers
            //User is already loaded
            var OM = new OffersManager(user);
            return(OM.AllActiveOffersForMember.Count);

        case NotificationType.UnreadSupportTickets:

            return((int)TableHelper.SelectScalar(String.Format("SELECT COUNT(*) FROM SupportTickets WHERE IsRead = 0 AND FromUsername = '******'",
                                                               Member.CurrentName)));


        case NotificationType.NewAdPacksAds:

            List <AdPacksAdvert> AdPacksAdList = AdPackManager.GetAdPacksAdvertsForUsers(user.Membership.AdPackDailyRequiredClicks);
            int numberofAdsViewed = user.RSAPTCAdsViewed.Count();

            int adsRequiredToWatch = user.Membership.AdPackDailyRequiredClicks - numberofAdsViewed;

            if (adsRequiredToWatch <= 0)
            {
                return(0);
            }

            if (adsRequiredToWatch > AdPacksAdList.Count)
            {
                int adCount = 0;
                foreach (AdPacksAdvert ad in AdPacksAdList)
                {
                    if (!user.RSAPTCAdsViewed.Contains(ad.Id))
                    {
                        adCount++;
                    }
                }
                return(adCount);
            }
            return(adsRequiredToWatch);

        case NotificationType.UnassignedMatrixMembers:
            return(user.GetUnassignedMatrixMembersCount());

        case NotificationType.PendingRepresentativePaymentRequest:
            return(ConversationMessage.GetPendingRequestForRepresentativeCount(user.Id));

        default:
            return(0);
        }
    }
示例#10
0
 /// <summary>
 /// Adds a message to this Conversation.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <returns></returns>
 public Conversation AddMessage( ConversationMessage message )
 {
     Messages.Add( message );
     Version++;
     message.Version = Version;
     return this;
 }
示例#11
0
        public dynamic CallBack(
            string SdkAppid,
            string CallbackCommand,
            string ClientIP,
            string OptPlatform,
            [FromBody] dynamic model)
        {
            try
            {
                //发单聊消息之前回调 https://www.qcloud.com/doc/product/269/1632
                if (CallbackCommand == "C2C.CallbackBeforeSendMsg")
                {
                    /*{
                     *  "CallbackCommand": "C2C.CallbackBeforeSendMsg",  // 回调命令
                     *  "From_Account": "jared",  // 发送者
                     *  "To_Account": "Jonh",  // 接收者
                     *  "MsgBody": [  // 消息体,参见TIMMessage消息对象
                     *      {
                     *          "MsgType": "TIMTextElem", // 文本
                     *          "MsgContent": {
                     *              "Text": "red packet"
                     *          }
                     *      }
                     *  ]
                     * }*/

                    //TODO:过滤垃圾消息,修改用户的消息,记录日志
                }
                //发单聊消息之后回调 https://www.qcloud.com/doc/product/269/2716
                else if (CallbackCommand == "C2C.CallbackAfterSendMsg")
                {
                    /*{
                     *  "CallbackCommand": "C2C.CallbackAfterSendMsg",  // 回调命令
                     *  "From_Account": "jared",  // 发送者
                     *  "To_Account": "Jonh",  // 接收者
                     *  "MsgBody": [  // 消息体,参见TIMMessage消息对象
                     *      {
                     *          "MsgType": "TIMTextElem", // 文本
                     *          "MsgContent": {
                     *              "Text": "red packet"
                     *          }
                     *      }
                     *  ]
                     * }*/
                }
                //群内发言之前回调 https://www.qcloud.com/doc/product/269/1619
                else if (CallbackCommand == "Group.CallbackBeforeSendMsg")
                {
                    #region 群内发言之前回调

                    /*{
                     *  "CallbackCommand": "Group.CallbackBeforeSendMsg",  // 回调命令
                     *  "GroupId": "@TGS#2J4SZEAEL",  // 群组ID
                     *  "Type": "Public",  // 群组类型
                     *  "From_Account": "jared",  // 发送者
                     *  "Operator_Account":"admin", //请求的发起者
                     *  "Random": 123456,  // 随机数
                     *  "MsgBody": [  // 消息体,参见TIMMessage消息对象
                     *      {
                     *          "MsgType": "TIMTextElem", // 文本
                     *          "MsgContent": {
                     *              "Text": "red packet"
                     *          }
                     *      }
                     *  ]
                     * }*/

                    //群组编号
                    int GroupId = model.GroupId;
                    //房间编号
                    int ChannelID = GroupId;
                    //发送者
                    string From_Account = model.From_Account;
                    //消息主题内容
                    dynamic MsgBody = model.MsgBody;

                    string MsgSeq = Guid.NewGuid().ToString("N");

                    if (From_Account != null)
                    {
                        ConversationMessage[] messages = new ConversationMessage[MsgBody.Count];
                        BLL.Sys.Implements.ConversationRoomService bllRoom = new BLL.Sys.Implements.ConversationRoomService();
                        //获取房间
                        var room = bllRoom.GetChannelInfo(ChannelID);

                        if (room != null)
                        {
                            #region 记录聊天日志

                            int i = 0;
                            foreach (var msg in MsgBody)
                            {
                                var msgType = msg.MsgType;
                                var content = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                                messages[i] = new ConversationMessage();
                                messages[i].ConversationMessageID = Guid.NewGuid().ToString("N");
                                messages[i].ConversationRoomID    = GroupId;      //房间
                                messages[i].MessageContent        = content;      //内容
                                messages[i].MessageState          = 0;            //消息状态
                                messages[i].MessageTime           = DateTime.Now; //消息发送时间
                                messages[i].MessageType           = msgType;      //消息发送类型 TIMTextElem/TIMImageElem/TIMCustomElem
                                messages[i].ServiceID             = room.ServiceID;
                                messages[i].UserID       = From_Account.ToString();
                                messages[i].MessageSeq   = MsgSeq;
                                messages[i].MessageIndex = i;
                                i++;
                            }

                            using (XuHos.EventBus.MQChannel mqChannel = new EventBus.MQChannel())
                            {
                                if (mqChannel.Publish <EventBus.Events.ChannelNewMsgEvent>(new EventBus.Events.ChannelNewMsgEvent()
                                {
                                    ChannelID = GroupId,
                                    ServiceID = room.ServiceID,
                                    ServiceType = room.ServiceType,
                                    FromAccount = From_Account,
                                    Messages = messages,
                                    OptPlatform = OptPlatform
                                }))
                                {
                                    // 0为允许发言
                                    return(new { ActionStatus = "OK", ErrorInfo = "", ErrorCode = 0 });
                                }
                                else
                                {
                                    // 0为允许发言
                                    return(new { ActionStatus = "OK", ErrorInfo = "", ErrorCode = 1 });
                                }
                            }

                            #endregion
                        }
                    }

                    #endregion
                }
                //群内发言之后回调 https://www.qcloud.com/doc/product/269/2661
                else if (CallbackCommand == "Group.CallbackAfterSendMsg")
                {
                    /*{
                     *  "CallbackCommand": "Group.CallbackAfterSendMsg",  // 回调命令
                     *  "GroupId": "@TGS#2J4SZEAEL",  // 群组ID
                     *  "Type": "Public",  // 群组类型
                     *  "From_Account": "jared",  // 发送者
                     *  "MsgBody": [  // 消息体,参见TIMMessage消息对象
                     *      {
                     *          "MsgType": "TIMTextElem", // 文本
                     *          "MsgContent": {
                     *              "Text": "red packet"
                     *          }
                     *      }
                     *  ]
                     * }*/
                }
                //状态变更回调 https://www.qcloud.com/doc/product/269/2570
                else if (CallbackCommand == "State.StateChange")
                {
                    /*{
                     *  "CallbackCommand": "State.StateChange",
                     *      "Info": {
                     *          "Action": "Logout",
                     *          "To_Account": "testuser316",
                     *          "Reason": "Unregister"
                     *      }
                     * }
                     */
                    var Action     = model.Info.Action;
                    var To_Account = model.Info.To_Account;

                    using (XuHos.EventBus.MQChannel mqChannel = new EventBus.MQChannel())
                    {
                        if (mqChannel.Publish <EventBus.Events.UserOnlineStateChangedEvent>(new EventBus.Events.UserOnlineStateChangedEvent()
                        {
                            Action = Action,
                            UserID = To_Account,
                        }))
                        {
                            // 0为允许发言
                            return(new { ActionStatus = "OK", ErrorInfo = "", ErrorCode = 0 });
                        }
                        else
                        {
                            // 0为允许发言
                            return(new { ActionStatus = "OK", ErrorInfo = "", ErrorCode = 1 });
                        }
                    }
                }

                //正常返回
                return(new { ActionStatus = "OK", ErrorInfo = "", ErrorCode = 0 });
            }
            catch (Exception E)
            {
                LogHelper.WriteError(E.GetDetailException());

                return(new { ActionStatus = "OK", ErrorInfo = E.GetDetailException().StackTrace, ErrorCode = 0 });
            }
        }
示例#12
0
        /// <summary>
        /// Submits a Conversation message.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="message">The message.</param>
        /// <param name="conversationId">The Conversation id.</param>
        /// <param name="version">The version of the Conversation submitting to.</param>
        /// <returns></returns>
        public static Dictionary<string, object> SubmitConversationMessage( Int64 userId, string message,
		 string conversationId, Int64 version )
        {
            /* get the session of the submtting user */
            Commerce.User user = Commerce.Users.GetUserById( Convert.ToInt32( userId ) );
            /* find the Conversation, or create it if it does't exist */
            Guid id = new Guid( conversationId );
            List<Conversation> cons = Main.Conversations.FindAll( delegate( Conversation c ) {
                return c.Id == id;
            } );
            Conversation con = null;
            if( cons.Count==0 ) {
                con = new Conversation(new Guid(conversationId));
                con.OwnerId = user.UserId;
                con.Users.Add( user );
                con.UserIds.Add( user.UserId );
                Main.Conversations.Add(con);
            }else{
                con = cons[0];
            }
            /* if this is the owner check if the user has submitted a command */
            bool command = false;
            try{
                if( message.StartsWith("/#name")) {
                    con.Name = message.Substring(message.IndexOf("/#name")+7);
                    ConversationMessage msg = new ConversationMessage( String.Format( "Channel name has been changed to {0}.", con.Name ), Main.Site.NullUser );
                    con.AddMessage( msg );
                    command = true;
                }
                if( message.StartsWith( "/#subject" ) ) {
                    con.Subject = message.Substring( message.IndexOf( "/#subject" ) + 10 );
                    ConversationMessage msg = new ConversationMessage( String.Format( "Channel subject has been changed to {0}.", con.Subject ), Main.Site.NullUser );
                    con.AddMessage( msg );
                    command = true;
                }
                if( message.StartsWith( "/#tags" ) ) {
                    con.Tags = message.Substring( message.IndexOf( "/#tags" ) + 7 );
                    ConversationMessage msg = new ConversationMessage( String.Format( "Channel tags has been changed to {0}.", con.Tags ), Main.Site.NullUser );
                    con.AddMessage( msg );
                    command = true;
                }
                if( message.StartsWith( "/#password" ) ) {
                    con.Password = message.Substring( message.IndexOf( "/#password" ) + 11 );
                    ConversationMessage msg = new ConversationMessage("Channel password has been set/changed.", Main.Site.NullUser );
                    con.AddMessage( msg );
                    command = true;
                }
                if( message.StartsWith( "/#ownerId" ) ) {
                    con.OwnerId = Convert.ToInt32(message.Substring( message.IndexOf( "/#ownerId" ) + 7 ));
                    Commerce.User usr = Commerce.Users.GetUserById( con.OwnerId );
                    if(usr==null){
                        ConversationMessage msg = new ConversationMessage( "User does not exist.", Main.Site.NullUser );
                        con.AddMessage( msg );
                    }
                    ConversationMessage msgx = new ConversationMessage( String.Format( "Channel owner has been changed to {0}.", usr.Handle ), Main.Site.NullUser );
                    con.AddMessage( msgx );
                    command = true;
                }
                if( message.StartsWith( "/#kick" ) ) {
                    int uid = Convert.ToInt32( message.Substring( message.IndexOf( "/#kick" ) + 7 ) );
                    Commerce.User usr = Commerce.Users.GetUserById(uid);
                    ConversationMessage msg = new ConversationMessage( String.Format( "Kicking {0}.", usr.Handle ), Main.Site.NullUser );
                    con.AddMessage( msg );
                    con.RemoveUser(usr);
                    command = true;
                }
            }catch(Exception e){
                ConversationMessage msg = new ConversationMessage( e.Message, Main.Site.NullUser );
                con.AddMessage( msg );
                return GetConversation( con.Id.ToString(), version );
            }
            /* only add messages with length > 0 */
            if( message.Length > 0 && !command ) {
                ConversationMessage msg = new ConversationMessage( message, user );
                con.AddMessage( msg );
            }
            return GetConversation( con.Id.ToString(), version );
        }
示例#13
0
        public async Task <bool> Send(MessageSubmission messageSubmission)
        {
            Guid.TryParseExact(messageSubmission.ConversationId, "D", out var convoId);

            if (convoId == null)
            {
                return(false);
            }

            var convo = ConvoDal.GetById(convoId) as Conversation;

            using (var transaction = DbContext.Database.BeginTransaction())
            {
                try
                {
                    if (convo != null)
                    {   // ConvoDal.Update(convoID);
                        var newMessage = new ConversationMessage
                        {
                            Message      = messageSubmission.Message,
                            User         = CurrentUser,
                            Conversation = convo
                        };

                        ConversationMessageDAL.Add(newMessage);
                        await ConversationMessageDAL.Commit();

                        ConvoDal.Update(convo);
                        convo.LatestMessage = newMessage;
                        await ConvoDal.Commit();

                        // update related entities of the convo some how?
                        // TODO next
                        // Add user to the same conversation?
                    }
                    else
                    {  // Initial Creation
                        var newConvo = new Conversation(convoId);
                        var users    = new List <User>();

                        var newMessage = new ConversationMessage
                        {
                            Message      = messageSubmission.Message,
                            User         = CurrentUser,
                            Conversation = newConvo
                        };

                        var conversationUsers = new List <ConversationUser>();

                        conversationUsers.Add(new ConversationUser
                        {
                            Conversation = newConvo,
                            User         = CurrentUser
                        });

                        foreach (var recipientId in messageSubmission.RecipientIds)
                        {
                            var user = DbContext.Users.Find(recipientId);

                            conversationUsers.Add(new ConversationUser
                            {
                                Conversation = newConvo,
                                User         = user
                            });

                            users.Add(user);
                        }

                        //Update Conversation
                        newConvo.Name = users?.Select(u => u.Name)?.Aggregate((a, b) => a + ", " + b);

                        ;
                        ConvoDal.Add(newConvo);

                        await ConvoDal.Commit();

                        foreach (var cu in conversationUsers)
                        {
                            ConversationUserDAL.Add(cu);
                            await ConversationUserDAL.Commit();
                        }

                        ConversationMessageDAL.Add(newMessage);
                        await ConversationMessageDAL.Commit();

                        // Update Convo after message is created

                        ConvoDal.Update(newConvo);
                        newConvo.LatestMessage = newMessage;

                        await ConvoDal.Commit();
                    }

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Dispose();

                    throw new ArgumentException(e.Message);
                }
            }

            return(true);
        }
示例#14
0
        protected internal sealed override bool Process(ConversationMessage message)
        {
            switch (State)
            {
            case RequesterState.RequestRecovering:
                if (message is ConversationRecoverAgreedMessage)
                {
                    //对方同意恢复会话。
                    State = RequesterState.Running;
                    OnRecoverAgreed(message as ConversationRecoverAgreedMessage);
                    RecoverAgreed?.Invoke();
                }
                else if (message is ConversationRejectMessage)
                {
                    var rm = message as ConversationRejectMessage;
                    State = RequesterState.Rejected;
                    End();
                    OnRecoverRejected(rm);
                    RecoverRejected?.Invoke(rm.RejectCode);
                }
                else
                {
                    //对方再ConversationAgree或者Reject之前发来的消息,到底要不要处理?怎样才能保证对方不在我准备好之前发消息过来?
                    //其他消息,不理会。
                    OnMessageReceived(message);
                }
                break;

            case RequesterState.Requesting:
                if (message is ConversationAgreeMessage)
                {
                    WasAgreed = true;
                    State     = RequesterState.Running;
                    OnRequestAgreed(message as ConversationAgreeMessage);
                    Agreed?.Invoke();
                    if (!Response.IsEnded())
                    {
                        Response?.SetResult(message);
                    }
                    else
                    {
                        End();
                    }
                }
                else if (message is ConversationRejectMessage)
                {
                    if (!Response.IsEnded())
                    {
                        Response?.SetResult(message);
                    }
                    State = RequesterState.Rejected;
                    //终止此会话
                    End();
                    Rejected?.Invoke();
                }
                else
                {
                    //对方再ConversationAgree或者Reject之前发来的消息,到底要不要处理?怎样才能保证对方不在我准备好之前发消息过来?
                    //其他消息,不理会。
                    OnMessageReceived(message);
                }
                break;

            case RequesterState.Running:
                OnMessageReceived(message);
                break;
            }
            return(true);
        }
示例#15
0
 public CreatedNotification(ConversationMessage item)
 {
     Item = item;
 }
示例#16
0
        // GET: Conversation
        public ActionResult Index(string sortType)
        {
            if (TempData.ContainsKey("message"))
            {
                ViewBag.message = TempData["message"].ToString();
            }

            if (sortType == null)
            {
                sortType = "Received";
            }
            var currentUser = User.Identity.GetUserId();

            if (currentUser == null)
            {
                return(RedirectToAction("Login", "Account"));
            }
            else
            {
                if (sortType == "Received")
                {
                    /*var conversations = from conv in _db.Conversations.Include("Product").Include("Sender")
                     *                  where conv.Product.UserId == currentUser
                     *                  select conv;
                     * var conversations = from conv in _db.Conversations.Include("Product").Include("Sender")
                     *                  where conv.Product.UserId == currentUser
                     *                  select conv;
                     * ViewBag.conversations = conversations;
                     *
                     * var latestMessages = new List<Message>();
                     * foreach (var conv in conversations)
                     * {
                     *  var message = (from mess in _db.Messages.Include("Sender").Include("Receiver")
                     *                 where mess.ConversationId == conv.ConversationId
                     *                 orderby mess.Date descending
                     *                 select mess).First();
                     *  latestMessages.Add(message);
                     * }*/

                    var conversations = (from c in _db.Conversations.Include("Product").Include("Sender")
                                         join m in _db.Messages.Include("Sender").Include("User")
                                         on c.ConversationId equals m.ConversationId
                                         where c.Product.UserId == currentUser
                                         select new { c, m } into x
                                         group x by new { x.c } into g
                                         select new
                                         { Conversation = g.Key.c,
                                           Message = g.Select(x => x.m).Where(y => y.ConversationId == g.Key.c.ConversationId).OrderByDescending(m => m.Date),
                                           MessageDate = g.Select(x => x.m).Max(x => x.Date) }).OrderByDescending(y => y.MessageDate);

                    var conversationsMes = new List <ConversationMessage>();
                    foreach (var conversation in conversations)
                    {
                        var convMes = new ConversationMessage {
                            Conversation  = conversation.Conversation,
                            LatestMessage = conversation.Message.Where(m => m.ConversationId == conversation.Conversation.ConversationId).First()
                        };

                        convMes.LatestMessage.Content = MessageController.Decrypt(convMes.LatestMessage.Content);
                        conversationsMes.Add(convMes);
                    }
                    var model = new ConversationViewModel {
                        Conversations = conversationsMes
                    };

                    return(View(model));
                }
                else
                if (sortType == "Sent")
                {
                    /*var conversations = from conv in _db.Conversations.Include("Product").Include("Sender")
                     *                  where conv.SenderId == currentUser
                     *                  select conv;
                     * ViewBag.conversations = conversations;
                     *
                     * var latestMessages = new List<Message>();
                     * foreach (var conv in conversations)
                     * {
                     *  var message = (from mess in _db.Messages.Include("Sender").Include("Receiver")
                     *                 where mess.ConversationId == conv.ConversationId
                     *                 orderby mess.Date descending
                     *                 select mess).First();
                     *  latestMessages.Add(message);
                     * }*/

                    var conversations = (from c in _db.Conversations.Include("Product").Include("Sender")
                                         join m in _db.Messages.Include("Sender").Include("User")
                                         on c.ConversationId equals m.ConversationId
                                         where c.SenderId == currentUser
                                         select new { c, m } into x
                                         group x by new { x.c } into g
                                         select new
                    {
                        Conversation = g.Key.c,
                        Message = g.Select(x => x.m).Where(y => y.ConversationId == g.Key.c.ConversationId).OrderByDescending(m => m.Date),
                        MessageDate = g.Select(x => x.m).Max(x => x.Date)
                    }).OrderByDescending(y => y.MessageDate);

                    var conversationsMes = new List <ConversationMessage>();
                    foreach (var conversation in conversations)
                    {
                        var convMes = new ConversationMessage
                        {
                            Conversation  = conversation.Conversation,
                            LatestMessage = conversation.Message.Where(m => m.ConversationId == conversation.Conversation.ConversationId).First()
                        };
                        convMes.LatestMessage.Content = MessageController.Decrypt(convMes.LatestMessage.Content);
                        conversationsMes.Add(convMes);
                    }
                    var model = new ConversationViewModel {
                        Conversations = conversationsMes
                    };

                    return(View(model));
                }

                return(View());
            }
        }