private void CopyClones(LBGame lBGame, string destLocation) { //ITrace.WriteLine(prefix: false); /* 26/03/2021 * OPFiles opF = new OPFiles() * { * Buttons = Dcs_Buttons.NoStop, * WhoCallMe = "Clone" * }; * opF.IWriteLine += (string message) => ITrace.WriteLine(message); * opF.IWrite += (string message) => ITrace.BeginLine(message);*/ List <Clone> clones = XML_Games.ListClones(_XMLPlatformFile, "GameID", lBGame.Id).ToList(); // tri des doublons / filter duplicates List <Clone> fClones = FilesFunc.DistinctClones(clones, lBGame.ApplicationPath, PS.Default.LBPath); // On va vérifier que chaque clone n'est pas déjà présent et selon déjà copier foreach (Clone zeClone in fClones) { //waiting zeClone.ApplicationPath = ReconstructPath(zeClone.ApplicationPath); SimpleCopyManager(Path.GetFullPath(zeClone.ApplicationPath, PS.Default.LBPath), destLocation, ref _FileConflictDecision); } }
private Dictionary <string, string> FindPossibilities(LBGame game, IEnumerable <string> titleElements) { Dictionary <string, string> possibilities = new Dictionary <string, string>(); possibilities.Add("id", game.Id); int i = 1; string sEmpty, sSpace, s8; sEmpty = sSpace = s8 = string.Empty; foreach (string element in titleElements) { sEmpty += element; sSpace += $"{element} "; s8 += $"{element}_"; if (i == 3) { possibilities.Add("3Empty", new string(sEmpty)); possibilities.Add("3Space", new string(sSpace).TrimEnd(' ')); possibilities.Add("3_", new string(s8).TrimEnd('_')); } i++; } possibilities.Add("FullEmpty", sEmpty); possibilities.Add("FullSpace", sSpace.TrimEnd(' ')); possibilities.Add("Full_", s8.TrimEnd('_')); return(possibilities); }
/// <summary> /// Récupère tous les fichiers en fonction du LBGame, ainsi que des dossiers de la plateforme /// </summary> /// <param name="lbGame"></param> /// <param name="gpX"></param> private void GetFiles(LBGame lbGame, GameDataCont gdC) { HeTrace.WriteLine($"[GetFiles]", this); var possibilities = GetBasicPossibilities(lbGame.Id, lbGame.Title); // Jeu principal + Clones gdC.SetApplications = GetFilesForGames(lbGame); // CheatCodes if (!string.IsNullOrEmpty(Config.HCCodesPath)) { gdC.SetSCheatCodes = GetFilesByPredict(possibilities, Path.Combine(Config.HCCodesPath, _ZePlatform.Name), "CheatCodes"); } // Manuels gdC.SetDefaultManual = GetFileForSpecifics(lbGame.ManualPath, Common.Config.HLaunchBoxPath); gdC.AddSManuals = GetMoreFiles("Manual", possibilities); // Musics gdC.SetDefaultMusic = GetFileForSpecifics(lbGame.MusicPath, Common.Config.HLaunchBoxPath); gdC.AddSMusics = GetMoreFiles("Music", possibilities); // Videos gdC.SetDefaultVideo = GetFileForSpecifics(lbGame.VideoPath, Common.Config.HLaunchBoxPath); gdC.SetDefaultThemeVideo = GetFileForSpecifics(lbGame.ThemeVideoPath, Common.Config.HLaunchBoxPath); gdC.AddSVideos = GetMoreFiles("Video", possibilities); //GetMoreFiles(toSearch, gpX.CompVideos, "Video", gpX.VideoPath, gpX.ThemeVideoPath); // Images gdC.Images = GetImagesFiles(lbGame, possibilities); }
/// <summary> /// /// </summary> /// <param name="gpX"></param> /// <param name="lbGame"></param> /// <param name="gamePath"></param> /// <remarks> /// Modifie le lbgame /// </remarks> private void Make_EnhanceBackup(GameDataCont gdC, LBGame lbGame, string gamePath) { lbGame.ApplicationPath = DxPath.To_RelativeOrNull(Common.Config.HLaunchBoxPath, gdC.DefaultApp?.CurrentPath); lbGame.ManualPath = DxPath.To_RelativeOrNull(Common.Config.HLaunchBoxPath, gdC.DefaultManual?.CurrentPath); lbGame.MusicPath = DxPath.To_RelativeOrNull(Common.Config.HLaunchBoxPath, gdC.DefaultMusic?.CurrentPath); lbGame.VideoPath = DxPath.To_RelativeOrNull(Common.Config.HLaunchBoxPath, gdC.DefaultVideo?.CurrentPath); lbGame.ThemeVideoPath = DxPath.To_RelativeOrNull(Common.Config.HLaunchBoxPath, gdC.DefaultThemeVideo?.CurrentPath); XML_Games.EnhancedBackup(_XMLPlatformFile, lbGame, gamePath); }
private void ManageDefaultFiles(LBGame lbGame, string gamePath, Folder tree) { GamePaths gp = (GamePaths)lbGame; gp.ApplicationPath = ManageRomPath(lbGame.ApplicationPath, tree.Children[Common.Games]); gp.ManualPath = ManageDefaultFile(lbGame.ManualPath, tree.Children[Common.Manuals], "Manual"); gp.MusicPath = ManageDefaultFile(lbGame.MusicPath, tree.Children[Common.Musics], "Music"); //gp.VideoPath = ManageDefaultFile(lbGame.VideoPath, tree.Children[Common.Videos]); //gp.ThemeVideoPath = ManageDefaultFile(lbGame.ThemeVideoPath, tree.Children[Common.]); gp.WriteToJson(Path.Combine(gamePath, "DPGame.json")); }
/// <summary> /// Copie les fichiers en fonction du dossier source /// </summary> /// <param name="destPath"></param> /// <param name="objMachine"></param> private void Copy_Manager(LBGame lbGame, string tempFolder) { foreach (string d in Directory.GetDirectories(tempFolder)) { if (CancelToken.IsCancellationRequested) { throw new OperationCanceledException(CancelToken); } string dirName = Path.GetFileName(d); // Games if (dirName == PS.Default.Games) { CopyContent(d, Path.GetDirectoryName(lbGame.ApplicationPath)); } // Cheats Codes else if (dirName == PS.Default.CheatCodes) { CopyContent(d, TCheatsCodesP); } // Images else if (dirName == PS.Default.Images) { CopyContent(d, TImagesP); } // Manuals else if (dirName == PS.Default.Manuals) { CopyContent(d, Path.GetDirectoryName(lbGame.ManualPath)); } // Musics else if (dirName == PS.Default.Musics) { CopyContent(d, Path.GetDirectoryName(lbGame.MusicPath)); } // Videos else if (dirName == PS.Default.Videos) { CopyContent(d, Path.GetDirectoryName(lbGame.VideoPath)); } } }
internal static Dictionary <string, bool?> CheckGameValidity(ShortGame g, string platformXmlFile) { LBGame game = XML_Games.Scrap_LBGame <LBGame>(platformXmlFile, GameTag.ID, g.Id); //clones var clones = XML_Games.ListClones(platformXmlFile, Tag.GameId, g.Id); bool bMG = CheckValidity(game.ApplicationPath); if (!bMG) { return(null); } Dictionary <string, bool?> yEP = new Dictionary <string, bool?>(); yEP.Add("Main Game", bMG); yEP.Add("Manual", CheckValidity(game.ManualPath)); yEP.Add("Music", CheckValidity(game.MusicPath)); yEP.Add("Video", CheckValidity(game.VideoPath)); yEP.Add("ThemeVideo", CheckValidity(game.ThemeVideoPath)); foreach (var c in clones) { yEP.Add(Path.GetFileName(c.ApplicationPath), CheckValidity(c.ApplicationPath)); } return(yEP); /// <summary> /// Vérifie que le jeu sélectionné a bien le manuel, la musique et le jeu /// </summary> bool CheckValidity(string link) { string tmp; tmp = Path.GetFullPath(link, Config.HLaunchBoxPath); if (!File.Exists(tmp)) { return(false); } return(true); } }
/// <summary> /// Open a window to ask for paths /// </summary> /// <param name="lbGame"></param> protected void Modify_Paths(LBGame lbGame, List <AdditionalApplication> clones) { Application.Current.Dispatcher?.Invoke(() => { W_ModTargetPaths window = new W_ModTargetPaths() { Model = new Models.M_ModTargetPaths() { Game = lbGame, Clones = clones, TGamePath = TGamesP, TImagesPath = TImagesP, TManualPath = TManualsP, TMusicsPath = TMusicsP, TVideosPath = TVideosP, } }; if (window.ShowDialog() == true) { } else { TokenSource.Cancel(); } }); /* * new W_ModTargetPaths() * { * Model = new Models.M_ModTargetPaths() * { * Game = lbGame, * TGamePath = TGamesP, * TImagesPath = TImagesP, * TManualPath = TManualsP, * TMusicsPath = TMusicsP, * TVideosPath = TVideosP, * } * }.ShowDialog()); */ //lbGame.ApplicationPath }
private GamePaths MakeGamePaths(LBGame lbGame, GameDataCont gdC, Folder tree) { GamePaths gpX = GamePaths.CreateBasic(lbGame); // gpX.ApplicationPath = AssignDefaultPath(tree.Children[Common.Games].Path, gdC.DefaultApp); gpX.SetApplications = gdC.Applications.Select(x => new DataPlus() { Id = x.Id, Name = x.Name, CurrentPath = x.Name, IsSelected = x.IsSelected, }); gpX.ManualPath = AssignDefaultPath(tree.Children[Common.Manuals].Path, gdC.DefaultManual); gpX.MusicPath = AssignDefaultPath(tree.Children[Common.Musics].Path, gdC.DefaultMusic); gpX.VideoPath = AssignDefaultPath(tree.Children[Common.Videos].Path, gdC.DefaultVideo); gpX.ThemeVideoPath = AssignDefaultPath(tree.Children[Common.Videos].Path, gdC.DefaultThemeVideo); return(gpX); }
private List <DataRepExt> GetImagesFiles(LBGame lbGame, string toSearch /*, List<DataRepExt> images*/) { //Queue<string> lPackFile = new Queue<string>(); List <DataRepExt> images = new List <DataRepExt>(); foreach (PlatformFolder plfmFolder in _ZePlatform.PlatformFolders) { //filtre sur tout ce qui n'est pas image switch (plfmFolder.MediaType) { case "Manual": case "Music": case "Theme Video": case "Video": continue; } string folder = Path.GetFullPath(plfmFolder.FolderPath, Common.Config.HLaunchBoxPath); // Liste du contenu des dossiers foreach (var fichier in Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories)) { string fileName = Path.GetFileName(fichier); if ( !fileName.StartsWith($"{toSearch}-") && !fileName.StartsWith($"{ lbGame.Title}.{ lbGame.Id}-")) { continue; } HeTrace.WriteLine($"\t[GetImages] Found '{fichier}' in '{folder}'"); DataRepExt tmp = new DataRepExt(plfmFolder.MediaType, fichier); // lPackFile.Enqueue(fichier); images.Add(tmp); } } return(images); }
private void Modify_Paths(LBGame lbGame) { string root = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(lbGame.ApplicationPath))); Application.Current.Dispatcher?.Invoke(() => { W_DefinePaths window = new W_DefinePaths() { Model = new Models.M_ModDefinePaths() { RootCheats = Path.Combine(root, "Cheat Codes", lbGame.Platform), RootImg = Path.Combine(root, "Images", lbGame.Platform), } }; if (window.ShowDialog() == true) { TImagesP = window.Model.RootImg; TCheatsCodesP = window.Model.RootCheats; } else { TokenSource.Cancel(); } }); /* * Application.Current.Dispatcher?.Invoke(() => * new W_DefinePaths() * { * Model = new Models.M_ModDefinePaths() * { * RootCheats = Path.Combine(root, "Cheat Codes", lbGame.Platform), * RootImg = Path.Combine(root, "Images", lbGame.Platform), * } * }.ShowDialog()); */ }
private void CopyFiles(LBGame lbGame, Folder tree) { // 2021 - Formatage de la chaine pour éviter les erreurs string toSearch = lbGame.Title.Replace(':', '_').Replace('\'', '_').Replace("__", "_"); // Jeu CopyRoms(lbGame.ApplicationPath, tree.Children[Common.Games].Path); // Video, Music, Manual CopySpecific(toSearch, lbGame.ManualPath, tree.Children[Common.Manuals].Path, "Manual", x => lbGame.ManualPath = x); CopySpecific(toSearch, lbGame.MusicPath, tree.Children[Common.Musics].Path, "Music", x => lbGame.MusicPath = x); CopySpecific(toSearch, lbGame.VideoPath, tree.Children[Common.Videos].Path, "Video", x => lbGame.VideoPath = x);; // Images CopyImages(lbGame, tree.Children[Common.Images].Path); // CheatCodes #region Copy CheatCodes if (PS.Default.opCheatCodes && !string.IsNullOrEmpty(PS.Default.CCodesPath)) { CopyCheatCodes(toSearch, tree.Children[Common.CheatCodes].Path); } else { HeTrace.WriteLine("[Run] Copy Cheat Codes disabled", this); } #endregion // Clones #region Copy Clones if (PS.Default.opClones) { CopyClones(lbGame, tree.Children[Common.Games].Path); } else { HeTrace.WriteLine($"[Run] Clone copy disabled", this); } #endregion }
/// <summary> /// /// </summary> /// <param name="applicationPath"></param> /// <param name="applications"></param> /// <returns>Le fichier sélectionné</returns> private ICollection <DataPlus> GetFilesForGames(LBGame lbGame) { List <DataPlus> games = new List <DataPlus>(); HeTrace.WriteLine($"\t[GetFilesForGames]", this); if (string.IsNullOrEmpty(lbGame.ApplicationPath)) { throw new ArgumentNullException("[GetFiles] Folder of application path is empty"); } string extension = Path.GetExtension(lbGame.ApplicationPath); // si aucune extension on ne pack pas le fichier if (string.IsNullOrEmpty(extension)) { throw new ArgumentNullException("[GetFiles] Extension of application is null"); } // --- Cas des extensions cue if (extension.Equals(".cue", StringComparison.OrdinalIgnoreCase)) { string srcFile = Path.GetFullPath(lbGame.ApplicationPath, Common.Config.HLaunchBoxPath); //Lecture du fichier cue Cue_Scrapper cuecont = new Cue_Scrapper(srcFile); //Folder containing files string sourceFold = Path.GetDirectoryName(srcFile); // Fonctionne avec le nom du fichier foreach (string fileName in cuecont.Files) { // Donne le lien complet vers le fichier games.Add(DataPlus.MakeNormal(Path.Combine(sourceFold, fileName))); } } games.Add(DataPlus.MakeChosen(lbGame.Id, lbGame.Title, Path.GetFullPath(lbGame.ApplicationPath, Common.Config.HLaunchBoxPath))); // --- Récupération des clones List <Clone> clones = XML_Games.ListClones(_XMLPlatformFile, "GameID", lbGame.Id).ToList(); // tri des doublons / filter duplicates List <Clone> fClones = FilesFunc.DistinctClones(clones, lbGame.ApplicationPath, Common.Config.HLaunchBoxPath); if (fClones.Any()) { HeTrace.WriteLine($"\t[{nameof(XML_Games.ListClones)}] found: '{fClones.Count()}'", this); foreach (Clone c in fClones) { string path = Path.GetFullPath(c.ApplicationPath, Common.Config.HLaunchBoxPath); if (File.Exists(path)) { games.Add(DataPlus.MakeNormal(c.Id, Path.GetFileName(path), path)); } } } return(games); }
private void Copy_LBManager(LBGame lbGame, string tempFolder) { // todo ajouter une fonctino pour grouper les jeux dans le sous dossier //string gameF = Path.Combine(Path.GetDirectoryName(lbGame.ApplicationPath), lbGame.Title); UpdateStatus?.Invoke(this, "Copy files"); MaximumProgress?.Invoke(this, 6); UpdateProgress?.Invoke(this, 0); int i = 0; foreach (string d in Directory.GetDirectories(tempFolder)) { UpdateProgress?.Invoke(this, i); string dirName = Path.GetFileName(d); // Games if (dirName == PS.Default.Games) { string tmp = Path.GetDirectoryName(lbGame.ApplicationPath); UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.Games} => '{tmp}'"); CopyContent(d, tmp); } // Cheat Codes else if (dirName == PS.Default.CheatCodes) { UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.CheatCodes} => '{TCheatsCodesP}'"); CopyContent(d, TCheatsCodesP); } // Images else if (dirName == PS.Default.Images) { UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.Images} => '{TImagesP}'"); CopyContent(d, TImagesP); } // Manuals else if (dirName == PS.Default.Manuals) { string tmp = Path.GetDirectoryName(lbGame.ManualPath); UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.Manuals} => ({ tmp }'"); CopyContent(d, tmp); } // Musics else if (dirName == PS.Default.Musics) { string tmp = Path.GetDirectoryName(lbGame.MusicPath); UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.Musics} => '{tmp}'"); CopyContent(d, tmp); } // Videos else if (dirName == PS.Default.Videos) { string tmp = Path.GetDirectoryName(lbGame.VideoPath); UpdateStatus?.Invoke(this, $"\t{Lang.I_Copy}: {Lang.Videos} => '{tmp}'"); CopyContent(d, tmp); } i++; } UpdateProgress?.Invoke(this, 6); }
public void CachePlatformGamesAsync(Platform platform) { if (launchboxFile == null) { GetLaunchBoxFile(); } // Create a dictionary of existing Games to speed lookups Dictionary <long, LBGame> existingLBGameDict = R.Data.LBGames.ToDictionary(x => x.ID); // Create a Hashset of LBGames to store any new LBGames that we discover HashSet <LBGame> newLBGames = new(); List <XElement> platformGameElements = gameElementLookupByPlatform[platform.LBPlatform.Title].ToList(); int gameCount = platformGameElements.Count; Reporter.Report($"Found {gameCount} {platform.LBPlatform.Title} games in LaunchBox zip file."); int j = 0; foreach (XElement gameElement in platformGameElements) { // Reporting only if ((gameCount / 10) != 0 && ++j % (gameCount / 10) == 0) { Reporter.Report(" Working " + j + " / " + gameCount + " " + platform.LBPlatform.Title + " games in the LaunchBox database."); } string title = gameElement.Element("Name")?.Value; // Don't create this game if the title or database ID is null if (string.IsNullOrEmpty(title) || !long.TryParse(gameElement.SafeGetA("DatabaseID"), out long id)) { continue; } // Check if the game alredy exists in the local cache before trying to add it if (!existingLBGameDict.TryGetValue(id, out LBGame LBGame)) { LBGame = new LBGame { ID = id }; newLBGames.Add(LBGame); Debug.WriteLine("New game: " + LBGame.Title); } // If a game has changed platforms, catch it and zero out match if (LBGame.LBPlatform_ID != platform.LBPlatform.ID) { LBGame.LBPlatform = platform.LBPlatform; Release release = R.Data.Releases.FirstOrDefault(x => x.ID_LB == LBGame.ID); if (release != null) { release.ID_LB = null; } } // Set or overwrite game properties LBGame.Title = title; LBGame.Date = DateTimeRoutines.SafeGetDateTime(gameElement.SafeGetA("ReleaseDate") ?? gameElement.SafeGetA("ReleaseYear") + @"-01-01 00:00:00"); LBGame.Overview = gameElement.Element("Overview")?.Value ?? LBGame.Overview; LBGame.Genres = gameElement.Element("Genres")?.Value ?? LBGame.Genres; LBGame.Developer = gameElement.Element("Developer")?.Value ?? LBGame.Developer; LBGame.Publisher = gameElement.Element("Publisher")?.Value ?? LBGame.Publisher; LBGame.VideoUrl = gameElement.Element("VideoUrl")?.Value ?? LBGame.VideoUrl; LBGame.WikiUrl = gameElement.Element("WikipediaURL")?.Value ?? LBGame.WikiUrl; LBGame.Players = gameElement.Element("MaxPlayers")?.Value ?? LBGame.Players; } R.Data.LBGames.AddRange(newLBGames); }
public object Run(int timeSleep = 10) { bool backupDone = false; /*// Tracing * MeSimpleLog log = new MeSimpleLog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Common.Logs, $"{DateTime.Now.ToFileTime()}.log")) * { * LogLevel = 1, * FuncPrefix = EPrefix.Horodating, * }; * log.AddCaller(this); * HeTrace.AddLogger("LaunchBox", log);*/ // UpdateStatus += (x, y) => HeTrace.WriteLine(y, this); // Redirige les signaux //RedirectSignals(); // int i = 0; foreach (FileObj game in Games) { UpdateProgressT?.Invoke(this, i); UpdateStatus?.Invoke(this, $"Work on: {game.Nom}"); string gameName = Path.GetFileNameWithoutExtension(game.Nom); string tmpPath = Path.Combine(Config.WorkingFolder, Path.GetFileNameWithoutExtension(game.Nom)); // Décompresser if (Path.GetExtension(game.Path).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { ZipDecompression.UnCompressArchive(game.Path, tmpPath, CancelToken); } if (CancelToken.IsCancellationRequested) { UpdateStatus?.Invoke(this, "Stopped by user"); return(false); } // Chargement des données du jeu string xmlFile = Path.Combine(tmpPath, "EBGame.xml"); LBGame lbGame = XML_Games.Scrap_LBGame(xmlFile); List <AdditionalApplication> clones = XML_Games.ListAddApps(xmlFile); UpdateStatus?.Invoke(this, $"Game info xml loaded: {lbGame.Title}"); // Vérification de la présence du fichier xml de la plateforme string machineXMLFile = Path.Combine(PS.Default.LastLBpath, PS.Default.dPlatforms, $"{lbGame.Platform}.xml"); if (!File.Exists(machineXMLFile)) { UpdateStatus?.Invoke(this, $"Creation of xml file: '{machineXMLFile}'"); XML_Games.NewPlatform(machineXMLFile); } // Backup datas if (!backupDone) { BackupPlatformFile(machineXMLFile); UpdateStatus?.Invoke(this, $"Backup of '{machineXMLFile}'"); backupDone = true; } // Initialisation des dossiers TGamesP = Path.GetDirectoryName(lbGame.ApplicationPath); UpdateStatus?.Invoke(this, $"Target Game path: {TGamesP}"); /*TCheatsCodesP = Path.Combine(root, "Cheat Codes", lbGame.Platform); * UpdateStatus?.Invoke($"Target Cheats path: {TCheatsCodesP}"); * * TImagesP = Path.Combine(root, "Images", lbGame.Platform); * UpdateStatus?.Invoke($"Target Images path: {TImagesP}");*/ TManualsP = Path.GetDirectoryName(lbGame.ManualPath); UpdateStatus?.Invoke(this, $"Target Manuals path: {TManualsP}"); TMusicsP = Path.GetDirectoryName(lbGame.MusicPath); UpdateStatus?.Invoke(this, $"Target Musics path: {TMusicsP}"); TVideosP = Path.GetDirectoryName(lbGame.VideoPath); UpdateStatus?.Invoke(this, $"Target Videos path: {TVideosP}"); // Modification des chemins dans le jeu Modify_Paths(lbGame); // Copy des jeux Copy_Manager(lbGame, tmpPath); // Retrait du jeu si présence bool?replace = false; if (XML_Custom.TestPresence(machineXMLFile, "Game", nameof(lbGame.Id).ToUpper(), lbGame.Id)) { replace = AskDxMBox("Game is Already present", "Question", E_DxButtons.Yes | E_DxButtons.No, lbGame.Title); } if (replace == true) { XML_Games.Remove_Game(lbGame.Id, machineXMLFile); } // Injection XML_Games.InjectGame(lbGame, machineXMLFile); XML_Games.InjectAddApps(clones, machineXMLFile); if (PS.Default.wCustomFields) { //var r = XML_Games.ListCustomFields(xmlFile, "CustomField"); XML_Games.Trans_CustomF(xmlFile, machineXMLFile); } UpdateStatus?.Invoke(this, $"Injection in xml Launchbox's files"); //XMLBackup.Copy_EBGame(gameName, Path.Combine(tmpPath, "EBGame.xml"), MachineXMLFile); // Effacer le dossier temporaire Delete(tmpPath); //i++; UpdateProgress?.Invoke(this, 100); UpdateStatus?.Invoke(this, "Game Finished"); } UpdateStatus?.Invoke(this, "Task Finished"); HeTrace.RemoveLogger("LaunchBoxEB"); UpdateProgressT?.Invoke(this, 100); return(true); }
public object Run(int timeSleep = 10) { try { /* * * log.AddCaller(this); * HeTrace.AddLogger("LaunchBox", log); */ //UpdateStatus += (x, y) => HeTrace.WriteLine(y, this); // Redirige les signaux //RedirectSignals(); // Récupération des infos de la plateforme UpdateStatus?.Invoke(this, "Get infos from platform"); /* * Normalement on peut virer * XML_Functions xf = new XML_Functions(); * xf.ReadFile(Common.PlatformsFile); * * Machine = xf.ScrapPlatform(PlatformName);*/ Machine = XML_Platforms.GetPlatformPaths(Common.PlatformsFile, PlatformName); if (Machine.PlatformFolders.Count < 1) { UpdateStatus?.Invoke(this, "Error: this machine has no path"); return(false); } // Backup datas MachineXMLFile = Path.Combine(PS.Default.LastLBpath, PS.Default.dPlatforms, $"{PlatformName}.xml"); BackupPlatformFile(MachineXMLFile); UpdateStatus?.Invoke(this, $"Backup of '{MachineXMLFile}'"); // Initialisation des dossiers cible // Memo solution la plus simple, fixant des limites et normalement évolutive string root = Path.GetDirectoryName(Path.GetDirectoryName(Machine.FolderPath)); TGamesP = Path.Combine(Machine.FolderPath); UpdateStatus?.Invoke(this, $"Target Game path: {TGamesP}"); TCheatsCodesP = Path.Combine(root, "Cheat Codes", PlatformName); UpdateStatus?.Invoke(this, $"Target Cheats path: {TCheatsCodesP}"); TImagesP = Path.GetDirectoryName(Machine.PlatformFolders.First((x) => x.MediaType.Contains("Box", StringComparison.OrdinalIgnoreCase)).FolderPath); UpdateStatus?.Invoke(this, $"Target Images path: {TImagesP}"); TManualsP = Machine.PlatformFolders.First((x) => x.MediaType == "Manual").FolderPath; UpdateStatus?.Invoke(this, $"Target Manuals path: {TManualsP}"); TMusicsP = Machine.PlatformFolders.First((x) => x.MediaType == "Music").FolderPath; UpdateStatus?.Invoke(this, $"Target Musics path: {TMusicsP}"); TVideosP = Machine.PlatformFolders.First((x) => x.MediaType == "Video").FolderPath; UpdateStatus?.Invoke(this, $"Target Videos path: {TVideosP}"); // int i = 0; //MaximumProgressT?.Invoke(this, Games.Count()); //MaximumProgress?.Invoke(this, 100); foreach (FileObj game in Games) { UpdateProgressT?.Invoke(this, i); UpdateStatus?.Invoke(this, $"Work on: {game.Nom}"); string gameName = Path.GetFileNameWithoutExtension(game.Nom); string tmpPath = Path.Combine(Config.WorkingFolder, Path.GetFileNameWithoutExtension(game.Nom)); // Décompresser if (Path.GetExtension(game.Path).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { ZipDecompression.UnCompressArchive(game.Path, tmpPath, CancelToken); } if (CancelToken.IsCancellationRequested) { UpdateStatus?.Invoke(this, "Stopped by user"); return(false); } // todo 7zip // Chargement des données du jeu string xmlFile = Path.Combine(tmpPath, "EBGame.xml"); LBGame lbGame = XML_Games.Scrap_LBGame(xmlFile); List <AdditionalApplication> clones = XML_Games.ListAddApps(xmlFile); //05/04/2021 LBGame lbGame = XML_Games.Scrap_GameLB(Path.Combine(tmpPath, "EBGame.xml"), "LaunchBox_Backup", PS.Default.wCustomFields); UpdateStatus?.Invoke(this, $"Game info xml loaded: {lbGame.Title}"); // Modification des chemins dans le jeu Modify_Paths(lbGame, clones); // Modification de la platforme du jeu UpdateStatus?.Invoke(this, $"Altération of platform {lbGame.Platform} => {PlatformName}"); lbGame.Platform = PlatformName; // Copier Copy_LBManager(lbGame, tmpPath); /*// Platform modification * if (PS.Default.ChangePlatform) * XMLBackup.Change_Platform(Path.Combine(destPath, "EBGame.xml"), machine);*/ // Retrait du jeu si présence bool?replace = false; if (XML_Custom.TestPresence(MachineXMLFile, "Game", nameof(lbGame.Id).ToUpper(), lbGame.Id)) { replace = AskDxMBox("Game is Already present", "Question", E_DxButtons.Yes | E_DxButtons.No, lbGame.Title); } if (replace == true) { XML_Games.Remove_Game(lbGame.Id, MachineXMLFile); } // Injection XML_Games.InjectGame(lbGame, MachineXMLFile); XML_Games.InjectAddApps(clones, MachineXMLFile); if (PS.Default.wCustomFields) { //var r = XML_Games.ListCustomFields(xmlFile, "CustomField"); XML_Games.Trans_CustomF(xmlFile, MachineXMLFile); } UpdateStatus?.Invoke(this, $"Injection in xml Launchbox's files"); //XMLBackup.Copy_EBGame(gameName, Path.Combine(tmpPath, "EBGame.xml"), MachineXMLFile); // Effacer le dossier temporaire Delete(tmpPath); UpdateStatus?.Invoke(this, "Game Finished"); UpdateProgress?.Invoke(this, 100); i++; } UpdateStatus?.Invoke(this, "Task Finished"); HeTrace.RemoveLogger("LaunchBoxAdapt"); UpdateProgressT?.Invoke(this, 100); return(true); } catch (Exception exc) { HeTrace.WriteLine(exc.Message); return(false); } }
/// <summary> /// Récupère les images /// </summary> /// <param name="possibilities">Possibilités de nom des fichiers</param> /// <param name="lbGame"></param> /// <returns></returns> private List <DataRepImg> GetImagesFiles(LBGame lbGame, Dictionary <string, string> possibilities) { //Queue<string> lPackFile = new Queue<string>(); List <DataRepImg> images = new List <DataRepImg>(); foreach (PlatformFolder plfmFolder in _ZePlatform.PlatformFolders) { //filtre sur tout ce qui n'est pas image switch (plfmFolder.MediaType) { case "Manual": case "Music": case "Theme Video": case "Video": continue; } if (string.IsNullOrEmpty(plfmFolder.FolderPath)) { SetStatus(this, new StateArg($"Directory link is empty: '{plfmFolder.FolderPath}'", CancelFlag)); continue; } string folder = Path.GetFullPath(plfmFolder.FolderPath, Config.HLaunchBoxPath); // Test si le dossier existe if (!Directory.Exists(folder)) { SetStatus(this, new StateArg($"Directory doesn't exist: '{folder}'", CancelFlag)); continue; } // Liste du contenu des dossiers foreach (var fichier in Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories)) { string fileName = Path.GetFileName(fichier); bool res = false; // Test des possibilités de nom foreach (var possibility in possibilities) { if (possibility.Key.Equals("ID") && fileName.Contains(possibility.Value, StringComparison.OrdinalIgnoreCase)) { res = true; } else if (fileName.StartsWith($"{possibility.Value}-", StringComparison.OrdinalIgnoreCase)) { res = true; } if (res) { break; } } if (res) { HeTrace.WriteLine($"\t[GetImages] Found '{fichier}' in '{folder}'"); DataRepImg tmp = new DataRepImg(plfmFolder.MediaType, fichier); images.Add(tmp); } } } return(images); }
/// <summary> /// Copie les images / Copy the images /// </summary> /// <remarks>To Add Mask see 'Where'</remarks> private void CopyImages(LBGame lbGame, string imgsFolder) { if (!imgsFolder.Contains(_WFolder)) { throw new Exception($"[CreateFolders] Erreur la chaine '{imgsFolder}' ne contient pas '{_WFolder}'"); } //ITrace.WriteLine(prefix: false); Queue <PackFile> lPackFile = new Queue <PackFile>(); // Get All images (To Add mask see at Where) Console.WriteLine($"[CopyImages] Search all images for '{lbGame.Title}'"); foreach (PlatformFolder plfmFolder in _ZePlatform.PlatformFolders) { //filtre sur tout ce qui n'est pas image switch (plfmFolder.MediaType) { case "Manual": case "Music": case "Theme Video": case "Video": continue; } // 2020 - on modify pour certains titres, la recherche string toSearch = lbGame.Title.Replace(':', '_').Replace('\'', '_').Replace("__", "_"); // Liste du contenu des dossiers foreach (var fichier in Directory.EnumerateFiles(plfmFolder.FolderPath, "*.*", SearchOption.AllDirectories)) { string fileName = Path.GetFileName(fichier); if ( !fileName.StartsWith($"{toSearch}-") && !fileName.StartsWith($"{ lbGame.Title}.{ lbGame.Id}-")) { continue; } HeTrace.WriteLine($"\t\t[CopyImages] Found '{fichier}' in '{plfmFolder.FolderPath}'"); PackFile tmp = new PackFile(plfmFolder.MediaType, fichier); lPackFile.Enqueue(tmp); } } // ITrace.WriteLine(prefix: false); E_Decision resMem = E_Decision.None; while (lPackFile.Count != 0) { var pkFile = lPackFile.Dequeue(); // On récupère la tail int pos = pkFile.LinkToThePath.IndexOf(pkFile.Categorie); string tail1 = Path.GetDirectoryName(pkFile.LinkToThePath).Substring(pos); // Dossier de destination //25/03/2021string destFolder = Path.Combine(_Tree.Children[nameof(SubFolder.Images)].Path, tail1); string destFolder = Path.Combine(imgsFolder, tail1); SimpleCopyManager(pkFile.LinkToThePath, destFolder, ref resMem); } }
// --- /// <summary> /// Travail pour un jeu /// </summary> /// <param name="shGame"></param> public void PackMe(ShortGame shGame) { TempDecision = MemorizedDecision; // Verif if (shGame == null || string.IsNullOrEmpty(shGame.Id)) { HeTrace.WriteLine("Game property: null"); return; } // Dossiers string gamePath = Path.Combine(_SystemPath, $"{shGame.ExploitableFileName}"); // New Working Folder //Compress_ZipMode(gamePath, shGame.Title); // Compress_7ZipMode(gamePath, shGame.Title); // Contrôle de collisions pour les dossiers if (Directory.Exists(gamePath)) { HeTrace.WriteLine($"Directory Exists '{gamePath}'", this); // Demande à l'utilisateur si aucune précédente if (MemorizedDecision == E_Decision.None) { Application.Current.Dispatcher?.Invoke(() => TempDecision = MBDecision.ShowDial(null, gamePath, LanguageManager.Instance.Lang.Folder_Ex, E_DxConfB.Trash | E_DxConfB.OverWrite)); switch (TempDecision) { /* // Gestion des stops * case E_Decision.Stop: * HeTrace.WriteLine("Stopped by user", this); * HeTrace.RemoveLogger("game"); * return; * case E_Decision.StopAll: * HeTrace.WriteLine("Stopped by user", this); * HeTrace.RemoveLogger("game"); * throw new OperationCanceledException("Stopped by user"); */ case E_Decision.OverWriteAll: case E_Decision.TrashAll: MemorizedDecision = TempDecision; break; } switch (TempDecision) { case E_Decision.Trash: case E_Decision.TrashAll: HeTrace.WriteLine($"Trash existing folder: '{gamePath}'", this); OpFolders.Trash(@gamePath); break; } } } // --- On part du principe que tout peut être overwritté à partir de là. // Construction de la structure var tree = MakeStructure(gamePath); // --- #region Original Backup Game - Before all modifications if (Config.CreateTBGame) { XML_Games.TrueBackup(_XMLPlatformFile, shGame.Id, gamePath); } else { HeTrace.WriteLine("[Run] Original Backup Game disabled"); } #endregion #region Backup without paths XML_Games.NPBackup(_XMLPlatformFile, shGame.Id, gamePath); #endregion // Récupération du jeu LBGame lbGame = XML_Games.Scrap_LBGame <LBGame>(_XMLPlatformFile, "ID", shGame.Id); // Récupération des clones HeTrace.WriteLine("Alarms about not managed field are not important except if it's about a path containing datas"); HeTrace.WriteLine("EBGames and TBGames don't use a class they copy directly from xml to xml"); #region Creation of the Infos.xml (on ne récupère que ce que l'on veut) if (Config.CreateInfos) { // --- Get game from Launchbox (on a besoin que jusqu'au game info) XML_Custom.Make_InfoGame(gamePath, lbGame); } else { HeTrace.WriteLine("[Run] Make info disabled", this); } #endregion // --- Récupération des fichiers GameDataCont gdC = new GameDataCont(lbGame.Title, lbGame.Platform); GetFiles(lbGame, gdC); if (PackMe_IHM.LaunchBoxCore_Prev(gamePath, _ZePlatform, gdC) != true) { throw new Exception("Stopped by user"); } // --- Prepare files; PrepareList(gdC.Applications, tree, Config.KeepGameStruct, "Game"); PrepareList(gdC.CheatCodes, tree, Config.KeepCheatStruct, "CheatCode"); PrepareList(gdC.Manuals, tree, Config.KeepManualStruct, "Manual"); PrepareList(gdC.Musics, tree, Config.KeepMusicStruct, "Music"); PrepareList(gdC.Videos, tree, true, "Video"); PrepareImages(gdC.Images, tree.Children[Common.Images].Path); // --- Copie des fichiers CopyFiles(gdC, tree); // --- Récapitulatif permettant de rajouter ou lever des fichiers au pack if (PackMe_IHM.LaunchBoxCore_Recap(gamePath, _ZePlatform, gdC) != true) { throw new Exception("Stopped by user"); } // --- GamePaths --- GamePaths gpX = MakeGamePaths(lbGame, gdC, tree); #region Serialization / improved backup of Launchbox datas (with found medias missing) /* - En théorie on est toujours sur du relative path * - On a fait un assign sur les dossiers spécifiques * - On va récupérer la structure exacte sans aucune interprétation et modifier ce que l'on veut * - Les Paths */ if (Config.CreateEBGame) { Make_EnhanceBackup(gdC, lbGame, gamePath); } else { HeTrace.WriteLine($"[Run] Enhanced Backup Game disabled", this); } #endregion // --- Création d'un fichier conservant les fichiers par défaut définis par l'utilisateur en vue de réutilisation plus tard gpX.WriteToJson(Path.Combine(gamePath, "DPGame.json")); // --- On complète l'arborescence FoncSchem.MakeListFolder(tree.Children[Common.Manuals]); FoncSchem.MakeListFolder(tree.Children[Common.Images]); FoncSchem.MakeListFolder(tree.Children[Common.Musics]); FoncSchem.MakeListFolder(tree.Children[Common.Videos]); #region Save Struct if (Config.CreateTreeV) { FoncSchem.MakeStruct(tree, gamePath); } else { HeTrace.WriteLine($"[Run] Save Struct disabled", this); } #endregion #region 2020 choix du nom string name = PackMe_IHM.AskName(shGame.ExploitableFileName, _SystemPath); // Changement de nom du dossier <= Pour le moment ça ne fait que vérifier s'il peut écrire //si un dossier a le même nom ça ne pourra pas le renommer ushort i = 0; string destFolder = Path.Combine(_SystemPath, name); if (!gamePath.Equals(destFolder)) { while (i < 10) { try { Directory.Move(gamePath, destFolder); HeTrace.WriteLine("Folder successfully renamed"); // Attribution du résultat gamePath = destFolder; // Sortie break; } catch (IOException ioe) { HeTrace.WriteLine($"Try {i}: {ioe}"); Thread.Sleep(10); i++; } } } gamePath = destFolder; #endregion #region Compression // Zip if (Config.ZipCompression) { Compress_ZipMode(gamePath); } else { HeTrace.WriteLine($"[Run] Zip Compression disabled", this); } // 7zip if (Config.SevZipCompression) { Compress_7ZipMode(gamePath); } else { HeTrace.WriteLine($"[Run] 7Zip Compression disabled", this); } #endregion #region suppression du dossier de travail if (SafeBoxes.Dispatch_Mbox(this, "Would you want to ERASE the temp folder", "Erase", E_DxButtons.No | E_DxButtons.Yes, optMessage: shGame.ExploitableFileName) == true) { // Erase the temp folder try { Directory.SetCurrentDirectory(_WFolder); Directory.Delete(gamePath, true); HeTrace.WriteLine($"[Run] folder {gamePath} erased", this); } catch (Exception exc) { HeTrace.WriteLine($"[Run] Error when Erasing temp folder {gamePath}\n{exc.Message }", this); } } #endregion SetStatus(this, new StateArg($"Finished: {lbGame.Title}", CancelFlag)); }