Esempio n. 1
0
        private int Watch(UserModel summoner, string server)
        {
            var summonerDb = Shared.GetDbSummoner(summoner.Id, dal).Result;

            if (summonerDb != null)
            {
                if (summonerDb.Watch)
                {
                    logger.LogInformation("Summoner is already set to watching. Skipping action.");
                    return(0);
                }

                summonerDb.Watch = true;
                dal.Update(summonerDb);
            }
            else
            {
                summonerDb = new DatabaseAccessLayer.Models.UserModel
                {
                    Server     = server.ToLower(),
                    SummonerId = summoner.Id,
                    Username   = summoner.Name,
                    Watch      = true,
                };
                dal.Add(summonerDb);
            }

            Shared.CommitDatabaseChanges(dal, logger).Wait();

            return(0);
        }
        public async Task <IActionResult> Watch(
            [FromRoute] string server,
            [FromRoute] string userName)
        {
            server = server.ToLower();

            var key = $"{server}/{userName}";

            if (!registrationCache.RegistrationCodeCache.ContainsKey(key))
            {
                return(Unauthorized());
            }

            var stateCode = registrationCache.RegistrationCodeCache.Get(key);

            UserModel user = new UserModel();
            string    obtainedCode;

            try
            {
                user = await wrapper.GetSummonerByName(server, userName);
            }
            catch (ResponseException e)
            {
                if (e.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(BadRequest("user not found"));
                }
            }

            try
            {
                obtainedCode = await wrapper.GetThirdPartyCode(server, user.Id);

                if (obtainedCode != stateCode)
                {
                    return(Unauthorized());
                }
            }
            catch (ResponseException e)
            {
                if (e.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(Unauthorized());
                }
            }

            var dbUser = await dal.GetUserByNameAsync(server, user.Name);

            if (dbUser == null)
            {
                dbUser = new DatabaseAccessLayer.Models.UserModel
                {
                    Server     = server,
                    Username   = user.Name,
                    SummonerId = user.Id,
                    Watch      = true,
                };

                dal.Add(dbUser);
            }
            else
            {
                dbUser.SummonerId = user.Id;
                dbUser.Watch      = true;

                dal.Update(dbUser);
            }

            await dal.CommitChangesAsync();

            return(Ok());
        }
Esempio n. 3
0
        public async Task <bool> GetUserStats(UserModel user, bool addToLog = false, bool isRetry = false)
        {
            if (requestCount++ > maxRequestsPerSecond)
            {
                logger.LogInformation("Max request coun exceed, waiting until continuing...");
                Thread.Sleep(1_000);
                requestCount = 0;
            }

            if (user.SummonerId == null)
            {
                await GetSummonerID(user);
            }

            RiotAPIAccessLayer.Models.PointsModel[] pointsRes;

            try
            {
                pointsRes = await wrapper.GetSummonerPoints(user.Server, user.SummonerId);
            }
            catch (Exception e)
            {
                if (e is ResponseException &&
                    !(e as ResponseException).Response.IsSuccessStatusCode &&
                    (e as ResponseException).Response.StatusCode != HttpStatusCode.TooManyRequests)
                {
                    // If the data can not be fetched by the summoner ID saved in the databse,
                    // then firstly try to collect the user ID of the user from the API again
                    // and retry this function with isRetry passed as true.
                    // If isRetry is true, the user will be 'Watch' flag of the user will be set
                    // to false to prevent further errors.
                    if (!isRetry)
                    {
                        logger.LogInformation($"Requesting stats of user '{user.Username}' failed: ${(e as ResponseException).Response.StatusCode}");
                        logger.LogInformation($"Trying to refresh users ID and retry getting stats...");
                        await GetSummonerID(user);

                        return(await GetUserStats(user, addToLog, true));
                    }
                    else
                    {
                        user.Watch = false;
                        logger.LogError("retry getting stats failed - settings 'Watch' flag to false");
                        dal.Update(user);
                    }
                }
                else
                {
                    logger.LogError($"An unexpected error occured during request: {e.Message}");
                }

                return(false);
            }


            var pointsDb = await dal.GetPointsAsync(user.Id);

            Array.ForEach(pointsRes, p =>
            {
                var pChamp = pointsDb.FirstOrDefault(pdb => pdb.ChampionId == p.ChampionId);

                if (pChamp == null)
                {
                    pChamp = new PointsModel
                    {
                        ChampionId     = p.ChampionId,
                        ChampionLevel  = p.ChampionLevel,
                        ChampionPoints = p.ChampionPoints,
                        LastPlayed     = TimeUtils.UnixToDateTime(p.LastPlayed),
                        User           = user,
                    };

                    dal.Add(pChamp);
                }
                else
                {
                    pChamp.ChampionLevel  = p.ChampionLevel;
                    pChamp.ChampionPoints = p.ChampionPoints;
                    pChamp.LastPlayed     = TimeUtils.UnixToDateTime(p.LastPlayed);
                    pChamp.Updated        = DateTime.Now;

                    dal.Update(pChamp);
                }

                if (addToLog)
                {
                    var pointsLog = new PointsLogModel
                    {
                        ChampionLevel  = p.ChampionLevel,
                        ChampionId     = p.ChampionId,
                        ChampionPoints = p.ChampionPoints,
                        User           = user,
                    };

                    dal.Add(pointsLog);
                }
            });

            await dal.CommitChangesAsync();

            logger.LogInformation("Changed commited to database");

            return(true);
        }