public async Task <IActionResult> GetRankings()
        {
            string bucketName = "reinvent-gottalent";

            List <Ranking> rankingList = new List <Ranking>();
            var            topRankings = RedisUtil.GetTopRankings(0, 4);

            foreach (var item in topRankings)
            {
                Ranking ranking = new Ranking();
                ranking.total_rank = item.total_rank;

                var game = await _context.Game.FirstOrDefaultAsync(x => x.game_id == item.game_id);

                ranking.game_id = item.game_id;
                ranking.name    = game.name;

                var gameResult = await _context.GameResult.FirstOrDefaultAsync(x => x.game_id == item.game_id);

                ranking.total_score = gameResult.total_score;
                ranking.gender      = gameResult.gender_result;
                ranking.age         = gameResult.age_result;
                ranking.grade       = gameResult.grade_result;

                var stageLog = await _context.StageLog.FirstOrDefaultAsync(x => x.game_id == item.game_id && x.action_type == "Profile");

                ranking.photoURL = S3Util.GetPresignedURL(this.S3Client, bucketName, stageLog.file_loc);

                rankingList.Add(ranking);
            }

            return(Ok(rankingList));
        }
        public async static Task <string> PollyDemo(IAmazonPolly pollyClient, IAmazonS3 S3Client, string text)
        {
            string result = null;
            SynthesizeSpeechRequest synthesizeRequest = new SynthesizeSpeechRequest()
            {
                LanguageCode = LanguageCode.EnUS,
                OutputFormat = "mp3",
                SampleRate   = "8000",
                Text         = text,
                TextType     = "text",
                VoiceId      = "Joanna"
            };

            try
            {
                Task <SynthesizeSpeechResponse> synthesizeTask    = pollyClient.SynthesizeSpeechAsync(synthesizeRequest);
                SynthesizeSpeechResponse        syntheizeResponse = await synthesizeTask;

                Console.WriteLine(syntheizeResponse.ContentType);
                Console.WriteLine(syntheizeResponse.RequestCharacters);

                using (MemoryStream ms = new MemoryStream())
                {
                    syntheizeResponse.AudioStream.CopyTo(ms);
                    Console.WriteLine(ms.Length);

                    // Upload image to S3 bucket
                    string bucketName = "reinvent-indiamazones";
                    //string key = dto.text;
                    string key = "pollytest";
                    await Task.Run(() => S3Util.UploadToS3(S3Client, bucketName, key, ms));

                    // TODO : need to check the file exists in S3
                    result = S3Util.GetPresignedURL(S3Client, bucketName, key);
                }
                //syntheizeResponse.AudioStream.CopyTo(result);
                //result.Flush();
            }
            catch (AmazonPollyException pollyException)
            {
                Console.WriteLine(pollyException.Message, pollyException.InnerException);
            }

            return(result);
        }
        public async Task <IActionResult> CalcGameResult(int game_id)
        {
            string bucketName = "reinvent-gottalent";

            var stageLogs = await _context.StageLog.Where(x => x.game_id == game_id).ToListAsync();

            double        totalScore   = 0.0f;
            string        genderResult = "";
            string        gradeResult  = "";
            List <string> signedURLs   = new List <string>();
            int           ageResult    = 0;

            foreach (var stageLog in stageLogs)
            {
                if (stageLog.action_type == "Profile")
                {
                    genderResult = stageLog.gender;
                    ageResult    = stageLog.age;
                }
                else
                {
                    totalScore += stageLog.score;
                    signedURLs.Add(S3Util.GetPresignedURL(this.S3Client, bucketName, stageLog.file_loc));
                }
            }

            // TODO : need to use Cache service for judgement
            if (totalScore < 160)
            {
                gradeResult = "Extra";
            }
            else if (160 <= totalScore && totalScore < 190)
            {
                gradeResult = "Supporting";
            }
            else
            {
                gradeResult = "Leading";
            }

            // casting randomly
            int    randomRecord  = new Random().Next() % _context.Cast.Where(x => x.gender == genderResult && x.grade == gradeResult).Count();;
            var    castResult    = _context.Cast.Where(x => x.gender == genderResult && x.grade == gradeResult).Skip(randomRecord).Take(1).First();
            string resultPageUrl = "TBD";

            // Database update
            GameResult newGameResult = new GameResult {
                game_id         = game_id,
                result_page_url = resultPageUrl,
                total_score     = totalScore,
                total_rank      = 0,
                cast_result     = castResult.cast_id,
                grade_result    = gradeResult,
                gender_result   = genderResult,
                age_result      = ageResult
            };

            Game game = await _context.Game.Where(x => x.game_id == game_id).FirstOrDefaultAsync();

            game.end_date = DateTime.Now;
            game.share_yn = "Y";

            var value = _context.GameResult.Add(newGameResult);
            await _context.SaveChangesAsync();

            RedisUtil.AddGameResultToRedis(newGameResult);
            newGameResult.total_rank = RedisUtil.GetGameRanking(newGameResult.game_id) + 1;

            return(Ok(new { newGameResult, castResult.actor, castResult.title, signedURLs }));
        }
        public async Task <IActionResult> Post([FromBody] GameStagePostImageDTO dto)
        {
            Console.WriteLine("PostImage entered.");

            string bucketName = "reinvent-gottalent";

            // Retrieving image data
            // ex: game/10/Happiness.jpg
            string keyName        = string.Format("game/{0}/{1}.jpg", dto.gameId, dto.actionType);
            string croppedKeyName = string.Format("game/{0}/{1}_cropped.jpg", dto.gameId, dto.actionType);

            byte[] imageByteArray = Convert.FromBase64String(dto.base64Image);
            if (imageByteArray.Length == 0)
            {
                return(BadRequest("Image length is 0."));
            }

            StageLog newStageLog = null;

            using (MemoryStream ms = new MemoryStream(imageByteArray))
            {
                // call Rekonition API
                FaceDetail faceDetail = await RekognitionUtil.GetFaceDetailFromStream(this.RekognitionClient, ms);

                // Crop image to get face only
                System.Drawing.Image originalImage = System.Drawing.Image.FromStream(ms);
                System.Drawing.Image croppedImage  = GetCroppedFaceImage(originalImage, faceDetail.BoundingBox);
                MemoryStream         croppedms     = new MemoryStream();
                croppedImage.Save(croppedms, ImageFormat.Jpeg);

                // Upload image to S3 bucket
                //await Task.Run(() => S3Util.UploadToS3(this.S3Client, bucketName, keyName, ms));
                await Task.Run(() => S3Util.UploadToS3(this.S3Client, bucketName, keyName, croppedms));

                // Get a specific emotion score
                double emotionScore = 0.0f;
                if (dto.actionType != "Profile")
                {
                    emotionScore = RekognitionUtil.GetEmotionScore(faceDetail.Emotions, dto.actionType);
                }

                int    evaluatedAge    = (faceDetail.AgeRange.High + faceDetail.AgeRange.Low) / 2;
                string evaluatedGender = faceDetail.Gender.Value;

                // Database update
                newStageLog = new StageLog {
                    game_id     = dto.gameId,
                    action_type = dto.actionType,
                    score       = emotionScore,
                    file_loc    = keyName,
                    age         = evaluatedAge,
                    gender      = evaluatedGender,
                    log_date    = DateTime.Now
                };

                var value = _context.StageLog.Add(newStageLog);
                await _context.SaveChangesAsync();
            }

            // Send response
            string signedURL = S3Util.GetPresignedURL(this.S3Client, bucketName, keyName);

            newStageLog.file_loc = signedURL;

            return(Ok(newStageLog));
        }