public IHttpActionResult PutAvatar([FromBody] int siteUserId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, siteUserId, "Moder"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            Avatar oldAvatar = db.Avatars.FirstOrDefault(x => x.siteUserId == siteUserId &&
                                                         x.confirmState == "PrevAva");

            if (oldAvatar != null)
            {
                db.Avatars.Remove(oldAvatar);
                File.Delete(oldAvatar.base64);
            }

            Avatar NewAva = db.Avatars.FirstOrDefault(x => x.siteUserId == siteUserId &&
                                                      x.confirmState == "Waiting");         //Если пользователь изменил мнение и решил изменить отправленный, но еще не подтвержденный аватар

            //FileInfo fileInfo = new FileInfo(NewAva.base64);
            //System.IO.File.Move(fileInfo.FullName, fileInfo.DirectoryName + "//Confirmed.jpg");

            NewAva.confirmState    = "Confirmed";
            db.Entry(NewAva).State = EntityState.Modified;
            db.SaveChanges();

            return(Ok(NewAva));
        }
        public IHttpActionResult GetLikeList(int id, int page)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            int             startNum = (page - 1) * 12;
            List <LikeList> likeList = db.LikeList.Where(x => x.from == id ||
                                                         x.to == id).OrderBy(x => x.id).Skip(startNum).Take(12).ToList();

            if (likeList == null)
            {
                return(NotFound());
            }
            List <int> usersId = new List <int>();

            for (int i = 0; i < likeList.Count; i++)
            {
                int userId;
                if (likeList[i].from != id)// && !usersId.Contains(likeList[i].from) && !usersId.Contains(likeList[i].to))
                {
                    userId = likeList[i].from;
                }
                else
                {
                    userId = likeList[i].to;
                }

                usersId.Add(userId);
            }
            return(Ok(SelectionWithId(usersId.Distinct().ToArray())));
        }
예제 #3
0
        public IHttpActionResult PostDialogList(DialogList dialogList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, dialogList.firstUserId, "User") && !CheckAccess.IsAccess(cookie, dialogList.secondUserId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            if (db.DialogLists.FirstOrDefault(x => x.firstUserId == dialogList.firstUserId &&
                                              x.secondUserId == dialogList.secondUserId) == null)     //создаем новый диалог в списке если до этого он не был создан
            {
                db.DialogLists.Add(dialogList);
                db.SaveChanges();
            }
            else
            {
                return(BadRequest(ModelState));
            }

            return(CreatedAtRoute("DefaultApi", new { id = dialogList.id }, dialogList));
        }
        public IHttpActionResult GetFriendList(int id, int page)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            List <FriendList> fullFavoriteList = db.Friends.Where(x => x.who == id).ToList();

            int startNum = (page - 1) * 12;
            List <FriendList> friendList = fullFavoriteList.OrderBy(x => x.id).Skip(startNum).Take(12).ToList();//db.Friends.Where(x => x.who == id).OrderBy(x => x.id).Skip(0).Take(12).ToList();

            if (friendList == null)
            {
                return(NotFound());
            }
            List <int> usersId = new List <int>();

            for (int i = 0; i < friendList.Count; i++)
            {
                usersId.Add(friendList[i].with);
            }

            return(Ok(SelectionWithId(usersId.ToArray(), fullFavoriteList)));
        }
예제 #5
0
        public IHttpActionResult GetGuestList(int id, int page)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }


            int startNum = (page - 1) * 12;
            List <GuestList> guestList = db.Guests.Where(x => x.to == id).OrderBy(x => x.id).Skip(startNum).Take(12).ToList();

            if (guestList == null)
            {
                return(NotFound());
            }

            List <int> usersId = new List <int>();

            for (int i = 0; i < guestList.Count; i++)
            {
                usersId.Add(guestList[i].who);
            }

            return(Ok(LikeListsController.SelectionWithId(usersId.ToArray())));
        }
예제 #6
0
        public IHttpActionResult GetDialogList(int id)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            /*
             *          List<Dialog> dialogList = db.Dialogs.Where(x => x.from == id || x.to == id).Distinct().ToList();
             * if (dialogList == null)
             * {
             *  return NotFound();
             * }
             * List<int> usersId = new List<int>();
             * for (int i = 0; i < dialogList.Count; i++)
             * {
             *  int userId;
             *  if (dialogList[i].to != id && !usersId.Contains(dialogList[i].to) && !usersId.Contains(dialogList[i].from))
             *      userId = dialogList[i].to;
             *  else
             *      userId = dialogList[i].from;
             *
             *  usersId.Add(userId);
             * }
             */
            List <DialogList> dialogList = db.DialogLists.Where(x => x.firstUserId == id || x.secondUserId == id).ToList();

            if (dialogList == null)
            {
                return(NotFound());
            }

            List <int> usersId = new List <int>();

            for (int i = 0; i < dialogList.Count; i++)
            {
                int userId;
                if (dialogList[i].firstUserId != id && !usersId.Contains(dialogList[i].firstUserId) && !usersId.Contains(dialogList[i].secondUserId))
                {
                    userId = dialogList[i].firstUserId;
                }
                else
                {
                    userId = dialogList[i].secondUserId;
                }

                usersId.Add(userId);
            }

            return(Ok(LikeListsController.SelectionWithId(usersId.ToArray())));
        }
예제 #7
0
        public IHttpActionResult GetGuestList(int id)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            List <GuestList> guests = db.Guests.Where(x => x.to == id).ToList();

            return(Ok(guests.ToArray()));
        }
        public IHttpActionResult DeleteSiteUser([FromBody] int id)
        {
            SiteUser siteUser = db.SiteUsers.Find(id);

            if (siteUser == null)
            {
                return(NotFound());
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, 0, "Admin"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            //List<Avatar> avatar=db.Avatars.Where(x=>x.siteUserId== id).ToList();
            //List<DialogList> dialogList = db.DialogLists.Where(x => x.firstUserId == id || x.secondUserId == id).ToList();//?
            //List<Dialog> dialogs = db.Dialogs.Where(x => x.from == id || x.to == id).ToList();//?
            //List <FriendList> friends = db.Friends.Where(x => x.who == id || x.with == id).ToList();
            //List <Gallery> gallery = db.Galleries.Where(x => x.siteUserid == id).ToList();
            //List <GuestList> guests = db.Guests.Where(x => x.who == id).ToList();
            //List <Hobby> hobby = db.Hobbies.Where(x => x.siteUserid == id).ToList();
            //List <LikeList> likes = db.LikeList.Where(x => x.from == id || x.to == id).ToList();

            //db.Avatars.RemoveRange(avatar);
            //db.DialogLists.RemoveRange(dialogList);
            //db.Dialogs.RemoveRange(dialogs);
            //db.Friends.RemoveRange(friends);
            //db.Galleries.RemoveRange(gallery);
            //db.Guests.RemoveRange(guests);
            //db.Hobbies.RemoveRange(hobby);
            //db.LikeList.RemoveRange(likes);
            //db.SiteUsers.Remove(siteUser);
            string path = HttpContext.Current.Server.MapPath("~")
                          + "UserFiles\\"
                          + db.SiteUsers.FirstOrDefault(x => x.id == siteUser.id).id + "\\";

            if (!Directory.Exists(path))
            {
                Directory.Delete(path, true); //true - если директория не пуста удаляем все ее содержимое
            }
            db.SiteUsers.Remove(siteUser);

            db.SaveChanges();

            return(Ok(siteUser));
        }
예제 #9
0
        public IHttpActionResult PutHobby(List <HobbyOfUser> hobby)//Hobby hobby)
        {
            if (hobby.Count == 0)
            {
                return(BadRequest());
            }
            int userId = hobby[0].siteUserid;

            if (hobby.FirstOrDefault(x => x.siteUserid != hobby[0].siteUserid) != null)
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, userId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            List <HobbyOfUser> oldUserHobbies = db.HobbyOfUsers.Where(x => x.siteUserid == userId).ToList();

            foreach (HobbyOfUser oneHobby in oldUserHobbies)
            {
                int oldHobbyId = oneHobby.hobbyid;
                if (hobby.FirstOrDefault(x => x.hobbyid == oldHobbyId) == null)
                {
                    db.HobbyOfUsers.Remove(oneHobby);
                }
            }

            foreach (HobbyOfUser oneHobby in hobby)
            {
                int newHobbyId = oneHobby.hobbyid;
                if (oldUserHobbies.FirstOrDefault(x => x.hobbyid == newHobbyId) == null)
                {
                    db.HobbyOfUsers.Add(oneHobby);
                }
            }

            //db.Entry(hobby).State = EntityState.Modified;

            db.SaveChanges();

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #10
0
        public IHttpActionResult GetDialog(int id)
        {
            List <Dialog> GetAllMsg = db.Dialogs.Where(x => x.dialogId == id).ToList();

            if (GetAllMsg.Count == 0)
            {
                return(NotFound());
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, GetAllMsg[0].to, "User") && !CheckAccess.IsAccess(cookie, GetAllMsg[0].from, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            return(Ok(GetAllMsg));
        }
예제 #11
0
        public IHttpActionResult PostHobby(HobbyList hobby)//Hobby hobby)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, 0, "Admin"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            db.HobbiesList.Add(hobby);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = hobby.id }, hobby));
        }
예제 #12
0
        public IHttpActionResult DeleteHobby([FromBody] int id)//Hobby hobby)
        {
            if (id == 0)
            {
                return(BadRequest());
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, 0, "Admin"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            HobbyList hobby = db.HobbiesList.FirstOrDefault(x => x.id == id);

            db.HobbiesList.Remove(hobby);
            db.SaveChanges();

            return(Ok());
        }
        public IHttpActionResult DeleteFriendList(int id)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, id, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            FriendList friendList = db.Friends.Find(id);

            if (friendList == null)
            {
                return(NotFound());
            }

            db.Friends.Remove(friendList);
            db.SaveChanges();

            return(Ok(friendList));
        }
예제 #14
0
        public IHttpActionResult DeleteDialogList([FromBody] int[] id)
        {
            List <DialogList> removeDialogLists = new List <DialogList>();

            //List<Dialog> removeDialogs = new List<Dialog>();
            for (int i = 0; i < id.Length; i++)
            {
                int currentId = id[i];
                removeDialogLists.Add(db.DialogLists.FirstOrDefault(x => x.id == currentId));
                //removeDialogs.Add(db.Dialogs.FirstOrDefault(x => x.dialogid == currentId ));
            }


            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, removeDialogLists[0].firstUserId, "User") && !CheckAccess.IsAccess(cookie, removeDialogLists[0].secondUserId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            if (removeDialogLists.Count == 0)// || removeDialogs.Count == 0)
            {
                return(NotFound());
            }
            if (removeDialogLists.Count == 1)// && removeDialogs.Count == 1)
            {
                db.DialogLists.Remove(removeDialogLists[0]);
                //db.Dialogs.Remove(removeDialogs[0]);
            }
            else
            {
                db.DialogLists.RemoveRange(removeDialogLists);
                //db.Dialogs.RemoveRange(removeDialogs);
            }


            db.SaveChanges();

            return(Ok("Success"));
        }
        public IHttpActionResult PostAvatar(Avatar avatar)
        {
            string uniqueName = "Ava";//Если у юзера уже была автарака, то новая ава будет называться так, для избежания конфликта имен
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, avatar.siteUserId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            Avatar prevNewAva = db.Avatars.FirstOrDefault(x => x.siteUserId == avatar.siteUserId &&
                                                          x.confirmState == "Waiting");    //Если пользователь изменил мнение и решил изменить отправленный, но еще не подтвержденный аватар

            if (prevNewAva != null)
            {
                db.Avatars.Remove(prevNewAva);
                File.Delete(prevNewAva.base64);
            }


            Avatar oldAvatar = db.Avatars.FirstOrDefault(x => x.siteUserId == avatar.siteUserId &&
                                                         x.confirmState == "Confirmed");     //Меняем состояние старой аватарки

            if (oldAvatar != null)
            {
                oldAvatar.confirmState    = "PrevAva";
                db.Entry(oldAvatar).State = EntityState.Modified;
                uniqueName = "Ava" + oldAvatar.id;
            }

            string path = HttpContext.Current.Server.MapPath("~")
                          + "UserFiles\\"
                          + db.SiteUsers.FirstOrDefault(x => x.id == avatar.siteUserId).id + "\\Avatars\\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }


            var base64 = (avatar.base64).Substring((avatar.base64).IndexOf(',') + 1);//Удаляем хэдер, сгенерированный js т к в c# он не воспринимается, как часть base64 строки и нельзя будет с ней  работать

            path += uniqueName + ".png";

            var bytes = Convert.FromBase64String(base64);

            using (var imageFile = new FileStream(path, FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }


            avatar.dateOfChange = DateTime.Now;
            avatar.confirmState = "Waiting";
            avatar.base64       = path;

            db.Avatars.Add(avatar);
            db.SaveChanges();

            avatar.base64 = "data:image / png; base64," + base64;//Для того, чтобы вернуть на фронт новый автара, а не бесполезный(для клиента) путь К файлу на сервере
            return(CreatedAtRoute("DefaultApi", new { id = avatar.id }, avatar));
        }
        public IHttpActionResult PutSiteUser(EditUser siteUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            using (var ldb = new DatingContext())
            {
                //находим пользователя, от корого собираемся редактировать, для того, чтобы при редактировании не потерять id сессии
                //и пароль, которые от клиента могли бы не прийти и могут обнулиться из за этого
                SiteUser user = ldb.SiteUsers.FirstOrDefault(x => x.id == siteUser.id);
                //копируем сессию и пароль(если не был отправлен новый) пришедший объект и применяем редактирование
                if (siteUser.password == null)
                {
                    siteUser.password = user.password;
                }
                else
                {
                    siteUser.password = PasswordToMD5(siteUser.password);
                }
                siteUser.sessionId  = user.sessionId;
                siteUser.online     = user.online;
                siteUser.dateOfEdit = DateTime.Now;

                int id;

                //if (siteUser.cityForSearch == "All")
                //{
                //    id = user.typeForSearchid;
                //    siteUser.typeForSearch = db.TypeForSearch.FirstOrDefault(x => x.id == id).typeName;
                //}

                //if (siteUser.ageForSearch == "All")
                //{
                //    id = user.ageForSearchid;
                //    siteUser.ageForSearch = db.AgeForSearch.FirstOrDefault(x => x.id == id).rangeOfAge;
                //}

                //if (siteUser.cityForSearch == "All")
                //{
                //    id = user.cityForSearchid;
                //    siteUser.cityForSearch = db.Cities.FirstOrDefault(x => x.id == id).cityName;
                //}



                int AdminId = db.Roles.FirstOrDefault(x => x.roleName == "Admin").id;
                int ModerId = db.Roles.FirstOrDefault(x => x.roleName == "Moder").id;

                if ((user.roleid == AdminId) ||                                                                                               //Запрещаем не админам реактировать админа
                    ((siteUser.roleid == AdminId || siteUser.roleid == ModerId) && (user.roleid != AdminId && siteUser.roleid != ModerId)) || //Только админ может дать юзеру дали роль модера или админа
                    ((siteUser.roleid != AdminId && siteUser.roleid != ModerId) && (user.roleid == AdminId && siteUser.roleid == ModerId)))   //Только админ может понизить модера или админа в роли(до юзера или забанить)
                {
                    CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();
                    if (!CheckAccess.IsAccess(cookie, siteUser.id, "Admin"))
                    {
                        return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
                    }
                }
                else
                {
                    CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();
                    if (!CheckAccess.IsAccess(cookie, siteUser.id, "User"))
                    {
                        return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
                    }
                }
            }

            SiteUser editedUser = new SiteUser(siteUser);

            db.Entry(editedUser).State = EntityState.Modified;//в данном случае EntityState.Modified рвет веб сокет(onlineChecker) при редактировании

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SiteUserExists(siteUser.id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            ClientUser clientUser = new ClientUser(editedUser);

            //return Ok(SortByFilter(new Filter(siteUser),1));
            return(CreatedAtRoute("DefaultApi", new { id = clientUser.id }, clientUser));
        }
        public IHttpActionResult PostGallery(List <Gallery> gallery)
        {
            if (gallery.Count == 0)
            {
                return(NotFound());
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, gallery[0].siteUserid, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            int    siteUserid = gallery[0].siteUserid;//gallery[0].siteUserid -все siteUserid в массиве одинаковы, т к это галлерея 1 пользователся
            string path       = HttpContext.Current.Server.MapPath("~")
                                + "UserFiles\\"
                                + db.SiteUsers.FirstOrDefault(x => x.id == siteUserid).id + "\\Gallery\\";


            List <Gallery> usersGalleryFromDB = db.Galleries.Where(x => x.siteUserid == siteUserid).ToList();


            if (gallery[0].content == null)//значит, что всё было удалено и стоит очистить бд
            {
                for (int i = 0; i < usersGalleryFromDB.Count; i++)
                {
                    db.Galleries.Remove(usersGalleryFromDB[i]);
                    File.Delete(usersGalleryFromDB[i].content);
                }
                db.SaveChanges();
                return(Ok(gallery));
            }


            for (int i = 0; i < usersGalleryFromDB.Count; i++)
            {
                //Поиск вхождения старых данных в новых(если в новых данныъ нет старых, значит они удаляются из базы)
                if (gallery.Find(x => x.content.Contains(usersGalleryFromDB[i].content)) == null)
                {
                    db.Galleries.Remove(usersGalleryFromDB[i]);
                    File.Delete(usersGalleryFromDB[i].content);
                }
            }

            for (int i = 0; i < gallery.Count; i++)
            {
                string content = gallery[i].content;

                if (db.Galleries.Where(x => x.content == content).ToList().Count == 0)
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var base64 = (gallery[i].content).Substring((gallery[i].content).IndexOf(',') + 1);

                    string fileName = String.Format(@"{0}.png", System.Guid.NewGuid());


                    var bytes = Convert.FromBase64String(base64);
                    using (var imageFile = new FileStream(path + fileName, FileMode.Create))
                    {
                        imageFile.Write(bytes, 0, bytes.Length);
                        imageFile.Flush();
                    }
                    gallery[i].content = path + fileName;
                    db.Galleries.Add(gallery[i]);
                }
            }
            db.SaveChanges();

            return(Ok(gallery));
        }