public ActionResult Info()
        {
            Guid userID = (Guid)Session["UserID"];
            Info info   = new Info();

            using (var db = new WebChatEntities())
            {
                var userInfo = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                ViewBag.Avatar          = userInfo.avatar;
                ViewBag.Fullname        = userInfo.fullname;
                info.Id                 = userInfo.app_user_id;
                info.Avatar             = userInfo.avatar;
                info.Username           = userInfo.app_user.username;
                info.LastChangePassword = userInfo.last_change_password;
                info.Email              = userInfo.email;
                info.Phone              = userInfo.phone;
                info.Fullname           = userInfo.fullname;
                info.Birth              = userInfo.birth;
                info.Gender             = userInfo.gender;
                info.City               = userInfo.city;
                info.ShortDescription   = userInfo.customer_description;
            }
            ViewBag.View = "info";
            return(View(info));
        }
        public ActionResult FindFriend(string input)
        {
            Guid userID = (Guid)Session["UserID"];
            List <FriendToFind> list = new List <FriendToFind>();

            using (var db = new WebChatEntities())
            {
                var cusomerList = db.customers.Where(s => (s.fullname.Contains(input) || s.app_user.username.Contains(input) ||
                                                           s.email.Contains(input) || s.phone.Contains(input)) && s.app_user_id != userID).ToList();
                foreach (var cus in cusomerList)
                {
                    FriendToFind friendToFind = new FriendToFind();
                    friendToFind.Id          = cus.app_user_id.ToString();
                    friendToFind.Avatar      = cus.avatar;
                    friendToFind.Name        = cus.fullname;
                    friendToFind.Email       = cus.email;
                    friendToFind.Phone       = cus.phone;
                    friendToFind.Birth       = cus.birth.ToString("dd/MM/yyyy");
                    friendToFind.Gender      = cus.gender ? "Nam" : "Nữ";
                    friendToFind.City        = cus.city;
                    friendToFind.Description = cus.customer_description;
                    var relation = db.relationships.Where(s => (s.cus1_id == userID && s.cus2_id == cus.app_user_id) || (s.cus1_id == cus.app_user_id && s.cus2_id == userID)).FirstOrDefault();
                    friendToFind.StatusRelation = relation == null ? 3 : relation.relationship_status;
                    list.Add(friendToFind);
                }
            }
            return(Json(list));
        }
        public ActionResult Logout()
        {
            Guid userID = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                var user = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                user.status_online = false;
                user.last_online   = DateTimeOffset.Now;
                db.SaveChanges();
            }
            try
            {
                // First we clean the authentication ticket like always
                //required NameSpace: using System.Web.Security;
                FormsAuthentication.SignOut();

                // Second we clear the principal to ensure the user does not retain any authentication
                //required NameSpace: using System.Security.Principal;
                HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);

                Session.Clear();
                System.Web.HttpContext.Current.Session.RemoveAll();

                //Redirect to index
                return(RedirectToAction("Index", "WebChat"));
            }
            catch
            {
                throw;
            }
        }
        public string SendFileMessage(HttpPostedFileBase file, string id)
        {
            Guid userID = (Guid)Session["UserID"];

            if (file != null && file.ContentLength > 0)
            {
                string directory = Server.MapPath("~/UploadedFiles/File");
                string fileName  = file.FileName;
                string path      = System.IO.Path.Combine(directory, fileName);

                file.SaveAs(path);

                Guid   toUserId = Guid.Parse(id);
                string toUsername;
                using (var db = new WebChatEntities())
                {
                    var user = db.app_user.Where(s => s.app_user_id == toUserId).FirstOrDefault();
                    toUsername = user.username;
                }
                var hubContext = GlobalHost.ConnectionManager.GetHubContext <ChatHub>();
                hubContext.Clients.User(toUsername).getMessagesFile(userID, fileName);
                return(fileName);
            }
            else
            {
                return("Xin hãy chọn file");
            }
        }
Exemple #5
0
        public void SendMessageToUser(string toUserId, string message)
        {
            var    currentUser = Context.User;
            string toUsername;
            string currentUserId;

            using (var db = new WebChatEntities())
            {
                Guid id   = Guid.Parse(toUserId);
                var  user = db.app_user.Where(s => s.app_user_id == id).FirstOrDefault();
                toUsername    = user.username;
                user          = db.app_user.Where(s => s.username == currentUser.Identity.Name).FirstOrDefault();
                currentUserId = user.app_user_id.ToString();
                message mes = new message
                {
                    id             = Guid.NewGuid(),
                    cus_send_id    = user.app_user_id,
                    cus_receive_id = id,
                    message1       = message,
                    message_status = 1,
                    send_time      = DateTimeOffset.Now
                };
                db.messages.Add(mes);
                db.SaveChanges();
            }
            Clients.User(toUsername).getMessages(currentUserId, message);
        }
        public ActionResult Login(AuthenticationModel entity)
        {
            // Ensure we have a valid viewModel to work with
            if (!ModelState.IsValid)
            {
                return(View("Form", entity));
            }
            try
            {
                using (var db = new WebChatEntities())
                {
                    //Retrive Stored Encrypt Password From Database According To Username (one unique field)
                    var userInfo = db.app_user.Where(s => s.username == entity.Login.Username.Trim().ToLower()).FirstOrDefault();

                    //Verify password
                    bool isLogin;
                    if (userInfo != null)
                    {
                        string encrypt_password = userInfo.encrypted_password;
                        isLogin = BCrypt.Net.BCrypt.Verify(entity.Login.Password.Trim().ToLower(), encrypt_password);
                    }
                    else
                    {
                        isLogin = false;
                    }


                    if (isLogin)
                    {
                        //Login Success
                        //For Set Authentication in Cookie (Remeber ME Option)
                        SignInRemember(entity.Login.Username, entity.Login.IsRemember);

                        //Set A Unique ID in session
                        Session["UserID"] = userInfo.app_user_id;

                        //Change status online to true
                        var customer = db.customers.Find(userInfo.app_user_id);
                        customer.status_online = true;
                        db.SaveChanges();

                        //Redirect to Index
                        return(RedirectToAction("Index", "WebChat"));
                    }
                    else
                    {
                        //Login Fail
                        TempData["ErrorMSG"] = "Thông tin đăng nhập không đúng";
                        return(View("Form", entity));
                    }
                }
            }
            catch
            {
                throw;
            }
        }
Exemple #7
0
        public override Task OnConnected()
        {
            var currentUser = Context.User;

            using (var db = new WebChatEntities())
            {
                var user = db.app_user.Where(s => s.username == currentUser.Identity.Name).FirstOrDefault();
                user.customer.status_online = true;
                db.SaveChanges();
            }
            return(base.OnDisconnected(true));
        }
        public ActionResult Index()
        {
            Guid userID = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                var userInfo = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                ViewBag.Avatar   = userInfo.avatar;
                ViewBag.Fullname = userInfo.fullname;
            }
            ViewBag.View = "index";
            return(View());
        }
Exemple #9
0
        public override Task OnDisconnected(bool stopCalled)
        {
            var currentUser = Context.User;

            using (var db = new WebChatEntities())
            {
                var user = db.app_user.Where(s => s.username == currentUser.Identity.Name).FirstOrDefault();
                user.customer.status_online = false;
                user.customer.last_online   = DateTimeOffset.Now;
                db.SaveChanges();
            }
            return(base.OnDisconnected(true));
        }
        public ActionResult GetCurrentFriend()
        {
            Guid userID = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                //TODO need pagging here
                //For pagging get 20 lastMessageSend
                var lastMessageSend = db.messages.Where(s => s.cus_send_id == userID).OrderByDescending(s => s.send_time).GroupBy(s => s.cus_receive_id);
                //For pagging get 20 lastMessageReceive
                var         lastMessageReceive = db.messages.Where(s => s.cus_receive_id == userID).OrderByDescending(s => s.send_time).GroupBy(s => s.cus_send_id);
                List <Guid> lastUserContact    = new List <Guid>();
                foreach (var groupItem in lastMessageSend)
                {
                    lastUserContact.Add(groupItem.Key);
                }
                foreach (var groupItem in lastMessageReceive)
                {
                    lastUserContact.Add(groupItem.Key);
                }
                // => lastUserContact have max 40
                lastUserContact = lastUserContact.Distinct().ToList();

                List <FriendModelJson> FriendList = new List <FriendModelJson>();
                foreach (var friendId in lastUserContact)
                {
                    FriendModelJson friend = new FriendModelJson();
                    friend.FriendId = friendId.ToString();
                    var friendInfo = db.customers.Where(s => s.app_user_id == friendId).FirstOrDefault();
                    friend.FriendName    = friendInfo.fullname;
                    friend.Avatar        = friendInfo.avatar;
                    friend.Status_online = friendInfo.status_online;
                    var lastMessage = db.messages.Where(s => (s.cus_send_id == friendId && s.cus_receive_id == userID) ||
                                                        (s.cus_receive_id == friendId && s.cus_send_id == userID)).OrderByDescending(s => s.send_time).FirstOrDefault();
                    friend.LastMessage = lastMessage.message1;
                    if (lastMessage.cus_send_id.Equals(userID))
                    {
                        friend.IsSend        = true;
                        friend.MessageStatus = 2;
                    }
                    else
                    {
                        friend.MessageStatus = lastMessage.message_status;
                    }
                    friend.LastSendTime = lastMessage.send_time.ToString("o");
                    FriendList.Add(friend);
                }
                FriendList = FriendList.OrderByDescending(s => s.LastSendTime).ToList();
                return(Json(FriendList));
            }
        }
        public string SendImageMessage(HttpPostedFileBase file, string id)
        {
            Guid userID = (Guid)Session["UserID"];

            if (file != null && file.ContentLength > 0 && IsImage(file))
            {
                string directory = Server.MapPath("~/UploadedFiles/Image");
                string imageName = Guid.NewGuid().ToString().Replace("-", "") + ".png";
                string path      = System.IO.Path.Combine(directory, imageName);

                using (Image image = Image.FromStream(file.InputStream, true, false))
                {
                    try
                    {
                        var thumbnailBitmap = new Bitmap(image.Width, image.Height);
                        var thumbnailGraph  = Graphics.FromImage(thumbnailBitmap);
                        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                        thumbnailGraph.SmoothingMode      = SmoothingMode.HighQuality;
                        thumbnailGraph.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        var imageRectangle = new Rectangle(0, 0, image.Width, image.Height);
                        thumbnailGraph.DrawImage(image, imageRectangle);
                        var ms = new MemoryStream();
                        thumbnailBitmap.Save(path, ImageFormat.Png);
                        ms.Position = 0;
                        GC.Collect();
                        thumbnailGraph.Dispose();
                        thumbnailBitmap.Dispose();
                        image.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                Guid   toUserId = Guid.Parse(id);
                string toUsername;
                using (var db = new WebChatEntities())
                {
                    var user = db.app_user.Where(s => s.app_user_id == toUserId).FirstOrDefault();
                    toUsername = user.username;
                }
                var hubContext = GlobalHost.ConnectionManager.GetHubContext <ChatHub>();
                hubContext.Clients.User(toUsername).getMessagesImage(userID, imageName);
                return(imageName);
            }
            else
            {
                return("Xin hãy chọn file ảnh");
            }
        }
        public void MakeAllRead(string id)
        {
            Guid userID   = (Guid)Session["UserID"];
            var  toUserId = Guid.Parse(id);

            using (var db = new WebChatEntities())
            {
                var messageList = db.messages.Where(s => s.cus_send_id == toUserId && s.cus_receive_id == userID && (s.message_status == 0 || s.message_status == 1)).ToList();
                foreach (var message in messageList)
                {
                    message.message_status = 2;
                }
                db.SaveChanges();
            }
        }
        public ActionResult Unfriend(string id)
        {
            Guid userID = (Guid)Session["UserID"];

            System.Diagnostics.Debug.WriteLine(id);
            Guid friendId = Guid.Parse(id);

            System.Diagnostics.Debug.WriteLine(friendId);
            using (var db = new WebChatEntities())
            {
                var relationShip = db.relationships.Where(s => (s.cus1_id == friendId && s.cus2_id == userID) || (s.cus1_id == userID && s.cus2_id == friendId)).FirstOrDefault();
                db.relationships.Remove(relationShip);
                db.SaveChanges();
            }
            return(RedirectToAction("ListFriend", "Friend"));
        }
        public ActionResult GetCurrentFriendSearch(string input)
        {
            Guid userID = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                List <Guid> lastUserContact = new List <Guid>();
                var         listUserId      = db.customers.Where(s => s.fullname.Contains(input)).ToList();
                foreach (var userId in listUserId)
                {
                    var temp = db.messages.Where(s => (s.cus_send_id == userID && s.cus_receive_id == userId.app_user_id) ||
                                                 (s.cus_receive_id == userID && s.cus_send_id == userId.app_user_id)).FirstOrDefault();
                    if (temp != null)
                    {
                        lastUserContact.Add(userId.app_user_id);
                    }
                }
                List <FriendModelJson> FriendList = new List <FriendModelJson>();
                foreach (var friendId in lastUserContact)
                {
                    FriendModelJson friend = new FriendModelJson();
                    friend.FriendId = friendId.ToString();
                    var friendInfo = db.customers.Where(s => s.app_user_id == friendId).FirstOrDefault();
                    friend.FriendName    = friendInfo.fullname;
                    friend.Avatar        = friendInfo.avatar;
                    friend.Status_online = friendInfo.status_online;
                    var lastMessage = db.messages.Where(s => (s.cus_send_id == friendId && s.cus_receive_id == userID) ||
                                                        (s.cus_receive_id == friendId && s.cus_send_id == userID)).OrderByDescending(s => s.send_time).FirstOrDefault();
                    friend.LastMessage = lastMessage.message1;
                    if (lastMessage.cus_send_id.Equals(userID))
                    {
                        friend.IsSend        = true;
                        friend.MessageStatus = 2;
                    }
                    else
                    {
                        friend.MessageStatus = lastMessage.message_status;
                    }
                    friend.LastSendTime = lastMessage.send_time.ToString("o");
                    FriendList.Add(friend);
                }
                FriendList = FriendList.OrderByDescending(s => s.LastSendTime).ToList();
                return(Json(FriendList));
            }
        }
        public ActionResult GetChatContent(string guid, int page)
        {
            int  numberOfMessageInOnePage = 20;
            Guid friendId = Guid.Parse(guid);
            Guid userID   = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                //Change status
                var listMessage = db.messages.Where(s => s.cus_send_id == friendId && s.cus_receive_id == userID && (s.message_status == 0 || s.message_status == 1)).ToList();
                foreach (var mes in listMessage)
                {
                    mes.message_status = 2;
                }
                db.SaveChanges();
                //Get content
                FriendAndChatContentModel friendInfo = new FriendAndChatContentModel();
                var userInfo = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                friendInfo.AvatarCurrent = userInfo.avatar;
                var temp = db.customers.Where(s => s.app_user_id == friendId).FirstOrDefault();
                friendInfo.FriendId      = temp.app_user_id;
                friendInfo.AvatarFriend  = temp.avatar;
                friendInfo.Fullname      = temp.fullname;
                friendInfo.Status_online = temp.status_online;
                friendInfo.Last_online   = temp.last_online.ToString("o");
                var messages = db.messages.Where(s => (s.cus_send_id == userID && s.cus_receive_id == friendId) ||
                                                 (s.cus_send_id == friendId && s.cus_receive_id == userID)).OrderByDescending(s => s.send_time)
                               .Skip(numberOfMessageInOnePage * (page - 1)).Take(numberOfMessageInOnePage).OrderBy(s => s.send_time).ToList();
                friendInfo.Messages = new List <MessageContentModel>();
                foreach (var message in messages)
                {
                    MessageContentModel messageContent = new MessageContentModel();
                    messageContent.Content        = message.message1;
                    messageContent.Send_time      = message.send_time.ToString("o");
                    messageContent.Message_status = message.message_status;
                    messageContent.IsSend         = message.cus_send_id == userID ? true : false;
                    friendInfo.Messages.Add(messageContent);
                }
                return(Json(friendInfo));
            }
        }
        public string ChangePassword(string oldPassword, string newPassword)
        {
            Guid userID = (Guid)Session["UserID"];

            using (var db = new WebChatEntities())
            {
                var user = db.app_user.Where(s => s.app_user_id == userID).FirstOrDefault();
                if (BCrypt.Net.BCrypt.Verify(oldPassword.Trim().ToLower(), user.encrypted_password))
                {
                    string encrypt_password = BCrypt.Net.BCrypt.HashPassword(newPassword.Trim().ToLower());
                    user.encrypted_password = encrypt_password;
                    var customer = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                    customer.last_change_password = DateTime.Now;
                    db.SaveChanges();
                    return("Đổi mật khẩu thành công");
                }
                else
                {
                    return("Mật khẩu cũ không đúng");
                }
            }
        }
        public ActionResult GetFriendSearch(int page, string input)
        {
            int  numberFriendInOnePage = 30;
            Guid userID = (Guid)Session["UserID"];
            List <FriendForListFriend> FriendForListFriend = new List <FriendForListFriend>();

            using (var db = new WebChatEntities())
            {
                var listRelationShip = db.relationships.Where(s => ((s.cus1_id == userID && s.customer1.fullname.Contains(input)) ||
                                                                    (s.cus2_id == userID && s.customer.fullname.Contains(input))) &&
                                                              (s.relationship_status == 1 || s.relationship_status == 2)).OrderBy(s => s.relationship_id)
                                       .Skip(numberFriendInOnePage * (page - 1)).Take(numberFriendInOnePage).ToList();
                foreach (var rela in listRelationShip)
                {
                    if (rela.cus1_id.Equals(userID))
                    {
                        var friendInfo           = db.customers.Where(s => s.app_user_id == rela.cus2_id).FirstOrDefault();
                        FriendForListFriend temp = new FriendForListFriend();
                        temp.Id                 = friendInfo.app_user_id.ToString();
                        temp.Avatar             = friendInfo.avatar;
                        temp.Fullname           = friendInfo.fullname;
                        temp.RelationshipStatus = rela.relationship_status;
                        FriendForListFriend.Add(temp);
                    }
                    else
                    {
                        var friendInfo           = db.customers.Where(s => s.app_user_id == rela.cus1_id).FirstOrDefault();
                        FriendForListFriend temp = new FriendForListFriend();
                        temp.Id                 = friendInfo.app_user_id.ToString();
                        temp.Avatar             = friendInfo.avatar;
                        temp.Fullname           = friendInfo.fullname;
                        temp.RelationshipStatus = rela.relationship_status;
                        FriendForListFriend.Add(temp);
                    }
                }
            }
            return(Json(FriendForListFriend));
        }
        public string ChangeAvatar(HttpPostedFileBase file)
        {
            Guid userID = (Guid)Session["UserID"];

            if (file != null && file.ContentLength > 0 && IsImage(file))
            {
                //TODO convert to png type, resize image and save it to database
                string directory = Server.MapPath("~/UploadedFiles/Avatar");
                string imageName = Guid.NewGuid().ToString().Replace("-", "") + ".png";
                string path      = System.IO.Path.Combine(directory, imageName);

                using (Image image = Image.FromStream(file.InputStream, true, false))
                {
                    try
                    {
                        float thumbWidth  = 500;
                        float thumbHeight = 500;
                        if (image.Width > image.Height)
                        {
                            thumbHeight = ((float)image.Height / image.Width) * thumbWidth;
                        }
                        else
                        {
                            thumbWidth = ((float)image.Width / image.Height) * thumbHeight;
                        }

                        int actualthumbWidth  = Convert.ToInt32(Math.Floor(thumbWidth));
                        int actualthumbHeight = Convert.ToInt32(Math.Floor(thumbHeight));
                        var thumbnailBitmap   = new Bitmap(actualthumbWidth, actualthumbHeight);
                        var thumbnailGraph    = Graphics.FromImage(thumbnailBitmap);
                        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                        thumbnailGraph.SmoothingMode      = SmoothingMode.HighQuality;
                        thumbnailGraph.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        var imageRectangle = new Rectangle(0, 0, actualthumbWidth, actualthumbHeight);
                        thumbnailGraph.DrawImage(image, imageRectangle);
                        var ms = new MemoryStream();
                        thumbnailBitmap.Save(path, ImageFormat.Png);
                        ms.Position = 0;
                        GC.Collect();
                        thumbnailGraph.Dispose();
                        thumbnailBitmap.Dispose();
                        image.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                using (var db = new WebChatEntities())
                {
                    var user = db.customers.Where(s => s.app_user_id == userID).FirstOrDefault();
                    if (user.avatar != null)
                    {
                        string filePath = System.IO.Path.Combine(directory, user.avatar);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }
                    user.avatar = imageName;
                    db.SaveChanges();
                }
                return("Đổi ảnh đại diện thành công");
            }
            else
            {
                return("Xin hãy chọn file ảnh");
            }
        }
        public ActionResult Register(AuthenticationModel entity)
        {
            // Ensure we have a valid viewModel to work with
            if (!ModelState.IsValid)
            {
                return(View("Form", entity));
            }
            try
            {
                using (var db = new WebChatEntities())
                {
                    //Generate new id
                    Guid id = Guid.NewGuid();

                    /*
                     * Save username and password to app_user
                     */
                    string username = entity.Regesiter.Username.Trim().ToLower();
                    string password = entity.Regesiter.Password.Trim().ToLower();
                    //Hash password before save to database
                    string encrypt_password = BCrypt.Net.BCrypt.HashPassword(password);
                    var    loginInfo        = new app_user
                    {
                        app_user_id        = id,
                        username           = username,
                        encrypted_password = encrypt_password
                    };
                    db.app_user.Add(loginInfo);
                    //maybe check error here, method return 0 => no record added to database
                    db.SaveChanges();

                    /*
                     * Save customer info to customer table
                     */
                    string   email        = entity.Regesiter.Email.Trim().ToLower();
                    string   fullname     = entity.Regesiter.Fullname.Trim();
                    DateTime birth        = entity.Regesiter.Birth;
                    string   gender       = entity.Regesiter.Gender;
                    var      customerInfo = new customer();
                    customerInfo.app_user_id          = id;
                    customerInfo.fullname             = fullname;
                    customerInfo.status_online        = true;
                    customerInfo.last_online          = DateTime.Now;
                    customerInfo.email                = email;
                    customerInfo.gender               = gender.Equals("Male") ? true : false;
                    customerInfo.birth                = birth;
                    customerInfo.last_change_password = DateTime.Now;
                    db.customers.Add(customerInfo);
                    //maybe check error here, method return 0 => no record added to database
                    db.SaveChanges();

                    //Login with new account
                    FormsAuthentication.SignOut();
                    FormsAuthentication.SetAuthCookie(loginInfo.username, false);
                    Session["UserID"] = loginInfo.app_user_id;

                    //TODO add role customer
                    //TODO add notify for user to update information
                }
            }
            catch
            {
                throw;
            }

            return(RedirectToAction("Index", "WebChat"));
        }