Esempio n. 1
0
 public Cost(QueryTimePeriod period, UsageResponse response)
 {
     Period      = period;
     Currency    = ExtractCurrency(response);
     Categorized = OrganizeData(period, response);
     Total       = Categorized.Values.SelectMany(vs => vs.Values).Sum();
 }
Esempio n. 2
0
        public IActionResult Log()
        {
            UsageResponse response = new UsageResponse();

            string[] strElements, strSubElements;
            string   strData, strEvent;
            bool     bMode = false, bWall = false;

            Logging.WriteDebugLog("UsageController.Log() Client: {0}:{1}", HttpContext.Connection.RemoteIpAddress.ToString(), HttpContext.Connection.RemotePort.ToString());

            HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", new Microsoft.Extensions.Primitives.StringValues("X-Requested-With"));
            HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", new Microsoft.Extensions.Primitives.StringValues("*"));

            response.status  = 200;
            response.message = "Usage tracked";
            response.value   = null;

            try
            {
                strData = new StreamReader(Request.Body).ReadToEnd();
            }
            catch (Exception eException)
            {
                Logging.WriteDebugLogError("UsageController.Log()", eException, "Unable to capture post data.");
                goto Cleanup;
            }

            try
            {
                strElements = strData.Substring(strData.IndexOf("{")).Replace("{", "").Replace("}", "").Trim().Replace("\"", "").Split(new char[] { ',' });

                foreach (string strElement in strElements)
                {
                    strSubElements = strElement.Split(new char[] { ':' });

                    if (strSubElements.Length == 2)
                    {
                        if (strSubElements[0] == "mode")
                        {
                            bMode = (strSubElements[1] == "on" ? true : false);
                        }
                        else if (strSubElements[0] == "method")
                        {
                            bWall = (strSubElements[1] == "wall" ? true : false);
                        }
                    }
                }

                strEvent = string.Format("The air conditioner was turned {0} locally.", bMode ? "on" : "off");
                Logging.WriteDebugLog("UsageController.Log() [0x{0}] Log Entry: {1}", 0.ToString("X8"), strEvent);
            }
            catch (Exception eException)
            {
                Logging.WriteDebugLogError("UsageController.Log()", eException, "Unable to send log data.");
            }

Cleanup:
            return(new ObjectResult(response));
        }
Esempio n. 3
0
        public List <GameInfo> GetLibraryGames()
        {
            using (var view = PlayniteApi.WebViews.CreateOffscreenView())
            {
                var api = new OriginAccountClient(view);

                if (!api.GetIsUserLoggedIn())
                {
                    throw new Exception("User is not logged in.");
                }

                var token = api.GetAccessToken();
                if (token == null)
                {
                    throw new Exception("Failed to get access to user account.");
                }

                if (!string.IsNullOrEmpty(token.error))
                {
                    throw new Exception("Access error: " + token.error);
                }

                var info = api.GetAccountInfo(token);
                if (!string.IsNullOrEmpty(info.error))
                {
                    throw new Exception("Access error: " + info.error);
                }

                var games = new List <GameInfo>();

                foreach (var game in api.GetOwnedGames(info.pid.pidId, token).Where(a => a.offerType == "basegame"))
                {
                    UsageResponse usage = null;
                    try
                    {
                        usage = api.GetUsage(info.pid.pidId, game.offerId, token);
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, $"Failed to get usage data for {game.offerId}");
                    }

                    games.Add(new GameInfo()
                    {
                        Source       = "Origin",
                        GameId       = game.offerId,
                        Name         = game.offerId,
                        LastActivity = usage?.lastSessionEndTimeStamp,
                        Playtime     = usage?.total ?? 0
                    });
                }

                return(games);
            }
        }
Esempio n. 4
0
        private static IReadOnlyDictionary <string, SortedDictionary <DateTimeOffset, double> > OrganizeData(
            QueryTimePeriod period,
            UsageResponse response)
        {
            var result = new Dictionary <string, SortedDictionary <DateTimeOffset, double> >();

            var cols             = response.Properties.Columns;
            var dateIndex        = cols.FindIndex(col => col.Name == "UsageDate");
            var costIndex        = cols.FindIndex(col => col.Name == "PreTaxCost");
            var serviceNameIndex = cols.FindIndex(col => col.Name == "ServiceName");

            foreach (var meterCategory in response.Properties.Rows.GroupBy(row => (string)row[serviceNameIndex]))
            {
                var category = string.IsNullOrWhiteSpace(meterCategory.Key) ? "uncategorized" : meterCategory.Key;
                result[category] = GenerateDataForCategory(category, meterCategory);
            }

            return(result);

            SortedDictionary <DateTimeOffset, double> GenerateDataForCategory(string meterCategory, IEnumerable <IReadOnlyList <object> > days)
            {
                return(new SortedDictionary <DateTimeOffset, double>(EnumerateDays().ToDictionary(kvp => kvp.Day, kvp => kvp.Cost)));

                IEnumerable <(DateTimeOffset Day, double Cost)> EnumerateDays()
                {
                    var convertedDays = days.Select(x => new { date = ParseDate((long)x[dateIndex]), cost = (double)x[costIndex] });

                    var currentDay = period.From;

                    foreach (var day in convertedDays.OrderBy(d => d.date))
                    {
                        // we have to pad the data with zeroes because ChartJS can't handle it otherwise
                        currentDay = currentDay.AddDays(1);
                        while (currentDay < day.date)
                        {
                            yield return(currentDay, 0);

                            currentDay = currentDay.AddDays(1);
                        }

                        yield return(currentDay, day.cost);
                    }

                    // we have to pad the data with zeroes because ChartJS can't handle it otherwise
                    currentDay = currentDay.AddDays(1);
                    while (currentDay <= period.To)
                    {
                        yield return(currentDay, 0);

                        currentDay = currentDay.AddDays(1);
                    }
                }
            }
        }
Esempio n. 5
0
        public async Task UsageAsyncTest(UsageType type)
        {
            var response = await sandBoxClient.Account.UsageAsync(type);

            Assert.IsNull(response.ErrorMessage);
            Assert.IsNotNull(response.Data);

            UsageResponse         usageResponse = response.Data;
            UsageResponseMessages messages      = usageResponse.messages;

            Assert.Greater(messages.monthlyUsage, 0);
            Assert.Greater(int.Parse(messages.keyUsage.GetValueOrDefault("FX_CONVERSION")), 0);
        }
Esempio n. 6
0
        public List <GameInfo> GetLibraryGames()
        {
            using (var view = PlayniteApi.WebViews.CreateOffscreenView())
            {
                var api = new OriginAccountClient(view);

                if (!api.GetIsUserLoggedIn())
                {
                    throw new Exception("User is not logged in.");
                }

                var token = api.GetAccessToken();
                if (token == null)
                {
                    throw new Exception("Failed to get access to user account.");
                }

                if (!string.IsNullOrEmpty(token.error))
                {
                    throw new Exception("Access error: " + token.error);
                }

                var info = api.GetAccountInfo(token);
                if (!string.IsNullOrEmpty(info.error))
                {
                    throw new Exception("Access error: " + info.error);
                }

                var games = new List <GameInfo>();

                foreach (var game in api.GetOwnedGames(info.pid.pidId, token).Where(a => a.offerType == "basegame"))
                {
                    UsageResponse usage = null;
                    try
                    {
                        usage = api.GetUsage(info.pid.pidId, game.offerId, token);
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, $"Failed to get usage data for {game.offerId}");
                    }

                    var gameName = game.offerId;
                    try
                    {
                        var localData = GetLocalManifest(game.offerId);
                        if (localData != null)
                        {
                            gameName = StringExtensions.NormalizeGameName(localData.localizableAttributes.displayName);
                        }
                    }
                    catch (Exception e) when(!Environment.IsDebugBuild)
                    {
                        logger.Error(e, $"Failed to get Origin manifest for a {game.offerId}");
                        continue;
                    }

                    games.Add(new GameInfo()
                    {
                        Source       = "Origin",
                        GameId       = game.offerId,
                        Name         = gameName,
                        LastActivity = usage?.lastSessionEndTimeStamp,
                        Playtime     = usage?.total ?? 0,
                        Platform     = "PC"
                    });
                }

                return(games);
            }
        }
Esempio n. 7
0
        private static string ExtractCurrency(UsageResponse response)
        {
            var currencyIndex = response.Properties.Columns.FindIndex(col => col.Name == "Currency");

            return((string)response.Properties.Rows.FirstOrDefault()?[currencyIndex]); // assumption: all values have same currency(!)
        }
Esempio n. 8
0
        public async Task UsageAsyncTest(UsageType type)
        {
            UsageResponse response = await sandBoxClient.Account.UsageAsync(type);

            Assert.IsNotNull(response);
        }