public List <GenericItemOption> SearchMetadata(string searchTerm)
        {
            if (searchTerm.IsNullOrEmpty())
            {
                return(new List <GenericItemOption>());
            }

            var url          = string.Format(@"https://en.wikipedia.org/w/api.php?action=query&srsearch={0}&format=json&list=search&srlimit=50", HttpUtility.UrlEncode(searchTerm));
            var stringResult = HttpDownloader.DownloadString(url);
            var result       = JsonConvert.DeserializeObject <SearchResponse>(stringResult);

            if (result.error != null)
            {
                throw new Exception(result.error.info);
            }
            else
            {
                var ret    = new List <GenericItemOption>();
                var parser = new HtmlParser();
                foreach (var searchResult in result.query.search)
                {
                    ret.Add(new WikipediaSearchItem
                    {
                        Title       = searchResult.title,
                        Name        = searchResult.title,
                        Description = parser.Parse(searchResult.snippet).DocumentElement.TextContent
                    });
                }

                return(ret);
            }
        }
Esempio n. 2
0
        public List <LibraryGameResponse> GetOwnedGamesFromPublicAccount(string accountName)
        {
            var baseUrl     = @"https://www.gog.com/u/{0}/games/stats?sort=recent_playtime&order=desc&page={1}";
            var url         = string.Format(baseUrl, accountName, 1);
            var gamesList   = HttpDownloader.DownloadString(url);
            var games       = new List <LibraryGameResponse>();
            var libraryData = JsonConvert.DeserializeObject <PagedResponse <LibraryGameResponse> >(gamesList);

            if (libraryData == null)
            {
                logger.Error("GOG library content is empty or private.");
                return(null);
            }

            games.AddRange(libraryData._embedded.items);

            if (libraryData.pages > 1)
            {
                for (int i = 2; i <= libraryData.pages; i++)
                {
                    gamesList = HttpDownloader.DownloadString(string.Format(baseUrl, accountName, i));
                    var pageData = JsonConvert.DeserializeObject <PagedResponse <LibraryGameResponse> >(gamesList);
                    games.AddRange(pageData._embedded.items);
                }
            }

            return(games);
        }
Esempio n. 3
0
        internal GetOwnedGamesResult GetPrivateOwnedGames(ulong userId, string apiKey)
        {
            var libraryUrl    = @"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={0}&include_appinfo=1&include_played_free_games=1&format=json&steamid={1}";
            var stringLibrary = HttpDownloader.DownloadString(string.Format(libraryUrl, apiKey, userId));

            return(JsonConvert.DeserializeObject <GetOwnedGamesResult>(stringLibrary));
        }
Esempio n. 4
0
        public static string GetRawStoreAppDetail(int appId)
        {
            var url = @"http://store.steampowered.com/api/appdetails?appids={0}";

            url = string.Format(url, appId);
            return(HttpDownloader.DownloadString(url));
        }
Esempio n. 5
0
        public bool Login(Window parent = null)
        {
            var loginUrl = string.Empty;
            var mainPage = HttpDownloader.DownloadString("https://www.gog.com/").Split('\n');

            foreach (var line in mainPage)
            {
                if (line.TrimStart().StartsWith("var galaxyAccounts"))
                {
                    var match = Regex.Match(line, "'(.*)','(.*)'");
                    if (match.Success)
                    {
                        loginUrl = match.Groups[1].Value;
                    }
                }
            }

            loginSuccess = false;
            loginWindow  = new LoginWindow()
            {
                Height = 465,
                Width  = 400
            };
            loginWindow.WindowStartupLocation        = WindowStartupLocation.CenterScreen;
            loginWindow.Browser.LoadingStateChanged += login_StateChanged;
            loginWindow.Owner           = parent;
            loginWindow.Browser.Address = loginUrl;
            loginWindow.ShowDialog();
            return(loginSuccess);
        }
Esempio n. 6
0
        public StorePageResult.ProductDetails GetGameStoreData(string gameUrl)
        {
            string[] data;

            try
            {
                data = HttpDownloader.DownloadString(gameUrl, new List <System.Net.Cookie>()
                {
                    new System.Net.Cookie("gog_lc", Gog.EnStoreLocaleString)
                }).Split('\n');
            }
            catch (WebException e)
            {
                var response = (HttpWebResponse)e.Response;
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }

            var dataStarted = false;
            var stringData  = string.Empty;

            foreach (var line in data)
            {
                var trimmed = line.TrimStart();
                if (line.TrimStart().StartsWith("window.productcardData"))
                {
                    dataStarted = true;
                    stringData  = trimmed.Substring(25).TrimEnd(';');
                    continue;
                }

                if (line.TrimStart().StartsWith("window.activeFeatures"))
                {
                    var desData = JsonConvert.DeserializeObject <StorePageResult>(stringData.TrimEnd(';'));
                    if (desData.cardProduct == null)
                    {
                        return(null);
                    }

                    return(desData.cardProduct);
                }

                if (dataStarted)
                {
                    stringData += trimmed;
                }
            }

            logger.Warn("Failed to get store data from page, no data found. " + gameUrl);
            return(null);
        }
Esempio n. 7
0
        private List <Achievements> GetGameInfoAndUserProgress(int gameID)
        {
            List <Achievements> Achievements = new List <Achievements>();

            string Target = "API_GetGameInfoAndUserProgress.php";
            string url    = string.Format(BaseUrl + Target + @"?z={0}&y={1}&u={0}&g={2}", User, Key, gameID);

            string ResultWeb = "";

            try
            {
                ResultWeb = HttpDownloader.DownloadString(url, Encoding.UTF8);
            }
            catch (WebException ex)
            {
                Common.LogError(ex, "SuccessStory", $"Failed to load from {url}");
                return(Achievements);
            }

            try
            {
                JObject resultObj = new JObject();
                resultObj = JObject.Parse(ResultWeb);

                int NumDistinctPlayersCasual = (int)resultObj["NumDistinctPlayersCasual"];

                if (resultObj["Achievements"] != null)
                {
                    foreach (var item in resultObj["Achievements"])
                    {
                        foreach (var it in item)
                        {
                            Achievements.Add(new Achievements
                            {
                                Name         = (string)it["Title"],
                                Description  = (string)it["Description"],
                                UrlLocked    = string.Format(BaseUrlLocked, (string)it["BadgeName"]),
                                UrlUnlocked  = string.Format(BaseUrlUnlocked, (string)it["BadgeName"]),
                                DateUnlocked = (it["DateEarned"] == null) ? default(DateTime) : Convert.ToDateTime((string)it["DateEarned"]),
                                Percent      = (int)it["NumAwarded"] * 100 / NumDistinctPlayersCasual
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogError(ex, "SuccessStory", $"[{gameID}] Failed to parse {ResultWeb}");
                return(Achievements);
            }

            return(Achievements);
        }
Esempio n. 8
0
        internal GetOwnedGamesResult GetPrivateOwnedGames(ulong userId, string apiKey, bool freeSub)
        {
            var libraryUrl = @"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={0}&include_appinfo=1&include_played_free_games=1&format=json&steamid={1}&skip_unvetted_apps=0";

            if (freeSub)
            {
                libraryUrl += "&include_free_sub=1";
            }

            var stringLibrary = HttpDownloader.DownloadString(string.Format(libraryUrl, apiKey, userId));

            return(Serialization.FromJson <GetOwnedGamesResult>(stringLibrary));
        }
Esempio n. 9
0
        public WikiPage GetPage(string pageTitle)
        {
            var url          = string.Format(@"https://en.wikipedia.org/w/api.php?action=parse&page={0}&format=json", HttpUtility.UrlEncode(pageTitle));
            var stringResult = HttpDownloader.DownloadString(url);
            var result       = JsonConvert.DeserializeObject <ParseResponse>(stringResult);

            if (result.error != null)
            {
                throw new Exception(result.error.info);
            }
            else
            {
                return(result.parse);
            }
        }
Esempio n. 10
0
        internal static string GetGameInfoFromUrl(string url)
        {
            var data  = HttpDownloader.DownloadString(url);
            var regex = Regex.Match(data, @"games\/(\d+)\/rates");

            if (regex.Success)
            {
                return(regex.Groups[1].Value);
            }
            else
            {
                logger.Error($"Failed to get game id from {url}");
                return(string.Empty);
            }
        }
Esempio n. 11
0
        public List <StoreGamesFilteredListResponse.Product> GetStoreSearch(string searchTerm)
        {
            var baseUrl = @"https://www.gog.com/games/ajax/filtered?limit=20&search={0}";
            var url     = string.Format(baseUrl, WebUtility.UrlEncode(searchTerm));

            try
            {
                var stringData = HttpDownloader.DownloadString(url);
                return(Serialization.FromJson <StoreGamesFilteredListResponse>(stringData)?.products);
            }
            catch (WebException exc)
            {
                logger.Warn(exc, "Failed to get GOG store search data for " + searchTerm);
                return(null);
            }
        }
Esempio n. 12
0
        internal List <Game> GetLibraryGames(string userName, string apiKey)
        {
            var userNameUrl = @"https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={0}&vanityurl={1}";
            var libraryUrl  = @"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={0}&include_appinfo=1&include_played_free_games=1&format=json&steamid={1}";

            ulong userId = 0;

            if (!ulong.TryParse(userName, out userId))
            {
                var stringData = HttpDownloader.DownloadString(string.Format(userNameUrl, apiKey, userName));
                userId = ulong.Parse(JsonConvert.DeserializeObject <ResolveVanityResult>(stringData).response.steamid);
            }

            var stringLibrary = HttpDownloader.DownloadString(string.Format(libraryUrl, apiKey, userId));
            var library       = JsonConvert.DeserializeObject <GetOwnedGamesResult>(stringLibrary);

            if (library.response.games == null)
            {
                throw new Exception("No games found on specified Steam account.");
            }

            var games = new List <Game>();

            foreach (var game in library.response.games)
            {
                // Ignore games without name, like 243870
                if (string.IsNullOrEmpty(game.name))
                {
                    continue;
                }

                var newGame = new Game()
                {
                    PluginId         = Id,
                    Source           = "Steam",
                    Name             = game.name,
                    GameId           = game.appid.ToString(),
                    Playtime         = game.playtime_forever * 60,
                    CompletionStatus = game.playtime_forever > 0 ? CompletionStatus.Played : CompletionStatus.NotPlayed
                };

                games.Add(newGame);
            }

            return(games);
        }
Esempio n. 13
0
        public ProductApiDetail GetGameDetails(string id)
        {
            var baseUrl = @"http://api.gog.com/products/{0}?expand=description";

            try
            {
                var stringData = HttpDownloader.DownloadString(string.Format(baseUrl, id), new List <System.Net.Cookie>()
                {
                    new System.Net.Cookie("gog_lc", Gog.EnStoreLocaleString)
                });
                return(JsonConvert.DeserializeObject <ProductApiDetail>(stringData));
            }
            catch (WebException exc)
            {
                logger.Warn(exc, "Failed to download GOG game details for " + id);
                return(null);
            }
        }
Esempio n. 14
0
        public static StorePageResult.ProductDetails GetGameStoreData(string gameUrl)
        {
            string[] data;

            try
            {
                data = HttpDownloader.DownloadString(gameUrl, new List <System.Net.Cookie>()
                {
                    new System.Net.Cookie("gog_lc", localeString)
                }).Split('\n');
            }
            catch (WebException e)
            {
                var response = (HttpWebResponse)e.Response;
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }

            foreach (var line in data)
            {
                var trimmed = line.TrimStart();
                if (line.TrimStart().StartsWith("var gogData"))
                {
                    var stringData = trimmed.Substring(14).TrimEnd(';');
                    var desData    = JsonConvert.DeserializeObject <StorePageResult>(stringData);

                    if (desData.gameProductData == null)
                    {
                        return(null);
                    }

                    return(desData.gameProductData);
                }
            }

            throw new Exception("Failed to get store data from page, no data found. " + gameUrl);
        }
Esempio n. 15
0
        public static string GetLoginUrl()
        {
            var loginUrl = string.Empty;
            var mainPage = HttpDownloader.DownloadString("https://www.gog.com/").Split('\n');

            foreach (var line in mainPage)
            {
                if (line.TrimStart().StartsWith("var galaxyAccounts"))
                {
                    var match = Regex.Match(line, "'(.*)','(.*)'");
                    if (match.Success)
                    {
                        loginUrl = match.Groups[1].Value;
                    }
                }
            }

            return(loginUrl);
        }
Esempio n. 16
0
        public bool?CheckAddonLicense()
        {
            try
            {
                if (UserAgreement != null)
                {
                    var acceptState = ExtensionInstaller.GetAddonLicenseAgreed(AddonId);
                    if (acceptState == null || acceptState < UserAgreement.Updated)
                    {
                        var license      = HttpDownloader.DownloadString(UserAgreement.AgreementUrl);
                        var licenseAgree = new LicenseAgreementViewModel(
                            new LicenseAgreementWindowFactory(),
                            license,
                            Name);

                        if (licenseAgree.OpenView() == true)
                        {
                            ExtensionInstaller.AgreeAddonLicense(AddonId);
                            return(true);
                        }
                        else
                        {
                            ExtensionInstaller.RemoveAddonLicenseAgreement(AddonId);
                            return(false);
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
            {
                logger.Error(e, $"Failed to process addon license.");
                return(null);
            }
        }
Esempio n. 17
0
        public List <SearchResult> Search(string searchTerm)
        {
            var url          = string.Format(@"https://en.wikipedia.org/w/api.php?action=query&srsearch={0}&format=json&list=search&srlimit=50", HttpUtility.UrlEncode(searchTerm));
            var stringResult = HttpDownloader.DownloadString(url);
            var result       = JsonConvert.DeserializeObject <SearchResponse>(stringResult);

            if (result.error != null)
            {
                throw new Exception(result.error.info);
            }
            else
            {
                var parser = new HtmlParser();
                foreach (var searchResult in result.query.search)
                {
                    searchResult.snippet = parser.Parse(searchResult.snippet).DocumentElement.TextContent;
                }

                return(result.query.search);
            }
        }
Esempio n. 18
0
        private RA_Consoles GetConsoleIDs(string PluginUserDataPath)
        {
            string Target = "API_GetConsoleIDs.php";
            string url    = string.Format(BaseUrl + Target + @"?z={0}&y={1}", User, Key);

            RA_Consoles resultObj = new RA_Consoles();

            string fileConsoles = PluginUserDataPath + "\\RA_Consoles.json";

            if (File.Exists(fileConsoles))
            {
                resultObj = JsonConvert.DeserializeObject <RA_Consoles>(File.ReadAllText(fileConsoles));
                return(resultObj);
            }

            string ResultWeb = "";

            try
            {
                ResultWeb = HttpDownloader.DownloadString(url, Encoding.UTF8);
            }
            catch (WebException ex)
            {
                Common.LogError(ex, "SuccessStory", $"Failed to load from {url}");
            }


            try
            {
                resultObj.ListConsoles = JsonConvert.DeserializeObject <List <RA_Console> >(ResultWeb);
                File.WriteAllText(fileConsoles, JsonConvert.SerializeObject(resultObj));
            }
            catch (Exception ex)
            {
                Common.LogError(ex, "SuccessStory", $"Failed to parse {ResultWeb}");
            }

            return(resultObj);
        }
        private List <Achievements> GetAchievementsInPublic(int AppId, bool TryByName = false)
        {
            List <Achievements> achievements = new List <Achievements>();

            string url       = string.Empty;
            string ResultWeb = string.Empty;
            bool   noData    = true;

            // Get data
            if (HtmlDocument == null)
            {
                var cookieLang = new Cookie("Steam_Language", "en_US");
                var cookies    = new List <Cookie>();
                cookies.Add(cookieLang);

                if (!TryByName)
                {
#if DEBUG
                    logger.Debug($"SuccessStory [Ignored] - GetAchievementsInPublic() for {SteamId} - {AppId}");
#endif
                    url = string.Format(UrlProfilById, SteamId, AppId);
                    try
                    {
                        ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                    }
                    catch (WebException ex)
                    {
                        Common.LogError(ex, "SuccessStory");
                    }
                }
                else
                {
#if DEBUG
                    logger.Debug($"SuccessStory [Ignored] - GetAchievementsInPublic() for {SteamUser} - {AppId}");
#endif
                    url = string.Format(UrlProfilByName, SteamUser, AppId);
                    try
                    {
                        ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                    }
                    catch (WebException ex)
                    {
                        Common.LogError(ex, "SuccessStory");
                    }
                }

                if (!ResultWeb.IsNullOrEmpty())
                {
                    HtmlParser parser = new HtmlParser();
                    HtmlDocument = parser.Parse(ResultWeb);

                    if (HtmlDocument.QuerySelectorAll("div.achieveRow").Length != 0)
                    {
                        noData = false;
                    }
                }

                if (!TryByName && noData)
                {
                    HtmlDocument = null;
                    return(GetAchievementsInPublic(AppId, TryByName = true));
                }
                else if (noData)
                {
                    return(achievements);
                }
            }


            // Find the achievement description
            if (HtmlDocument != null)
            {
                foreach (var achieveRow in HtmlDocument.QuerySelectorAll("div.achieveRow"))
                {
                    try
                    {
                        string UrlUnlocked = achieveRow.QuerySelector(".achieveImgHolder img").GetAttribute("src");

                        DateTime DateUnlocked = default(DateTime);
                        string   TempDate     = string.Empty;
                        if (achieveRow.QuerySelector(".achieveUnlockTime") != null)
                        {
                            TempDate = achieveRow.QuerySelector(".achieveUnlockTime").InnerHtml.Trim();
                            TempDate = TempDate.ToLower().Replace("unlocked", string.Empty).Replace("@ ", string.Empty).Replace("<br>", string.Empty).Trim();
                            try
                            {
                                DateUnlocked = DateTime.ParseExact(TempDate, "d MMM h:mmtt", CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                            }
                            try
                            {
                                DateUnlocked = DateTime.ParseExact(TempDate, "d MMM, yyyy h:mmtt", CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                            }
                        }

                        string Name = string.Empty;
                        if (achieveRow.QuerySelector("h3") != null)
                        {
                            Name = achieveRow.QuerySelector("h3").InnerHtml.Trim();
                        }

                        string Description = string.Empty;
                        if (achieveRow.QuerySelector("h5") != null)
                        {
                            Description = achieveRow.QuerySelector("h5").InnerHtml;
                            if (Description.Contains("steamdb_achievement_spoiler"))
                            {
                                Description = achieveRow.QuerySelector("h5 span").InnerHtml.Trim();
                            }

                            Description = WebUtility.HtmlDecode(Description);
                        }

                        achievements.Add(new Achievements
                        {
                            Name         = Name,
                            ApiName      = string.Empty,
                            Description  = Description,
                            UrlUnlocked  = UrlUnlocked,
                            UrlLocked    = string.Empty,
                            DateUnlocked = DateUnlocked,
                            IsHidden     = false,
                            Percent      = 100
                        });
                    }
                    catch (Exception ex)
                    {
                        Common.LogError(ex, "SuccessStory");
                    }
                }
            }

            return(achievements);
        }
        // TODO Use "profileurl" in "ISteamUser"
        private string FindHiddenDescription(int AppId, string DisplayName, bool TryByName = false)
        {
            string url       = string.Empty;
            string ResultWeb = string.Empty;
            bool   noData    = true;

            // Get data
            if (HtmlDocument == null)
            {
                var cookieLang = new Cookie("Steam_Language", LocalLang);
                var cookies    = new List <Cookie>();
                cookies.Add(cookieLang);

                if (!TryByName)
                {
#if DEBUG
                    logger.Debug($"SuccessStory [Ignored] - FindHiddenDescription() for {SteamId} - {AppId}");
#endif
                    url = string.Format(UrlProfilById, SteamId, AppId);
                    try
                    {
                        ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                    }
                    catch (WebException ex)
                    {
                        Common.LogError(ex, "SuccessStory", $"Error on FindHiddenDescription()");
                    }
                }
                else
                {
#if DEBUG
                    logger.Debug($"SuccessStory [Ignored] - FindHiddenDescription() for {SteamUser} - {AppId}");
#endif
                    url = string.Format(UrlProfilByName, SteamUser, AppId);
                    try
                    {
                        ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                    }
                    catch (WebException ex)
                    {
                        Common.LogError(ex, "SuccessStory", $"Error on FindHiddenDescription()");
                    }
                }

                if (!ResultWeb.IsNullOrEmpty())
                {
                    HtmlParser parser = new HtmlParser();
                    HtmlDocument = parser.Parse(ResultWeb);

                    if (HtmlDocument.QuerySelectorAll("div.achieveRow").Length != 0)
                    {
                        noData = false;
                    }
                }

                if (!TryByName && noData)
                {
                    HtmlDocument = null;
                    return(FindHiddenDescription(AppId, DisplayName, TryByName = true));
                }
                else if (noData)
                {
                    return(string.Empty);
                }
            }

            // Find the achievement description
            if (HtmlDocument != null)
            {
                foreach (var achieveRow in HtmlDocument.QuerySelectorAll("div.achieveRow"))
                {
                    try {
                        if (achieveRow.QuerySelector("h3").InnerHtml.Trim().ToLower() == DisplayName.Trim().ToLower())
                        {
                            string TempDescription = achieveRow.QuerySelector("h5").InnerHtml;

                            if (TempDescription.Contains("steamdb_achievement_spoiler"))
                            {
                                TempDescription = achieveRow.QuerySelector("h5 span").InnerHtml;
                                return(WebUtility.HtmlDecode(TempDescription.Trim()));
                            }
                            else
                            {
                                return(WebUtility.HtmlDecode(TempDescription.Trim()));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.LogError(ex, "SuccessStory");
                    }
                }
            }

            return(string.Empty);
        }
        public bool CheckIsPublic(int AppId)
        {
            GetSteamConfig();

            if (_settings.EnableSteamWithoutWebApi)
            {
                string ProfilById   = @"https://steamcommunity.com/profiles/{0}/";
                string ProfilByName = @"https://steamcommunity.com/id/{0}";

                ProfilById   = string.Format(ProfilById, SteamId);
                ProfilByName = string.Format(UrlProfilByName, SteamUser);

                string        ResultWeb = string.Empty;
                HtmlParser    parser    = new HtmlParser();
                IHtmlDocument HtmlDoc   = null;

                try
                {
                    ResultWeb = HttpDownloader.DownloadString(ProfilById);
                    HtmlDoc   = parser.Parse(ResultWeb);
                    if (HtmlDocument.QuerySelectorAll("div.achieveRow").Length > 0)
                    {
                        return(true);
                    }
                }
                catch (WebException ex)
                {
                    Common.LogError(ex, "SuccessStory");
                    return(false);
                }

                try
                {
                    ResultWeb = HttpDownloader.DownloadString(ProfilByName);
                    HtmlDoc   = parser.Parse(ResultWeb);
                    if (HtmlDocument.QuerySelectorAll("div.achieveRow").Length > 0)
                    {
                        return(true);
                    }
                }
                catch (WebException ex)
                {
                    Common.LogError(ex, "SuccessStory");
                    return(false);
                }
            }
            else
            {
                try
                {
                    using (dynamic steamWebAPI = WebAPI.GetInterface("ISteamUserStats", SteamApiKey))
                    {
                        KeyValue PlayerAchievements = steamWebAPI.GetPlayerAchievements(steamid: SteamId, appid: AppId, l: LocalLang);
                        return(true);
                    }
                }
                // TODO With recent SteamKit
                //catch (WebAPIRequestException wex)
                //{
                //    if (wex.StatusCode == HttpStatusCode.Forbidden)
                //    {
                //        _PlayniteApi.Notifications.Add(new NotificationMessage(
                //            $"SuccessStory-Steam-PrivateProfil",
                //            "SuccessStory - Steam profil is private",
                //            NotificationType.Error
                //        ));
                //        logger.Warn("SuccessStory - Steam profil is private");
                //    }
                //    else
                //    {
                //        Common.LogError(wex, "SuccessStory", $"Error on GetPlayerAchievements({SteamId}, {AppId}, {LocalLang})");
                //    }
                //}
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        if (ex.Response is HttpWebResponse response)
                        {
                            if (response.StatusCode == HttpStatusCode.Forbidden)
                            {
                                _PlayniteApi.Notifications.Add(new NotificationMessage(
                                                                   "SuccessStory-Steam-PrivateProfil",
                                                                   $"SuccessStory\r\n{resources.GetString("LOCSuccessStoryNotificationsSteamPrivate")}",
                                                                   NotificationType.Error,
                                                                   () => Process.Start(@"https://steamcommunity.com/my/edit/settings")
                                                                   ));
                                logger.Warn("SuccessStory - Steam profil is private");

                                // TODO https://github.com/Lacro59/playnite-successstory-plugin/issues/76
                                Common.LogError(ex, "SuccessStory", "Error on CheckIsPublic()");

                                return(false);
                            }
                        }
                        else
                        {
                            // no http status code available
                            Common.LogError(ex, "SuccessStory", $"Error on CheckIsPublic({AppId})");
                        }
                    }
                    else
                    {
                        // no http status code available
                        Common.LogError(ex, "SuccessStory", $"Error on CheckIsPublic({AppId})");
                    }

                    return(true);
                }
            }

            return(false);
        }
Esempio n. 22
0
        public override GameMetadata GetMetadata(Game game)
        {
            var gameData = new GameInfo()
            {
                Links    = new List <Link>(),
                Tags     = new List <string>(),
                Genres   = new List <string>(),
                Features = new List <string>()
            };

            var metadata = new GameMetadata
            {
                GameInfo = gameData
            };

            var itchGame = butler.GetGame(Convert.ToInt32(game.GameId));

            // Cover image
            if (!string.IsNullOrEmpty(itchGame.coverUrl))
            {
                metadata.CoverImage = new MetadataFile(itchGame.coverUrl);
            }

            if (!string.IsNullOrEmpty(itchGame.url))
            {
                gameData.Links.Add(new Link(
                                       library.PlayniteApi.Resources.GetString("LOCCommonLinksStorePage"),
                                       itchGame.url));
                var gamePageSrc = HttpDownloader.DownloadString(itchGame.url);
                var parser      = new HtmlParser();
                var gamePage    = parser.Parse(gamePageSrc);

                // Description
                gameData.Description = gamePage.QuerySelector(".formatted_description").InnerHtml;

                // Background
                var gameTheme = gamePage.QuerySelector("#game_theme").InnerHtml;
                var bckMatch  = Regex.Match(gameTheme, @"background-image:\surl\((.+?)\)");
                if (bckMatch.Success)
                {
                    metadata.BackgroundImage = new MetadataFile(bckMatch.Groups[1].Value);
                }

                // Other info
                var infoPanel = gamePage.QuerySelector(".game_info_panel_widget");
                var fields    = infoPanel.QuerySelectorAll("tr");
                gameData.Links.Add(new Link("PCGamingWiki", @"http://pcgamingwiki.com/w/index.php?search=" + game.Name));

                foreach (var field in fields)
                {
                    var name = field.QuerySelectorAll("td")[0].TextContent;
                    if (name == "Genre")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            gameData.Genres.Add(item.TextContent);
                        }

                        continue;
                    }

                    if (name == "Tags")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            if (item.TextContent == "Virtual Reality (VR)")
                            {
                                gameData.Features.Add("VR");
                            }
                            else
                            {
                                gameData.Tags.Add(item.TextContent);
                            }
                        }

                        continue;
                    }

                    if (name == "Links")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            gameData.Links.Add(new Link(item.TextContent, item.Attributes["href"].Value));
                        }

                        continue;
                    }

                    if (name == "Author")
                    {
                        gameData.Developers = new List <string> {
                            field.ChildNodes[1].TextContent
                        };
                    }

                    if (name == "Release date")
                    {
                        var strDate = field.QuerySelector("abbr").Attributes["title"].Value.Split('@')[0].Trim();
                        if (DateTime.TryParseExact(strDate, "d MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime))
                        {
                            gameData.ReleaseDate = dateTime;
                        }
                    }
                }
            }

            return(metadata);
        }
Esempio n. 23
0
        public List <Wishlist> GetWishlist(IPlayniteAPI PlayniteApi, Guid SourceId, string HumbleBundleId, string PluginUserDataPath, IsThereAnyDealSettings settings, bool CacheOnly = false, bool Force = false)
        {
            List <Wishlist> Result = new List <Wishlist>();

            List <Wishlist> ResultLoad = LoadWishlists("HumbleBundle", PluginUserDataPath);

            if (ResultLoad != null && !Force)
            {
                ResultLoad = SetCurrentPrice(ResultLoad, settings, PlayniteApi);
                SaveWishlist("HumbleBundle", PluginUserDataPath, ResultLoad);
                return(ResultLoad);
            }

            if (CacheOnly)
            {
                return(Result);
            }

            if (HumbleBundleId.IsNullOrEmpty())
            {
                return(Result);
            }

            string ResultWeb = "";
            string url       = string.Format(@"https://www.humblebundle.com/store/wishlist/{0}", HumbleBundleId);

            try
            {
                ResultWeb = HttpDownloader.DownloadString(url, Encoding.UTF8);

                if (ResultWeb != "")
                {
                    int startSub = ResultWeb.IndexOf("<script id=\"storefront-webpack-json-data\" type=\"application/json\">");
                    ResultWeb = ResultWeb.Substring(startSub, (ResultWeb.Length - startSub));

                    int endSub = ResultWeb.IndexOf("</script>");
                    ResultWeb = ResultWeb.Substring(0, endSub);

                    ResultWeb = ResultWeb.Replace("<script id=\"storefront-webpack-json-data\" type=\"application/json\">", "");

                    JObject dataObj = JObject.Parse(ResultWeb);

                    IsThereAnyDealApi isThereAnyDealApi = new IsThereAnyDealApi();
                    foreach (JObject gameWish in dataObj["products_json"])
                    {
                        int      StoreId     = 0;
                        string   StoreUrl    = "https://www.humblebundle.com/store/" + gameWish["human_url"];
                        string   Name        = (string)gameWish["human_name"];
                        DateTime ReleaseDate = default(DateTime);
                        string   Capsule     = (string)gameWish["standard_carousel_image"];

                        Result.Add(new Wishlist
                        {
                            StoreId     = StoreId,
                            StoreName   = "Humble",
                            StoreUrl    = StoreUrl,
                            Name        = WebUtility.HtmlDecode(Name),
                            SourceId    = SourceId,
                            ReleaseDate = ReleaseDate.ToUniversalTime(),
                            Capsule     = Capsule,
                            Plain       = isThereAnyDealApi.GetPlain(Name)
                        });
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    Common.LogError(ex, "IsThereAnyDeal", "Error in download HumbleBundle wishlist");
                    return(Result);
                }
            }

            Result = SetCurrentPrice(Result, settings, PlayniteApi);
            SaveWishlist("HumbleBundle", PluginUserDataPath, Result);
            return(Result);
        }
Esempio n. 24
0
        public static void CheckForUpdates(bool silent = true)
        {
            HttpDownloader downloader = new HttpDownloader(Constants.UpdateJsonURL);
            downloader.DownloadString(delegate(string response, Exception error)
            {
                if (error != null)
                {
                    Log.e(error, "Can't get updater info");
                    if (!silent)
                    {
                        Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
                    }
                    return;
                }

                UpdateInfo info;
                if (response != null && TryParseUpdateInfo(response, out info))
                {
                    if (IsShouldSkipVersion(info.version))
                    {
                        Log.d("User decided to skip version {0}", info.version);
                        return;
                    }

                    if (PluginVersionChecker.IsNewerVersion(info.version))
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("A new version {0} is available!\n\n", info.version);
                        if (info.message != null && info.message.Length > 0)
                        {
                            message.Append(info.message);
                            message.AppendLine();
                        }

                        Utils.ShowDialog(kMessageBoxTitle, message.ToString(),
                            new DialogButton("Details...", delegate(string obj)
                            {
                                Application.OpenURL(info.url);
                            }),
                            new DialogButton("Remind me later"),
                            new DialogButton("Skip this version", delegate(string obj)
                            {
                                SetShouldSkipVersion(info.version);
                            })
                        );
                    }
                    else
                    {
                        if (!silent)
                        {
                            Utils.ShowMessageDialog(kMessageBoxTitle, "Everything is up to date");
                        }
                        Debug.Log("Everything is up to date");
                    }
                }
                else
                {
                    Log.e("Unable to parse response: '{0}'", response);
                    if (!silent)
                    {
                        Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
                    }
                }
            });
        }
Esempio n. 25
0
        public GameMetadata GetMetadata(Game game)
        {
            var gameData = new Game()
            {
                Links  = new ObservableCollection <Link>(),
                Tags   = new ComparableList <string>(),
                Genres = new ComparableList <string>()
            };

            var metadata = new GameMetadata
            {
                GameData = gameData
            };

            var itchGame = butler.GetGame(Convert.ToInt32(game.GameId));

            // Cover image
            if (!string.IsNullOrEmpty(itchGame.coverUrl))
            {
                var cover     = HttpDownloader.DownloadData(itchGame.coverUrl);
                var coverFile = Path.GetFileName(itchGame.coverUrl);
                metadata.Image = new MetadataFile(coverFile, cover);
            }

            if (!string.IsNullOrEmpty(itchGame.url))
            {
                gameData.Links.Add(new Link("Store", itchGame.url));
                var gamePageSrc = HttpDownloader.DownloadString(itchGame.url);
                var parser      = new HtmlParser();
                var gamePage    = parser.Parse(gamePageSrc);

                // Description
                gameData.Description = gamePage.QuerySelector(".formatted_description").InnerHtml;

                // Background
                var gameTheme = gamePage.QuerySelector("#game_theme").InnerHtml;
                var bckMatch  = Regex.Match(gameTheme, @"background-image:\surl\((.+?)\)");
                if (bckMatch.Success)
                {
                    metadata.BackgroundImage = bckMatch.Groups[1].Value;
                    gameData.BackgroundImage = bckMatch.Groups[1].Value;
                }

                // Other info
                var infoPanel = gamePage.QuerySelector(".game_info_panel_widget");
                var fields    = infoPanel.QuerySelectorAll("tr");
                foreach (var field in fields)
                {
                    var name = field.QuerySelectorAll("td")[0].TextContent;
                    if (name == "Genre")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            gameData.Genres.Add(item.TextContent);
                        }

                        continue;
                    }

                    if (name == "Tags")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            gameData.Tags.Add(item.TextContent);
                        }

                        continue;
                    }

                    if (name == "Links")
                    {
                        foreach (var item in field.QuerySelectorAll("a"))
                        {
                            gameData.Links.Add(new Link(item.TextContent, item.Attributes["href"].Value));
                        }

                        continue;
                    }

                    if (name == "Author")
                    {
                        gameData.Developers = new ComparableList <string> {
                            field.ChildNodes[1].TextContent
                        };
                    }

                    if (name == "Release date")
                    {
                        var strDate = field.QuerySelector("abbr").Attributes["title"].Value.Split('@')[0].Trim();
                        if (DateTime.TryParseExact(strDate, "d MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime))
                        {
                            gameData.ReleaseDate = dateTime;
                        }
                    }
                }
            }

            return(metadata);
        }
Esempio n. 26
0
        public static string GetRawStoreAppDetail(uint appId)
        {
            var url = $"https://store.steampowered.com/api/appdetails?appids={appId}&l=english";

            return(HttpDownloader.DownloadString(url));
        }
        private string FindHiddenDescription(string SteamUser, string userId, string AppId, string DisplayName, string Lang)
        {
            if (htmlDocument == null)
            {
                logger.Debug($"SuccessStory - Load profil data for {SteamUser} - {AppId}");
                string url = string.Format(@"https://steamcommunity.com/id/{0}/stats/{1}/?tab=achievements",
                                           SteamUser, AppId);
                string ResultWeb = "";
                try
                {
                    var cookieLang = new Cookie("Steam_Language", Lang);
                    var cookies    = new List <Cookie>();
                    cookies.Add(cookieLang);
                    ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                    {
                        var resp = (HttpWebResponse)ex.Response;
                        switch (resp.StatusCode)
                        {
                        case HttpStatusCode.BadRequest:     // HTTP 400
                            break;

                        case HttpStatusCode.ServiceUnavailable:     // HTTP 503
                            break;

                        default:
                            Common.LogError(ex, "SuccessStory", $"Failed to load from {url}. ");
                            break;
                        }
                    }
                }

                if (!ResultWeb.IsNullOrEmpty())
                {
                    HtmlParser parser = new HtmlParser();
                    htmlDocument = parser.Parse(ResultWeb);

                    if (htmlDocument.QuerySelectorAll("div.achieveRow").Length == 0)
                    {
                        logger.Debug($"SuccessStory - Load profil data for {userId} - {AppId}");
                        url = string.Format(@"https://steamcommunity.com/profiles/{0}/stats/{1}/?tab=achievements",
                                            userId, AppId);
                        ResultWeb = "";
                        try
                        {
                            var cookieLang = new Cookie("Steam_Language", Lang);
                            var cookies    = new List <Cookie>();
                            cookies.Add(cookieLang);
                            ResultWeb = HttpDownloader.DownloadString(url, cookies, Encoding.UTF8);
                        }
                        catch (WebException ex)
                        {
                            if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                            {
                                var resp = (HttpWebResponse)ex.Response;
                                switch (resp.StatusCode)
                                {
                                case HttpStatusCode.BadRequest:     // HTTP 400
                                    break;

                                case HttpStatusCode.ServiceUnavailable:     // HTTP 503
                                    break;

                                default:
                                    Common.LogError(ex, "SuccessStory", $"Failed to load from {url}. ");
                                    break;
                                }
                            }
                        }
                    }

                    if (!ResultWeb.IsNullOrEmpty())
                    {
                        parser       = new HtmlParser();
                        htmlDocument = parser.Parse(ResultWeb);
                    }
                }
            }

            if (htmlDocument != null)
            {
                foreach (var achieveRow in htmlDocument.QuerySelectorAll("div.achieveRow"))
                {
                    //logger.Debug($"SuccessStory - {DisplayName.Trim().ToLower()} - {achieveRow.QuerySelector("h3").InnerHtml.Trim().ToLower()}");
                    if (achieveRow.QuerySelector("h3").InnerHtml.Trim().ToLower() == DisplayName.Trim().ToLower())
                    {
                        return(achieveRow.QuerySelector("h5").InnerHtml);
                    }
                }
            }

            return("");
        }
Esempio n. 28
0
        public static AppReviewsResult GetUserRating(uint appId)
        {
            var url = $"https://store.steampowered.com/appreviews/{appId}?json=1&purchase_type=all&language=all";

            return(JsonConvert.DeserializeObject <AppReviewsResult>(HttpDownloader.DownloadString(url)));
        }
Esempio n. 29
0
        public void DownloadInstallerManifest(CancellationToken cancelToken)
        {
            try
            {
                if (InstallerManifestUrl.IsNullOrEmpty())
                {
                    throw new Exception("No addon manifest installer url.");
                }

                if (InstallerManifestUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    installerManifest = Serialization.FromYaml <AddonInstallerManifest>(HttpDownloader.DownloadString(InstallerManifestUrl, cancelToken));
                }
                else if (File.Exists(InstallerManifestUrl))
                {
                    installerManifest = Serialization.FromYamlFile <AddonInstallerManifest>(InstallerManifestUrl);
                }
                else
                {
                    throw new Exception($"Uknown installer manifest url format {InstallerManifestUrl}.");
                }
            }
            catch (Exception exc) when(!PlayniteEnvironment.ThrowAllErrors)
            {
                logger.Error(exc, "Failed to get addon installer manifest data.");
                installerManifest = new AddonInstallerManifest();
            }

            installerManifest.AddonType = Type;
        }
Esempio n. 30
0
        public static StoreAppDetailsResult.AppDetails GetStoreAppDetail(uint appId)
        {
            var url        = $"https://store.steampowered.com/api/appdetails?appids={appId}&l=english";
            var parsedData = JsonConvert.DeserializeObject <Dictionary <string, StoreAppDetailsResult> >(HttpDownloader.DownloadString(url));
            var response   = parsedData[appId.ToString()];

            // No store data for this appid
            if (response.success != true)
            {
                return(null);
            }

            return(response.data);
        }
Esempio n. 31
0
        public static void CheckForUpdates(bool silent = true)
        {
            HttpDownloader downloader = new HttpDownloader(Constants.UpdateJsonURL);

            downloader.DownloadString(delegate(string response, Exception error)
            {
                if (error != null)
                {
                    Log.e(error, "Can't get updater info");
                    if (!silent)
                    {
                        Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
                    }
                    return;
                }

                UpdateInfo info;
                if (response != null && TryParseUpdateInfo(response, out info))
                {
                    if (IsShouldSkipVersion(info.version))
                    {
                        Log.d("User decided to skip version {0}", info.version);
                        return;
                    }

                    if (PluginVersionChecker.IsNewerVersion(info.version))
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("A new version {0} is available!\n\n", info.version);
                        if (info.message != null && info.message.Length > 0)
                        {
                            message.Append(info.message);
                            message.AppendLine();
                        }

                        Utils.ShowDialog(kMessageBoxTitle, message.ToString(),
                                         new DialogButton("Details...", delegate(string obj)
                        {
                            Application.OpenURL(info.url);
                        }),
                                         new DialogButton("Remind me later"),
                                         new DialogButton("Skip this version", delegate(string obj)
                        {
                            SetShouldSkipVersion(info.version);
                        })
                                         );
                    }
                    else
                    {
                        if (!silent)
                        {
                            Utils.ShowMessageDialog(kMessageBoxTitle, "Everything is up to date");
                        }
                        Debug.Log("Everything is up to date");
                    }
                }
                else
                {
                    Log.e("Unable to parse response: '{0}'", response);
                    if (!silent)
                    {
                        Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
                    }
                }
            });
        }