//Updates shopping list public async Task UpdateShoppingListAsync(UserModel user, ShoppingListModel shoppingList) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); ShoppingListModel old = await _shoppingListRepository.GetShoppingListByHomeIdAsync(user.Home.Id, true); if (old == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Shopping List Not Exist", "Shopping list is not exist"); errors.Throw(); } old.List = shoppingList.List; old.Status = shoppingList.Status; _shoppingListRepository.Update(old); foreach (var friend in user.Home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "ShoppingListUpdate"); fcm.data.Add("UpdatedShoppingList", old); await _fcmService.SendFCMAsync(fcm); } }
//Send Firebase Cloud Message to given user public async Task SendFCMAsync(FCMModel fcmMessage) { string serverKey = string.Format("key={0}", _config["FCM:ServerKey"]); string senderId = string.Format("id={0}", _config["FCM:SenderId"]); string requestUri = _config["FCM:RequestUri"]; var jsonMessageBody = JsonConvert.SerializeObject(fcmMessage); using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, requestUri)) { httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey); httpRequest.Headers.TryAddWithoutValidation("Sender", senderId); httpRequest.Content = new StringContent(jsonMessageBody, Encoding.UTF8, "application/json"); using (var httpClient = new HttpClient()) { var result = await httpClient.SendAsync(httpRequest); if (result.IsSuccessStatusCode) { return; } else { CustomException errors = new CustomException(); errors.AddError("FCM Error", "Unexpected error occured while FCM sending"); errors.Throw(); } } } }
//Changes forgotten password public async Task ForgotPasswordAsync(UserModel user, ForgotPasswordModel forgotPassword) { if (user.Status == (int)UserStatus.NotValid) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("None Verified Email", "Your email is not verified"); errors.Throw(); } if (user.Status == (int)UserStatus.Banned) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Is Banned", "User is banned from application"); errors.Throw(); } InformationModel ForgotPasswordVerificationCodeInfo = await _informationRepository.GetInformationByInformationNameAsync("ForgotPasswordVerificationCode"); InformationModel ForgotPasswordVerificationCodeGenerateDateInfo = await _informationRepository.GetInformationByInformationNameAsync("ForgotPasswordVerificationCodeGenerateDate"); UserInformationModel ForgotPasswordVerificationCode = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, ForgotPasswordVerificationCodeInfo.Id); UserInformationModel ForgotPasswordVerificationCodeGenerateDate = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, ForgotPasswordVerificationCodeGenerateDateInfo.Id); //Bad request if (ForgotPasswordVerificationCode == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Email Verification Code Not Exist", "There is no verification code which is generated for you"); errors.Throw(); } //Generated code timed out if (String.Format("{0:u}", DateTime.UtcNow.AddMinutes(-15)).CompareTo(ForgotPasswordVerificationCodeGenerateDate.Value) > 0) { _userInformationRepository.Delete(ForgotPasswordVerificationCode); _userInformationRepository.Delete(ForgotPasswordVerificationCodeGenerateDate); CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Verification Code Timeout", "Verification code timed out, please request another verification code"); errors.Throw(); } //Verification code accepted if (ForgotPasswordVerificationCode.Value == forgotPassword.VerificationCode) { user.Password = forgotPassword.NewPassword; _userRepository.Update(user); _userInformationRepository.Delete(ForgotPasswordVerificationCode); _userInformationRepository.Delete(ForgotPasswordVerificationCodeGenerateDate); } //Verification code does not matched else { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Verification Code", "Verification code does not matched"); errors.Throw(); } }
//User synchronize home menu meals public async Task <List <ClientMenuModel> > SynchronizeMenusAsync(UserModel user) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); List <MenuModel> homeMenus = await _menuRepository.GetAllHomeMenusAsync(user.Home.Id); List <ClientMenuModel> clientMenus = new List <ClientMenuModel>(); foreach (var menu in homeMenus) { ClientMenuModel clientMenu = new ClientMenuModel(); clientMenu.Menu = menu; List <MenuMealModel> menuMeals = await _menuMealRepository.GetAllMenuMealsByMenuIdAsync(menu.Id, true); foreach (var menuMeal in menuMeals) { clientMenu.MealIds.Add(menuMeal.Meal.Id); } clientMenus.Add(clientMenu); } return(clientMenus); }
//User adds meal public async Task AddMealAsync(UserModel user, MealModel meal) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); MealModel tmp = await _mealRepository.GetHomeMealByNameAsync(home.Id, meal.Name); if (tmp != null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Already Exist", "This meal has already exist"); errors.Throw(); } meal.Home = home; _mealRepository.Insert(meal); foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "AddMeal"); fcm.data.Add("Meal", meal); await _fcmService.SendFCMAsync(fcm); } }
//Logins user public async Task <UserModel> LoginAsync(LoginModel login) { UserModel user = await _userRepository.GetByUsernameAsync(login.Username); if (user == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Username", "Username is not registered"); errors.Throw(); } if (user.Password != login.Password) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Password", "Username and password is not matched"); errors.Throw(); } if (user.Status == (int)UserStatus.Banned) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Is Banned", "User is banned from application"); errors.Throw(); } user.Token = _jwtTokenService.CreateToken(user); user.DeviceId = login.DeviceId; _userRepository.Update(user); return(user); }
//Admin creates the home public async Task CreateNewHomeAsync(UserModel user, HomeModel home) { if (user.Position != (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Has Home", "User has home already"); errors.Throw(); } var isHomeExist = await _homeRepository.GetByHomeNameAsync(home.Name); if (isHomeExist != null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Name Exist", "Home name has already exist"); errors.Throw(); } user.Position = (int)UserPosition.Admin; home.Admin = user; home.Users = new List <UserModel>(); home.Users.Add(user); _homeRepository.Insert(home); user.Home = home; _userRepository.Update(user); _shoppingListRepository.Insert(new ShoppingListModel(home)); }
//Controls registration form is valid public async Task ControlRegisterFormAsync(RegistrationModel registrationForm) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); UserModel authentication = new UserModel(); authentication.Username = registrationForm.Username; var UsernameExist = await _userRepository.GetByUsernameAsync(authentication.Username); if (UsernameExist != null) { errors.AddError("Username", "Username already exist"); } var EmailExist = await _userInformationRepository.GetUserInformationByValueAsync(registrationForm.Email); if (EmailExist != null) { errors.AddError("Email", "Email already exist"); } var PhoneNumberExist = await _userInformationRepository.GetUserInformationByValueAsync(registrationForm.PhoneNumber); if (PhoneNumberExist != null) { errors.AddError("PhoneNumber", "Phone number already exist"); } if (errors.Errors.Count != 0) { errors.Throw(); } }
//Sends notification to all friends for shopping public async Task SendNotification(UserModel user) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); foreach (var f in home.Users) { if (f.Id == user.Id) { continue; } FCMModel fcm = new FCMModel(f.DeviceId, new Dictionary <string, object>()); fcm.notification.Add("title", "Alışveriş Talebi"); fcm.notification.Add("body", "Alışveriş listesindeki ürünlerin alınması isteniyor."); await _fcmService.SendFCMAsync(fcm); } }
//Admin adds a housework assign public async Task AddHouseworkAsync(UserModel user, HouseworkModel housework, int friendId) { if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorization Error", "You are not authorized for housework assignment"); errors.Throw(); } if (housework.Day < 1 || housework.Day > 31) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Day Error", "You can assign a day only between 1-31"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); UserModel friend = await _userRepository.GetByIdAsync(friendId, true); if ((friend == null) || (friend.Home != user.Home)) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Friendship Not Found", "Friendship not found for assignment"); errors.Throw(); } housework.User = friend; housework.Home = home; _houseworkRepository.Insert(housework); //Sends fcm to assigned friend FCMModel fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>()); fcmFriend.notification.Add("title", "Yeni Ev İşi"); fcmFriend.notification.Add("body", String.Format("Ayın {0}. günü {1} yapmanız gerekmektedir.", housework.Day, housework.Work)); await _fcmService.SendFCMAsync(fcmFriend); //Sends fcm to all friends foreach (var f in home.Users) { FCMModel fcm = new FCMModel(f.DeviceId, type: "AddHousework"); fcm.data.Add("Housework", housework); fcm.data.Add("FriendId", friendId); await _fcmService.SendFCMAsync(fcm); } }
//Admin request to user for inviting home public async Task InviteHomeRequestAsync(UserModel user, string invitedUsername) { Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName"); Task <InformationModel> lastNameInfo = _informationRepository.GetInformationByInformationNameAsync("LastName"); if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorisation Constraint", "You are not authorized for this request, you must be administrator of home"); errors.Throw(); } var home = (await _userRepository.GetByIdAsync(user.Id, true)).Home; //Admin waiting for user's accept UserModel invitedUser = await _userRepository.GetByUsernameAsync(invitedUsername); if (invitedUser == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Not Exist", "User is not exist"); errors.Throw(); } if (invitedUser.Position != (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Has Home", "You can not invite a user who already has home"); errors.Throw(); } UserInformationModel firstName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await firstNameInfo).Id); UserInformationModel lastName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await lastNameInfo).Id); FCMModel fcm = new FCMModel(invitedUser.DeviceId, new Dictionary <string, object>()); fcm.notification.Add("title", "Eve Katılma Daveti"); fcm.notification.Add("body", String.Format("{0} {1}({2}) evine katılmanız için davet ediyor.", firstName.Value, lastName.Value, user.Username)); await _fcmService.SendFCMAsync(fcm); fcm = new FCMModel(invitedUser.DeviceId, type: "InviteHomeRequest"); fcm.data.Add("InvitedHomeId", home.Id); fcm.data.Add("InviterUsername", user.Username); fcm.data.Add("InviterFirstName", firstName.Value); fcm.data.Add("InviterLastName", lastName.Value); await _fcmService.SendFCMAsync(fcm); }
//Synchronizes clients notepad public async Task <List <NotepadModel> > SynchronizeNotepadAsync(UserModel user) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); return(await _notepadRepository.GetAllNoteByHomeIdAsync(user.Home.Id)); }
//Gets user from email public async Task <UserModel> GetUserByMailAsync(string email) { var Email = await _userInformationRepository.GetUserInformationByValueAsync(email, true); if (Email == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Email Not Exist", "Email does not exist"); errors.Throw(); } return(Email.User); }
//Gets user from user id public async Task <UserModel> GetUserByIdAsync(int id, bool include = false) { UserModel user = await _userRepository.GetByIdAsync(id, include); if (user == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Not Exist", "User is not exist"); errors.Throw(); } return(user); }
//Admin deletes a housework assign public async Task DeleteHouseworkAsync(UserModel user, int houseworkId) { if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorization Error", "You are not authorized for housework assignment"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); HouseworkModel housework = await _houseworkRepository.GetHouseworkByIdAsync(houseworkId, true); if ((housework == null)) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Not Found", "Housework not found for delete"); errors.Throw(); } if (housework.Home != user.Home) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Not Belongs Home", "Housework not belongs for this home"); errors.Throw(); } //Sends fcm to assigned friend FCMModel fcmFriend = new FCMModel(housework.User.DeviceId, new Dictionary <string, object>()); fcmFriend.notification.Add("title", "Ev İşi İptal Edildi"); fcmFriend.notification.Add("body", String.Format("Ayın {0}. yapmanız gereken {1} işi iptal edildi.", housework.Day, housework.Work)); await _fcmService.SendFCMAsync(fcmFriend); _houseworkRepository.Delete(housework); await _fcmService.SendFCMAsync(fcmFriend); //Sends fcm to all friends foreach (var f in home.Users) { FCMModel fcm = new FCMModel(f.DeviceId, type: "DeleteHousework"); fcm.data.Add("HouseworkId", houseworkId); await _fcmService.SendFCMAsync(fcm); } }
//User updates note public async Task UpdateNoteAsync(UserModel user, NotepadModel note) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } if (note.Id == 0) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Id Not Exist", "Notepad id field is required"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); NotepadModel old = await _notepadRepository.GetNoteByIdAsync(note.Id, true); if (old == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Note Not Exist", "Note is not exist"); errors.Throw(); } if (old.Id != note.Id) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Note Not Belongs Home", "Note does not belong this home"); errors.Throw(); } old.Title = note.Title; old.Content = note.Content; await _notepadRepository.UpdateAsync(old); foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "NotepadUpdate"); fcm.data.Add("UpdatedNote", old); await _fcmService.SendFCMAsync(fcm); } }
//User deletes meal public async Task DeleteMealAsync(UserModel user, int mealId) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); MealModel meal = await _mealRepository.GetHomeMealByIdAsync(mealId, true); if (meal == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Not Exist", "This meal has not exist"); errors.Throw(); } if (meal.Home.Id != home.Id) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Not Related Home", "This meal is not related with user home"); errors.Throw(); } //Finds and deletes all related menu meals List <MenuMealModel> menuMeals = await _menuMealRepository.GetAllMenuMealsByMealIdAsync(mealId); foreach (var menuMeal in menuMeals) { _menuMealRepository.Delete(menuMeal); } foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "DeleteMeal"); fcm.data.Add("MealId", mealId); await _fcmService.SendFCMAsync(fcm); } _mealRepository.Delete(meal); }
//User requests to admin for joining home public async Task JoinHomeRequestAsync(UserModel user, string joinHomeName) { Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName"); Task <InformationModel> lastNameInfo = _informationRepository.GetInformationByInformationNameAsync("LastName"); if (user.Position != (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Has Home", "User has home already"); errors.Throw(); } var home = await _homeRepository.GetByHomeNameAsync(joinHomeName, true); if (home == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Name Not Exist", "Home name has not exist"); errors.Throw(); } //User waiting for admin's accept UserInformationModel firstName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await firstNameInfo).Id); UserInformationModel lastName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await lastNameInfo).Id); FCMModel fcm = new FCMModel(home.Admin.DeviceId, new Dictionary <string, object>()); fcm.notification.Add("title", "Eve Katılma İsteği"); fcm.notification.Add("body", String.Format("{0} {1}({2}) evinize katılmak istiyor.", firstName.Value, lastName.Value, user.Username)); await _fcmService.SendFCMAsync(fcm); fcm = new FCMModel(home.Admin.DeviceId, type: "JoinHomeRequest"); fcm.data.Add("RequesterId", user.Id); fcm.data.Add("RequesterUsername", user.Username); fcm.data.Add("RequesterName", firstName.Value); fcm.data.Add("RequesterLastName", lastName.Value); await _fcmService.SendFCMAsync(fcm); }
//User updates meal public async Task UpdateMealAsync(UserModel user, MealModel meal) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); MealModel old = await _mealRepository.GetHomeMealByIdAsync(meal.Id, true); if (old == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Not Exist", "This meal has not exist"); errors.Throw(); } if (old.Home.Id != home.Id) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Not Related Home", "This meal is not related with user home"); errors.Throw(); } old.Name = meal.Name; old.Ingredients = meal.Ingredients; old.Note = meal.Note; _mealRepository.Update(old); foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "UpdateMeal"); fcm.data.Add("Meal", meal); await _fcmService.SendFCMAsync(fcm); } }
//User deletes menu public async Task DeleteMenuAsync(UserModel user, int menuId) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); MenuModel menu = await _menuRepository.GetHomeMenuByIdAsync(menuId, true); if ((menu == null) || (menu.Home.Id != home.Id)) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Menu Id Not Valid", "Menu id not valid, that day has not related menu"); errors.Throw(); } //Finds and deletes all related menu meals List <MenuMealModel> menuMeals = await _menuMealRepository.GetAllMenuMealsByMenuIdAsync(menu.Id); foreach (var menuMeal in menuMeals) { _menuMealRepository.Delete(menuMeal); } //Sends fcm to all users foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "DeleteMenu"); fcm.data.Add("MenuId", menuId); await _fcmService.SendFCMAsync(fcm); } _menuRepository.Delete(menu); }
//User deletes note public async Task DeleteNoteAsync(UserModel user, int noteId) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); NotepadModel note = await _notepadRepository.GetNoteByIdAsync(noteId, true); if (note == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Note Not Exist", "Note is not exist"); errors.Throw(); } if (note.Home != home) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Note Not Belongs Home", "Note does not belong this home"); errors.Throw(); } foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "NotepadDelete"); fcm.data.Add("DeletedNote", note.Id); await _fcmService.SendFCMAsync(fcm); } await _notepadRepository.DeleteAsync(note); }
//Synchronizes clients houseworks public async Task <List <ClientHouseworkModel> > SynchronizeHouseworksAsync(UserModel user) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); //Gets all home houseworks List <HouseworkModel> homeAllHouseworks = await _houseworkRepository.GetAllHomeHouseworksAsync(user.Home.Id, true); List <ClientHouseworkModel> clientHouseworks = new List <ClientHouseworkModel>(); foreach (var hw in homeAllHouseworks) { clientHouseworks.Add(new ClientHouseworkModel(hw, hw.User.Id)); } return(clientHouseworks); }
public async Task BanishFromHomeAsync(UserModel user, int bannedUserId) { if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorization Error", "User is not admin of home"); errors.Throw(); } UserModel bannedUser = await _userRepository.GetByIdAsync(bannedUserId, true); if (user.Id == bannedUser.Id) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Bad Request", "You can not bannish yourself"); errors.Throw(); } if (user.Home.Id == bannedUser.Home.Id) { await LeaveHomeAsync(bannedUser, 0); } }
//User adds note public async Task AddNoteAsync(UserModel user, NotepadModel note) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); note.Home = home; await _notepadRepository.InsertAsync(note); foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "NotepadAdd"); fcm.data.Add("NewNote", note); await _fcmService.SendFCMAsync(fcm); } }
//User gives money to his/her friend public async Task TransferMoneyToFriendAsync(UserModel from, UserModel to, double givenMoney) { if (to == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Friend Not Found", "Friend not found for lend"); errors.Throw(); } if (from.Position == (int)UserPosition.HasNotHome || to.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } FriendshipModel friendship = await _friendshipRepository.GetFriendshipByIdAsync(from.Id, to.Id); if (friendship == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Friendship Not Found", "Friendship not found for lend"); errors.Throw(); } if (friendship.User1.Id == from.Id) { friendship.Debt -= givenMoney; Task update = _friendshipRepository.UpdateAsync(friendship); FCMModel fcmFrom = new FCMModel(from.DeviceId, type: "GiveMoney"); fcmFrom.data.Add("ToId", to.Id); fcmFrom.data.Add("NewDebt", friendship.Debt); Task sendFCMFrom = _fcmService.SendFCMAsync(fcmFrom); FCMModel fcmTo = new FCMModel(to.DeviceId, type: "TakeMoney"); fcmTo.data.Add("FromId", from.Id); fcmTo.data.Add("NewDebt", -friendship.Debt); await _fcmService.SendFCMAsync(fcmTo); await sendFCMFrom; await update; } else { friendship.Debt += givenMoney; Task update = _friendshipRepository.UpdateAsync(friendship); FCMModel fcmFrom = new FCMModel(from.DeviceId, type: "GiveMoney"); fcmFrom.data.Add("ToId", to.Id); fcmFrom.data.Add("NewDebt", -friendship.Debt); Task sendFCMFrom = _fcmService.SendFCMAsync(fcmFrom); FCMModel fcmTo = new FCMModel(to.DeviceId, type: "TakeMoney"); fcmTo.data.Add("FromId", from.Id); fcmTo.data.Add("NewDebt", friendship.Debt); await _fcmService.SendFCMAsync(fcmTo); await sendFCMFrom; await update; } }
//Admin updates a housework assign public async Task UpdateHouseworkAsync(UserModel user, HouseworkModel housework, int friendId) { if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorization Error", "You are not authorized for housework assignment"); errors.Throw(); } if (housework.Day < 1 || housework.Day > 31) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Day Error", "You can assign a day only between 1-31"); errors.Throw(); } HouseworkModel oldHousework = await _houseworkRepository.GetHouseworkByIdAsync(housework.Id); user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); UserModel newFriend = await _userRepository.GetByIdAsync(friendId, true); if (oldHousework == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Not Found", "Housework not found for delete"); errors.Throw(); } if (oldHousework.Home != user.Home) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Housework Not Belongs Home", "Housework not belongs for this home"); errors.Throw(); } if ((newFriend == null) || (newFriend.Home != user.Home)) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Friendship Not Found", "Friendship not found for assignment"); errors.Throw(); } oldHousework.Day = housework.Day; oldHousework.User = newFriend; oldHousework.Work = housework.Work; _houseworkRepository.Update(oldHousework); //Sends fcm to assigned friend FCMModel fcmFriend = new FCMModel(housework.User.DeviceId, new Dictionary <string, object>()); fcmFriend.notification.Add("title", "Ev İşi Güncellendi"); fcmFriend.notification.Add("body", "Yapmanız gereken bir ev işi güncellendi."); await _fcmService.SendFCMAsync(fcmFriend); //Sends fcm to all friends foreach (var f in home.Users) { FCMModel fcm = new FCMModel(f.DeviceId, type: "UpdateHousework"); fcm.data.Add("Housework", housework); fcm.data.Add("FriendId", friendId); await _fcmService.SendFCMAsync(fcm); } }
//User adds menu public async Task AddMenuAsync(UserModel user, MenuModel menu, List <int> mealIds) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } if (menu.Date.Kind != DateTimeKind.Utc) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Date Not Valid", "Date is not valid, please convert to UTC"); errors.Throw(); } menu.Date = menu.Date.AddHours(-menu.Date.Hour); menu.Date = menu.Date.AddMinutes(-menu.Date.Minute); menu.Date = menu.Date.AddSeconds(-menu.Date.Second); menu.Date = menu.Date.AddMilliseconds(-menu.Date.Millisecond); user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); MenuModel tmp = await _menuRepository.GetHomeMenuByDateAsync(home.Id, menu.Date); if (tmp != null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Date Not Valid", "Date is not valid, that day has already menu"); errors.Throw(); } mealIds = mealIds.Distinct().ToList(); if (mealIds.Count == 0) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Menu Has Not Meal", "There is no meals for this menu"); errors.Throw(); } menu.Home = home; //Finds meals that are not related home foreach (var mealId in mealIds) { MealModel meal = await _mealRepository.GetHomeMealByIdAsync(mealId, true); if ((meal == null) || (meal.Home.Id != home.Id)) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Meal Not Related Home", "This meal is not related with user home"); errors.Throw(); } } _menuRepository.Insert(menu); //Inserts menu meal to database foreach (var mealId in mealIds) { MealModel meal = await _mealRepository.GetHomeMealByIdAsync(mealId, true); MenuMealModel menuMeal = new MenuMealModel(menu, meal); _menuMealRepository.Insert(menuMeal); } //Sends fcm to all users foreach (var friend in home.Users) { FCMModel fcm = new FCMModel(friend.DeviceId, type: "AddMenu"); fcm.data.Add("Menu", menu); fcm.data.Add("MealIds", mealIds); await _fcmService.SendFCMAsync(fcm); } }
//Admin accepts or rejects user's request public async Task JoinHomeAcceptAsync(UserModel user, int requesterId, bool isAccepted) { Task <UserModel> getAdmin = _userRepository.GetByIdAsync(user.Id, true); Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName"); Task <InformationModel> lastNameInfo = _informationRepository.GetInformationByInformationNameAsync("LastName"); if (user.Position != (int)UserPosition.Admin) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Authorisation Constraint", "You are not authorized for this request, you must be administrator of home"); errors.Throw(); } UserModel requester = await _userRepository.GetByIdAsync(requesterId); if (requester == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Invalid User Id", "User not exist"); errors.Throw(); } if (requester.Position != (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Requester Has Home", "Requester has already home"); errors.Throw(); } user = await getAdmin; if (isAccepted == true) { requester.Position = (int)UserPosition.HasHome; UserInformationModel requesterFirstName = await _userInformationRepository.GetUserInformationByIdAsync(requester.Id, (await firstNameInfo).Id); UserInformationModel requesterLastName = await _userInformationRepository.GetUserInformationByIdAsync(requester.Id, (await lastNameInfo).Id); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); FCMModel fcmRequester = new FCMModel(requester.DeviceId, new Dictionary <string, object>()); fcmRequester.notification.Add("title", "Eve Katılma İsteği"); fcmRequester.notification.Add("body", "Eve katılma isteğiniz ev yöneticisi tarafından kabul edildi."); await _fcmService.SendFCMAsync(fcmRequester); List <UserBaseModel> friendsBaseModels = new List <UserBaseModel>(); UserBaseModel requesterBaseModel = new UserBaseModel(requester.Id, requester.Username, requester.Position, requesterFirstName.Value, requesterLastName.Value, 0); foreach (var friend in home.Users) { FriendshipModel friendship = new FriendshipModel(requester, friend, 0); Task insertFriendship = _friendshipRepository.InsertAsync(friendship); //Sends notification to all friends FCMModel fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>()); fcmFriend.notification.Add("title", "Yeni Ev Arkadaşı"); fcmFriend.notification.Add("body", String.Format("{0} {1}({2}) evinize katıldı.", requesterFirstName.Value, requesterLastName.Value, requester.Username)); await _fcmService.SendFCMAsync(fcmFriend); //Sends notification to all friends fcmFriend = new FCMModel(friend.DeviceId, type: "NewFriend"); fcmFriend.data.Add("Friend", requesterBaseModel); await _fcmService.SendFCMAsync(fcmFriend); //Sends all friends to requester UserInformationModel friendFirstName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await firstNameInfo).Id); UserInformationModel friendLastName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await lastNameInfo).Id); friendsBaseModels.Add(new UserBaseModel(friend.Id, friend.Username, friend.Position, friendFirstName.Value, friendLastName.Value, 0)); await insertFriendship; } home.Users.Add(requester); _homeRepository.Update(home); requester.Home = home; _userRepository.Update(requester); fcmRequester = new FCMModel(requester.DeviceId, type: "AllFriends"); fcmRequester.data.Add("NumberOfFriends", home.Users.Count - 1); fcmRequester.data.Add("Friends", friendsBaseModels); await _fcmService.SendFCMAsync(fcmRequester); } }
//User accepts or rejects admin's request public async Task InviteHomeAcceptAsync(UserModel user, int invitedHomeId, bool isAccepted) { Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName"); Task <InformationModel> lastNameInfo = _informationRepository.GetInformationByInformationNameAsync("LastName"); if (user.Position != (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Has Home", "User can not accept invite requests while already has home"); errors.Throw(); } HomeModel home = await _homeRepository.GetByIdAsync(invitedHomeId, true); if (home == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Invalid Home Id", "Home not exist"); errors.Throw(); } if (isAccepted == true) { user.Position = (int)UserPosition.HasHome; UserInformationModel userFirstName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await firstNameInfo).Id); UserInformationModel userLastName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await lastNameInfo).Id); List <UserBaseModel> friendsBaseModels = new List <UserBaseModel>(); UserBaseModel userBaseModel = new UserBaseModel(user.Id, user.Username, user.Position, userFirstName.Value, userLastName.Value, 0); FCMModel fcmUser = new FCMModel(user.DeviceId, type: "AllFriends"); foreach (var friend in home.Users) { FriendshipModel friendship = new FriendshipModel(user, friend, 0); Task insertFriendship = _friendshipRepository.InsertAsync(friendship); //Sends notification to all friends FCMModel fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>()); fcmFriend.notification.Add("title", "Yeni Ev Arkadaşı"); fcmFriend.notification.Add("body", String.Format("{0} {1}({2}) evinize katıldı", userFirstName.Value, userLastName.Value, user.Username)); await _fcmService.SendFCMAsync(fcmFriend); //Sends notification to all friends fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>(), "NewFriend"); fcmFriend.data.Add("Friend", userBaseModel); await _fcmService.SendFCMAsync(fcmFriend); //Sends all friends to requester UserInformationModel friendFirstName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await firstNameInfo).Id); UserInformationModel friendLastName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await lastNameInfo).Id); friendsBaseModels.Add(new UserBaseModel(friend.Id, friend.Username, friend.Position, friendFirstName.Value, friendLastName.Value, 0)); await insertFriendship; } home.Users.Add(user); _homeRepository.Update(home); user.Home = home; _userRepository.Update(user); fcmUser.data.Add("NumberOfFriends", home.Users.Count - 1); fcmUser.data.Add("Friends", friendsBaseModels); await _fcmService.SendFCMAsync(fcmUser); } }
//User request to quit home public async Task LeaveHomeAsync(UserModel user, int newAdminId) { if (user.Position == (int)UserPosition.HasNotHome) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Home Not Exist", "User is not member of a home"); errors.Throw(); } Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName"); Task <InformationModel> lastNameInfo = _informationRepository.GetInformationByInformationNameAsync("LastName"); user = await _userRepository.GetByIdAsync(user.Id, true); HomeModel home = await _homeRepository.GetByIdAsync(user.Home.Id, true); UserInformationModel userFirstName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await firstNameInfo).Id); UserInformationModel userLastName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await lastNameInfo).Id); List <UserExpenseModel> userExpenses = await _userExpenseRepository.GetAllUserExpenseByUserIdAsync(user.Id); foreach (var ue in userExpenses) { _userExpenseRepository.Delete(ue); } if (home.Users.Count != 1) { if (user.Position == (int)UserPosition.Admin) { UserModel newAdmin = await _userRepository.GetByIdAsync(newAdminId); if (newAdmin == null || newAdmin.Home.Id != user.Home.Id) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Friendship Not Found", "Friendship not found for admin assignment"); errors.Throw(); } newAdmin.Position = (int)UserPosition.Admin; home.Admin = newAdmin; } home.Users.Remove(user); user.Home = null; user.Position = (int)UserPosition.HasNotHome; _homeRepository.Update(home); _userRepository.Update(user); //Home friends notification foreach (var u in home.Users) { FriendshipModel friendship = await _friendshipRepository.GetFriendshipByIdAsync(user.Id, u.Id); FCMModel fcm = new FCMModel(u.DeviceId, new Dictionary <string, object>()); fcm.notification.Add("title", "Evden Ayrılma"); if (friendship.User1.Id == user.Id) { if (friendship.Debt > 0) { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Alacağınız : {2:c}", userFirstName.Value, userLastName.Value, friendship.Debt)); } else if (friendship.Debt == 0) { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Borcunuz veya alacağınız bulunmamaktadır.", userFirstName.Value, userLastName.Value)); } else { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Borcunuz : {2:c}", userFirstName.Value, userLastName.Value, -friendship.Debt)); } } else { if (friendship.Debt > 0) { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Borcunuz : {2:c}", userFirstName.Value, userLastName.Value, friendship.Debt)); } else if (friendship.Debt == 0) { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Borcunuz veya alacağınız bulunmamaktadır.", userFirstName.Value, userLastName.Value)); } else { fcm.notification.Add("body", String.Format("{0} {1} evden ayrılıyor. Alacağınız : {2:c}", userFirstName.Value, userLastName.Value, -friendship.Debt)); } } await _fcmService.SendFCMAsync(fcm); fcm = new FCMModel(u.DeviceId, type: "LeaveHome"); fcm.data.Add("LeaverId", user.Id); await _fcmService.SendFCMAsync(fcm); _friendshipRepository.Delete(friendship); } } else { ShoppingListModel shoppingList = await _shoppingListRepository.GetShoppingListByHomeIdAsync(user.Home.Id); List <NotepadModel> notepad = await _notepadRepository.GetAllNoteByHomeIdAsync(user.Home.Id); List <ExpenseModel> expenses = await _expenseRepository.GetAllExpensesByHomeIdAsync(user.Home.Id); _shoppingListRepository.Delete(shoppingList); foreach (var note in notepad) { _notepadRepository.Delete(note); } foreach (var expense in expenses) { _expenseRepository.Delete(expense); } user.Home = null; user.Position = (int)UserPosition.HasNotHome; _userRepository.Update(user); _homeRepository.Delete(home); } }