Beispiel #1
0
        /// <summary>
        /// GETs following data to display back to user
        /// number of images
        /// guess minus actual answer
        /// average time (Time/images)
        /// </summary>
        /// <param name="userGuid"></param>
        /// <returns></returns>
        public async Task <ActionResult> PhaseTwoFinish(string userGuid)
        {
            if (_session._isLoggedin)
            {
                var getUserRequest  = new HttpRequestMessage(HttpMethod.Get, $"/api/user/hash/{userGuid}");
                var getUserResponse = await _db.BuildApiResponse <UserModel>(getUserRequest, _session._accessToken);

                if (getUserResponse.Status == HttpStatusCode.OK)
                {
                    var getUserGuessRequest  = new HttpRequestMessage(HttpMethod.Get, $"/api/usersGuess/{getUserResponse.Content.UserId}/{(byte)Phase.TWO}");
                    var getUserGuessResponse = await _db.BuildApiResponse <List <UserGuessModel> >(getUserGuessRequest, _session._accessToken);

                    if (getUserResponse.Status == HttpStatusCode.OK)
                    {
                        var imageNumberArray  = new List <int>();
                        var guessResultsArray = new List <decimal>();
                        var time = getUserResponse.Content.TimePhase2.HasValue ? getUserResponse.Content.TimePhase2.Value : DateTime.Now.Date;

                        //convert time into seconds
                        var seconds = time.Second;
                        seconds += (time.Minute * 60);
                        seconds += (time.Hour * 3600);

                        //Get GuessPercentage - Actual Answer for table
                        int i       = 1;
                        var guesses = getUserGuessResponse.Content.OrderBy(x => x.UsersGuessId);
                        foreach (var item in guesses)
                        {
                            var result = (item.GuessPercentage - item.Image.DecayRate) * 100;
                            guessResultsArray.Add(result);
                            imageNumberArray.Add(i);
                            i++;
                        }

                        //Total Time
                        TimeSpan t         = TimeSpan.FromSeconds(seconds);
                        string   totalTime = string.Format("{0:D2}:{1:D2}:{2:D2}s",
                                                           t.Hours,
                                                           t.Minutes,
                                                           t.Seconds);

                        //Average Time
                        TimeSpan t2          = TimeSpan.FromSeconds((seconds / imageNumberArray.Count));
                        string   averageTime = string.Format("{0:D2}:{1:D2}:{2:D2}s",
                                                             t2.Hours,
                                                             t2.Minutes,
                                                             t2.Seconds);

                        var model = new FinishedModelView()
                        {
                            GuessResult    = guessResultsArray.ToArray(),
                            NumberOfImages = imageNumberArray.ToArray(),
                            TotalTime      = totalTime,
                            AverageTime    = averageTime,
                            UserGuid       = userGuid
                        };

                        return(View(model));
                    }
                }

                return(RedirectToAction("Errorpage", "Home"));
            }

            return(RedirectToAction("Login", "Account"));
        }
Beispiel #2
0
        /// <summary>
        /// Search and return all user guesses
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> UserGuessSearch()
        {
            if (_session._isLoggedin)
            {
                if (_session._userRole == Session.Role.Admin)
                {
                    var model = new UserGuessSearchModel()
                    {
                        UserGuessSearchResults = new List <UserGuessSearchResultsModel>()
                    };


                    var request  = new HttpRequestMessage(HttpMethod.Get, "/api/users");
                    var response = await _db.BuildApiResponse <List <UserModel> >(request, _session._accessToken);

                    if (response.Status == HttpStatusCode.OK)
                    {
                        var users = new List <UserModel>();
                        users = response.Content;

                        List <UserGuessSearchResultsModel> UserResults = new List <UserGuessSearchResultsModel>();
                        foreach (var item in users)
                        {
                            var imageCountP1 = item.Guesses.Where(x => x.Phase == Phase.ONE).ToList();
                            var imageCountP2 = item.Guesses.Where(x => x.Phase == Phase.TWO).ToList();
                            var imageCountP3 = item.Guesses.Where(x => x.Phase == Phase.THREE).ToList();

                            var trimmedUserModel = new UserGuessSearchResultsModel()
                            {
                                CreatedUtc    = item.CreatedUtc.Date.ToString("dd-MM-yyyy"),
                                HashUser      = item.HashUser.Value.ToString(),
                                UserId        = item.UserId,
                                RetentionUser = imageCountP1.Any() ? "No" : "Yes",

                                //PHASE 1
                                FinishedPhase1Utc = item.FinishedPhase1Utc.HasValue
                                    ? item.FinishedPhase1Utc.Value.Date.ToString("dd-MM-yyyy")
                                    : "",
                                FinishingPercentPhase1 = item.FinishingPercentPhase1.HasValue
                                    ? item.FinishingPercentPhase1.Value.ToString()
                                    : "0",
                                PictureCycledPhase1 = imageCountP1.Count.ToString(),
                                TimePhase1          = item.TimePhase1.HasValue ? item.TimePhase1.Value.TimeOfDay.ToString() : "",

                                //PHASE 2
                                FinishedPhase2Utc = item.FinishedPhase2Utc.HasValue
                                    ? item.FinishedPhase2Utc.Value.Date.ToString("dd-MM-yyyy")
                                    : "",
                                FinishingPercentPhase2 = item.FinishingPercentPhase2.HasValue
                                    ? item.FinishingPercentPhase2.Value.ToString()
                                    : "0",
                                PictureCycledPhase2 = imageCountP2.Count.ToString(),
                                TimePhase2          = item.TimePhase2.HasValue ? item.TimePhase2.Value.TimeOfDay.ToString() : "",

                                //PHASE 3
                                FinishedPhase3Utc = item.FinishedPhase3Utc.HasValue
                                    ? item.FinishedPhase3Utc.Value.Date.ToString("dd-MM-yyyy")
                                    : "",
                                FinishingPercentPhase3 = item.FinishingPercentPhase3.HasValue
                                    ? item.FinishingPercentPhase3.Value.ToString()
                                    : "0",
                                PictureCycledPhase3 = imageCountP3.Count.ToString(),
                                TimePhase3          = item.TimePhase3.HasValue ? item.TimePhase3.Value.TimeOfDay.ToString() : ""
                            };
                            UserResults.Add(trimmedUserModel);
                        }

                        model = new UserGuessSearchModel()
                        {
                            UserGuessSearchResults = UserResults
                        };

                        return(View(model));
                    }

                    return(View(model));
                }
                else
                {
                    return(RedirectToAction("Start", "Home"));
                }
            }

            return(RedirectToAction("Login", "Account"));
        }
Beispiel #3
0
        public async Task <ActionResult> Login(LoginModel model)
        {
            string recaptchaResponse = this.Request.Form["g-recaptcha-response"];
            var    client            = _httpClientFactory.CreateClient();

            try
            {
                var parameters = new Dictionary <string, string>
                {
                    { "secret", _config.Value.RecaptchaSecret },
                    { "response", recaptchaResponse },
                    { "remoteip", this.HttpContext.Connection.RemoteIpAddress.ToString() }
                };

                HttpResponseMessage response = await client.PostAsync("https://www.google.com/recaptcha/api/siteverify",
                                                                      new FormUrlEncodedContent(parameters));

                response.EnsureSuccessStatusCode();

                string apiResponse = await response.Content.ReadAsStringAsync();

                dynamic apiJson = JObject.Parse(apiResponse);
                if (apiJson.success == Boolean.TrueString)
                //if (true)
                {
                    if (ModelState.IsValid)
                    {
                        var binding = new
                        {
                            UserName = model.UserName,
                            Password = model.Password
                        };
                        var request = new HttpRequestMessage(HttpMethod.Post, "/api/authenticate")
                        {
                            Content = new StringContent(JsonSerializer.Serialize(binding), Encoding.UTF8,
                                                        "application/json")
                        };
                        var authResponse = await _db.BuildApiResponse <AuthenticateModel>(request);

                        if (authResponse.Status == HttpStatusCode.OK)
                        {
                            _session._accessToken = authResponse.Content.BearerToken;
                            _session._userRole    = (Session.Role)authResponse.Content.RoleType;
                            _session._isLoggedin  = true;
                            _session._expiryDate  = authResponse.Content.ExpiryDate;
                            _session._accessId    = authResponse.Content.AccessId;

                            if (_session._userRole == Session.Role.Guest)
                            {
                                return(RedirectToAction("Start", "Home"));
                            }
                            else if (_session._userRole == Session.Role.Admin)
                            {
                                return(RedirectToAction("UserGuessSearch", "Admin"));
                            }
                            else if (_session._userRole == Session.Role.ReturnGuest)
                            {
                                return(RedirectToAction("GuessWithFeedback", "UserGuess"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("CustomError", "Username or password is incorrect");
                            return(View());
                        }

                        //AccessTrainer
                        if (!model.AccessResults)
                        {
                            return(RedirectToAction("Start", "Home"));
                        }
                        else
                        {
                            return(RedirectToAction("UserGuessSearch", "Admin"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("CustomError", "Make sure the reCAPTCHA is ticked");
                    return(View());
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("CustomError", "Make sure the reCAPTCHA is ticked");
                return(View());
            }

            ModelState.AddModelError("CustomError", "Please contact support");
            return(View());
        }
Beispiel #4
0
        /// <summary>
        /// Init Guess set up
        /// Get user details or creat them
        /// Old guesses
        /// New image
        /// </summary>
        /// <param name="userGuid">Can be null if so new user is created</param>
        /// <returns></returns>
        public async Task <ActionResult> GuessNoFeedback(string userGuid, byte?phase = 0)
        {
            if (_session._isLoggedin)
            {
                //create if no guid
                var getUserRequest = new HttpRequestMessage(HttpMethod.Post, "/api/user");

                //Get if exists
                if (!string.IsNullOrEmpty(userGuid) && new Guid(userGuid) != Guid.Empty)
                {
                    getUserRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("/api/user/hash/{0}", userGuid));
                }

                var getUserResponse = await _db.BuildApiResponse <UserModel>(getUserRequest, _session._accessToken);

                GuessViewModel model = new GuessViewModel();
                if (getUserResponse.Status == HttpStatusCode.OK)
                {
                    model.UserHash = getUserResponse.Content.HashUser.Value;
                    model.UserId   = getUserResponse.Content.UserId;

                    //returning details
                    model.ReturningUser  = (getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any());
                    model.ReturningTimer = (getUserResponse.Content.TimePhase1.HasValue)
                        ? ((getUserResponse.Content.TimePhase1.Value.Hour * 3600) +
                           (getUserResponse.Content.TimePhase1.Value.Minute * 60) + (getUserResponse.Content.TimePhase1.Value.Second))
                        : 0;

                    //Login logging
                    var updateLoginTokenRequest  = new HttpRequestMessage(HttpMethod.Post, string.Format("/api/token/{0}/{1}", _session._accessId, model.UserHash.ToString()));
                    var updateLoginTokenResponse = await _db.BuildApiResponse <Token>(updateLoginTokenRequest, _session._accessToken);

                    //Past guesses
                    var usersGuessRequest = new HttpRequestMessage(HttpMethod.Get,
                                                                   string.Format("/api/usersGuess/{0}/{1}", getUserResponse.Content.UserId, phase));
                    var usersGuessResponse = await _db.BuildApiResponse <List <UserGuessModel> >(usersGuessRequest, _session._accessToken);


                    model.FinalPercentage = getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any() && usersGuessResponse.Content.Count >= 10
                        ? (decimal)Calculations.FindAverageDifferenceOfList(usersGuessResponse.Content.OrderBy(x => x.UsersGuessId).Skip(usersGuessResponse.Content.Count - 10).ToList())
                        : (decimal)0.0;


                    model.ImagesUsed = usersGuessResponse.Content.Count;
                    model.Phase      = (byte)(phase.HasValue ? phase.Value : 0);

                    //Get random new image that hasn't been used
                    var binding = new RandomImageBinding
                    {
                        PreviousImageIds = getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any()
                            ? getUserResponse.Content.Guesses.Select(x => x.ImageId).ToArray()
                            : new int[0],
                        ReturnRandom = true
                    };
                    var image = await GetRandomImage(binding);


                    if (image != null)
                    {
                        model.CurrentCloudinaryUrl = Common.BuildCloudinaryUrl(image.FileName);
                        model.CurrentImageId       = image.ImageId;

                        return(View(model));
                    }
                }

                return(RedirectToAction("Errorpage", "Home"));
            }

            return(RedirectToAction("Login", "Account"));
        }