Example #1
0
        protected bool CopyFiles(GameDataCont gdC)
        {
            var files = new List <DataTrans>();

            files.AddRange(gdC.Applications);
            files.AddRange(gdC.Manuals);
            files.AddRange(gdC.Musics);
            files.AddRange(gdC.Videos);

            CopyFExt copyObj = new CopyFExt();

            copyObj.AskToUser     += IHMStatic.Ask4_FileConflict2;
            copyObj.UpdateStatus  += (x, y) => HeTrace.WriteLine(y.Message);
            copyObj.UpdateStatusT += (x, y) => HeTrace.WriteLine(y.Message);

            bool resultat = false;

            SafeBoxes.LaunchDouble(copyObj, () => resultat = copyObj.CopyN(files), "Copy files");

            if (!resultat)
            {
                return(false);
            }

            SafeBoxes.LaunchDouble(copyObj, () => resultat = copyObj.CopyN(gdC.Images), "Copy Images files");

            return(resultat);
        }
Example #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="timeSleep"></param>
        /// <returns></returns>
        public object Run(int timeSleep = 10)
        {
            foreach (var zeGame in _SelectedGames)
            {
                HeTrace.WriteLine($"[Main] PackMe for '{zeGame.Title}' | '{zeGame.Id}'");

                // Système de log par jeu
                if (Config.UseLogFile)
                {
                    MeSimpleLog gameLog = new MeSimpleLog(Path.Combine(_WFolder, $"{_ZePlatform.Name} - {zeGame.ExploitableFileName}.log"))
                    {
                    };
                    gameLog.AddCaller(this);
                    HeTrace.AddLogger("game", gameLog);
                }

                try
                {
                    PackMe(zeGame);
                }
                catch (Exception exc)
                {
                    HeTrace.WriteLine(exc.Message, this);
                    HeTrace.WriteLine(exc.StackTrace, this);
                    SafeBoxes.Dispatch_Mbox(this, exc.Message, "Error", E_DxButtons.Ok);
                }
                finally
                {
                    HeTrace.RemoveLogger("game");
                }
            }
            return(null);
        }
Example #3
0
        /// <summary>
        /// Check if directory structure match with real structure
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        private bool?CheckDirectoryStructure(string root)
        {
            HeTrace.WriteLine("Check directory structure");


            // Vérification des dossiers;
            string gameF     = Path.Combine(root, Config.Games);
            bool   gameDirOk = Directory.Exists(gameF);

            if (!gameDirOk)
            {
                gameF = SafeBoxes.SelectFolder(gameF, "Game folder doesn't match, select folder");
                if (!gameF.StartsWith(root))
                {
                    return(false);
                }

                gameDirOk = Directory.Exists(gameF);
                if (!gameDirOk)
                {
                    return(false);
                }

                Config.Games = Path.GetFileName(gameF);

                Config.Save();
            }

            bool cheatCDirOk = Directory.Exists(Path.Combine(root, Config.CheatCodes));
            bool imageDirOk  = Directory.Exists(Path.Combine(root, Config.Images));
            bool manualDirOk = Directory.Exists(Path.Combine(root, Config.Manuals));
            bool musicDirOk  = Directory.Exists(Path.Combine(root, Config.Musics));
            bool videoDirOk  = Directory.Exists(Path.Combine(root, Config.Videos));

            bool isOk = true;

            isOk &= gameDirOk;
            isOk &= cheatCDirOk;
            isOk &= imageDirOk;
            isOk &= manualDirOk;
            isOk &= musicDirOk;
            isOk &= videoDirOk;

            bool?res = true;

            if (!isOk)
            {
                res = SafeBoxes.ShowStatus("Structure seems to have directories missing or different, continue ? ", "Warning",
                                           new Dictionary <string, bool?>()
                {
                    { "Games", gameDirOk }, { "Cheats", cheatCDirOk }, { "Images", imageDirOk }, { "Manuals", manualDirOk }, { "Musics", musicDirOk }, { "Videos", videoDirOk }
                },
                                           "#FF60DC32", "#FFFF2323"
                                           );
            }
            //   IHMStatic.AskDxMBox("Structure seems to have directories missing or different, continue ? ", "Warning", E_DxButtons.Yes | E_DxButtons.No, "If you continue, files into folders will not been copied");

            return(res);
        }
Example #4
0
        private void Depack7Zip(string pathLink, string tmpPath)
        {
            // Extraction des fichiers
            SevenZipDecompression sevZippy = new SevenZipDecompression()
            {
                TokenSource = this.TokenSource,
                IsPaused    = this.IsPaused,
            };

            SafeBoxes.LaunchDouble(sevZippy, () => sevZippy.ExtractAll(pathLink, tmpPath), "Zip Extraction");
        }
Example #5
0
        void DPG7ZipCore(DataRep zF, string gamePath)
        {
            // Extraction des fichiers xml
            SevenZipDecompression zippy = new SevenZipDecompression()
            {
                TokenSource = this.TokenSource,
                IsPaused    = this.IsPaused,
            };

            SafeBoxes.LaunchDouble(zippy, () => zippy.ExtractSpecificFiles(zF.CurrentPath, gamePath,
                                                                           "NBGame.xml", "TBGame.xml", "EBGame.xml", "DPGame.json"),
                                   "SevenZip Extraction");
        }
Example #6
0
        internal List <string> GetFilesByPredict(string toSearch, string folder, string mediatype)
        {
            // array of files with a part of the name
            string[] files = Directory.GetFiles(Path.GetFullPath(folder, Common.Config.HLaunchBoxPath), $"{toSearch}*.*", SearchOption.AllDirectories);

            #region processing on files found
            // bypass -
            string[] bypass = new string[] { "-", " -" };

            List <string> filteredFiles = new List <string>();
            foreach (string fichier in files)
            {
                string filename = Path.GetFileNameWithoutExtension(fichier);
                // Test if total match
                if (filename.Equals(toSearch))
                {
                    // On ajoute à la liste des checkbox
                    filteredFiles.Add(fichier);
                }
                //Test if match with bypass
                else
                {
                    // On test avec chaque bypass
                    foreach (var b in bypass)
                    {
                        if (filename.StartsWith(toSearch + b))
                        {
                            // On ajoute à la liste des checkbox
                            filteredFiles.Add(fichier);
                            break;
                        }
                    }
                }
            }

            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);
        }
Example #7
0
        void DPGZipCore(DataRep archive, string gamePath)
        {
            // Extraction des fichiers xml
            ZipDecompression zippy = new ZipDecompression()
            {
                TokenSource = this.TokenSource,
                IsPaused    = this.IsPaused,
            };


            SafeBoxes.LaunchDouble(zippy, () => zippy.ExtractSpecificFiles(archive.CurrentPath, gamePath,
                                                                           "NBGame.xml", "TBGame.xml", "EBGame.xml", "DPGame.json"),
                                   "Zip Extraction");

            /*var res = PackMe_IHM.ZipCompressFolder(zippy, () => zippy.CompressFolder(
             *                           gamePath, title, PS.Default.cZipCompLvl), "Compression Zip");*/
        }
Example #8
0
        internal static void CheckGamesValidity(ObservableCollection <ShortGame> selectedGames, string selectedPlatform)
        {
            string platformXmlFile = Path.Combine(Config.HLaunchBoxPath, Config.PlatformsFolder, $"{selectedPlatform}.xml");

            //IEnumerable<ShortGame> filteredGames = new List<ShortGame>(selectedGames);
            foreach (var g in selectedGames.ToList())
            {
                Dictionary <string, bool?> res = CheckGameValidity(g, platformXmlFile);

                bool?keepit = true;

                // Erreur sur le chemin principal
                if (res == null)
                {
                    DxMBox.ShowDial($"{LanguageManager.Instance.Lang.S_MainLAppBroken} '{g.Title}'");

                    keepit = false;
                }
                else
                {
                    bool test = true;
                    // Vérification si c'est utile d'afficher la fenêtre
                    foreach (var kvp in res)
                    {
                        test &= (bool)kvp.Value;
                    }

                    if (test == false)
                    {
                        keepit = SafeBoxes.ShowStatus(
                            $"{LanguageManager.Instance.Lang.S_GameStatus4} '{g.Title}'." +
                            $"\n{LanguageManager.Instance.Lang.Q_KeepIt}",
                            LanguageManager.Instance.Lang.S_GameStatus,
                            res);
                    }
                }

                if (keepit != true)
                {
                    selectedGames.Remove(g);
                    g.IsSelected = false;
                    continue;
                }
            }
        }
Example #9
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
        }
Example #10
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));
        }