예제 #1
0
        public async Task <string> _getcurrentLevelInfos()
        {
            var stats = await Context.Inventory.GetPlayerStats();

            var output = string.Empty;
            var stat   = stats.FirstOrDefault();

            if (stat != null)
            {
                Currentlevel = stat.Level;
                var ep      = (stat.NextLevelXp - stat.PrevLevelXp) - (stat.Experience - stat.PrevLevelXp);
                var time    = Math.Round(ep / (TotalExperience / _getSessionRuntime()), 2);
                var hours   = 0.00;
                var minutes = 0.00;
                if (Double.IsInfinity(time) == false && time > 0)
                {
                    time    = Convert.ToDouble(TimeSpan.FromHours(time).ToString("h\\.mm"), System.Globalization.CultureInfo.InvariantCulture);
                    hours   = Math.Truncate(time);
                    minutes = Math.Round((time - hours) * 100);
                }

                bool didLevelUp = false;

                if (LevelForRewards == -1 || stat.Level >= LevelForRewards)
                {
                    LevelUpRewardsResponse Result = await Context.Inventory.GetLevelUpRewards(stat.Level);

                    if (Result.Result == LevelUpRewardsResponse.Types.Result.AwardedAlready)
                    {
                        LevelForRewards = stat.Level + 1;
                    }

                    if (Result.Result == LevelUpRewardsResponse.Types.Result.Success)
                    {
                        didLevelUp = true;
                        Logger.Write($"(LEVEL) Reached level {stat.Level}!", LogLevel.None, ConsoleColor.Green);

                        RepeatedField <ItemAward> items = Result.ItemsAwarded;

                        if (items.Any <ItemAward>())
                        {
                            Logger.Write("Received Bonus Items:", LogLevel.None, ConsoleColor.Green);
                            foreach (ItemAward item in items)
                            {
                                Logger.Write($"{item.ItemId} x {item.ItemCount} ", LogLevel.None, ConsoleColor.Green);
                            }
                        }
                    }
                }

                if (!didLevelUp)
                {
                    output = $"{stat.Level} (Level in {hours}h {minutes}m | {stat.Experience - stat.PrevLevelXp - GetXpDiff(stat.Level)}/{stat.NextLevelXp - stat.PrevLevelXp - GetXpDiff(stat.Level)} XP)";
                }
            }
            return(output);
        }
        public override async Task <GetPanelResponse> Get(GetPanelRequest request, ServerCallContext context)
        {
            RepeatedField <Loan>        loans        = new RepeatedField <Loan>();
            RepeatedField <Payment>     payments     = new RepeatedField <Payment>();
            RepeatedField <Account>     accounts     = new RepeatedField <Account>();
            RepeatedField <Card>        cards        = new RepeatedField <Card>();
            RepeatedField <Transaction> transactions = new RepeatedField <Transaction>();

            var accountsResponse = await accountsClient.GetUserAccountsAsync(new GetUserAccountsRequest { UserId = request.UserId }, context.RequestHeaders.SelectCustom());

            var accountsIds = accountsResponse.Accounts.Select(a => a.Id).ToArray();

            accounts = accountsResponse.Accounts;

            if (accounts.Any())
            {
                var parallelTasks = new List <Task>();
                parallelTasks.Add(Task.Run(async() =>
                {
                    var transactionsResponse = await transactionsClient.FilterAsync(
                        new FilterTransactionsRequest {
                        Senders = { accountsIds }, Top = PanelTransactionsCount
                    }
                        , context.RequestHeaders.SelectCustom());
                }));

                parallelTasks.Add(Task.Run(async() =>
                {
                    var paymentsAndLoans = await paymentsClient.GetByAccountsAsync(new GetPaymentsRequest {
                        Ids = { accountsIds }
                    }, context.RequestHeaders.SelectCustom());
                    loans    = paymentsAndLoans.Loans;
                    payments = paymentsAndLoans.Payments;
                }));

                parallelTasks.Add(Task.Run(async() =>
                {
                    var cardsResponse = await cardsClient.GetByAccountsAsync(new GetCardsRequest {
                        Ids = { accountsIds }
                    }, context.RequestHeaders.SelectCustom());
                    cards = cardsResponse.Cards;
                }));


                await Task.WhenAll(parallelTasks);
            }

            return(new GetPanelResponse
            {
                Cards = { cards },
                Payments = { payments },
                Accounts = { accounts },
                Loans = { loans },
                Transactions = { transactions.OrderByDescending(t => t.Timestamp) }
            });
        }
예제 #3
0
        public async static Task <dynamic> ImpressionsYesterday(List <string> companyNames)
        {
            var dailyImpressionsDTO = new DailyImpressionsDTO();

            dailyImpressionsDTO.DailyImpressionsSummary = new List <CompanyDailyImpressionsSummary>();

            foreach (string company in companyNames)
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(company, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company { company }"));
                }

                try
                {
                    GoogleAdsClient client = new GoogleAdsClient();

                    // Get the GoogleAdsService.
                    GoogleAdsServiceClient googleAdsService = client.GetService(
                        Services.V4.GoogleAdsService);

                    string dailyImpressionsQuery = "SELECT "
                                                   + "campaign.id, "
                                                   + "campaign.name, "
                                                   + "metrics.impressions "
                                                   + "FROM campaign "
                                                   + "WHERE campaign.serving_status='SERVING' "
                                                   + "AND segments.date DURING YESTERDAY";

                    RepeatedField <GoogleAdsRow> dailyImpressionsResults = RequestMethods.SearchRequest(customerID, dailyImpressionsQuery, googleAdsService);

                    if (dailyImpressionsResults.Any(x => x.Metrics.Impressions > 0 && x.Metrics.Impressions < 100))
                    {
                        dailyImpressionsDTO.DailyImpressionsSummary.Add(new CompanyDailyImpressionsSummary(company, dailyImpressionsResults));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                }
            }

            return(await SendEmailAlert(dailyImpressionsDTO));
        }
예제 #4
0
        public StatsExport GetCurrentInfo(Inventory inventory)
        {
            var         stats  = inventory.GetPlayerStats().Result;
            StatsExport output = null;
            var         stat   = stats.FirstOrDefault();

            if (stat != null)
            {
                var ep      = stat.NextLevelXp - stat.PrevLevelXp - (stat.Experience - stat.PrevLevelXp);
                var time    = Math.Round(ep / (TotalExperience / GetRuntime()), 2);
                var hours   = 0.00;
                var minutes = 0.00;
                if (double.IsInfinity(time) == false && time > 0)
                {
                    hours   = Math.Truncate(TimeSpan.FromHours(time).TotalHours);
                    minutes = TimeSpan.FromHours(time).Minutes;
                }

                if (LevelForRewards == -1 || stat.Level >= LevelForRewards)
                {
                    LevelUpRewardsResponse Result = Execute(inventory).Result;

                    if (Result.ToString().ToLower().Contains("awarded_already"))
                    {
                        LevelForRewards = stat.Level + 1;
                    }

                    if (Result.ToString().ToLower().Contains("success"))
                    {
                        Logger.Write("Leveled up: " + stat.Level, LogLevel.Info);

                        RepeatedField <ItemAward> items = Result.ItemsAwarded;

                        if (items.Any <ItemAward>())
                        {
                            Logger.Write("- Received Items -", LogLevel.Info);
                            foreach (ItemAward item in items)
                            {
                                Logger.Write($"[ITEM] {item.ItemId} x {item.ItemCount} ", LogLevel.Info);
                            }
                        }
                    }
                }

                output = new StatsExport
                {
                    Level             = stat.Level,
                    HoursUntilLvl     = hours,
                    MinutesUntilLevel = minutes,
                    CurrentXp         = stat.Experience - stat.PrevLevelXp - GetXpDiff(stat.Level),
                    LevelupXp         = stat.NextLevelXp - stat.PrevLevelXp - GetXpDiff(stat.Level)
                };
            }
            return(output);
        }
예제 #5
0
        public async Task <StatsExport> GetCurrentInfo(ISession session, Inventory inventory)
        {
            var stats = await inventory.GetPlayerStats().ConfigureAwait(false);

            StatsExport output = null;
            var         stat   = stats.FirstOrDefault();

            if (stat != null)
            {
                var ep      = stat.NextLevelXp - stat.Experience;
                var time    = Math.Round(ep / (TotalExperience / GetRuntime()), 2);
                var hours   = 0.00;
                var minutes = 0.00;

                var TotXP = 0;

                for (int i = 0; i < stat.Level + 1; i++)
                {
                    TotXP = TotXP + Statistics.GetXpDiff(i);
                }

                if (double.IsInfinity(time) == false && time > 0)
                {
                    hours   = Math.Truncate(TimeSpan.FromHours(time).TotalHours);
                    minutes = TimeSpan.FromHours(time).Minutes;
                }

                if (LevelForRewards == -1 || stat.Level >= LevelForRewards)
                {
                    if (session.LogicSettings.SkipCollectingLevelUpRewards)
                    {
                        Logger.Write("Current Lvl: " + stat.Level + ". Skipped collecting level up rewards.", LogLevel.Info);
                    }
                    else
                    {
                        LevelUpRewardsResponse Result = await inventory.GetLevelUpRewards(stat.Level).ConfigureAwait(false);

                        if (Result.ToString().ToLower().Contains("awarded_already"))
                        {
                            LevelForRewards = stat.Level + 1;
                        }

                        if (Result.ToString().ToLower().Contains("success"))
                        {
                            Logger.Write($"{session.Profile.PlayerData.Username} has leveled up: " + stat.Level, LogLevel.Info);
                            LevelForRewards = stat.Level + 1;

                            RepeatedField <ItemAward> items = Result.ItemsAwarded;
                            string Rewards = "";

                            if (items.Any <ItemAward>())
                            {
                                Logger.Write("- Received Items -", LogLevel.Info);
                                Rewards = "\nItems Recieved:";
                                foreach (ItemAward item in items)
                                {
                                    Logger.Write($"{item.ItemCount,2:#0}x {item.ItemId}'s", LogLevel.Info);
                                    Rewards += $"\n{item.ItemCount,2:#0}x {item.ItemId}'s";
                                }
                            }

                            if (session.LogicSettings.NotificationConfig.EnablePushBulletNotification)
                            {
                                await PushNotificationClient.SendNotification(session, $"{session.Profile.PlayerData.Username} has leveled up.", $"Trainer just reached level {stat.Level}{Rewards}", true).ConfigureAwait(false);
                            }
                        }
                    }
                }

                output = new StatsExport
                {
                    Level             = stat.Level,
                    HoursUntilLvl     = hours,
                    MinutesUntilLevel = minutes,
                    LevelXp           = TotXP,
                    CurrentXp         = stat.Experience,
                    PreviousXp        = stat.PrevLevelXp,
                    LevelupXp         = stat.NextLevelXp
                };
            }
            return(output);
        }
예제 #6
0
        public async Task <StatsExport> GetCurrentInfo(ISession session, Inventory inventory)
        {
            var stats = await inventory.GetPlayerStats().ConfigureAwait(false);

            StatsExport output = null;
            var         stat   = stats.FirstOrDefault();

            if (stat != null)
            {
                var ep      = stat.NextLevelXp - stat.Experience;
                var time    = Math.Round(ep / (TotalExperience / GetRuntime()), 2);
                var hours   = 0.00;
                var minutes = 0.00;
                if (double.IsInfinity(time) == false && time > 0)
                {
                    hours   = Math.Truncate(TimeSpan.FromHours(time).TotalHours);
                    minutes = TimeSpan.FromHours(time).Minutes;
                }

                if (LevelForRewards == -1 || stat.Level >= LevelForRewards)
                {
                    if (session.LogicSettings.SkipCollectingLevelUpRewards)
                    {
                        Logger.Write("Current level: " + stat.Level + ". Skipped collecting level up rewards.", LogLevel.Info);
                    }
                    else
                    {
                        LevelUpRewardsResponse Result = await GetLevelUpRewards(session).ConfigureAwait(false);

                        if (Result.ToString().ToLower().Contains("awarded_already"))
                        {
                            LevelForRewards = stat.Level + 1;
                        }

                        if (Result.ToString().ToLower().Contains("success"))
                        {
                            Logger.Write("Leveled up: " + stat.Level, LogLevel.Info);

                            RepeatedField <ItemAward> items = Result.ItemsAwarded;

                            if (items.Any <ItemAward>())
                            {
                                Logger.Write("- Received Items -", LogLevel.Info);
                                foreach (ItemAward item in items)
                                {
                                    Logger.Write($"[ITEM] {item.ItemId} x {item.ItemCount} ", LogLevel.Info);
                                }
                            }
                        }
                    }
                }

                output = new StatsExport
                {
                    Level             = stat.Level,
                    HoursUntilLvl     = hours,
                    MinutesUntilLevel = minutes,
                    CurrentXp         = stat.Experience,
                    PreviousXp        = stat.PrevLevelXp,
                    LevelupXp         = stat.NextLevelXp
                };
            }
            return(output);
        }
        public dynamic Get(string companyName)
        {
            if (CheckClientSecret())
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(companyName, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company {companyName}"));
                }

                GoogleAdsClient client = new GoogleAdsClient();

                // Get the GoogleAdsService.
                GoogleAdsServiceClient googleAdsService = client.GetService(Services.V4.GoogleAdsService);

                string query = "SELECT "
                               + "account_budget.approved_spending_limit_micros, "
                               + "account_budget.proposed_spending_limit_micros, "
                               + "account_budget.approved_start_date_time, "
                               + "account_budget.proposed_start_date_time, "
                               + "account_budget.approved_end_date_time, "
                               + "account_budget.proposed_end_date_time, "
                               + "account_budget.amount_served_micros "
                               + "FROM account_budget";

                try
                {
                    RepeatedField <GoogleAdsRow> results = RequestMethods.SearchRequest(customerID, query, googleAdsService);

                    if (results.Any())
                    {
                        List <GoogleAdsBudgetDTO> resultsDTO = new List <GoogleAdsBudgetDTO>();

                        for (int i = 0; i < results.Count; i++)
                        {
                            resultsDTO.Add(new GoogleAdsBudgetDTO(results[i]));
                        }

                        return(resultsDTO);
                    }
                    else
                    {
                        return(JsonConvert.SerializeObject("No results were found"));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                    throw;
                }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
        }
예제 #8
0
        private String GetQuestTaskText(QuestType type, RepeatedField <QuestConditionProto> conditions, int target, String templateId)
        {
            if (RocketMapUtils.shared.GetQuestTemplateText(templateId) != null)
            {
                return(RocketMapUtils.shared.GetQuestTemplateText(templateId));
            }
            List <object> parameters = new List <object>();

            parameters.Add(Convert.ToString(target));
            String text = RocketMapUtils.shared.GetQuestTypeText(type);

            switch (type)
            {
            case QuestType.QuestCatchPokemon:
                parameters.Add("");
                parameters.Add("");
                parameters.Add("");
                parameters.Add("");

                text = "Catch {0}{1} {2}Pokemon{3}";

                foreach (QuestConditionProto condition in conditions)
                {
                    switch (condition.Type)
                    {
                    case QuestConditionProto.Types.ConditionType.WithPokemonType:
                        if (condition.WithPokemonType.PokemonType.Count == 1)
                        {
                            String temp = String.Join("-, ", condition.WithPokemonType.PokemonType.Select(type => RocketMapUtils.shared.GetPokemonType((int)type)));
                            parameters[2] = $"{temp}-type ";
                        }
                        break;

                    case QuestConditionProto.Types.ConditionType.WithPokemonCategory:
                        //TODO: Add translation
                        if (condition.WithPokemonCategory.PokemonIds.Count > 0)
                        {
                            text          = "Catch {0} {1}";
                            parameters[1] = String.Join(", ", condition.WithPokemonCategory.PokemonIds.Select(pokemon => RocketMapUtils.shared.GetPokemonName((int)pokemon)));
                        }
                        break;

                    case QuestConditionProto.Types.ConditionType.WithWeatherBoost:
                        parameters[3] = " with weather boost";
                        break;

                    case QuestConditionProto.Types.ConditionType.WithUniquePokemon:
                        parameters[1] = " different species of";
                        break;

                    case QuestConditionProto.Types.ConditionType.WithPokemonAlignment:
                        if (condition.WithPokemonAlignment.Alignment.Count == 1)
                        {
                            switch (condition.WithPokemonAlignment.Alignment[0])
                            {
                            case PokemonDisplayProto.Types.Alignment.Shadow:
                                parameters[1] = " shadow";
                                break;

                            case PokemonDisplayProto.Types.Alignment.Purified:
                                parameters[1] = " purified";
                                break;
                            }
                        }
                        break;
                    }
                }

                break;

            case QuestType.QuestSpinPokestop:
                if (conditions.Any(c => c.Type == QuestConditionProto.Types.ConditionType.WithUniquePokestop))
                {
                    text = "Spin {0} Pokestops you haven't visited before.";
                }
                else
                {
                    text = "Spin {0} Pokestops or Gyms.";
                }
                break;

            case QuestType.QuestCompleteGymBattle:
                if (conditions.Any(c => c.Type == QuestConditionProto.Types.ConditionType.WithWinGymBattleStatus))
                {
                    text = "Win {0} Gym Battles.";
                }
                else
                {
                    if (conditions.Any(c => c.Type == QuestConditionProto.Types.ConditionType.WithSuperEffectiveCharge))
                    {
                        text = "Use a supereffective Charged Attack in {0} Gym battles.";
                    }
                }
                break;

            case QuestType.QuestCompleteRaidBattle:
                QuestConditionProto raidCondition = conditions.FirstOrDefault(c => c.WithRaidLevel != null);
                if (raidCondition != null)
                {
                    text = "Win {0} Raids.";
                    switch (raidCondition.WithRaidLevel.RaidLevel[0])
                    {
                    case RaidLevel._2:
                        text = "Win a level 2 or higher raid.";
                        break;

                    case RaidLevel._3:
                        text = "Win a level 3 or higher raid.";
                        break;

                    case RaidLevel.Mega:
                        text = "Win a Mega raid.";
                        break;
                    }
                }
                break;

            case QuestType.QuestUseBerryInEncounter:
                text = "Use {0} {1}Berries to help catch Pokemon.";
                String berrie = "";
                QuestConditionProto berryCondition = conditions.FirstOrDefault(c => c.WithItem != null);
                if (berryCondition != null)
                {
                    berrie = RocketMapUtils.shared.GetItemName((int)berryCondition.WithItem.Item).Replace("Berry", "");
                }
                parameters.Add(berrie);
                break;

            case QuestType.QuestLandThrow:
                parameters.Add("");
                parameters.Add("");
                parameters.Add("");

                text = "Make {0} {1}{2}Throws{3}.";

                QuestConditionProto throwCondition = conditions.FirstOrDefault(c => c.WithThrowType != null);
                if (throwCondition != null)
                {
                    switch (throwCondition.WithThrowType.ThrowType)
                    {
                    case HoloActivityType.ActivityCatchNiceThrow:
                        parameters[1] = "Nice ";
                        break;

                    case HoloActivityType.ActivityCatchGreatThrow:
                        parameters[1] = "Great ";
                        break;

                    case HoloActivityType.ActivityCatchExcellentThrow:
                        parameters[1] = "Excellent ";
                        break;

                    case HoloActivityType.ActivityCatchCurveball:
                        parameters[1] = "Curveball ";
                        break;
                    }
                }
                if (conditions.Any(c => c.Type == QuestConditionProto.Types.ConditionType.WithCurveBall))
                {
                    parameters[2] = "Curveball ";
                }
                if (conditions.Any(c => c.Type == QuestConditionProto.Types.ConditionType.WithThrowTypeInARow))
                {
                    parameters[3] = " in a row";
                }

                break;
            }

            if (target == 1)
            {
                text          = text.Replace(" Eggs", "n Egg");
                text          = text.Replace(" Raids", " Raid");
                text          = text.Replace(" Battles", " Battle");
                text          = text.Replace(" candies", " candy");
                text          = text.Replace(" gifts", " gift");
                text          = text.Replace("Grunts", "Grunt");
                text          = text.Replace(" Pokestops", " Pokestop");
                text          = text.Replace(" {0} snapshots", " a snapshot");
                text          = text.Replace("Make {0} {1}{2}Throws", "Make a {1}{2}Throw");
                text          = text.Replace(" {0} times", "");
                text          = text.Replace("{0} hearts", "a heart");
                parameters[0] = "a";
            }

            text = String.Format(text, parameters.ToArray());
            return(text);
        }
        public async Task <Panel> Panel(string userId)
        {
            var headers = HttpContext.CreateHeadersWithFlowId();

            RepeatedField <Loan>        loans        = new RepeatedField <Loan>();
            RepeatedField <Payment>     payments     = new RepeatedField <Payment>();
            RepeatedField <Account>     accounts     = new RepeatedField <Account>();
            RepeatedField <Card>        cards        = new RepeatedField <Card>();
            RepeatedField <Transaction> transactions = new RepeatedField <Transaction>();

            var accountsResponse = await accountsReadClient.GetUserAccountsAsync(new GetUserAccountsRequest { UserId = userId }, headers);

            var accountsIds = accountsResponse.Accounts.Select(a => a.Id).ToArray();

            accounts = accountsResponse.Accounts;

            if (accounts.Any())
            {
                var parallelTasks = new List <Task>();
                parallelTasks.Add(Task.Run(async() =>
                {
                    var transactionsResponse = await transactionsReadClient.FilterAsync(new FilterTransactionsRequest {
                        Senders = { accountsIds }, Top = PanelTransactionsCount
                    }, headers);
                    transactions = transactionsResponse.Transactions;
                }));

                parallelTasks.Add(Task.Run(async() =>
                {
                    var paymentsResponse = await paymentsReadClient.GetByAccountsAsync(new GetPaymentsRequest {
                        Ids = { accountsIds }
                    }, headers);
                    payments = paymentsResponse.Payments;
                }));

                parallelTasks.Add(Task.Run(async() =>
                {
                    var loansResponse = await loansReadClient.GetByAccountsAsync(new GetLoansRequest {
                        Ids = { accountsIds }
                    }, headers);
                    loans = loansResponse.Loans;
                }));

                parallelTasks.Add(Task.Run(async() =>
                {
                    var cardsResponse = await cardsReadClient.GetByAccountsAsync(new GetCardsRequest {
                        Ids = { accountsIds }
                    }, headers);
                    cards = cardsResponse.Cards;
                }));


                await Task.WhenAll(parallelTasks);
            }

            return(new Panel
            {
                Accounts = mapper.Map <AccountDTO[]>(accounts),
                Loans = mapper.Map <LoanDTO[]>(loans),
                Payments = mapper.Map <PaymentDTO[]>(payments),
                Transactions = mapper.Map <TransactionDTO[]>(transactions),
                Cards = mapper.Map <CardDTO[]>(cards),
            });
        }
예제 #10
0
        public StatsExport GetCurrentInfo(Inventory inventory)
        {
            PlayerStats playerStats = inventory.GetPlayerStats().Result;

            if (playerStats == null)
            {
                return(null);
            }

            var ep      = playerStats.NextLevelXp - playerStats.PrevLevelXp - (playerStats.Experience - playerStats.PrevLevelXp);
            var time    = Math.Round(ep / (TotalExperience / GetRuntime()), 2);
            var hours   = 0.00;
            var minutes = 0.00;

            if (double.IsInfinity(time) == false && time > 0)
            {
                hours   = Math.Truncate(TimeSpan.FromHours(time).TotalHours);
                minutes = TimeSpan.FromHours(time).Minutes;
            }

            if (LevelForRewards == -1 || playerStats.Level >= LevelForRewards)
            {
                LevelUpRewardsResponse result = Execute(inventory).Result;

                if (result.ToString().ToLower().Contains("awarded_already"))
                {
                    LevelForRewards = playerStats.Level + 1;
                }

                if (result.ToString().ToLower().Contains("success"))
                {
                    Logger.Write("Leveled up: " + playerStats.Level, LogLevel.Info);

                    RepeatedField <ItemAward> items = result.ItemsAwarded;

                    if (items.Any <ItemAward>())
                    {
                        Logger.Write("- Received Items -", LogLevel.Info);
                        foreach (ItemAward item in items)
                        {
                            Logger.Write($"[ITEM] {item.ItemId} x {item.ItemCount} ", LogLevel.Info);
                        }
                    }
                }
            }

            LevelUpRewardsResponse result2 = Execute(inventory).Result;

            LevelForRewards = playerStats.Level;
            if (result2.ToString().ToLower().Contains("success"))
            {
                //string[] tokens = result2.Result.ToString().Split(new[] { "itemId" }, StringSplitOptions.None);
                Logger.Write("Items Awarded:" + result2.ItemsAwarded);
            }

            StatsExport output = new StatsExport
            {
                Level             = playerStats.Level,
                HoursUntilLvl     = hours,
                MinutesUntilLevel = minutes,
                CurrentXp         = playerStats.Experience - playerStats.PrevLevelXp - GetXpDiff(playerStats.Level),
                LevelupXp         = playerStats.NextLevelXp - playerStats.PrevLevelXp - GetXpDiff(playerStats.Level)
            };

            return(output);
        }
        public dynamic Get(string companyName)
        {
            if (CheckClientSecret())
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(companyName, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company {companyName}"));
                }

                GoogleAdsClient client = new GoogleAdsClient();

                // Get the GoogleAdsService.
                GoogleAdsServiceClient googleAdsService = client.GetService(
                    Services.V4.GoogleAdsService);



                string query = "SELECT "
                               + "campaign.id, "
                               + "campaign.name, "
                               + "campaign.start_date, "
                               + "campaign.end_date, "
                               + "metrics.impressions, "
                               + "metrics.clicks, "
                               + "metrics.conversions_value, "
                               + "metrics.conversions, "
                               + "metrics.cost_micros "
                               + "FROM campaign "
                               + "WHERE campaign.serving_status='SERVING' "
                               + "AND segments.date DURING THIS_MONTH "
                               + "ORDER BY metrics.impressions DESC";

                string lastMonthQuery = "SELECT "
                                        + "metrics.conversions_value, "
                                        + "metrics.conversions,"
                                        + "metrics.cost_micros "
                                        + "FROM campaign "
                                        + "WHERE segments.date DURING LAST_MONTH ";

                try
                {
                    RepeatedField <GoogleAdsRow> results = RequestMethods.SearchRequest(customerID, query, googleAdsService);

                    if (results.Any())
                    {
                        List <GoogleAdsCampaignDTO> campaignsDTO = new List <GoogleAdsCampaignDTO>();

                        double?totalSpend       = 0;
                        double?totalValue       = 0;
                        double?totalConversions = 0;
                        double?rOAS             = 0;

                        for (int i = 0; i < results.Count; i++)
                        {
                            campaignsDTO.Add(new GoogleAdsCampaignDTO(results[i]));

                            totalSpend       += results[i].Metrics.CostMicros;
                            totalValue       += results[i].Metrics.ConversionsValue;
                            totalConversions += results[i].Metrics.Conversions;
                        }

                        double?totalSpendPounds = totalSpend / 1000000;

                        if (totalValue != 0 && totalSpendPounds != 0)
                        {
                            rOAS = totalValue / totalSpendPounds;
                        }

                        RepeatedField <GoogleAdsRow> lastMonthResults = RequestMethods.SearchRequest(customerID, lastMonthQuery, googleAdsService);

                        if (lastMonthResults.Any())
                        {
                            double?lMTotalSpend       = 0;
                            double?lMTotalValue       = 0;
                            double?lMTotalConversions = 0;
                            double?lMROAS             = 0;

                            for (int i = 0; i < lastMonthResults.Count; i++)
                            {
                                lMTotalSpend       += lastMonthResults[i].Metrics.CostMicros;
                                lMTotalValue       += lastMonthResults[i].Metrics.ConversionsValue;
                                lMTotalConversions += lastMonthResults[i].Metrics.Conversions;
                            }

                            double?lMTotalSpendPounds = lMTotalSpend / 1000000;

                            if (lMTotalValue != 0 && lMTotalSpendPounds != 0)
                            {
                                lMROAS = lMTotalValue / lMTotalSpendPounds;
                            }

                            return(new GoogleAdsCampaignSummaryDTO(campaignsDTO, totalSpendPounds, totalConversions, totalValue, rOAS, lMROAS));
                        }
                        else
                        {
                            return(new GoogleAdsCampaignSummaryDTO(campaignsDTO, totalSpend / 1000000, totalConversions, totalValue, rOAS, 0));
                        }
                    }
                    else
                    {
                        return(JsonConvert.SerializeObject("No results were found"));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                    throw;
                }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
        }