using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using xCommons.Extensions; using xCommons.Helpers; using xExceptions.Constants; using xIdentityModels; using xIdentityModels.Constants; using xIdentityModels.Dtos; using xIdentityModels.Models; using xIdentityModels.Navigations; namespace xIds.Providers { public partial class XIdentityManager { // #region Generators ... /// /// Generate a Random Number ... /// /// a long value private long GenerateRandom() { return new Random().Next(100000, 999999); } #endregion // #region UserSelectBy Actions ... /// /// Retrieve UserSelectByType based on Given Info /// /// a user identifier /// a boolean value which specify the identifier /// must be specific and not empty, default is true /// a boolean value which specify the type /// must be specific, default is false /// a member of XUserSelectBy private XUserSelectBy GetUserSelectByType( string userSelectByParam, bool forceUserSelectByParamNotEmpty = true, bool forceUserSelectByTypeMustSpecified = false ) { // if (forceUserSelectByParamNotEmpty) { ValidationProvider.NotEmpty(userSelectByParam); } // var result = XUserSelectBy.NotSpecified; var normalizedString = userSelectByParam.ToNormalString(); if (userSelectByParam.IsValidEmail()) { // // Find User by Email ... result = XUserSelectBy.Email; } else if (userSelectByParam.IsValidMobileNumber()) { // // Find User by Mobile Number ... result = XUserSelectBy.MobileNumber; } else if (userSelectByParam.IsGuid()) { // // Find User By it's ID ... result = XUserSelectBy.ID; } else { // // UserName ... result = XUserSelectBy.Username; } // if (forceUserSelectByTypeMustSpecified && result == XUserSelectBy.NotSpecified) { XException.InvalidData.Throw(); } // return result; } /// /// Retrieve UserSelectByParam based on XUser Object /// /// an instance of XUser /// a boolean value which specify the identifier must nut empty, /// and throw exception if it is empty, default is true /// a collection of XUserSelectBy members which /// exclude them from result, default is null /// a user identifier private string GetUserSelectByParam( XUser user, bool forceNotNull = true, ICollection excludes = null ) { // // Validate Args ... ValidationProvider.NotNull(user); // var id = user.Id; var userName = user.UserName; var email = user.Email; var phoneNumber = user.PhoneNumber; // if (excludes != null) { if (excludes.Contains(XUserSelectBy.ID)) { id = null; } if (excludes.Contains(XUserSelectBy.Email)) { email = null; } if (excludes.Contains(XUserSelectBy.MobileNumber)) { phoneNumber = null; } if (excludes.Contains(XUserSelectBy.Username)) { userName = null; } } var selectByParam = id.IsNullOrEmpty() ? userName.IsNullOrEmpty() ? email.IsNullOrEmpty() ? phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; // // Check result ... if (forceNotNull && selectByParam.IsNullOrEmpty()) { XException.InvalidData.Throw(); } // return selectByParam; } /// /// Retrieve UserSelectByParam based on XActionRequestContext instance /// /// an instance of XActionRequestContext /// a boolean value which specify the identifier must nut empty, /// and throw exception if it is empty, default is true /// a collection of XUserSelectBy members which /// exclude them from result, default is null /// a user identifier private string GetUserSelectByParam( XActionRequestContext context, bool forceNotNull = true, ICollection excludes = null ) { // // Validate Args ... ValidationProvider.NotNull(context); // // Generate User SelectBy ... var id = context.UserId; var userName = context.UserName; var email = context.Email; var phoneNumber = context.MobileNumber; // if (excludes != null) { // if (excludes.Contains(XUserSelectBy.ID)) { id = null; } if (excludes.Contains(XUserSelectBy.Email)) { email = null; } if (excludes.Contains(XUserSelectBy.MobileNumber)) { phoneNumber = null; } if (excludes.Contains(XUserSelectBy.Username)) { userName = null; } } var selectByParam = id.IsNullOrEmpty() ? userName.IsNullOrEmpty() ? email.IsNullOrEmpty() ? phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; // // Check param ... if (forceNotNull && selectByParam.IsNullOrEmpty()) { XException.InvalidData.Throw(); } // return selectByParam; } /// /// Retrieve UserSelectByParam based on XActionRequestToken instance /// /// an instance of XActionRequestToken which /// provides required informations /// a boolean value which specify the identifier must nut empty, /// and throw exception if it is empty, default is true /// a collection of XUserSelectBy members which /// exclude them from result, default is null /// a user identifier private string GetUserSelectByParam( XActionRequestToken request, bool forceNotNull = true, ICollection excludes = null ) { // // Validate Args ... ValidationProvider.NotNull(request); // // Generate User SelectBy ... return GetUserSelectByParam( context: request.Context, forceNotNull: forceNotNull, excludes: excludes ); } /// /// Retrieve Available UserSelectByParams from given XUser /// /// an instance of XUser /// private ICollection GenerateUserSelectByParams( XUser user ) { // if (user == null) { return null; } // var result = new List { user.Id, user.UserName, user.PhoneNumber, user.Email, }; // return result; } /// /// Retrieve Required XUserSelectByTypes /// /// a collection of XUserSelectBy members which /// ignored in result /// a collection of available XUserSelectBy members private ICollection GenerateUserSelectByExcludes( ICollection ignores ) { // var result = ObjectHelper .ToEnumerableValues() .Except(ignores); // return result.ToList(); } #endregion // #region XAction Actions ... /// /// Retrieve Action Result Response based on XToken /// /// an instance of XToken /// an instance of XActionResponse private XActionResponse GetActionResultResponse( XToken xToken ) { // ValidationProvider.NotNull(xToken); ValidationProvider.NotEmpty(xToken.Hash, xToken.Token); // ValidateToken(xToken.Token); // var expDate = GetTokenExpirationDate(xToken.Token); ValidationProvider.NotNull(expDate); // // Generate Result class ... var result = new XActionResponse { Token = xToken.Hash, Expiration = expDate }; // return result; } #endregion // #region XIdentityMessage Actions ... /// /// Prepare Message Provider and Check it's State /// /// specify destination language private void HandleMessageProviderPreperation( string lang ) { // ValidationProvider .NotEmpty(lang); // // Prepare Identity Messages ... // the PrepareMessageMethod check IsReady of Helper automatically ... IdentityMessageProvider.PrepareMessages(lang); // // Check Message Provider ... var isMessageProviderReady = MessageProvider.IsReady(true); if (!isMessageProviderReady) { XException.MessageServiceInitialFailed.Throw(); } } #endregion // #region Friendship Actions ... /// /// Check Follow Request Sent Before /// from dest to source /// /// an instance of XUser /// an instance of XUser /// a boolean value private bool IsFollowRequested( XUser source, XUser dest ) { // // Validate Args ... ValidationProvider.NotNull(source, dest); // var result = source.Followings.Any(f => f.DestId == dest.Id); // return result; } /// /// Check Follow Request Sent Before /// from dest to source /// /// an instance of XUser /// an instance of XUser /// a member of XFriendshipState /// a boolean value private bool IsFollowRequested( XUser source, XUser dest, XFriendshipState state ) { // // Validate Args ... ValidationProvider.NotNull(source, dest); // var result = source.Followings .Any(f => f.DestId == dest.Id && f.State == state); // return result; } /// /// Converts to XFriendDto ... /// /// /// private async Task ToDto(XFriendshipFollower entity) { // XFriendDto result = null; // if (entity.IsNull()) { return result; } // // Reading Dest User Profile ... var profile = await GetUserProfileAsync( userSelectByParam: entity.DestId, requestedUserSelectByParam: entity.UserId, forceCheckRequestedUser: false, checkCanLoginPolicies: false, checkIsBanned: false ); // // Preparing Result ... result = new XFriendDto { UserId = profile.UserId, Avatar = profile.Avatar, Username = profile.UserName, Lastname = profile.LastName, Firstname = profile.FirstName, Type = XFriendshipType.Follower, State = profile.FriendshipInfo.FollowerState, }; // return result; } /// /// Converts to XFriendDto ... /// /// /// private async Task ToDto(XFriendshipFollowing entity) { // XFriendDto result = null; // if (entity.IsNull()) { return result; } // // Reading Dest User Profile ... var profile = await GetUserProfileAsync( checkIsBanned: false, checkCanLoginPolicies: false, forceCheckRequestedUser: false, userSelectByParam: entity.DestId, requestedUserSelectByParam: entity.UserId ); // // Preparing Result ... result = new XFriendDto { UserId = profile.UserId, Avatar = profile.Avatar, Username = profile.UserName, Lastname = profile.LastName, Firstname = profile.FirstName, Type = XFriendshipType.Following, State = profile.FriendshipInfo.FollowingState, }; // return result; } #endregion // #region User Profile ... /// /// Count User's Page /// /// an integer value which represent page size /// an inetger value which represent pages count public async Task UserPagesCount( int pageSize ) { // int count = await UserManager.Users.CountAsync(); int pagesCount = count / pageSize; // if (count % pageSize > 0) { pagesCount++; } // return pagesCount; } /// /// Count Avatar's Page /// /// an integer value which represent page size /// an inetger value which represent pages count public async Task ProfileImagePagesCount( int pageSize ) { // int count = await DbContext.Avatars.CountAsync(); int pagesCount = count / pageSize; // if (count % pageSize > 0) { pagesCount++; } // return pagesCount; } #endregion } }