/// <summary> /// Show Achievements for the selected game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListviewGames_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListGames GameSelected = (ListGames)((ListBox)sender).SelectedItem; if (GameSelected != null) { listAchievementBorder.BorderThickness = new Thickness(0); Guid GameId = Guid.Parse(GameSelected.Id); GameAchievements GameAchievements = AchievementsDatabase.Get(GameId); List <Achievements> ListAchievements = GameAchievements.Achievements; SuccessStory_Achievements_List.Children.Clear(); SuccessStory_Achievements_List.Children.Add(new SuccessStoryAchievementsList(ListAchievements, this)); SuccessStory_Achievements_List.UpdateLayout(); AchievementsGraphicsDataCount GraphicsData = AchievementsDatabase.GetCountByMonth(GameId); string[] StatsGraphicsAchievementsLabels = GraphicsData.Labels; SeriesCollection StatsGraphicAchievementsSeries = new SeriesCollection(); StatsGraphicAchievementsSeries.Add(new LineSeries { Title = "", Values = GraphicsData.Series }); SuccessStory_Achievements_Graphics_Game.Children.Clear(); SuccessStory_Achievements_Graphics_Game.Children.Add(new SuccessStoryAchievementsGraphics(StatsGraphicAchievementsSeries, StatsGraphicsAchievementsLabels, this)); SuccessStory_Achievements_Graphics_Game.UpdateLayout(); GC.Collect(); } }
public SuccessStoryEditManual(Game game) { InitializeComponent(); gameAchievements = PluginDatabase.Get(game, true); LoadData(game); }
private void SaveData() { isProgressSaved = true; player.SaveAccountBalance(); GameAchievements.Check(player.Account.Balance); GameData.IncrementDayCount(); }
public override GameAchievements GetAchievements(Game game) { List <Achievements> AllAchievements = new List <Achievements>(); GameAchievements Result = new GameAchievements { Name = game.Name, HaveAchivements = false, Total = 0, Unlocked = 0, Locked = 0, Progression = 0, Achievements = AllAchievements }; List <XboxAchievement> ListAchievements = new List <XboxAchievement>(); try { ListAchievements = GetXboxAchievements(game.GameId, game.Name).GetAwaiter().GetResult(); #if DEBUG logger.Debug("SuccessStory - XboxAchievements - " + JsonConvert.SerializeObject(ListAchievements)); #endif foreach (XboxAchievement xboxAchievement in ListAchievements) { AllAchievements.Add(new Achievements { ApiName = string.Empty, Name = xboxAchievement.name, Description = (xboxAchievement.progression.timeUnlocked == default(DateTime)) ? xboxAchievement.lockedDescription : xboxAchievement.description, IsHidden = xboxAchievement.isSecret, Percent = 100, DateUnlocked = xboxAchievement.progression.timeUnlocked, UrlLocked = string.Empty, UrlUnlocked = xboxAchievement.mediaAssets[0].url }); } Result = new GameAchievements { Name = game.Name, HaveAchivements = AllAchievements.HasItems(), Total = AllAchievements.Count, Unlocked = AllAchievements.FindAll(x => x.DateUnlocked != default(DateTime)).Count, Locked = AllAchievements.FindAll(x => x.DateUnlocked == default(DateTime)).Count, Progression = 0, Achievements = AllAchievements }; Result.Progression = (Result.Total != 0) ? (int)Math.Ceiling((double)(Result.Unlocked * 100 / Result.Total)) : 0; } catch (Exception ex) { Common.LogError(ex, "SuccessStory", "Failed to Xbox profile achievements"); } return(Result); }
private void Awake() { market = GetComponent <StockMarket>(); if (GameAchievements.IsMechanicUnlocked(Mechanic.News)) { market.OnDayStarted += Initialize; } }
private void Update() { if (KeyBindings.Find(binding => binding.Action == KeyBindingAction.Short) == null && GameAchievements.IsMechanicUnlocked(Mechanic.Short)) { KeyBindings.Add(ShortKeyBinding()); } }
public void ConvertDB(IPlayniteAPI PlayniteApi) { GlobalProgressOptions globalProgressOptions = new GlobalProgressOptions( "SuccessStory - Database migration", false ); globalProgressOptions.IsIndeterminate = true; PlayniteApi.Dialogs.ActivateGlobalProgress((Action <GlobalProgressActionArgs>)((activateGlobalProgress) => { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); logger.Info($"SuccessStory - ConvertDB()"); int Converted = 0; foreach (var item in Items) { try { if (PlayniteApi.Database.Games.Get(item.Key) != null) { GameAchievements gameAchievements = SuccessStory.PluginDatabase.Get(item.Key, true); gameAchievements.HaveAchivements = item.Value.HaveAchivements; gameAchievements.IsEmulators = item.Value.IsEmulators; gameAchievements.Total = item.Value.Total; gameAchievements.Unlocked = item.Value.Unlocked; gameAchievements.Locked = item.Value.Locked; gameAchievements.Progression = item.Value.Progression; gameAchievements.Items = item.Value.Achievements; Thread.Sleep(10); SuccessStory.PluginDatabase.Update(gameAchievements); Converted++; } else { logger.Warn($"SuccessStory - Game is deleted - {item.Key.ToString()}"); } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", $"Failed to load ConvertDB from {item.Key.ToString()}"); } } logger.Info($"SuccessStory - Converted {Converted} / {Items.Count}"); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; logger.Info($"SuccessStory - Migration - {string.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10)}"); }), globalProgressOptions); IsOld = false; }
private void Awake() { KeyBindings.Add(HelpKeyBinding()); KeyBindings.Add(BuyKeyBinding()); KeyBindings.Add(SellKeyBinding()); if (GameAchievements.IsMechanicUnlocked(Mechanic.Short)) { KeyBindings.Add(ShortKeyBinding()); } }
/// <summary> /// Show Achievements for the selected game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListviewGames_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListViewGames GameSelected = (ListViewGames)((ListBox)sender).SelectedItem; if (GameSelected != null) { listAchievementBorder.BorderThickness = new Thickness(0); Guid GameId = Guid.Parse(GameSelected.Id); GameAchievements GameAchievements = AchievementsDb.Get(GameId); List <Achievements> ListAchievements = GameAchievements.Achievements; SuccessStory_Achievements_List.Children.Clear(); SuccessStoryAchievementsList successStoryAchievementsList = new SuccessStoryAchievementsList(); successStoryAchievementsList.SetScData(ListAchievements, false, settings.EnableRaretyIndicator); SuccessStory_Achievements_List.Children.Add(successStoryAchievementsList); SuccessStory_Achievements_List.UpdateLayout(); AchievementsGraphicsDataCount GraphicsData = null; if (settings.GraphicAllUnlockedByDay) { GraphicTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitle"); GraphicsData = AchievementsDb.GetCountByMonth(GameId); } else { GraphicTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitleDay"); GraphicsData = AchievementsDb.GetCountByDay(GameId, 8); } string[] StatsGraphicsAchievementsLabels = GraphicsData.Labels; SeriesCollection StatsGraphicAchievementsSeries = new SeriesCollection(); StatsGraphicAchievementsSeries.Add(new LineSeries { Title = string.Empty, Values = GraphicsData.Series }); SuccessStory_Achievements_Graphics_Game.Children.Clear(); settings.IgnoreSettings = true; SuccessStory_Achievements_Graphics_Game.Children.Add(new SuccessStoryAchievementsGraphics(StatsGraphicAchievementsSeries, StatsGraphicsAchievementsLabels, settings)); SuccessStory_Achievements_Graphics_Game.UpdateLayout(); GC.Collect(); } }
public void SetData(GameAchievements GameSelectedData) { if (GameSelectedData.HasData) { this.Visibility = Visibility.Visible; } else { this.Visibility = Visibility.Collapsed; return; } PART_ScCountIndicator.Text = GameSelectedData.Unlocked + "/" + GameSelectedData.Total; PART_ScProgressBar.Value = GameSelectedData.Unlocked; PART_ScProgressBar.Maximum = GameSelectedData.Total; }
public GameAchievements GetAchievementsLocal(string GameName, string apiKey) { List <Achievements> Achievements = new List <Achievements>(); bool HaveAchivements = false; int Total = 0; int Unlocked = 0; int Locked = 0; SteamApi steamApi = new SteamApi(_PluginUserDataPath); SteamId = steamApi.GetSteamId(GameName); Achievements = Get(SteamId, apiKey); if (Achievements.Count > 0) { HaveAchivements = true; for (int i = 0; i < Achievements.Count; i++) { if (Achievements[i].DateUnlocked == default(DateTime)) { Locked += 1; } else { Unlocked += 1; } } Total = Achievements.Count; } GameAchievements Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = (Total != 0) ? (int)Math.Ceiling((double)(Unlocked * 100 / Total)) : 0, Achievements = Achievements }; return(Result); }
private void DisplayMarketDayStartedMessages() { var messages = new List <string>() { "The market is open", "It closes at 05:00PM", }; if (!GameAchievements.IsInLastAchievementLevel()) { messages.AddRange(new List <string>() { "Your current balance target is:", GameAchievements.Current().BalanceTarget.ToString("C2"), }); } MessageCentral.Instance.DisplayMessages("Message", messages.ToArray(), true); }
private void LoadData(Game GameSelected) { Guid GameId = GameSelected.Id; GameAchievements successStories = PluginDatabase.Get(GameSelected); List <Achievements> ListAchievements = successStories.Items; List <GameStats> ListGameStats = successStories.ItemsStats; // List Achievements SuccessStoryAchievementsList successStoryAchievementsList = new SuccessStoryAchievementsList(true); successStoryAchievementsList.SetScData(successStories); PART_Achievements_List.Children.Add(successStoryAchievementsList); // Chart achievements int limit = 0; if (!PluginDatabase.PluginSettings.GraphicAllUnlockedByDay) { PART_ChartTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitle"); limit = 20; } else { PART_ChartTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitleDay"); limit = 16; } PluginDatabase.PluginSettings.IgnoreSettings = true; SuccessStoryAchievementsGraphics successStoryAchievementsGraphics = new SuccessStoryAchievementsGraphics(); successStoryAchievementsGraphics.SetScData(GameId, limit); PART_Achievements_Graphics.Children.Add(successStoryAchievementsGraphics); // User stats SuccessStoryUserStats successStoryUserStats = new SuccessStoryUserStats(); successStoryUserStats.SetScData(ListGameStats); PART_ScUserStats.Children.Add(successStoryUserStats); }
/// <summary> /// Show Achievements for the selected game. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListviewGames_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListViewGames GameSelected = (ListViewGames)((ListBox)sender).SelectedItem; if (GameSelected != null) { listAchievementBorder.BorderThickness = new Thickness(0); Guid GameId = Guid.Parse(GameSelected.Id); GameAchievements successStories = PluginDatabase.Get(GameId); List <Achievements> ListAchievements = successStories.Items; SuccessStory_Achievements_List.Children.Clear(); SuccessStoryAchievementsList successStoryAchievementsList = new SuccessStoryAchievementsList(true); successStoryAchievementsList.SetScData(successStories, true); SuccessStory_Achievements_List.Children.Add(successStoryAchievementsList); int limit = 0; if (!PluginDatabase.PluginSettings.GraphicAllUnlockedByDay) { GraphicTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitle"); } else { GraphicTitle.Content = resources.GetString("LOCSuccessStoryGraphicTitleDay"); limit = 8; } SuccessStory_Achievements_Graphics_Game.Children.Clear(); PluginDatabase.PluginSettings.IgnoreSettings = true; SuccessStoryAchievementsGraphics successStoryAchievementsGraphics = new SuccessStoryAchievementsGraphics(); successStoryAchievementsGraphics.SetScData(GameId, limit); SuccessStory_Achievements_Graphics_Game.Children.Add(successStoryAchievementsGraphics); } }
private async Task <GameAchievements> LoadData(IPlayniteAPI PlayniteApi, string PluginUserDataPath, SuccessStorySettings settings) { // Refresh database if (SuccessStory.isFirstLoad) { achievementsDatabase = new AchievementsDatabase(PlayniteApi, settings, this.GetPluginUserDataPath()); achievementsDatabase.Initialize(); SuccessStory.isFirstLoad = false; } GameAchievements SelectedGameAchievements = achievementsDatabase.Get(GameSelected.Id); // Download Achievements if not exist in database. if (SelectedGameAchievements == null) { logger.Info("SuccessStory - Download achievements for " + GameSelected.Name); achievementsDatabase.Add(GameSelected, settings); achievementsDatabase.Initialize(); SelectedGameAchievements = achievementsDatabase.Get(GameSelected.Id); } return(SelectedGameAchievements); }
public void SetScData(GameAchievements gameAchievements, bool noControl = false) { List <Achievements> ListAchievements = gameAchievements.Items; Task.Run(() => { this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new ThreadStart(delegate { PART_ScCompactView.Children.Clear(); PART_ScCompactView.ColumnDefinitions.Clear(); })); AchievementsList = new List <ListBoxAchievements>(); // Select data if (_withUnlocked) { ListAchievements = ListAchievements.FindAll(x => x.DateUnlocked != default(DateTime)); ListAchievements.Sort((x, y) => DateTime.Compare((DateTime)x.DateUnlocked, (DateTime)y.DateUnlocked)); ListAchievements.Reverse(); } else { ListAchievements = ListAchievements.FindAll(x => x.DateUnlocked == default(DateTime)); ListAchievements.Sort((x, y) => string.Compare(x.Name, y.Name)); } // Prepare data for (int i = 0; i < ListAchievements.Count; i++) { DateTime?dateUnlock = null; BitmapImage iconImage = new BitmapImage(); bool IsGray = false; string urlImg = string.Empty; try { if (ListAchievements[i].DateUnlocked == default(DateTime) || ListAchievements[i].DateUnlocked == null) { if (ListAchievements[i].UrlLocked == string.Empty || ListAchievements[i].UrlLocked == ListAchievements[i].UrlUnlocked) { urlImg = ListAchievements[i].ImageUnlocked; IsGray = true; } else { urlImg = ListAchievements[i].ImageLocked; } } else { urlImg = ListAchievements[i].ImageUnlocked; dateUnlock = ListAchievements[i].DateUnlocked; } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", "Error on convert bitmap"); } string NameAchievement = ListAchievements[i].Name; if (dateUnlock == new DateTime(1982, 12, 15, 0, 0, 0, 0)) { dateUnlock = null; } AchievementsList.Add(new ListBoxAchievements() { Name = NameAchievement, DateUnlock = dateUnlock, Icon = urlImg, IconImage = urlImg, IsGray = IsGray, Description = ListAchievements[i].Description, Percent = ListAchievements[i].Percent }); iconImage = null; } #if DEBUG logger.Debug($"SuccessStory [Ignored] - SuccessStoryAchievementsCompact - ListAchievements({_withUnlocked}) - {JsonConvert.SerializeObject(ListAchievements)}"); #endif this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(delegate { if (!noControl) { if (gameAchievements.Id != SuccessStoryDatabase.GameSelected.Id) { return; } } PART_ScCompactView_IsLoaded(null, null); })); }); }
public override GameAchievements GetAchievements(Game game) { int AppId = 0; List <Achievements> AllAchievements = new List <Achievements>(); List <GameStats> AllStats = new List <GameStats>(); GameAchievements Result = SuccessStory.PluginDatabase.GetDefault(game); Result.Items = AllAchievements; // Get Steam configuration if exist. if (!GetSteamConfig()) { return(Result); } if (!IsLocal) { #if DEBUG logger.Debug($"SuccessStory [Ignored] - Steam - GetAchievements()"); #endif int.TryParse(game.GameId, out AppId); VerifSteamUser(); if (SteamUser.IsNullOrEmpty()) { logger.Warn("SuccessStory - No Steam user"); } if (_settings.EnableSteamWithoutWebApi) { AllAchievements = GetAchievementsInPublic(AppId); } else { AllAchievements = GetPlayerAchievements(AppId); AllStats = GetUsersStats(AppId); } if (AllAchievements.Count > 0) { var DataCompleted = GetSchemaForGame(AppId, AllAchievements, AllStats); AllAchievements = DataCompleted.Item1; AllStats = DataCompleted.Item2; Result.HaveAchivements = true; Result.Total = AllAchievements.Count; Result.Unlocked = AllAchievements.FindAll(x => x.DateUnlocked != null && x.DateUnlocked != default(DateTime)).Count; Result.Locked = Result.Total - Result.Locked; Result.Progression = (Result.Total != 0) ? (int)Math.Ceiling((double)(Result.Unlocked * 100 / Result.Total)) : 0; Result.Items = AllAchievements; Result.ItemsStats = AllStats; } } else { #if DEBUG logger.Debug($"SuccessStory [Ignored] - Steam - GetAchievementsLocal()"); #endif SteamEmulators se = new SteamEmulators(_PlayniteApi, _PluginUserDataPath); var temp = se.GetAchievementsLocal(game.Name, SteamApiKey); AppId = se.GetSteamId(); if (temp.Achievements.Count > 0) { Result.HaveAchivements = true; Result.Total = temp.Total; Result.Locked = temp.Locked; Result.Unlocked = temp.Unlocked; Result.Progression = temp.Progression; for (int i = 0; i < temp.Achievements.Count; i++) { Result.Items.Add(new Achievements { Name = temp.Achievements[i].Name, ApiName = temp.Achievements[i].ApiName, Description = temp.Achievements[i].Description, UrlUnlocked = temp.Achievements[i].UrlUnlocked, UrlLocked = temp.Achievements[i].UrlLocked, DateUnlocked = temp.Achievements[i].DateUnlocked }); } } } if (Result.Items.Count > 0) { Result.Items = GetGlobalAchievementPercentagesForApp(AppId, Result.Items); } return(Result); }
// To add new game menu items override GetGameMenuItems public override List <GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args) { Game GameMenu = args.Games.First(); string SourceName = PlayniteTools.GetSourceName(PlayniteApi, GameMenu); bool IsAddOrShowManual = SuccessStoryDatabase.IsAddOrShowManual(GameMenu, SourceName); GameAchievements gameAchievements = PluginDatabase.Get(GameMenu, true); List <GameMenuItem> gameMenuItems = new List <GameMenuItem>(); if (!settings.EnableOneGameView || (settings.EnableOneGameView && gameAchievements.HasData)) { // Show list achievements for the selected game gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = resources.GetString("LOCSuccessStoryViewGame"), Action = (gameMenuItem) => { dynamic ViewExtension = null; PluginDatabase.IsViewOpen = true; if (PluginDatabase.PluginSettings.EnableOneGameView) { ViewExtension = new SuccessStoryOneGameView(GameMenu); } else { ViewExtension = new SuccessView(this, PlayniteApi, this.GetPluginUserDataPath(), false, GameMenu); } Window windowExtension = PlayniteUiHelper.CreateExtensionWindow(PlayniteApi, resources.GetString("LOCSuccessStory"), ViewExtension); windowExtension.ShowDialog(); PluginDatabase.IsViewOpen = false; } }); } if (!IsAddOrShowManual) { gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = resources.GetString("LOCCommonRefreshGameData"), Action = (gameMenuItem) => { if (settings.EnableIntegrationInCustomTheme || settings.EnableIntegrationInDescription) { PlayniteUiHelper.ResetToggle(); } var TaskIntegrationUI = Task.Run(() => { PluginDatabase.Remove(GameMenu); var dispatcherOp = successStoryUI.AddElements(); dispatcherOp.Completed += (s, e) => { successStoryUI.RefreshElements(GameMenu); }; }); } }); } if (settings.EnableManual && IsAddOrShowManual) { if (!gameAchievements.HasData) { gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = resources.GetString("LOCAddTitle"), Action = (mainMenuItem) => { var TaskIntegrationUI = Task.Run(() => { PluginDatabase.Remove(GameMenu); PluginDatabase.GetManual(GameMenu); var dispatcherOp = successStoryUI.AddElements(); dispatcherOp.Completed += (s, e) => { successStoryUI.RefreshElements(GameMenu); }; }); } }); } else { gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = resources.GetString("LOCEditGame"), Action = (mainMenuItem) => { var ViewExtension = new SuccessStoryEditManual(GameMenu); Window windowExtension = PlayniteUiHelper.CreateExtensionWindow(PlayniteApi, resources.GetString("LOCSuccessStory"), ViewExtension); windowExtension.ShowDialog(); } }); gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = resources.GetString("LOCRemoveTitle"), Action = (gameMenuItem) => { if (settings.EnableIntegrationInCustomTheme || settings.EnableIntegrationInDescription) { PlayniteUiHelper.ResetToggle(); } var TaskIntegrationUI = Task.Run(() => { PluginDatabase.Remove(GameMenu); var dispatcherOp = successStoryUI.AddElements(); dispatcherOp.Completed += (s, e) => { successStoryUI.RefreshElements(GameMenu); }; }); } }); } } #if DEBUG gameMenuItems.Add(new GameMenuItem { MenuSection = resources.GetString("LOCSuccessStory"), Description = "Test", Action = (mainMenuItem) => { } }); #endif return(gameMenuItems); }
// Create FrameworkElement with achievements datas public StackPanel CreateSc(AchievementsDatabase achievementsDatabase, GameAchievements SelectedGameAchievements, bool ShowTitle, bool ShowGraphic, bool ShowAchievements, bool ShowProgressBar, bool IsCustom = false) { StackPanel spA = new StackPanel(); spA.Name = "PART_Achievements"; if (ShowTitle) { TextBlock tbA = new TextBlock(); tbA.Name = "PART_Achievements_TextBlock"; tbA.Text = resources.GetString("LOCSucessStoryAchievements"); tbA.Style = (Style)resources.GetResource("BaseTextBlockStyle"); tbA.Margin = new Thickness(0, 15, 0, 10); Separator sep = new Separator(); sep.Name = "PART_Achievements_Separator"; sep.Background = (Brush)resources.GetResource("PanelSeparatorBrush"); spA.Children.Add(tbA); spA.Children.Add(sep); spA.UpdateLayout(); } if (ShowGraphic) { StackPanel spAG = new StackPanel(); if (!IsCustom) { spAG.Name = "PART_Achievements_Graphics"; spAG.Height = 120; spAG.MaxHeight = 120; spAG.Margin = new Thickness(0, 5, 0, 5); } AchievementsGraphicsDataCount GraphicsData = null; if (settings.GraphicAllUnlockedByDay) { GraphicsData = achievementsDatabase.GetCountByMonth(GameSelected.Id); } else { GraphicsData = achievementsDatabase.GetCountByDay(GameSelected.Id); } string[] StatsGraphicsAchievementsLabels = GraphicsData.Labels; SeriesCollection StatsGraphicAchievementsSeries = new SeriesCollection(); StatsGraphicAchievementsSeries.Add(new LineSeries { Title = "", Values = GraphicsData.Series }); spAG.Children.Add(new SuccessStoryAchievementsGraphics(StatsGraphicAchievementsSeries, StatsGraphicsAchievementsLabels)); spA.Children.Add(spAG); spA.UpdateLayout(); } if (ShowProgressBar) { StackPanel spPB = new StackPanel(); if (!IsCustom) { spPB.Name = "PART_Achievements_ProgressBar"; spPB.Height = 40; spPB.Margin = new Thickness(0, 5, 0, 5); } spPB.Children.Add(new SuccessStoryAchievementsProgressBar(SelectedGameAchievements.Unlocked, SelectedGameAchievements.Total, settings.IntegrationShowProgressBarPercent, settings.IntegrationShowProgressBarIndicator)); spA.Children.Add(spPB); spA.UpdateLayout(); } if (ShowAchievements) { StackPanel spAL = new StackPanel(); if (!IsCustom) { spAL.Name = "PART_Achievements_List"; spAL.MaxHeight = 300; spAL.Margin = new Thickness(0, 5, 0, 5); } spAL.Children.Add(new SuccessStoryAchievementsList(SelectedGameAchievements.Achievements)); spA.Children.Add(spAL); spA.UpdateLayout(); } return(spA); }
private void Integration() { try { // Search game description if (PART_ElemDescription == null) { foreach (StackPanel sp in Tools.FindVisualChildren <StackPanel>(Application.Current.MainWindow)) { if (sp.Name == "PART_ElemDescription") { PART_ElemDescription = sp; break; } } } // Delete logger.Info("SuccessStory - Delete"); ui.RemoveButtonInGameSelectedActionBarButtonOrToggleButton("PART_ScButton"); ui.RemoveButtonInGameSelectedActionBarButtonOrToggleButton("PART_ScToggleButton"); ui.RemoveElementInGameSelectedDescription("PART_Achievements"); ui.ClearElementInCustomTheme("PART_Achievements_Graphics"); ui.ClearElementInCustomTheme("PART_Achievements_List"); ui.ClearElementInCustomTheme("PART_Achievements_ProgressBar"); // Reset resources List <ResourcesList> resourcesLists = new List <ResourcesList>(); resourcesLists.Add(new ResourcesList { Key = "Sc_Total", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_Unlocked", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_Locked", Value = "0" }); ui.AddResources(resourcesLists); var taskIntegration = Task.Run(() => LoadData(PlayniteApi, this.GetPluginUserDataPath(), settings)) .ContinueWith(antecedent => { GameAchievements SelectedGameAchievements = antecedent.Result; Application.Current.Dispatcher.Invoke(new Action(() => { // No achievements if (SelectedGameAchievements == null || !SelectedGameAchievements.HaveAchivements) { //logger.Debug(JsonConvert.SerializeObject(SelectedGameAchievements)); logger.Info("SuccessStory - No achievement for " + GameSelected.Name); return; } // Add resources resourcesLists.Add(new ResourcesList { Key = "Sc_Total", Value = SelectedGameAchievements.Total.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_Unlocked", Value = SelectedGameAchievements.Unlocked.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_Locked", Value = SelectedGameAchievements.Locked.ToString() }); ui.AddResources(resourcesLists); // Auto integration if (settings.EnableIntegrationInDescription || settings.EnableIntegrationInDescriptionWithToggle) { if (settings.EnableIntegrationInDescriptionWithToggle) { ToggleButton tb = new ToggleButton(); if (settings.IntegrationToggleDetails) { tb = new SuccessStoryToggleButtonDetails(SelectedGameAchievements.Unlocked, SelectedGameAchievements.Total); } else { tb = new SuccessStoryToggleButton(); tb.Content = resources.GetString("LOCSucessStoryAchievements"); } tb.IsChecked = false; tb.Name = "PART_ScToggleButton"; tb.Width = 150; tb.HorizontalAlignment = HorizontalAlignment.Right; tb.VerticalAlignment = VerticalAlignment.Stretch; tb.Margin = new Thickness(10, 0, 0, 0); tb.Click += OnGameSelectedToggleButtonClick; ui.AddButtonInGameSelectedActionBarButtonOrToggleButton(tb); } // Add Achievements elements StackPanel ScA = CreateSc(achievementsDatabase, SelectedGameAchievements, settings.IntegrationShowTitle, settings.IntegrationShowGraphic, settings.IntegrationShowAchievements, settings.IntegrationShowProgressBar, false); if (settings.EnableIntegrationInDescriptionWithToggle) { ScA.Visibility = Visibility.Collapsed; } ui.AddElementInGameSelectedDescription(ScA, settings.IntegrationTopGameDetails); } // Auto adding button if (settings.EnableIntegrationButton || settings.EnableIntegrationButtonDetails) { Button bt = new Button(); if (settings.EnableIntegrationButton) { bt.Content = resources.GetString("LOCSucessStoryAchievements"); } if (settings.EnableIntegrationButtonDetails) { bt = new SuccessStoryButtonDetails(SelectedGameAchievements.Unlocked, SelectedGameAchievements.Total); } bt.Name = "PART_ScButton"; bt.Width = 150; bt.HorizontalAlignment = HorizontalAlignment.Right; bt.VerticalAlignment = VerticalAlignment.Stretch; bt.Margin = new Thickness(10, 0, 0, 0); bt.Click += OnBtGameSelectedActionBarClick; ui.AddButtonInGameSelectedActionBarButtonOrToggleButton(bt); } // Custom theme if (settings.EnableIntegrationInCustomTheme) { if (settings.IntegrationShowGraphic) { StackPanel scAG = CreateSc(achievementsDatabase, SelectedGameAchievements, false, true, false, false, true); ui.AddElementInCustomTheme(scAG, "PART_Achievements_Graphics"); } if (settings.IntegrationShowAchievements) { StackPanel scAL = CreateSc(achievementsDatabase, SelectedGameAchievements, false, false, true, false, true); ui.AddElementInCustomTheme(scAL, "PART_Achievements_List"); } if (settings.IntegrationShowProgressBar) { StackPanel scPB = CreateSc(achievementsDatabase, SelectedGameAchievements, false, false, false, true, true); ui.AddElementInCustomTheme(scPB, "PART_Achievements_ProgressBar"); } } })); }); } catch (Exception ex) { Common.LogError(ex, "SucessStory", $"Impossible integration"); } }
public override void RefreshElements(Game GameSelected, bool force = false) { #if DEBUG logger.Debug($"SuccessStory [Ignored] - RefreshElements({GameSelected.Name})"); #endif CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken ct = tokenSource.Token; Task TaskRefresh = Task.Run(() => { #if DEBUG string IsCanceld = string.Empty; logger.Debug($"SuccessStory [Ignored] - TaskRefresh() - Start"); Stopwatch stopwatch = new Stopwatch(); TimeSpan ts; stopwatch.Start(); #endif try { Initial(); // Reset resources List <ResourcesList> resourcesLists = new List <ResourcesList>(); resourcesLists.Add(new ResourcesList { Key = "Sc_HasData", Value = false }); resourcesLists.Add(new ResourcesList { Key = "Sc_Is100Percent", Value = false }); resourcesLists.Add(new ResourcesList { Key = "Sc_Total", Value = 0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_TotalDouble", Value = (double)0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_TotalString", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_Unlocked", Value = 0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_UnlockedDouble", Value = (double)0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_UnlockedString", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_Locked", Value = 0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_LockedDouble", Value = (double)0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_LockedString", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlocked", Value = 0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlockedDouble", Value = (double)0 }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlockedString", Value = "0" }); resourcesLists.Add(new ResourcesList { Key = "Sc_ListAchievements", Value = new List <Achievements>() }); resourcesLists.Add(new ResourcesList { Key = "Sc_EnableIntegrationInCustomTheme", Value = PluginDatabase.PluginSettings.EnableIntegrationInCustomTheme }); resourcesLists.Add(new ResourcesList { Key = "Sc_IntegrationShowGraphic", Value = PluginDatabase.PluginSettings.IntegrationShowGraphic }); resourcesLists.Add(new ResourcesList { Key = "Sc_IntegrationShowAchievements", Value = PluginDatabase.PluginSettings.IntegrationShowAchievements }); resourcesLists.Add(new ResourcesList { Key = "Sc_IntegrationShowProgressBar", Value = PluginDatabase.PluginSettings.IntegrationShowProgressBar }); resourcesLists.Add(new ResourcesList { Key = "Sc_IntegrationShowAchievementsCompactLocked", Value = PluginDatabase.PluginSettings.IntegrationShowAchievementsCompactLocked }); resourcesLists.Add(new ResourcesList { Key = "Sc_IntegrationShowAchievementsCompactUnlocked", Value = PluginDatabase.PluginSettings.IntegrationShowAchievementsCompactUnlocked }); ui.AddResources(resourcesLists); // Load data if (!PluginDatabase.IsLoaded) { return; } GameAchievements successStories = PluginDatabase.Get(GameSelected); if (successStories.HasData) { resourcesLists = new List <ResourcesList>(); resourcesLists.Add(new ResourcesList { Key = "Sc_HasData", Value = true }); resourcesLists.Add(new ResourcesList { Key = "Sc_Is100Percent", Value = successStories.Is100Percent }); resourcesLists.Add(new ResourcesList { Key = "Sc_Total", Value = successStories.Total }); resourcesLists.Add(new ResourcesList { Key = "Sc_TotalDouble", Value = double.Parse(successStories.Total.ToString()) }); resourcesLists.Add(new ResourcesList { Key = "Sc_TotalString", Value = successStories.Total.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_Unlocked", Value = successStories.Unlocked }); resourcesLists.Add(new ResourcesList { Key = "Sc_UnlockedDouble", Value = double.Parse(successStories.Unlocked.ToString()) }); resourcesLists.Add(new ResourcesList { Key = "Sc_UnlockedString", Value = successStories.Unlocked.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_Locked", Value = successStories.Locked }); resourcesLists.Add(new ResourcesList { Key = "Sc_LockedDouble", Value = double.Parse(successStories.Locked.ToString()) }); resourcesLists.Add(new ResourcesList { Key = "Sc_LockedString", Value = successStories.Locked.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlocked", Value = successStories.Progression }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlockedDouble", Value = (double)successStories.Progression }); resourcesLists.Add(new ResourcesList { Key = "Sc_PercentageUnlockedString", Value = successStories.Progression.ToString() }); resourcesLists.Add(new ResourcesList { Key = "Sc_ListAchievements", Value = successStories.Items }); } // If not cancel, show if (!ct.IsCancellationRequested && GameSelected.Id == SuccessStoryDatabase.GameSelected.Id) { ui.AddResources(resourcesLists); if (_PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop) { PluginDatabase.SetCurrent(successStories); } } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", $"Error on TaskRefreshBtActionBar()"); } #if DEBUG stopwatch.Stop(); ts = stopwatch.Elapsed; logger.Debug($"SuccessStory [Ignored] - TaskRefresh(){IsCanceld} - End - {String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10)}"); #endif }, ct); taskHelper.Add(TaskRefresh, tokenSource); }
public void SetScData(GameAchievements gameAchievements, bool noControl = false) { List <Achievements> ListAchievements = gameAchievements.Items; this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new ThreadStart(delegate { lbAchievements.ItemsSource = null; lbAchievements.Items.Clear(); })); Task.Run(() => { List <ListBoxAchievements> ListBoxAchievements = new List <ListBoxAchievements>(); for (int i = 0; i < ListAchievements.Count; i++) { DateTime?dateUnlock = null; bool IsGray = false; string urlImg = string.Empty; try { if (ListAchievements[i].DateUnlocked == default(DateTime) || ListAchievements[i].DateUnlocked == null) { if (ListAchievements[i].UrlLocked == string.Empty || ListAchievements[i].UrlLocked == ListAchievements[i].UrlUnlocked) { urlImg = ListAchievements[i].ImageUnlocked; IsGray = true; } else { urlImg = ListAchievements[i].ImageLocked; } } else { urlImg = ListAchievements[i].ImageUnlocked; dateUnlock = ListAchievements[i].DateUnlocked; } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", "Error on convert bitmap"); } string NameAchievement = ListAchievements[i].Name; // Achievement without unlocktime but achieved = 1 if (dateUnlock == new DateTime(1982, 12, 15, 0, 0, 0, 0)) { dateUnlock = null; } ListBoxAchievements.Add(new ListBoxAchievements() { Name = NameAchievement, DateUnlock = dateUnlock, EnableRaretyIndicator = PluginDatabase.PluginSettings.EnableRaretyIndicator, Icon = urlImg, IconImage = urlImg, IsGray = IsGray, Description = ListAchievements[i].Description, Percent = ListAchievements[i].Percent }); } this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(delegate { if (!noControl) { if (gameAchievements.Id != SuccessStoryDatabase.GameSelected.Id) { return; } } // Sorting ListBoxAchievements = ListBoxAchievements.OrderByDescending(x => x.DateUnlock).ThenBy(x => x.Name).ToList(); lbAchievements.ItemsSource = ListBoxAchievements; })); }); }
public override GameAchievements GetAchievements(Game game) { GameAchievements Result = SuccessStory.PluginDatabase.GetDefault(game); Result.Items = new List <Achievements>(); Result.HaveAchivements = true; string TrophyDirectory = FindTrophyGameFolder(game); string TrophyFile = "TROPUSR.DAT"; string TrophyFileDetails = "TROPCONF.SFM"; // Directory control if (TrophyDirectory.IsNullOrEmpty()) { logger.Warn($"SuccessStory - No Trophy directoy found for {game.Name}"); return(Result); } if (!File.Exists(Path.Combine(TrophyDirectory, TrophyFile))) { logger.Warn($"SuccessStory - File {TrophyFile} not found for {game.Name} in {Path.Combine(TrophyDirectory, TrophyFile)}"); return(Result); } if (!File.Exists(Path.Combine(TrophyDirectory, TrophyFileDetails))) { logger.Warn($"SuccessStory - File {TrophyFileDetails} not found for {game.Name} in {Path.Combine(TrophyDirectory, TrophyFileDetails)}"); return(Result); } int TrophyCount = 0; List <string> TrophyHexData = new List <string>(); // Trophies details XDocument TrophyDetailsXml = XDocument.Load(Path.Combine(TrophyDirectory, TrophyFileDetails)); foreach (XElement TrophyXml in TrophyDetailsXml.Descendants("trophy")) { Console.WriteLine(TrophyXml); int.TryParse(TrophyXml.Attribute("id").Value, out int TrophyDetailsId); string TrophyType = TrophyXml.Attribute("ttype").Value; string Name = TrophyXml.Element("name").Value; string Description = TrophyXml.Element("detail").Value; int Percent = 100; if (TrophyType.ToLower() == "s") { Percent = 30; } if (TrophyType.ToLower() == "g") { Percent = 10; } Result.Items.Add(new Achievements { ApiName = string.Empty, Name = Name, Description = Description, UrlUnlocked = CopyTrophyFile(TrophyDirectory, "TROP" + TrophyDetailsId.ToString("000") + ".png"), UrlLocked = string.Empty, DateUnlocked = default(DateTime), Percent = Percent }); } TrophyCount = Result.Items.Count; // Trophies data byte[] TrophyByte = File.ReadAllBytes(Path.Combine(TrophyDirectory, TrophyFile)); string hex = Tools.ToHex(TrophyByte); List <string> splitHex = hex.Split(new[] { "0000000600000060000000" }, StringSplitOptions.None).ToList(); for (int i = (splitHex.Count - 1); i >= (splitHex.Count - TrophyCount); i--) { //TrophyHexData.Add(splitHex[i].Substring(0, 192)); TrophyHexData.Add(splitHex[i]); } TrophyHexData.Reverse(); foreach (string HexData in TrophyHexData) { string stringHexId = HexData.Substring(0, 2); int Id = (int)Int64.Parse(stringHexId, System.Globalization.NumberStyles.HexNumber); string Unlocked = HexData.Substring(18, 8); bool IsUnlocked = (Unlocked == "00000001"); // No unlock time if (IsUnlocked) { Result.Items[Id].DateUnlocked = new DateTime(1982, 12, 15, 0, 0, 0, 0); } } Result.Total = Result.Items.Count; Result.Unlocked = Result.Items.FindAll(x => x.DateUnlocked != default(DateTime)).Count(); Result.Locked = Result.Items.FindAll(x => x.DateUnlocked == default(DateTime)).Count(); Result.Progression = (Result.Total != 0) ? (int)Math.Ceiling((double)(Result.Unlocked * 100 / Result.Total)) : 0; return(Result); }
private void Integration() { bool noAchievements = false; try { AchievementsDatabase achievementsDatabase = new AchievementsDatabase(PlayniteApi, this.GetPluginUserDataPath()); achievementsDatabase.Initialize(); GameAchievements SelectedGameAchievements = achievementsDatabase.Get(GameSelected.Id); // Download Achievements if not exist in database. if (SelectedGameAchievements == null) { logger.Info("SuccesStory - Download achievements for " + GameSelected.Name); achievementsDatabase.Add(GameSelected, settings); achievementsDatabase.Initialize(); SelectedGameAchievements = achievementsDatabase.Get(GameSelected.Id); } if (SelectedGameAchievements == null || !SelectedGameAchievements.HaveAchivements) { logger.Info("SuccessStory - No achievement for " + GameSelected.Name); if (settings.EnableIntegrationInDescription || settings.EnableIntegrationInDescriptionWithToggle) { Button PART_ScButton = (Button)LogicalTreeHelper.FindLogicalNode(PART_ActionButtons, "PART_ScButton"); // Delete old ButtonDetails if (settings.EnableIntegrationButtonDetails) { PART_ActionButtons.Children.Remove(PART_ScButton); PART_ScButton = null; } ToggleButton PART_ScToggleButton = (ToggleButton)LogicalTreeHelper.FindLogicalNode(PART_ActionButtons, "PART_ScToggleButton"); // Delete old ToggleDetails if (settings.IntegrationToggleDetails) { PART_ActionButtons.Children.Remove(PART_ScToggleButton); PART_ScToggleButton = null; } // Delete old string NameControl = "PART_Achievements"; StackPanel PART_Achievements = (StackPanel)LogicalTreeHelper.FindLogicalNode(PART_ElemDescription, NameControl); if (PART_Achievements != null) { PART_ElemDescription.Children.Remove(PART_Achievements); } } noAchievements = true; } // Auto integration if (settings.EnableIntegrationInDescription || settings.EnableIntegrationInDescriptionWithToggle) { // Search parent action buttons if (PART_ActionButtons == null) { foreach (Button bt in Tools.FindVisualChildren <Button>(Application.Current.MainWindow)) { if (bt.Name == "PART_ButtonEditGame") { PART_ActionButtons = (StackPanel)bt.Parent; break; } } } //Adding togglebutton if (settings.EnableIntegrationInDescriptionWithToggle && PART_ActionButtons != null) { ToggleButton PART_ScToggleButton = (ToggleButton)LogicalTreeHelper.FindLogicalNode(PART_ActionButtons, "PART_ScToggleButton"); // Delete old ToggleDetails if (settings.IntegrationToggleDetails) { PART_ActionButtons.Children.Remove(PART_ScToggleButton); PART_ScToggleButton = null; } if (PART_ScToggleButton == null && !noAchievements) { ToggleButton tb = new ToggleButton(); if (settings.IntegrationToggleDetails) { tb = new SuccessStoryToggleButtonDetails(SelectedGameAchievements.Unlocked, SelectedGameAchievements.Total); } else { tb.Content = resources.GetString("LOCSucessStoryAchievements"); } tb.IsChecked = false; tb.Name = "PART_ScToggleButton"; tb.Width = 150; tb.Height = 40; tb.HorizontalAlignment = HorizontalAlignment.Right; tb.VerticalAlignment = VerticalAlignment.Stretch; tb.Margin = new Thickness(10, 0, 0, 0); tb.Click += ScToggleButton_Click; PART_ActionButtons.Children.Add(tb); PART_ActionButtons.UpdateLayout(); } } // Search game description if (PART_ElemDescription == null) { foreach (StackPanel sp in Tools.FindVisualChildren <StackPanel>(Application.Current.MainWindow)) { if (sp.Name == "PART_ElemDescription") { PART_ElemDescription = sp; break; } } } // Adding control if (PART_ElemDescription != null) { // Delete old string NameControl = "PART_Achievements"; StackPanel PART_Achievements = (StackPanel)LogicalTreeHelper.FindLogicalNode(PART_ElemDescription, NameControl); if (PART_Achievements != null) { if (settings.EnableIntegrationInDescription) { PART_ElemDescription.Children.Remove(PART_Achievements); } if (settings.EnableIntegrationInDescriptionWithToggle) { PART_ElemDescription.Children.Remove(PART_Achievements); } } else { logger.Error($"SuccessStory - {NameControl} not found in Integration()"); } if (SelectedGameAchievements != null && SelectedGameAchievements.HaveAchivements) { StackPanel ScA = CreateSc(achievementsDatabase, SelectedGameAchievements, settings.IntegrationShowTitle, settings.IntegrationShowGraphic, settings.IntegrationShowAchievements, false); if (settings.EnableIntegrationInDescription) { // Add if (settings.IntegrationTopGameDetails) { PART_ElemDescription.Children.Insert(0, ScA); } else { PART_ElemDescription.Children.Add(ScA); } PART_ElemDescription.UpdateLayout(); } if (settings.EnableIntegrationInDescriptionWithToggle) { ScA.Visibility = Visibility.Collapsed; PART_ElemDescription.Children.Add(ScA); PART_ElemDescription.UpdateLayout(); } } } else { logger.Error($"SuccessStory - PART_ElemDescription not found in Integration()"); } } // Auto adding button if (settings.EnableIntegrationButton || settings.EnableIntegrationButtonDetails) { // Search parent action buttons if (PART_ActionButtons == null) { foreach (Button bt in Tools.FindVisualChildren <Button>(Application.Current.MainWindow)) { if (bt.Name == "PART_ButtonEditGame") { PART_ActionButtons = (StackPanel)bt.Parent; break; } } } // Adding button if (PART_ActionButtons != null) { Button PART_ScButton = (Button)LogicalTreeHelper.FindLogicalNode(PART_ActionButtons, "PART_ScButton"); // Delete old ButtonDetails if (settings.EnableIntegrationButtonDetails) { PART_ActionButtons.Children.Remove(PART_ScButton); PART_ScButton = null; } if (PART_ScButton == null) { Button bt = new Button(); if (settings.EnableIntegrationButton) { bt.Content = resources.GetString("LOCSucessStoryAchievements"); } if (settings.EnableIntegrationButtonDetails) { bt = new SuccessStoryButtonDetails(SelectedGameAchievements.Unlocked, SelectedGameAchievements.Total); } bt.Name = "PART_ScButton"; bt.Width = 150; bt.Height = 40; bt.HorizontalAlignment = HorizontalAlignment.Right; bt.VerticalAlignment = VerticalAlignment.Stretch; bt.Margin = new Thickness(10, 0, 0, 0); bt.Click += ScButton_Click; PART_ActionButtons.Children.Add(bt); PART_ActionButtons.UpdateLayout(); } } } // Custom theme if (settings.EnableIntegrationInCustomTheme) { // Search custom element foreach (StackPanel sp in Tools.FindVisualChildren <StackPanel>(Application.Current.MainWindow)) { if (sp.Name == "PART_Achievements_Graphics") { if (SelectedGameAchievements != null && SelectedGameAchievements.HaveAchivements) { // Create StackPanel scAG = CreateSc(achievementsDatabase, SelectedGameAchievements, false, true, false, true); // Clear & add sp.Children.Clear(); sp.Children.Add(scAG); sp.UpdateLayout(); } else { sp.Children.Clear(); sp.UpdateLayout(); } } if (sp.Name == "PART_Achievements_List") { if (SelectedGameAchievements != null && SelectedGameAchievements.HaveAchivements) { // Create StackPanel scAL = CreateSc(achievementsDatabase, SelectedGameAchievements, false, false, true, true); // Clear & add sp.Children.Clear(); sp.Children.Add(scAL); sp.UpdateLayout(); } else { sp.Children.Clear(); sp.UpdateLayout(); } } } } } catch (Exception ex) { var LineNumber = new StackTrace(ex, true).GetFrame(0).GetFileLineNumber(); string FileName = new StackTrace(ex, true).GetFrame(0).GetFileName(); logger.Error(ex, $"SuccessStory [{FileName} {LineNumber}] - Impossible integration "); } }
/// <summary> /// Show list game with achievement. /// </summary> public void GetListGame() { string pluginFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); try { if (ListGames.Count == 0) { var dataGameAchievements = PluginDatabase.Database.Where(x => x.HaveAchivements && x.IsDeleted == false); foreach (GameAchievements item in dataGameAchievements) { string SourceName = PlayniteTools.GetSourceName(_PlayniteApi, item.Id); string GameId = item.Id.ToString(); string GameName = item.Name; string GameIcon = string.Empty; string Icon100 = string.Empty; DateTime?GameLastActivity = null; GameAchievements successStories = PluginDatabase.Get(item.Id); if (item.LastActivity != null) { GameLastActivity = ((DateTime)item.LastActivity).ToLocalTime(); } if (!item.Icon.IsNullOrEmpty()) { GameIcon = _PlayniteApiDatabase.GetFullFilePath(item.Icon); } if (successStories.Is100Percent) { Icon100 = Path.Combine(pluginFolder, "Resources\\badge.png"); } ListGames.Add(new ListViewGames() { Icon100Percent = Icon100, Id = GameId, Name = GameName, Icon = GameIcon, LastActivity = GameLastActivity, SourceName = SourceName, SourceIcon = TransformIcon.Get(SourceName), ProgressionValue = successStories.Progression, Total = successStories.Total, TotalPercent = successStories.Progression + "%", Unlocked = successStories.Unlocked, IsManual = successStories.IsManual }); } #if DEBUG logger.Debug($"SuccessStory [Ignored] - ListGames: {JsonConvert.SerializeObject(ListGames)}"); #endif } Application.Current.Dispatcher.BeginInvoke((Action) delegate { ListviewGames.ItemsSource = ListGames; Sorting(); }); } catch (Exception ex) { Common.LogError(ex, "SuccessStory", "Errorn on GetListGames()"); } }
public GameStorageController() { _localOptions = ReadOptions(); _localAchievements = ReadAchievements(); }
public GameAchievements GetAchievements(IPlayniteAPI PlayniteApi, Guid Id, string PluginUserDataPath) { List <Achievements> Achievements = new List <Achievements>(); Game game = PlayniteApi.Database.Games.Get(Id); string GameName = game.Name; string ClientId = game.PlayAction.EmulatorId.ToString(); bool HaveAchivements = false; int Total = 0; int Unlocked = 0; int Locked = 0; GameAchievements Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, IsEmulators = true, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = 0, Achievements = Achievements }; if (User == "" || Key == "") { logger.Error($"SuccessStory - No RetroAchievement configuration."); AchievementsDatabase.ListErrors.Add($"Error on RetroAchievement: no RetroAchievement configuration in settings menu of plugin."); return(null); } // Load list console RA_Consoles ra_Consoles = GetConsoleIDs(PluginUserDataPath); ra_Consoles.ListConsoles.Sort((x, y) => (y.Name).CompareTo(x.Name)); // Search id console for the game string PlatformName = game.Platform.Name; int consoleID = 0; foreach (RA_Console ra_Console in ra_Consoles.ListConsoles) { string NameConsole = ra_Console.Name.ToLower(); if (NameConsole == "snes") { NameConsole = "super nintendo"; } if (NameConsole == "nes") { NameConsole = "nintendo"; } if (NameConsole == "mega drive") { NameConsole = "sega genesis"; } if (PlatformName.ToLower().IndexOf(NameConsole) > -1) { consoleID = ra_Console.ID; break; } } // Search game id int gameID = 0; if (consoleID != 0) { RA_Games ra_Games = GetGameList(consoleID, PluginUserDataPath); ra_Games.ListGames.Sort((x, y) => (y.Title).CompareTo(x.Title)); foreach (RA_Game ra_Game in ra_Games.ListGames) { string Title = ra_Game.Title.Trim().ToLower(); //logger.Debug($"SuccessStory - {GameName.Trim().ToLower()} / {Title} / {gameID}"); if (GameName.Trim().ToLower() == Title && gameID == 0) { logger.Info($"SuccessStory - Find for {GameName.Trim().ToLower()} / {Title} with {PlatformName} in {consoleID}"); gameID = ra_Game.ID; break; } string[] TitleSplits = Title.Split('|'); if (TitleSplits.Length > 1) { foreach (string TitleSplit in TitleSplits) { //logger.Debug($"SuccessStory - {GameName.Trim().ToLower()} / {TitleSplit.Trim()} / {gameID}"); if (GameName.Trim().ToLower() == TitleSplit.Trim() && gameID == 0) { logger.Info($"SuccessStory - Find for {GameName.Trim().ToLower()} / {TitleSplit.Trim()} with {PlatformName} in {consoleID}"); gameID = ra_Game.ID; break; } } } TitleSplits = Title.Split('-'); if (TitleSplits.Length > 1) { foreach (string TitleSplit in TitleSplits) { //logger.Debug($"SuccessStory - {GameName.Trim().ToLower()} / {TitleSplit.Trim()} / {gameID}"); if (GameName.Trim().ToLower() == TitleSplit.Trim() && gameID == 0) { logger.Info($"SuccessStory - Find for {GameName.Trim().ToLower()} / {TitleSplit.Trim()} with {PlatformName} in {consoleID}"); gameID = ra_Game.ID; break; } } } } } else { logger.Info($"SuccessStory - No console find for {GameName} with {PlatformName}"); return(Result); } // Get achievements if (gameID != 0) { Achievements = GetGameInfoAndUserProgress(gameID); } else { logger.Info($"SuccessStory - No game find for {GameName} with {PlatformName} in {consoleID}"); return(Result); } Result.HaveAchivements = (Achievements.Count > 0); Result.Achievements = Achievements; Result.Total = Achievements.Count; Result.Unlocked = Achievements.FindAll(x => x.DateUnlocked != default(DateTime)).Count; Result.Locked = Result.Total - Result.Unlocked; Result.Progression = (Result.Total != 0) ? (int)Math.Ceiling((double)(Result.Unlocked * 100 / Result.Total)) : 0; return(Result); }
public override GameAchievements GetAchievements(Game game) { List <Achievements> AllAchievements = new List <Achievements>(); string GameName = game.Name; string ClientId = game.PlayAction.EmulatorId.ToString(); GameAchievements Result = SuccessStory.PluginDatabase.GetDefault(game); Result.Items = AllAchievements; if (User == string.Empty || Key == string.Empty) { logger.Error($"SuccessStory - No RetroAchievement configuration."); SuccessStoryDatabase.ListErrors.Add($"Error on RetroAchievement: no RetroAchievement configuration in settings menu of plugin."); return(null); } // Load list console RA_Consoles ra_Consoles = GetConsoleIDs(_PluginUserDataPath); if (ra_Consoles != null && ra_Consoles != new RA_Consoles()) { ra_Consoles.ListConsoles.Sort((x, y) => (y.Name).CompareTo(x.Name)); } else { logger.Warn($"SuccessStory - No ra_Consoles find"); } // List MD5 List <RA_MD5List> ListMD5 = GetMD5List(_PluginUserDataPath, ra_Consoles); // Game Id int gameID = 0; gameID = GetGameIdByHash(game, ListMD5); if (gameID == 0) { gameID = GetGameIdByName(game, ra_Consoles); } // Get achievements if (gameID != 0) { AllAchievements = GetGameInfoAndUserProgress(gameID); } else { return(Result); } Result.HaveAchivements = (AllAchievements.Count > 0); Result.Items = AllAchievements; Result.Total = AllAchievements.Count; Result.Unlocked = AllAchievements.FindAll(x => x.DateUnlocked != default(DateTime)).Count; Result.Locked = Result.Total - Result.Unlocked; Result.Progression = (Result.Total != 0) ? (int)Math.Ceiling((double)(Result.Unlocked * 100 / Result.Total)) : 0; return(Result); }
/// <summary> /// Get all achievements for a Origin game. /// </summary> /// <param name="PlayniteApi"></param> /// <param name="Id"></param> /// <returns></returns> public GameAchievements GetAchievements(IPlayniteAPI PlayniteApi, Guid Id) { List <Achievements> Achievements = new List <Achievements>(); string GameName = PlayniteApi.Database.Games.Get(Id).Name; bool HaveAchivements = false; int Total = 0; int Unlocked = 0; int Locked = 0; GameAchievements Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = 0, Achievements = Achievements }; // Only if user is logged. if (originAPI.GetIsUserLoggedIn()) { // Get informations from Origin plugin. string accessToken = originAPI.GetAccessToken().access_token; string personasId = GetPersonas(originAPI.GetAccessToken()); string origineGameId = GetOrigineGameAchievementId(PlayniteApi, Id); string lang = CodeLang.GetOriginLang(Localization.GetPlayniteLanguageConfiguration(PlayniteApi.Paths.ConfigurationPath)); // Achievements (default return in english) var url = string.Format(@"https://achievements.gameservices.ea.com/achievements/personas/{0}/{1}/all?lang={2}&metadata=true&fullset=true", personasId, origineGameId, lang); using (var webClient = new WebClient { Encoding = Encoding.UTF8 }) { try { webClient.Headers.Add("X-AuthToken", accessToken); webClient.Headers.Add("accept", "application/vnd.origin.v3+json; x-cache/force-write"); var stringData = webClient.DownloadString(url); JObject AchievementsData = JObject.Parse(stringData); foreach (var item in (JObject)AchievementsData["achievements"]) { var val = item.Value; HaveAchivements = true; Achievements.Add(new Achievements { Name = (string)item.Value["name"], Description = (string)item.Value["desc"], UrlUnlocked = (string)item.Value["icons"]["208"], UrlLocked = "", DateUnlocked = ((string)item.Value["state"]["a_st"] == "ACTIVE") ? default(DateTime) : new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((int)item.Value["u"]) }); Total += 1; if ((string)item.Value["state"]["a_st"] == "ACTIVE") { Locked += 1; } else { Unlocked += 1; } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; switch (resp.StatusCode) { case HttpStatusCode.NotFound: // HTTP 404 break; default: var LineNumber = new StackTrace(ex, true).GetFrame(0).GetFileLineNumber(); string FileName = new StackTrace(ex, true).GetFrame(0).GetFileName(); logger.Error(ex, $"SuccessStory [{FileName} {LineNumber}] - Failed to load from {url}. "); break; } return(Result); } } } } Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = (Total != 0) ? (int)Math.Ceiling((double)(Unlocked * 100 / Total)) : 0, Achievements = Achievements }; return(Result); }
/// <summary> /// Get all achievements for a GOG game. /// </summary> /// <param name="PlayniteApi"></param> /// <param name="Id"></param> /// <returns></returns> public GameAchievements GetAchievements(IPlayniteAPI PlayniteApi, Guid Id) { List <Achievements> Achievements = new List <Achievements>(); string GameName = PlayniteApi.Database.Games.Get(Id).Name; string ClientId = PlayniteApi.Database.Games.Get(Id).GameId; bool HaveAchivements = false; int Total = 0; int Unlocked = 0; int Locked = 0; GameAchievements Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = 0, Achievements = Achievements }; string ResultWeb = ""; // Only if user is logged. if (gogAPI.GetIsUserLoggedIn()) { string accessToken = gogAPI.GetAccountInfo().accessToken; string userId = gogAPI.GetAccountInfo().userId; string lang = CodeLang.GetGogLang(Localization.GetPlayniteLanguageConfiguration(PlayniteApi.Paths.ConfigurationPath)); // Only languages available string[] arrayLang = { "de", "en", "fr", "ru", "zh", "zh-Hans" }; if (!arrayLang.ContainsString(lang)) { lang = "en"; } // Achievements string url = string.Format(@"https://gameplay.gog.com/clients/{0}/users/{1}/achievements", ClientId, userId); try { string urlLang = string.Format(@"https://www.gog.com/user/changeLanguage/{0}", lang.ToLower()); ResultWeb = DonwloadStringData(urlLang, url, accessToken).GetAwaiter().GetResult(); } // TODO Environnement //catch (Exception e) when (!Environment.IsDebugBuild) catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; switch (resp.StatusCode) { case HttpStatusCode.ServiceUnavailable: // HTTP 503 Common.LogError(ex, "SuccessStory", $"HTTP 503 to load from {url}"); break; default: Common.LogError(ex, "SuccessStory", $"Failed to load from {url}"); break; } } return(Result); } if (ResultWeb != "") { JObject resultObj = JObject.Parse(ResultWeb); try { JArray resultItems = (JArray)resultObj["items"]; if (resultItems.Count > 0) { HaveAchivements = true; for (int i = 0; i < resultItems.Count; i++) { Achievements temp = new Achievements { ApiName = (string)resultItems[i]["achievement_key"], Name = (string)resultItems[i]["name"], Description = (string)resultItems[i]["description"], UrlUnlocked = (string)resultItems[i]["image_url_unlocked"], UrlLocked = (string)resultItems[i]["image_url_locked"], DateUnlocked = ((string)resultItems[i]["date_unlocked"] == null) ? default(DateTime) : (DateTime)resultItems[i]["date_unlocked"], Percent = (float)resultItems[i]["rarity"] }; Total += 1; if ((string)resultItems[i]["date_unlocked"] == null) { Locked += 1; } else { Unlocked += 1; } Achievements.Add(temp); } } } catch (Exception ex) { Common.LogError(ex, "SuccessStory", $"Failed to parse. "); return(Result); } } } Result = new GameAchievements { Name = GameName, HaveAchivements = HaveAchivements, Total = Total, Unlocked = Unlocked, Locked = Locked, Progression = (Total != 0) ? (int)Math.Ceiling((double)(Unlocked * 100 / Total)) : 0, Achievements = Achievements }; return(Result); }