示例#1
0
        private void Check_IfModifyRequired(C_PathsDouble pathO)
        {
            HeTrace.WriteLine($"\tHPath: {pathO.HardPath}", 10);
            HeTrace.WriteLine($"\tNewHPath: {pathO.NewHardPath}", 10);
            HeTrace.WriteLine($"\tRPath: {pathO.RelatPath}", 10);
            HeTrace.WriteLine($"\tNewRPath: {pathO.NewRelatPath}", 10);

            // Si les paths sont égaux pas besoin de modifier
            pathO.ToModify = !pathO.Test_Validity();
            HeTrace.WriteLine($"\tTestIMN: {pathO.ToModify}", 10);

            // On montre que les données n'ont pas besoin d'être modifiées
            if (!pathO.ToModify)
            {
                pathO.NewHardPath  = SPRLang.No_Modif;
                pathO.NewRelatPath = SPRLang.No_Modif;
            }
        }
示例#2
0
        internal void PrepareSimulation()
        {
            HeTrace.WriteLine($"--- Prepare Simulation ---");

            TaskLauncher tl = new TaskLauncher()
            {
                AutoCloseWindow = true,
                ProgressIHM     = new Splash()
                {
                    Model = new EphemProgress(Core),
                },
                MethodToRun = () => Core.Simulation(),
            };

            if (tl.Launch(Core) == true)
            {
                ActiveSimulate = false;
                ActiveApply    = true;
            }
        }
示例#3
0
        /// <summary>
        /// On va parcourir les PathsCollec et assigner les paths de la simulation aux paths de la plateforme
        /// </summary>
        /// <remarks>
        /// Il n'y a pas de sauvegarde ici, afin de pouvoir continuer en mode debug
        /// </remarks>
        private void Dematriochka()
        {
            HeTrace.WriteLine("[PlatformPaths] [Dematriochka]");
            // Trace.Indent();

            // Modification of App
            //C_PathsCollec game = ExtPlatformPaths[0];
            C_PathsDouble game = PlatformPaths.ApplicationPath;

            // Traitement manuel car ce dossier n'est pas contenu dans les ipfolder
            HeTrace.WriteLine("\t[Dematriochka] Management of 'Game' property", 5);
            game.RelatPath = game.NewRelatPath;
            game.HardPath  = game.NewHardPath;
            game.Raz_NewPaths();

            // Traitement des autres

            foreach (IPlatformFolder ipFolder in _PlatformFolders)
            // foreach (IPlatformFolder ipFolder in PlatformPaths)
            {
                HeTrace.WriteLine($"\t[PlatformPaths] [Dematriochka] Management of '{ipFolder.MediaType}' property", 5);

                //C_PathsCollec pFolder = ExtPlatformPaths.FirstOrDefault(x => x.Type == ipFolder.MediaType);
                C_PathsDouble pFolder = PlatformPaths.GetPaths().FirstOrDefault(x => x.Type == ipFolder.MediaType);

                //
                if (pFolder != null)
                {
                    // Assignation au platform Path de Launchbox
                    ipFolder.FolderPath = pFolder.NewRelatPath;

                    // Permutation new => old
                    pFolder.HardPath  = pFolder.NewHardPath;
                    pFolder.RelatPath = pFolder.NewRelatPath;

                    // Raz new
                    pFolder.Raz_NewPaths();
                }
            }
            Trace.Unindent();
        }
示例#4
0
        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);
        }
示例#5
0
        public bool CheckWriteFolderAccess(string path)
        {
            try
            {
                DirectoryInfo               di    = new DirectoryInfo(path);
                DirectorySecurity           acl   = di.GetAccessControl();
                AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));

                WindowsIdentity  currentUser = WindowsIdentity.GetCurrent();
                WindowsPrincipal group       = new WindowsPrincipal(currentUser);

                foreach (AuthorizationRule rule in rules)
                {
                    FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
                    if (fsAccessRule == null)
                    {
                        continue;
                    }

                    if ((fsAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0)
                    {
                        NTAccount ntAccount = rule.IdentityReference as NTAccount;
                        if (ntAccount == null)
                        {
                            continue;
                        }

                        if (group.IsInRole(ntAccount.Value))
                        {
                            HeTrace.WriteLine($"Current user is in role of {ntAccount.Value}, has write access");
                            continue;
                        }
                        HeTrace.WriteLine($"Current user is not in role of {ntAccount.Value}, does not write access");
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                HeTrace.WriteLine("does not have full access");
            }
        }
示例#6
0
        // ---

        private void CopyFiles(GameDataCont gdC, Folder tree)
        {
            HashCopy objCopy = new HashCopy();

            objCopy.AskToUser += PackMe_IHM.Ask4_FileConflict2;

            HeTrace.WriteLine("[CopyFiles] All files except images");
            // Fusion des fichiers sauf les images
            List <DataTrans> Fichiers = new List <DataTrans>();

            Fichiers.AddRange(gdC.Applications);
            Fichiers.AddRange(gdC.CheatCodes);
            Fichiers.AddRange(gdC.Manuals);
            Fichiers.AddRange(gdC.Musics);
            Fichiers.AddRange(gdC.Videos);

            PackMe_IHM.DoubleProgress(objCopy, "Copy",
                                      (test) => test = objCopy.CopySevNVerif(Fichiers),
                                      (test) => test = objCopy.CopySevNVerif(gdC.Images));
            //copyObj.CopySNVerif(Fichiers);
        }
示例#7
0
        internal void Exec()
        {
            IEnumerable <DataTrans> datas = GetFiles();


            HeTrace.WriteLine("Copy");
            HashCopy hashCopy = new HashCopy();

            hashCopy.AskToUser    += SafeBoxes.HashCopy_AskToUser;
            hashCopy.UpdateStatus += (x, y) => HeTrace.WriteLine(y.Message);
            PersistProgressD mee = new PersistProgressD(hashCopy);

            TaskLauncher launcher = new TaskLauncher()
            {
                ProgressIHM     = new DxDoubleProgress(mee),
                AutoCloseWindow = true,
                MethodToRun     = () => hashCopy.VerifSevNCopy(datas),
            };

            launcher.Launch(hashCopy);
        }
示例#8
0
        /// <summary>
        /// Vérifie l'intégrité des jeux (pas de renouvellement des jeux)
        /// </summary>
        public void PrepareCheckAllGames([CallerMemberName] string propertyName = null)
        {
            if (Core.ChosenMode == GamePathMode.None)
            {
                return;
            }

            HeTrace.WriteLine($"--- Check Validity of Games ({propertyName}) ---");

            TaskLauncher tl = new TaskLauncher()
            {
                AutoCloseWindow = true,
                ProgressIHM     = new Splash()
                {
                    Model = new EphemProgress(Core),
                },
                MethodToRun = () => Core.CheckAllGames(),
            };

            tl.Launch(Core);
        }
示例#9
0
        /// <summary>
        /// Récupération des fichiers (vérification si le dossier source existe à chaque fois)
        /// </summary>
        /// <returns></returns>
        private IEnumerable <DataTrans> GetFiles()
        {
            List <DataTrans> datas = new List <DataTrans>();

            foreach (var platFolder in VisPlatform)
            {
                if (!Directory.Exists(platFolder.HardPath))
                {
                    HeTrace.WriteLine($"Folder doesn't exist '{platFolder.HardPath}'", 5);
                    continue;
                }


                foreach (string f in Directory.EnumerateFiles(platFolder.HardPath, "*.*", SearchOption.AllDirectories))
                {
                    // Cas particulier du theme video
                    if (platFolder.Type.Equals("Video", StringComparison.OrdinalIgnoreCase) &&
                        f.Contains("Theme")
                        )
                    {
                        continue;
                    }


                    DataTrans dt = new DataTrans()
                    {
                        Name        = Path.GetFileName(f),
                        CurrentPath = f,
                        DestPath    = f.Replace(platFolder.HardPath, platFolder.NewHardPath),
                    };

                    HeTrace.WriteLine($"Copy from: {dt.CurrentPath}", 10);
                    HeTrace.WriteLine($"To: {dt.DestPath}", 10);

                    datas.Add(dt);
                }
            }
            return(datas);
        }
示例#10
0
        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
        }
示例#11
0
        /// <summary>
        /// (Re)Initialize les paths
        /// </summary>
        private void InitializePaths()
        {
            HeTrace.WriteLine("Paths initialization", 5);

            // Initialization according to the mode (debug/plugin)
            if (Global.DebugMode)
            {
                // Utilisation de pseudos dossiers
                _PlatformFolders = ((MvPlatform)PlatformObject).GetAllPlatformFolders();
            }
            else
            {
                // Récupération de tous les dossiers + tri
                _PlatformFolders = PlatformObject.GetAllPlatformFolders()
                                   .OrderBy(x => x.MediaType).ToArray();
            }

            //
            HeTrace.WriteLine($"Dossier de jeu: {PlatformObject.Folder}");
            C_Platform tmp = C_Platform.Platform_Maker(PlatformObject, _PlatformFolders);

            PlatformPaths = tmp;
            GC.Collect();
        }
示例#12
0
        /*
         * private void SetSelected(GamePaths gpX, GameDataCont gpC)
         * {
         *  var app = gpC.Apps.FirstOrDefault(x => x.ALinkToThePath.Equals(gpX.ApplicationPath));
         *  if (app != null)
         *      app.IsSelected = true;
         *  var manual = gpC.Apps.FirstOrDefault(x => x.ALinkToThePath.Equals(gpX.ApplicationPath));
         *  var music = gpC.Apps.FirstOrDefault(x => x.ALinkToThePath.Equals(gpX.ApplicationPath));
         *  var video = gpC.Apps.FirstOrDefault(x => x.ALinkToThePath.Equals(gpX.ApplicationPath));
         *  var themevideo = gpC.Apps.FirstOrDefault(x => x.ALinkToThePath.Equals(gpX.ApplicationPath));
         * }*/

        /// <summary>
        /// On rajoute les fichiers présents sur le disque dur
        /// </summary>
        /// <param name="gpC"></param>
        /// <param name="mode"></param>
        /// <param name="archiveName"></param>
        private void GameDataCompletion(GameDataCont gpC, ArchiveMode mode, string archiveName)
        {
            IEnumerable <string> files = null;

            if (mode == ArchiveMode.Zip)
            {
                files = ZipDecompression.StaticGetAllFiles(archiveName);
                files = files.Select(f => f.Replace('/', '\\'));
            }
            else if (mode == ArchiveMode.SevenZip)
            {
                files = SevenZipDecompression.StaticGetAllFiles(archiveName);
            }
            else if (mode == ArchiveMode.Folder)
            {
                files = Directory.GetFiles(archiveName, "*.*", SearchOption.AllDirectories);
                files = files.Select(f => f.Replace($@"{archiveName}\", string.Empty));
            }
            else
            {
                throw new Exception("Not supported");
            }


            // Vérification des fichiers entrés via le GamePaths;
            string tmp;

            //   gpC.SSetApplications = GameDataCompletion(files, Default.Games, "\\", "\\");
            foreach (DataPlus app in gpC.Applications.ToList())
            {
                tmp = $@"{Config.Games}{app.CurrentPath?.Substring(1)}";

                // Récupération du fichier correspondant
                var f = files.FirstOrDefault(x => x.StartsWith(tmp));

                // Si correspondance trouvée
                if (!string.IsNullOrEmpty(f))
                {
                    continue;
                }

                HeTrace.WriteLine($"File not found {app.CurrentPath}");
                f = files.FirstOrDefault(x => Path.GetFileName(x).Equals(Path.GetFileName(app.CurrentPath)));

                // Si remplacement possible
                if (!string.IsNullOrEmpty(f))
                {
                    app.CurrentPath = f.Replace(Config.Games, ".");
                    HeTrace.WriteLine($"Changed by {app.CurrentPath}");
                }
                else
                {
                    HeTrace.WriteLine("Removed");
                    gpC.RemoveApp(app);
                }
            }


            gpC.SetSCheatCodes = GameDataCompletion(files, Config.CheatCodes, "\\", "\\");
            // Manuals
            var tmp2 = $@"{Config.Manuals}{gpC.DefaultManual?.CurrentPath.Substring(1)}";

            if (!files.Contains(tmp2))
            {
                gpC.UnsetDefaultManual();
            }
            gpC.AddSManuals = GameDataCompletion(files, Config.Manuals, "\\", "\\");
            // Musics
            if (!files.Contains($@"{Config.Musics}{gpC.DefaultMusic?.CurrentPath.Substring(1)}"))
            {
                gpC.UnsetDefaultMusic();
            }
            gpC.AddSMusics = GameDataCompletion(files, Config.Musics, "\\", "\\");
            // Videos
            if (!files.Contains($@"{Config.Videos}{gpC.DefaultVideo?.CurrentPath.Substring(1)}"))
            {
                gpC.UnsetDefaultVideo();
            }

            if (!files.Contains($@"{Config.Videos}{gpC.DefaultThemeVideo?.CurrentPath.Substring(1)}"))
            {
                gpC.UnsetDefaultThemeVideo();
            }

            gpC.AddSVideos = GameDataCompletion(files, Config.Videos, "\\", "\\");
        }
示例#13
0
        /// <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);
            }
        }
示例#14
0
        public MigrateLModel(C_Platform backupPlatform, IPlatform currentPlatform)
        {
            CurrentPlatform = currentPlatform;
            ///OldPlatform = oldPlatform;
            VisPlatform = backupPlatform;


            //HeTrace.WriteLine($"Old Platform path '{oldPlatform.app}'");
            HeTrace.WriteLine($"Current Platform path '{CurrentPlatform.Folder}'");


            //VisPlatform = C_Platform.Platform_Maker(oldPlatform, oldPlatform.GetAllPlatformFolders());

            VisPlatform.ApplicationPath.NewRelatPath = currentPlatform.Folder;
            VisPlatform.ApplicationPath.NewHardPath  = Path.GetFullPath(currentPlatform.Folder, Global.LaunchBoxRoot);

            foreach (var elem in VisPlatform)
            {
                foreach (var elem2 in currentPlatform.GetAllPlatformFolders())
                {
                    if (elem2.MediaType.Equals(elem.Type))
                    {
                        elem.NewHardPath  = Path.GetFullPath(elem2.FolderPath, Global.LaunchBoxRoot);
                        elem.NewRelatPath = DxPath.To_RelativeOrNull(Global.LaunchBoxRoot, elem.NewHardPath);
                    }
                }
            }


            /*Platform_Tools.SetFolders(in oldPlatform);
             *
             * Platform_Tools.SetFolders(in currentPlatform);*/
            //oldPlatform.

            //HeTrace.WriteLine($"default boximagepath '{oldPlatform.DefaultBoxImagePath}'");


            // Initialization des dossiers
            // Initialization according to the mode (debug/plugin)

            /*if (Global.DebugMode)
             *  // Utilisation de pseudos dossiers
             *  _PlatformFolders = ((MvPlatform)PlatformObject).GetAllPlatformFolders();
             * else
             *  // Récupération de tous les dossiers + tri
             *  _PlatformFolders = PlatformObject.GetAllPlatformFolders()
             *                          .OrderBy(x => x.MediaType).ToArray();*/

            // Games

            /*            GamesPaths.Source = oldPlatform.Folder;
             *          GamesPaths.Destination = currentPlatform.Folder;
             *          HeTrace.WriteLine(oldPlatform.Folder, 5);
             *          HeTrace.WriteLine(currentPlatform.Folder, 5);
             *
             *          /*  // Images
             *            ImagesPaths.Source = Path.GetDirectoryName(OldPlatform.DefaultBoxImagePath);
             *            ImagesPaths.Destination = Path.GetDirectoryName(CurrentPlatform.DefaultBoxImagePath);*/
            // Manuals

            /*     ManualsPaths.Source = oldPlatform.ManualsFolder;
             *   ManualsPaths.Destination = currentPlatform.ManualsFolder;
             *   // Musics
             *   MusicsPaths.Source = oldPlatform.MusicFolder;
             *   MusicsPaths.Destination = currentPlatform.MusicFolder;
             *   // Videos
             *   VideosPaths.Source = oldPlatform.VideosFolder;
             *   VideosPaths.Destination = currentPlatform.VideosFolder;*/
        }
示例#15
0
        /// <summary>
        /// Format paths to seek the main and show him as hard and relative
        /// </summary>
        /// <param name="v"></param>
        internal void FormatMainPaths(string sep)
        {
            HeTrace.WriteLine("Format main paths", 5);
            // On détermine le path en selon l'emplacement de Launchbox
            if (String.IsNullOrEmpty(PlatformObject.Folder))
            {
                CHardLink  = Global.LaunchBoxRoot; // On récupère avec le core car ça correspond pas sinon
                CRelatLink = @".\";
                return;
            }

            // Détermination du chemin réel si c'est un chemin relatif
            string platformPath = null;

            if (PlatformObject.Folder.StartsWith('.') || PlatformObject.Folder.Substring(1, 2) != @":\")
            {
                //platformPath = Path.GetFullPath(PlatformObject.Folder, Global.LaunchBoxPath);
                platformPath = Path.GetFullPath(PlatformObject.Folder, Global.LaunchBoxRoot);
            }
            else
            {
                platformPath = PlatformObject.Folder;
            }

            #region Remplace FillInformation de l'ancienne version

            HeTrace.WriteLine($@"PlatformFolder: '{PlatformObject.Folder}'"); // Envnew
            HeTrace.WriteLine(@"Search main paths");                          // Envnew


            #region Recherche du dossier hard
            HeTrace.Write(@"--- Seek of HardLink: ");

            string[] foldersArr = platformPath.Split(sep);          // Sur windows le getfullpath a ramené le chemin avec des \

            // Ici une erreur peut se produire si on a un chemin de type "G:"
            CHardLink = String.Join(sep, foldersArr, 0, foldersArr.Length - 2);
            HeTrace.EndLine($"'{CHardLink}'"); // Envnew
            #endregion


            #region conversion en dur du lien vers le dossier actuel

            // Vérification que le path est sur le même chemin que l'application
            DriveInfo driveApp    = new DriveInfo(Global.LaunchBoxPath);
            DriveInfo driveFolder = new DriveInfo(platformPath);
            if (driveApp.Name.Equals(driveFolder.Name))
            {
                HeTrace.Write(@"--- Transformation HardLink RelatLink: ");
                CRelatLink = DxPath.To_Relative(Global.LaunchBoxRoot, CHardLink);
                //CRelatLink = Path.GetRelativePath(Global.LaunchBoxPath, CHardLink);
                HeTrace.WriteLine($"'{CRelatLink}'"); // Envnew
            }
            else
            {
                HeTrace.WriteLine(@"--- RelatLink impossible different drives letters "); // Envnew
            }


            //tmp = tmp.Replace($@"\{OldPlatformObject.Name}", "");

            //CRelatLink = tmp;
            //tmp = null;
            #endregion

            #endregion Remplace FillInformation de l'ancienne version
        }
示例#16
0
        /// <summary>
        /// Simulate effect on paths
        /// </summary>
        /// <remarks>
        /// On ne modifie pas le chemin pour laisser le soin à l'utilisateur de le modifier manuellement
        /// </remarks>
        internal bool Simulate()
        {
            HeTrace.WriteLine(">>> Simulation");

            // Vérification du chemin
            if (!VerifPath(ChosenFolder, nameof(ChosenFolder)))
            {
                return(false);
            }


            // --- Mettre à jour les chemins
            InitializePaths();

            // --- Lancer la simulation

            #region AlterPath

            HeTrace.WriteLine("Altération des dossiers", 5);

            // foreach (var ecp in ExtPlatformPaths)
            foreach (C_PathsDouble ecp in PlatformPaths)
            {
                HeTrace.WriteLine($"\t[AlterPath] {ecp.Type}", level: 10);

                // Choix de filtrer que videos / games / manuals / music et ... ?
                string hardPath;

                // Games
                if (ecp.Type.Equals("Games", StringComparison.OrdinalIgnoreCase))
                {
                    hardPath = Path.Combine(_chosenFolder, GamesFName, SystemFolderName);
                }
                // Manual
                else if (ecp.Type.Equals("Manual", StringComparison.OrdinalIgnoreCase))
                {
                    hardPath = Path.Combine(_chosenFolder, ManualsFName, SystemFolderName);
                }
                // Music
                else if (ecp.Type.Equals("Music", StringComparison.OrdinalIgnoreCase))
                {
                    hardPath = Path.Combine(_chosenFolder, MusicsFName, SystemFolderName);
                }
                // Video
                else if (ecp.Type.Equals("Video", StringComparison.OrdinalIgnoreCase))
                {
                    hardPath = Path.Combine(_chosenFolder, VideosFName, SystemFolderName);
                }
                // Other type of video
                else if (ecp.Type.Equals("Theme Video", StringComparison.OrdinalIgnoreCase))
                {
                    hardPath = Path.Combine(_chosenFolder, VideosFName, SystemFolderName, "Theme");
                }
                // Images
                else
                {
                    hardPath = Path.Combine(_chosenFolder, ImagesFName, SystemFolderName, ecp.Type);
                }


                //string relatPath = Path.GetRelativePath(Global.LaunchBoxPath, hardPath);
                string relatPath = DxPath.To_Relative(Global.LaunchBoxRoot, hardPath);

                ecp.NewRelatPath = relatPath;
                ecp.NewHardPath  = hardPath;

                HeTrace.WriteLine($"\tCombinaison give: {hardPath}", 10);
                HeTrace.WriteLine($"\tRelat find give: {relatPath}", 10);
                // Analyse props n'a plus d'utilité
                // Generate info path n'a apparemment plus d'utilité.
                // Style FLP change le fond mais pas utile ici
                // SetMainWindow Pour la taille de la fenêtre, pas utile ici non plus
            }

            #endregion AlterPath

            HeTrace.WriteLine(">>> End of Simulation"); // Envnew

            return(true);
        }
示例#17
0
        private GameDataCont PrepareGDC(string root, GamePaths gpX)
        {
            HeTrace.WriteLine($"[{nameof(PrepareGDC)}]");

            GameDataCont gdc = new GameDataCont(gpX.Title, gpX.Platform);

            string tmp = string.Empty;

            HeTrace.WriteLine($"\tGames: {Config.Games}");
            // Games
            tmp = Path.Combine(root, Config.Games);
            gdc.SetApplications = gpX.Applications.Select(x =>
                                                          new DataPlus()
            {
                Id          = x.Id,
                Name        = x.Name,
                CurrentPath = Path.GetFullPath(x.CurrentPath, tmp),
                IsSelected  = x.IsSelected,
            });

            if (Directory.Exists(tmp))
            {
                gdc.SSetApplications = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories);
            }

            /*gdc.SetDefaultApplication = gpX.ApplicationPath == null ? null : Path.GetFullPath(gpX.ApplicationPath, tmp);
             * gdc.SetApplications = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();*/

            // Manuals
            HeTrace.WriteLine($"\tManuals: {Config.Manuals}");
            tmp = Path.Combine(root, Config.Manuals);
            gdc.SetDefaultManual = string.IsNullOrEmpty(gpX.ManualPath)? null : Path.GetFullPath(gpX.ManualPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSManuals = Directory.GetFiles(Path.Combine(tmp), "*.*", SearchOption.AllDirectories).ToList();
            }

            // Musics
            HeTrace.WriteLine($"\tMusics: {Config.Musics}");
            tmp = Path.Combine(root, Config.Musics);
            gdc.SetDefaultMusic = string.IsNullOrEmpty(gpX.MusicPath) ? null : Path.GetFullPath(gpX.MusicPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSMusics = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();
            }

            // Videos
            HeTrace.WriteLine($"\tVideos: {Config.Videos}");
            tmp = Path.Combine(root, Config.Videos);
            gdc.SetDefaultVideo      = string.IsNullOrEmpty(gpX.VideoPath) ? null : Path.GetFullPath(gpX.VideoPath, tmp);
            gdc.SetDefaultThemeVideo = string.IsNullOrEmpty(gpX.ThemeVideoPath) ? null : Path.GetFullPath(gpX.ThemeVideoPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSVideos = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories);
            }

            // Cheat Codes
            HeTrace.WriteLine($"\tCheatCodes: {Config.CheatCodes}");
            tmp = Path.Combine(root, Config.CheatCodes);
            if (Directory.Exists(tmp))
            {
                gdc.SetSCheatCodes = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();
            }

            // Images
            HeTrace.WriteLine("\tImages");
            tmp = Path.Combine(root, Config.Images);
            if (Directory.Exists(tmp))
            {
                gdc.Images = PrepareImages(tmp);
            }


            return(gdc);
        }
示例#18
0
        /// <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);
        }
示例#19
0
        /// <summary>
        /// Récupère les fichiers par "prédiction"
        /// </summary>
        internal List <string> GetFilesByPredict(Dictionary <string, string> possibilities, string folder, string mediatype)
        {
            if (string.IsNullOrEmpty(folder))
            {
                SetStatus(this, new StateArg($"Directory link is empty: '{folder}'", CancelFlag));
                return(null);
            }

            string path = Path.GetFullPath(folder, Config.HLaunchBoxPath);

            // Test si le dossier existe
            if (!Directory.Exists(path))
            {
                SetStatus(this, new StateArg($"Directory doesn't exist: '{path}'", CancelFlag));
                return(null);
            }

            // bypass -
            string[] bypass = new string[] { "-", " -" };

            List <string> filteredFiles = new List <string>();

            //          foreach (string fichier in files)
            foreach (string fichier in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
            {
                string filename = Path.GetFileNameWithoutExtension(fichier);

                bool res = false;
                // Test des possibilités de nom
                foreach (var possibility in possibilities)
                {
                    // Sans Bypass
                    if (possibility.Key.Equals("ID") &&
                        filename.Contains(possibility.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        res = true;
                        break;
                    }
                    else if (filename.Equals(possibility.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        res = true;
                        break;
                    }

                    // Avec Bypass
                    foreach (var b in bypass)
                    {
                        if (filename.StartsWith(possibility.Value + b, StringComparison.OrdinalIgnoreCase))
                        {
                            res = true;
                            break;
                        }
                    }

                    //
                    if (res)
                    {
                        break;
                    }
                }

                if (res)
                {
                    HeTrace.WriteLine($"\t[GetFilesByPredict] Found '{fichier}'");
                    filteredFiles.Add(fichier);
                }
            }

            /* if (filteredFiles.Count <= 0)
             * {
             *   SafeBoxes.Dispatch_Mbox(this,
             *       $"{LanguageManager.Instance.Lang.S_SearchFor} {mediatype}: 0 {LanguageManager.Instance.Lang.Word_Result}",
             *       $"{LanguageManager.Instance.Lang.S_SearchFor} { mediatype}",
             *       E_DxButtons.Ok);
             * }
             * else
             * {
             *   //filteredFiles = PackMe_IHM.Validate_FilesFound(filteredFiles, mediatype).ToList();
             * }*/

            return(filteredFiles);
        }
示例#20
0
        /// <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);
        }
示例#21
0
        public override GamePaths Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            GamePaths gpX = new GamePaths();

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    return(gpX);
                }

                // ---

                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    string propertyName = reader.GetString();

                    while (reader.TokenType == JsonTokenType.PropertyName || reader.TokenType == JsonTokenType.Comment)
                    {
                        reader.Read();
                    }

                    switch (propertyName)
                    {
                    case "Id":
                        gpX.Id = reader.GetString();
                        break;

                    case "Title":
                        gpX.Title = reader.GetString();
                        break;

                    case "Platform":
                        gpX.Platform = reader.GetString();
                        break;

                    // ---
                    case "Games":

                        while (reader.Read())
                        {
                            if (reader.TokenType == JsonTokenType.EndArray)
                            {
                                break;
                            }

                            if (reader.TokenType == JsonTokenType.StartObject)
                            {
                                gpX.AddApplication(JsonSerializer.Deserialize <DataPlus>(ref reader, null));
                            }
                        }
                        //gpX.ManualPath = reader.GetString();
                        break;

                    // ---
                    case "ManualPath":
                        gpX.ManualPath = reader.GetString();
                        break;

                    case "MusicPath":
                        gpX.MusicPath = reader.GetString();
                        break;

                    case "VideoPath":
                        gpX.VideoPath = reader.GetString();
                        break;

                    case "ThemeVideoPath":
                        gpX.ThemeVideoPath = reader.GetString();
                        break;


                    default:
                        HeTrace.WriteLine($"Not managed: {propertyName}");
                        break;
                    }
                }
            }
            return(null);
        }
示例#22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="gamePath"></param>
        /// <param name="title">Titre du jeu</param>
        private void Compress_7ZipMode(string gamePath)
        {
            var archiveLink = Path.Combine(_SystemPath, $"{Path.GetFileName(gamePath)}.7z");

            if (File.Exists(archiveLink))
            {
                var Length      = DxLocalTransf.Tools.FileSizeFormatter.Convert(new FileInfo(archiveLink).Length);
                var resConflict = SafeBoxes.Ask4_DestConflict
                                  (
                    LanguageManager.Instance.Lang.File_Ex, archiveLink, Length,
                    E_DxConfB.OverWrite | E_DxConfB.Trash
                                  );

                switch (resConflict)
                {
                case E_Decision.OverWriteAll:
                case E_Decision.OverWrite:
                    File.Delete(archiveLink);
                    break;

                case E_Decision.Trash:
                case E_Decision.TrashAll:
                    OpDFiles.Trash(archiveLink);
                    break;
                }
            }

            SevenZipCompression sevZippy = new SevenZipCompression(_SystemPath)
            {
                IsPaused    = this.IsPaused,
                TokenSource = this.TokenSource
            };

            sevZippy.UpdateStatus += (x, y) => HeTrace.WriteLine(y.Message);


            var res = (bool?)PackMe_IHM.ZipCompressFolder(sevZippy, () => sevZippy.CompressFolder(
                                                              gamePath, Path.GetFileName(gamePath), Config.SevZipLvlCompression), "Compression 7z");

            if (res != true)
            {
                return;
            }

            #region Création du fichier  MD5
            if (Config.CreateMD5)
            {
                Gen_PlusCalculator calculator = Gen_PlusCalculator.Create(CancelToken);

                string sum = string.Empty;
                PackMe_IHM.LaunchOpProgress(calculator,
                                            () => sum = calculator.Calcul(sevZippy.ArchiveLink, () => MD5.Create()),
                                            "Calcul de somme");

                HashCalc.Files.ClassicParser.Write(sevZippy.ArchiveLink, sum, HashType.md5, overwrite: true);
            }
            else
            {
                HeTrace.WriteLine($"[Run] MD5 disabled", this);
            }
            #endregion
        }
示例#23
0
        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);
            }
        }
示例#24
0
        public GameDataCont InjectGame(string gamePath)
        {
            HeTrace.WriteLine("Dpg Step");

            string dpgFile = Path.Combine(gamePath, "DPGame.json");

            // Check if DPG file exists
            if (!File.Exists(dpgFile))
            {
                DPGMakerCore dpgMaker = new DPGMakerCore();
                dpgMaker.MakeDPG_Folder(gamePath);
            }

            GamePaths gpX = GamePaths.ReadFromJson(dpgFile);

            HeTrace.WriteLine($"Platform Step for '{gpX.Platform}'");
            string platformsFile = Path.Combine(Config.HLaunchBoxPath, Config.PlatformsFile);

            bool CheckIfInjectionNeeded = !XML_Custom.TestPresence(platformsFile, Tag.Platform, Tag.Name, gpX.Platform);

            if (CheckIfInjectionNeeded)
            {
                HeTrace.WriteLine($"Backup of platforms file");
                // Backup du fichier de la plateforme;
                BackupFile(platformsFile, _BackupFolder);

                string newPFile = IHMStatic.GetAFile(Config.LastTargetPath, $"Platform '{gpX.Platform}' doesn't exist. Select the xml file to inject for this platform", "xml");
                if (string.IsNullOrEmpty(newPFile))
                {
                    throw new Exception("File for injection is not filled");
                }

                // Vérification que c'est la bonne plateforme
                if (!XML_Custom.TestPresence(newPFile, Tag.Platform, Tag.Name, gpX.Platform))
                {
                    throw new Exception("File doesn't contain the good platform");
                }

                HeTrace.WriteLine($"Injecting {gpX.Platform} in platforms file for {gpX.Platform}");
                InjectPlatform(gpX.Platform, newPFile);
            }

            ContPlatFolders zePlatform = XML_Platforms.GetPlatformPaths(platformsFile, gpX.Platform);

            HeTrace.WriteLine("Preparing files");
            // Préparation des fichiers
            GameDataCont gdC = PrepareGDC(gamePath, gpX);

            // Manipulation des fichiers
            AssignTargets(gdC, gamePath, zePlatform);

            // --- Lecture de la plateforme
            string machineXMLFile = Path.Combine(Config.HLaunchBoxPath, Config.PlatformsFolder, $"{gpX.Platform}.xml");

            if (!File.Exists(machineXMLFile))
            {
                XML_Games.NewPlatform(machineXMLFile);
            }

            // Backup platform file
            BackupFile(machineXMLFile, _BackupFolder);
            HeTrace.WriteLine($"Backup of '{machineXMLFile}'");

            InjectInXMLFile(gamePath, gdC, machineXMLFile, zePlatform.FolderPath);

            HeTrace.WriteLine($"Game injected: {gdC.Title}");

            return(gdC);
        }
示例#25
0
        /// <summary>
        /// Load Language File
        /// </summary>
        /// <param name="xmlFile"></param>
        /// <returns></returns>
        internal static LangContent Load(string xmlFile)
        {

            XElement xelRoot = XElement.Load(xmlFile);
            LangContent lang = new LangContent();

            lang.Lang = xelRoot.Attribute(_LangAttr).Value;
            lang.Version = xelRoot.Attribute(_VersionAttr).Value;

            HeTrace.WriteLine($"Language {lang.Lang} - {lang.Version}, loading...");

            foreach (var element in xelRoot.Descendants())
            {
                switch (element.Name.LocalName)
                {
                    case "Add":
                        lang.AddExp = element.Attribute(_Value).Value;
                        break;

                    case "CCopy":
                        lang.CCopyExp = element.Attribute(_Value).Value;
                        break;

                    case "Ch_Games":
                        lang.Ch_Games = element.Attribute(_Value).Value;
                        break;

                    case "Ch_LBPath":
                        lang.Ch_LBPath = element.Attribute(_Value).Value;
                        break;

                    case "Ch_Path":
                        lang.Ch_Path = element.Attribute(_Value).Value;
                        break;

                    case "Ch_System":
                        lang.Ch_System = element.Attribute(_Value).Value;
                        break;

                    case "Cancel":
                        lang.CancelExp = element.Attribute(_Value).Value;
                        break;

                    case "Cheats":
                        lang.CheatsExp = element.Attribute(_Value).Value;
                        break;

                    case "CheatsCopy":
                        lang.Copy_Cheats = element.Attribute(_Value).Value;
                        break;

                    case "Compression":
                        lang.CompExp = element.Attribute(_Value).Value;
                        break;

                    case "Comp_LBMin":
                        lang.CompLBMin = element.Attribute(_Value).Value;
                        break;

                    case "Comp_LBMoy":
                        lang.CompLBMoy = element.Attribute(_Value).Value;
                        break;

                    case "Comp_LBMax":
                        lang.CompLBMax = element.Attribute(_Value).Value;
                        break;

                    case "Comp_Z":
                        lang.CompZExp = element.Attribute(_Value).Value;
                        break;

                    case "Comp_7Z":
                        lang.Comp7ZExp = element.Attribute(_Value).Value;
                        break;

                    case "CheatsPath":
                        lang.CheatsPathExp = element.Attribute(_Value).Value;
                        break;

                    case "CompLvl":
                        lang.LvlCompExp = element.Attribute(_Value).Value;
                        break;

                    case "Config":
                        lang.ConfigExp = element.Attribute(_Value).Value;
                        break;

                    case "Credits":
                        lang.Credits = element.Attribute(_Value).Value;
                        break;

                    case "Delete":
                        lang.DeleteExp = element.Attribute(_Value).Value;
                        break;

                    case "EnXB":
                        lang.EnXBExp = element.Attribute(_Value).Value;
                        break;

                    case "File":
                        lang.FileExp = element.Attribute(_Value).Value;
                        break;
                    case "FileExists":
                        lang.FileEExp = element.Attribute(_Value).Value;
                        break;

                    case "FilesFound":
                        lang.FilesFoundExp = element.Attribute(_Value).Value;
                        break;

                    case "FolderExists":
                        lang.FolderEEXp = element.Attribute(_Value).Value;
                        break;

                    case "Games":
                        lang.GamesExp = element.Attribute(_Value).Value;
                        break;

                    case "General":
                        lang.GeneralExp = element.Attribute(_Value).Value;
                        break;

                    case "Help":
                        lang.Help = element.Attribute(_Value).Value;
                        break;

                    case "Infos":
                        lang.InfExp = element.Attribute(_Value).Value;
                        break;

                    case "InfosG":
                        lang.InfosGExp = element.Attribute(_Value).Value;
                        break;

                    case "L_Games":
                        lang.ListGamesExp = element.Attribute(_Value).Value;
                        break;

                    case "LBPath":
                        lang.LBPathExp = element.Attribute(_Value).Value;
                        break;

                    case "Loggers":
                        lang.LoggersExp = element.Attribute(_Value).Value;
                        break;

                    case "Main":
                        lang.MainExp = element.Attribute(_Value).Value;
                        break;

                    case "Manuals":
                        lang.ManualsExp = element.Attribute(_Value).Value;
                        break;

                    case "Musics":
                        lang.MusicsExp = element.Attribute(_Value).Value;
                        break;

                    case "OK":
                        lang.OkExp = element.Attribute(_Value).Value;
                        break;

                    case "Options":
                        lang.OptionsExp = element.Attribute(_Value).Value;
                        break;

                    case "OriXB":
                        lang.OriXBExp = element.Attribute(_Value).Value;
                        break;

                    case "Params":
                        lang.ParamsExp = element.Attribute(_Value).Value;
                        break;

                    case "Paths":
                        lang.PathsExp = element.Attribute(_Value).Value;
                        break;

                    case "Process":
                        lang.ProcessExp = element.Attribute(_Value).Value;
                        break;

                    case "Q_Pack":
                        lang.Q_Pack = element.Attribute(_Value).Value;
                        break;

                    case "Region":
                        lang.RegionExp = element.Attribute(_Value).Value;
                        break;

                    case "Result":
                        lang.ResultExp = element.Attribute(_Value).Value;
                        break;

                    case "S_Language":
                        lang.S_Language = element.Attribute(_Value).Value;
                        break;

                    case "Select":
                        lang.Select = element.Attribute(_Value).Value;
                        break;

                    case "Selected":
                        lang.SelectedExp = element.Attribute(_Value).Value;
                        break;


                    case "Submit":
                        lang.SubmitExp = element.Attribute(_Value).Value;
                        break;


                    case "Title":
                        lang.TitleExp = element.Attribute(_Value).Value;
                        break;

                    case "TViewFile":
                        lang.TViewFExp = element.Attribute(_Value).Value;
                        break;

                    case "TwoRulz":
                        lang.Rulz = element.Attribute(_Value).Value;
                        break;

                    case "Version":
                        lang.VersionExp = element.Attribute(_Value).Value;
                        break;

                    case "Videos":
                        lang.VideosExp = element.Attribute(_Value).Value;
                        break;

                    case "WPath":
                        lang.WPathExp = element.Attribute(_Value).Value;
                        break;

                    case "Window":
                        lang.WindowExp = element.Attribute(_Value).Value;
                        break;


                    default:
                        HeTrace.WriteLine($"\t{element.Name.LocalName} is not supported");
                        break;

                }
            }

            return lang;
        }
示例#26
0
        // ---

        /// <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));
        }