public void ExtractAll()
 {
     using (ArchiveFile archiveFile = new ArchiveFile(ArchiveFileName))
     {
         archiveFile.Extract(extractTo, true);
     }
 }
Пример #2
0
        public static string CreateProject(string dir, ArchiveFile template)
        {
            System.IO.Directory.CreateDirectory(dir);
            template.Extract(dir);

            return System.IO.Path.Combine(dir, "Game.nkproj");
        }
Пример #3
0
        private static async Task InstallAsync()
        {
            if (ExePath != null)
            {
                return;
            }

            var exePath = $"{WKHtmlFolder}/bin";

            using (var fileLock = await NFileLock.AcquireAsync(WKHtmlFolder + "/wkhtml.lock")) {
                if (!Directory.Exists(exePath))
                {
                    using (var client = new HttpClient())
                    {
                        var tmpPath = $"{WKHtmlFolder}/tmp.7z";
                        using (var fs = File.OpenWrite(tmpPath))
                        {
                            using (var s = await client.GetStreamAsync(GitHubReleaseUrl))
                            {
                                await s.CopyToAsync(fs);
                            }
                        }

                        using (ArchiveFile archiveFile = new ArchiveFile(tmpPath))
                        {
                            archiveFile.Extract(exePath); // extract all
                        }

                        File.Delete(tmpPath);
                    }
                }
                ExePath = $"{exePath}/wkhtmltox/bin";
            }
        }
Пример #4
0
        private void ExtractDATA()
        {
            O_TextBox.AppendText(Environment.NewLine + "");
            if (File.Exists(EDir + @"\data.tar"))
            {
                O_TextBox.AppendText(Environment.NewLine + "Unpacking 'data.tar'...");
                using (ArchiveFile tardataFile = new ArchiveFile(@"C:\E_temp\data.tar"))
                {
                    tardataFile.Extract(EDir);
                }
            }
            else if (File.Exists(EDir + @"\data.tar.gz"))
            {
                O_TextBox.AppendText(Environment.NewLine + "File is 'data.tar.gz'! Rerunning method...");
                O_TextBox.AppendText(Environment.NewLine + "Unpacking 'data.tar'...");
                var processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName  = Application.StartupPath + @"\7Z\7z.exe";
                processStartInfo.Arguments = @"e C:\E_temp\data.tar.gz";
                var proc = Process.Start(processStartInfo);
                proc.WaitForExit();
                File.Copy(@"data.tar", @"C:\E_temp\data.tar");
                File.Delete(@"data.tar");
                O_TextBox.AppendText(Environment.NewLine + "Method ran successfully! Unpacking 'data.tar'...");
                using (ArchiveFile tar2dataFile = new ArchiveFile(@"C:\E_temp\data.tar"))
                {
                    tar2dataFile.Extract(EDir);
                }
            }

            O_TextBox.AppendText(Environment.NewLine + "Unpacked 'data.tar'!");
        }
Пример #5
0
 public void extractIPA(string path)
 {
     clean();
     log("Extracting IPA " + path);
     try
     {
         using (ArchiveFile archiveFile = new ArchiveFile(path))
         {
             if (verbose)
             {
                 log("Extracting payload");
             }
             archiveFile.Extract("temp");
         }
         createDirIfDoesntExist("files\\Applications");
         foreach (string app in Directory.GetDirectories("temp\\Payload\\"))
         {
             if (verbose)
             {
                 log("Moving payload");
             }
             Directory.Move(app, "files\\Applications\\" + new DirectoryInfo(app).Name);
             if (verbose)
             {
                 log("Moved payload");
             }
         }
     }
     catch (Exception e)
     {
         log("Not a valid IPA / Access Denied");
         throw e;
     }
 }
Пример #6
0
 /// <summary>
 /// Распаковать архив
 /// </summary>
 /// <param name="pathFile">Путь к архиву</param>
 static void archive(string pathFile)
 {
     using (var archFile = new ArchiveFile(pathFile))
     {
         archFile.Extract("");//распаковываем в текущую дерикторию файл
     }
 }
Пример #7
0
        static void Main(string[] args)
        {
            using (ArchiveFile archiveFile = new ArchiveFile(@"Archive.arj"))
            {
                // extract all
                archiveFile.Extract("Output");
            }

            using (ArchiveFile archiveFile = new ArchiveFile("archive.arj"))
            {
                foreach (Entry entry in archiveFile.Entries)
                {
                    Console.WriteLine(entry.FileName);

                    // extract to file
                    entry.Extract(entry.FileName);

                    // extract to stream
                    MemoryStream memoryStream = new MemoryStream();
                    entry.Extract(memoryStream);
                }
            }

            Console.WriteLine("");
            Console.WriteLine("done");
            Console.ReadKey();
        }
Пример #8
0
 public async Task <bool> ExtractFileAsync(IFileInfo file)
 {
     using (var archiveFile = new ArchiveFile(File.OpenRead(file.PhysicalPath)))
     {
         var directory = new DirectoryInfo(file.IsDirectory ? file.PhysicalPath : (Path.GetDirectoryName(file.PhysicalPath)));
         archiveFile.Extract(directory.FullName);
     }
     return(await Task.FromResult(true));
 }
Пример #9
0
        /// <summary>
        /// Update the application when the user presses the update button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void item_Update_Click(object sender, EventArgs e)
        {
            try
            {
                // Cast the button & ignore if currently downloading.
                Button testButton = (Button)sender;
                if (_isCurrentlyDownloading)
                {
                    return;
                }

                // If the progressbar is max, we are done here.
                if (borderless_UpdateProgressBar.Value == borderless_UpdateProgressBar.MAX_VALUE)
                {
                    this.Close();
                }

                // Set flags & GUI
                testButton.Text         = "Downloading";
                _isCurrentlyDownloading = true;

                // Get the current game configuration & file paths.
                GameConfig gameConfig       = _gameConfigs[borderless_SelectGame.SelectedIndex];
                string     gameModDirectory = $"{LoaderPaths.GetModLoaderModDirectory()}\\{gameConfig.ModDirectory}";
                CallUpdateSourcesOnDownloadLink(gameModDirectory);                                   // May change modification URL download link.
                string fileName         = "Temp.tmp";
                string downloadLocation = $"{gameModDirectory}\\{fileName}";

                // Start the modification download.
                byte[] remoteFile = await FileDownloader.DownloadFile
                                    (
                    new Uri(_modificationUrl),
                    downloadProgressChanged : ClientOnDownloadProgressChanged
                                    );

                // Start unpacking
                testButton.Text = "Unpacking";
                testButton.Refresh();
                using (Stream stream = new MemoryStream(remoteFile))
                    using (ArchiveFile archiveFile = new ArchiveFile(stream))
                    {
                        archiveFile.Extract($"{gameModDirectory}\\");
                        CallUpdateSourcesOnExtractLink(archiveFile);
                    }

                // Cleanup
                File.Delete(downloadLocation);
                _isCurrentlyDownloading            = false;
                borderless_UpdateProgressBar.Value = borderless_UpdateProgressBar.MAX_VALUE;
                testButton.Text = "Close";
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                _isCurrentlyDownloading = false;
            }
        }
Пример #10
0
        private void BuildArchivePatches(string archive_sha, IEnumerable <PatchedFromArchive> group, Dictionary <string, string> absolute_paths)
        {
            var archive = IndexedArchives.First(a => a.Hash == archive_sha);
            var paths   = group.Select(g => g.From).ToHashSet();
            var streams = new Dictionary <string, MemoryStream>();

            Status($"Extracting {paths.Count} patch files from {archive.Name}");
            // First we fetch the source files from the input archive
            using (var a = new ArchiveFile(archive.AbsolutePath))
            {
                a.Extract(entry =>
                {
                    if (!paths.Contains(entry.FileName))
                    {
                        return(null);
                    }

                    var result = new MemoryStream();
                    streams.Add(entry.FileName, result);
                    return(result);
                }, false);
            }

            /*
             * using (var a = ArchiveFactory.Open(archive.AbsolutePath))
             * {
             *  foreach (var entry in a.Entries)
             *  {
             *      var path = entry.Key.Replace("/", "\\");
             *      if (!paths.Contains(path)) continue;
             *      var result = new MemoryStream();
             *      streams.Add(path, result);
             *      Info("Extracting {0}", path);
             *      using (var stream = entry.OpenEntryStream())
             *          stream.CopyTo(result);
             *  }
             * }*/

            var extracted = streams.ToDictionary(k => k.Key, v => v.Value.ToArray());

            // Now Create the patches
            Status("Building Patches for {0}", archive.Name);
            group.PMap(entry =>
            {
                Info("Patching {0}", entry.To);
                var ss = extracted[entry.From];
                using (var origin = new MemoryStream(ss))
                    using (var output = new MemoryStream())
                    {
                        var a = origin.ReadAll();
                        var b = LoadDataForTo(entry.To, absolute_paths);
                        BSDiff.Create(a, b, output);
                        entry.Patch = output.ToArray().ToBase64();
                    }
            });
        }
Пример #11
0
 private void ExtractDEB()
 {
     O_TextBox.AppendText(Environment.NewLine + "");
     O_TextBox.AppendText(Environment.NewLine + "Unpacking '" + DEB_TextBox.Text + "'...");
     using (ArchiveFile DEBFile = new ArchiveFile(DEB_TextBox.Text))
     {
         DEBFile.Extract(EDir);
         O_TextBox.AppendText(Environment.NewLine + "Unpacked DEB!");
     }
 }
Пример #12
0
 public static void ExtractTo(this ArchiveFile archive, string destination, string baseDir, string outputDir = null)
 {
     archive.Extract(delegate(Entry entry) {
         if (entry.IsFolder || SkipEntry(entry, baseDir))
         {
             return(null);
         }
         return(GetOutputPath(entry, destination, baseDir, outputDir));
     });
 }
Пример #13
0
 public static void ExtractTo(this ArchiveFile archive, string destination)
 {
     archive.Extract(delegate(Entry entry) {
         if (entry.IsFolder)
         {
             return(null);
         }
         return(Path.Combine(destination, entry.FileName));
     });
 }
Пример #14
0
        public static void ExtractArchiveToFolder()
        {
            CleanFilePaths(out string inPath, out string outPath);
            using (ArchiveFile archiveFile = new ArchiveFile(Path.GetFullPath(inPath), _7ZipLibrary))
            {
                archiveFile.Extract(Path.GetFullPath(outPath));
            }

            AssetDatabase.Refresh();
        }
Пример #15
0
        public static void AddMods(params string[] paths)
        {
            try
            {
                if (paths == null || paths.Length == 0)
                {
                    var dialog = new WinForms.OpenFileDialog();
                    // Dialog to select a mod archive
                    dialog.DefaultExt  = "zip";
                    dialog.Filter      = "Mod Archives (*.zip, *.rar, *.7z)|*.zip;*.rar;*.7z|all files|*";
                    dialog.Multiselect = true;
                    if (dialog.ShowDialog() == WinForms.DialogResult.OK)
                    {
                        paths = dialog.FileNames;
                    }
                    else
                    {
                        return;
                    }
                }
                var tmpFolder = Path.Combine(Path.GetTempPath(), "SMMMaddMod");

                if (!Directory.Exists(tmpFolder))
                {
                    Directory.CreateDirectory(tmpFolder);
                }

                foreach (var file in paths)
                {
                    // Separate the path and unzip mod
                    var splittedPath = file.Split('\\');
                    using (ArchiveFile archiveFile = new ArchiveFile(file))
                        archiveFile.Extract(tmpFolder);

                    // Get the name of the extracted folder (without the .zip at the end), not the
                    // full path
                    InstallMod(tmpFolder, splittedPath[splittedPath.GetLength(0) - 1].Split('.')[0]);
                    try
                    {
                        Directory.Delete(tmpFolder, true);
                    }
                    catch (DirectoryNotFoundException)
                    {
                        //the folder may be missing if it has no nativePC and moved the entire folder, deleting it
                    }

                    GetMods(); // Refresh the modlist
                }
                MhwModManager.MainWindow.Instance.UpdateModsList();
            }
            catch (Exception ex) { logStream.Error(ex); }
        }
Пример #16
0
        /*
         *  --------------
         *  Business Logic
         *  --------------
         */

        /// <summary>
        /// Update the application when the user presses the update button.
        /// </summary>
        private async void item_Update_Click(object sender, EventArgs e)
        {
            if (_isUpdating)
            {
                return;
            }

            if (_downloadComplete)
            {
                this.Close();
            }

            var senderControl = (Control)sender;

            senderControl.Text = "Downloading";

            // First obtain our mod list.
            _isUpdating = true;
            var enabledMods = GetEnabledMods();

            // Now we tally up the cumulative download size that is about to happen.
            enabledMods.ForEach(x => _totalDownloadSize += x.FileSize);

            // Update bottom left label.
            int filesComplete = 0;
            int totalFiles    = enabledMods.Count;

            borderless_FilesCompleteNumber.Text = $"{filesComplete:00}/{totalFiles:00}";
            foreach (var mod in enabledMods)
            {
                // Reset progress bar, start downloading with synced progress bar.
                borderless_FileUpdateProgressBar.Value = 0;
                byte[] file = await FileDownloader.DownloadFile(mod.DownloadLink, DownloadCompleted, UpdateFileProgress);

                // Extract the current file.
                using (Stream memoryStream = new MemoryStream(file))
                    using (ArchiveFile archiveFile = new ArchiveFile(memoryStream))
                    {
                        archiveFile.Extract(mod.GameModFolder, true);
                    }

                filesComplete += 1;
                _currentDownloadedCumulativeFileSize += mod.FileSize;
                borderless_FilesCompleteNumber.Text   = $"{filesComplete:00}/{totalFiles:00}";
            }

            AllDownloadsCompleted();
            _isUpdating        = false;
            _downloadComplete  = true;
            senderControl.Text = "Close";
        }
Пример #17
0
        private string ExtractFile(string fName)
        {
            // get full file name
            string filename = textBox1.Text + @"\" + fName;

            // create the directory name
            string dirname = filename.Substring(0, filename.Length - 4);

            // unarchive
            using (ArchiveFile archiveFile = new ArchiveFile(filename))
            {
                archiveFile.Extract(dirname); // extract all
            }
            return(dirname);
        }
Пример #18
0
 public static void ExtractGame(string sourceArchiveName, string targetDirectory, string archiveExtension)
 {
     if (File.Exists(sourceArchiveName + archiveExtension))
     {
         stopwatch.Start();
         ArchiveFile archiveFile = new ArchiveFile(sourceArchiveName + archiveExtension);
         archiveFile.Extract(targetDirectory);
         stopwatch.Stop();
         Console.WriteLine("[{0:mm\\:ss}] DONE", stopwatch.Elapsed);
         stopwatch.Reset();
     }
     else
     {
         Console.WriteLine("File not found! [" + sourceArchiveName + "].");
     }
 }
Пример #19
0
        public IActionResult FileDownloaderDrive([FromBody] DuAn duAn)
        {
            CustomResult cusRes = new CustomResult();

            try {
                if (String.IsNullOrEmpty(duAn.UrlDrive) || String.IsNullOrEmpty(duAn.DiaChi) || String.IsNullOrEmpty(duAn.TenLoai) || String.IsNullOrEmpty(duAn.Ma))
                {
                    cusRes.SetException(new Exception("Dữ liệu không hợp lệ. Vui lòng kiểm tra lại thông tin dự án"));
                    CommonMethods.notifycation_tele($"Đã tải ảnh thất bại T.T:%0ADự án: {duAn.Name ?? duAn.Ma}%0ALỗi: Vui lòng kiểm tra lại thông tin dự án.");
                }
                else
                {
                    var fileName = duAn.Ma;
                    fileName = CommonMethods.convertToNameFolder(fileName);
                    string zipPath     = Variables.SELENIUM_PATH_UPLOADS + $"\\{fileName}.7z";
                    string extractPath = Variables.SELENIUM_PATH_UPLOADS + $"\\{fileName}";
                    if (Directory.Exists(extractPath))
                    {
                        Directory.Delete(extractPath, true);
                    }
                    if (!Directory.Exists(extractPath))
                    {
                        Directory.CreateDirectory(extractPath);
                    }

                    var infoFile = FileDownloader.DownloadFileFromURLToPath(duAn.UrlDrive, zipPath);
                    if (infoFile != null)
                    {
                        using (ArchiveFile archiveFile = new ArchiveFile(zipPath)) {
                            archiveFile.Extract(extractPath);  // extract all
                        }

                        if (System.IO.File.Exists(zipPath))
                        {
                            System.IO.File.Delete(zipPath);
                        }
                        CommonMethods.notifycation_tele($"Đã tải ảnh thành công :))%0ATên dự án: {duAn.Name ?? "Không xác định"}%0AMã dự án: {duAn.Ma}%0AĐịa chỉ: {duAn.DiaChi}");
                    }
                    cusRes.IntResult = 1;
                }
            } catch (Exception ex) {
                CommonMethods.notifycation_tele($"Đã tải ảnh thất bại T.T:%0A%0ATên dự án: {duAn.Name ?? "Không xác định"}%0AMã dự án: {duAn.Ma}%0AĐịa chỉ: {duAn.DiaChi}%0ALỗi: {ex.Message} ");
                cusRes.SetException(ex);
            }
            return(Ok(cusRes));
        }
Пример #20
0
        static int Main(string[] args)
        {
            string fileName      = string.Empty;
            string target        = string.Empty;
            string source        = string.Empty;
            int    selectedValue = SelectDeployment(ref fileName, ref source);

            if (fileName != null && fileName != "" && source != null && source != "")
            {
                target = GetTargetPath(selectedValue);
                string source1 = Path.Combine(source, fileName);
                if (target != null && target != string.Empty)
                {
                    string target1 = Path.Combine(target, fileName);
                    if (File.Exists(source1))
                    {
                        DeleteFiles(target);
                        System.IO.File.Copy(source1, target1, true);
                        if (File.Exists(target1))
                        {
                            System.Console.WriteLine("Copy deployment Initiated...............................");
                            using (ArchiveFile file = new ArchiveFile(target1))
                            {
                                file.Extract(target, true);
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("File Not Found in Directory");
                        }
                    }
                    else
                    {
                        System.Console.WriteLine("File Not Found in Network");
                    }
                    System.Console.Read();
                }
            }
            else
            {
                Console.WriteLine("File.Source Not Found");
            }
            return(0);
        }
Пример #21
0
        public static void DownloadAndInstall()
        {
            string thisDir = Path.Combine(Directory.GetCurrentDirectory());

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Build.DownloadLink);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                string update = "";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    var fn = response.Headers["Content-Disposition"].Split(new string[] { "=" }, StringSplitOptions.None)[1].Replace("\"", "");
                    if (fn.Contains("?"))
                    {
                        fn = fn.Replace("?", "");
                    }
                    var    responseStream = response.GetResponseStream();
                    string name           = fn;

                    Write("Downloading update...");
                    // Otherwise do download.
                    using (var fileStream = File.Open(Path.Combine(thisDir, fn), FileMode.Create))
                    {
                        responseStream.CopyTo(fileStream);
                    }
                    update = Path.Combine(thisDir, fn);
                    Write("Download done. Extracting...");

                    ArchiveFile file = new ArchiveFile(update);
                    file.Extract(thisDir, true);

                    file.Dispose();
                    File.Delete(update);
                    Write("Update installed successfully!");
                    Thread.Sleep(1300);
                    Launch();
                }
            }
            catch (SevenZipException e)
            {
                Write("Archieve error: {0}", e.Message);
            }
        }
Пример #22
0
        private bool ExtractFile(FileInfo fileDownloadInfo, string destinyPath)
        {
            try
            {
                //Extract compress file
                if (fileDownloadInfo.Extension.Equals(Constantes.RAR)) //rar
                {
                    using ArchiveFile archiveFile = new ArchiveFile(fileDownloadInfo.FullName);
                    archiveFile.Extract(Environment.CurrentDirectory + Constantes.DownloadComics);
                }
                else //zip
                {
                    ZipFile.ExtractToDirectory(fileDownloadInfo.FullName, Environment.CurrentDirectory + Constantes.DownloadComics);
                }

                //Create/Rename extract file(s)
                int countFiles = new DirectoryInfo(Environment.CurrentDirectory + Constantes.DownloadComics).GetFiles().Count();
                if (countFiles == 0) //folder
                {
                    RenameFolderExtract(destinyPath);
                }

                if (countFiles == 1) //file
                {
                    RenameFileExtract(fileDownloadInfo, destinyPath);
                }

                if (countFiles > 1) //collection photo
                {
                    RenameCollectionExtract(fileDownloadInfo, destinyPath);
                }

                Directory.Delete(Environment.CurrentDirectory + Constantes.DownloadComics, true);
                return(true);
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.Error(string.Format("Error en el método: '{0}', Mensaje de error: '{1}'", MethodBase.GetCurrentMethod().Name, ex.Message));
                }
                return(false);
            }
        }
Пример #23
0
        /// <summary>
        /// Extracts the content of the defined archive to the destination path provided
        /// </summary>
        /// <param name="from">The path to the archive</param>
        /// <param name="to">The extraction path</param>
        /// <returns>True when the operation is completed without errors, False otherwise</returns>
        public bool Unzip(string from, string to)
        {
            var result = true;
            try
            {
                var libsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libs");
                var libraryFilePath = Path.Combine(libsPath, Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
                using (var archiveFile = new ArchiveFile(from, libraryFilePath))
                {
                    archiveFile.Extract(to);
                }
            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }
Пример #24
0
        private void UnZip(string name)
        {
            Trace.TraceInformation($"UnZip: {name}");
            var dirPath = GetDirectoryUnZip(name);

            History += "Распаковка нового архива " + name + " в " + dirPath;

            if (Directory.Exists(dirPath))
            {
                Directory.Delete(dirPath, true);
            }

            Directory.CreateDirectory(dirPath);

            using (ArchiveFile archiveFile = new ArchiveFile(name))
            {
                archiveFile.Extract(dirPath);
            }
            File.Delete(name);
        }
Пример #25
0
        private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            pbUpdate.Visible = false;
            pbUpdate.Value   = 0;

            string coreFolder = Path.GetDirectoryName(_corePath);

            coreFolder = Path.GetFullPath(Path.Combine(coreFolder, @"..\"));

            using (ArchiveFile archiveFile = new ArchiveFile(_tempFile))
            {
                archiveFile.Extract(_tempDir);
            }

            _tempDir = Path.GetFullPath(Path.Combine(_tempDir, @"game\"));

            Utils.CopyFolder(_tempDir, coreFolder);

            File.Delete(_tempFile);

            Application.Restart();
        }
Пример #26
0
        private void ExtractFile(FileInfo fiObj)
        {
            // get full file name
            string filename = directoryTextBox.Text + @"\" + fiObj.Name;

            statusTextBox.Text += "Unarchiving " + filename + "\r\n";

            // create the directory name
            string dirname = filename.Substring(0, filename.Length - 4);

            // unarchive
            try
            {
                using (ArchiveFile archiveFile = new ArchiveFile(filename))
                {
                    archiveFile.Extract(dirname); // extract all
                }
            }
            catch (Exception ex)
            {
                statusTextBox.Text += ex.Message + "\r\n";
            }
        }
Пример #27
0
        public DownloaderResult DownloadFolder(Uri uri)
        {
            var client = new MegaApiClient();

            client.LoginAnonymous();

            Logger.Debug("Successfully log into mega");
            try
            {
                var nodes = client.GetNodesFromLink(uri)
                            .Where(x => x.Type == NodeType.File && x.Name.EndsWith(".rar"))
                            .ToArray();
                if (nodes.Length > 1)
                {
                    throw new Exception("There's more that 1 rar file on the mega folder");
                }
                else if (nodes.Length <= 0)
                {
                    throw new Exception("There's no rar in the remote mega folder");
                }

                Logger.Debug("Found a rar file in {0}", uri);

                var node = nodes[0];


                var path = Path.GetTempFileName();
                Logger.Debug("Downloading {0} into {1}", node.Name, path);
                try
                {
                    using var file = File.Open(path, FileMode.Truncate);

                    {
                        using var downloadStream = client.Download(node);
                        downloadStream.CopyTo(file);
                    }

                    file.Seek(0, 0);
                    using var rar = new ArchiveFile(file);
                    var dir = path + ".extracted";
                    Logger.Debug("Extracting into {0}", dir);
                    Directory.CreateDirectory(dir);
                    try
                    {
                        rar.Extract(dir);
                        return(new DownloaderResult(dir, node.Name, node.Id, node.Owner, node.ModificationDate ?? node.CreationDate));
                    }
                    catch
                    {
                        Logger.Warning("Deleting {0} before throwing", dir);
                        Directory.Delete(dir, true);
                        throw;
                    }
                }
                finally
                {
                    Logger.Debug("Removing temporary file {0}", path);
                    File.Delete(path);
                }
            }
            finally
            {
                client.Logout();
            }
        }
Пример #28
0
 public void extractDeb(string path)
 {
     clean();
     log("Extracting " + path);
     try
     {
         using (ArchiveFile archiveFile = new ArchiveFile(path))
         {
             if (verbose)
             {
                 log("Extracting data.tar.lzma || data.tar.gz");
             }
             archiveFile.Extract("temp");
             if (verbose)
             {
                 log("Extracted");
             }
         }
         if (verbose)
         {
             log("Extracting data.tar");
         }
         var p = Process.Start(@"7z.exe", "e " + "temp\\data.tar." + (File.Exists("temp\\data.tar.lzma") ? "lzma" : "gz") + " -o.");
         if (verbose)
         {
             log("Waiting for subprocess to complete");
         }
         p.WaitForExit();
         if (verbose)
         {
             log("Extracting control file");
         }
         p = Process.Start(@"7z.exe", "e " + "temp\\control.tar.gz -o.");
         p.WaitForExit();
         if (verbose)
         {
             log("Successfully extracted data.tar");
         }
         using (ArchiveFile archiveFile = new ArchiveFile("data.tar"))
         {
             if (verbose)
             {
                 log("Extracting deb files");
             }
             archiveFile.Extract("files");
             if (verbose)
             {
                 log("Extracted");
             }
         }
         using (ArchiveFile archiveFile = new ArchiveFile("control.tar"))
         {
             archiveFile.Extract(".");
         }
         Dictionary <string, string> control = new Dictionary <string, string>();
         foreach (string i in File.ReadAllLines("control"))
         {
             var j = i.Split(':');
             if (j.Length < 2)
             {
                 return;
             }
             control.Add(j[0].ToLower().Replace(" ", ""), j[1]);
         }
         if (Directory.Exists("files\\Applications") && control.ContainsKey("skipsigning"))
         {
             using (ArchiveFile archiveFile = new ArchiveFile("data.tar"))
             {
                 archiveFile.Extract("temp");
             }
             foreach (string app in Directory.GetDirectories("temp\\Applications\\"))
             {
                 File.Create(app.Replace("temp\\", "files\\") + "\\skip-signing").Close();
             }
         }
         clean();
     }
     catch (Exception e)
     {
         log("Not a valid deb file / Access Denied");
         throw e;
     };
 }
Пример #29
0
 public void extractZip(string path)
 {
     log("Extracting Zip " + path);
     try
     {
         using (ArchiveFile archiveFile = new ArchiveFile(path))
         {
             if (verbose)
             {
                 log("Extracting zip");
             }
             archiveFile.Extract("temp");
             if (verbose)
             {
                 log("Extracted zip");
             }
         }
     }
     catch (Exception e)
     {
         log("Not a valid ZIP archive / Access Denied");
         throw e;
     }
     if (Directory.Exists("temp\\bootstrap\\"))
     {
         log("Found bootstrap");
         if (Directory.Exists("temp\\bootstrap\\Library\\SBInject\\"))
         {
             createDirIfDoesntExist("files\\usr\\lib\\SBInject");
             foreach (string file in Directory.GetFiles("temp\\bootstrap\\Library\\SBInject\\"))
             {
                 File.Move(file, "files\\usr\\lib\\SBInject\\" + new FileInfo(file).Name);
             }
             foreach (string file in Directory.GetDirectories("temp\\bootstrap\\Library\\SBInject\\"))
             {
                 Directory.Move(file, "files\\usr\\lib\\SBInject\\" + new DirectoryInfo(file).Name);
             }
             Directory.Delete("temp\\bootstrap\\Library\\SBInject", true);
         }
         moveDirIfPresent("temp\\bootstrap\\Library\\Themes\\", "files\\bootstrap\\Library\\Themes\\");
         foreach (string dir in Directory.GetDirectories("temp"))
         {
             FileSystem.MoveDirectory(dir, "files\\" + new DirectoryInfo(dir).Name, true);
         }
         foreach (string file in Directory.GetFiles("temp"))
         {
             File.Copy(file, "files\\" + new FileInfo(file).Name, true);
         }
     }
     else
     {
         log("Unrecognised format. Determining ability to install");
         List <string> exts        = new List <string>();
         List <string> directories = new List <string>();
         foreach (string dir in Directory.GetDirectories("temp", "*", System.IO.SearchOption.AllDirectories))
         {
             directories.Add(new DirectoryInfo(dir).Name);
         }
         if (directories.Contains("bootstrap"))
         {
             log("Found bootstrap");
             foreach (string dir in Directory.GetDirectories("temp", "*", System.IO.SearchOption.AllDirectories))
             {
                 if (new DirectoryInfo(dir).Name == "bootstrap")
                 {
                     createDirIfDoesntExist("files\\bootstrap\\");
                     FileSystem.CopyDirectory(dir, "files\\bootstrap");
                     moveDirIfPresent("files\\bootstrap\\SBInject", "files\\bootstrap\\Library\\SBInject", "files\\bootstrap\\Library\\SBInject");
                     break;
                 }
             }
         }
         else
         {
             foreach (string i in Directory.GetFiles("temp"))
             {
                 string ext = new FileInfo(i).Extension;
                 if (!exts.Contains(ext))
                 {
                     exts.Add(ext);
                 }
             }
             if (exts.Count == 2 && exts.Contains(".dylib") && exts.Contains(".plist"))
             {
                 log("Substrate Addon. Installing");
                 createDirIfDoesntExist("files\\usr\\lib\\SBInject");
                 foreach (string i in Directory.GetFiles("temp"))
                 {
                     File.Copy(i, "files\\usr\\lib\\SBInject\\" + new FileInfo(i).Name, true);
                 }
                 moveDirIfPresent("files\\Library\\PreferenceBundles\\", "files\\bootstrap\\Library\\PreferenceBundles\\");
                 moveDirIfPresent("files\\Library\\PreferenceLoader\\", "files\\bootstrap\\Library\\PreferenceLoader\\");
                 moveDirIfPresent("files\\Library\\LaunchDaemons\\", "files\\bootstrap\\Library\\LaunchDaemons\\");
             }
             else
             {
                 MessageBox.Show("Unsafe to install. To install this tweak you must do so manually. Press enter to continue...");
                 Environment.Exit(0);
             }
         }
     }
 }
Пример #30
0
        public static void Extract(string FilePath)
        {
            foundFolder       = false;
            Form1.AddingStart = true;
            Form1.AddingEnd   = false;
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args) {
                try {
                    string AddonName;
                    Console.WriteLine(FilePath);
                    AddonName            = Path.GetFileNameWithoutExtension(FilePath);
                    AddonName            = AddonName.Replace("_", " ");
                    AddonName            = Regex.Replace(AddonName, "(?<=[a-z])([A-Z])", " $1");
                    string extensionName = Path.GetExtension(FilePath);
                    Console.WriteLine("Compressed addon is " + extensionName);
                    Console.WriteLine("Adding Addon " + AddonName);
                    Directory.CreateDirectory(managerDir + AddonName);
                    if (extensionName == ".7z")
                    {
                        Console.WriteLine("Using 7za.exe");
                        string zPath = @"Resources\7za.exe";// change the path and give yours
                        try {
                            ProcessStartInfo pro = new ProcessStartInfo();
                            pro.WindowStyle      = ProcessWindowStyle.Hidden;
                            pro.FileName         = zPath;
                            pro.Arguments        = "x \"" + FilePath + "\" -o" + "\"" + managerDir + AddonName + "\"";
                            Process x            = Process.Start(pro);
                            x.WaitForExit();
                        }
                        catch (System.Exception Ex) {
                            Console.WriteLine("Error in .7z extraction " + Ex);
                            //DO logic here
                        }
                        DirCheckLister(AddonName);
                    }
                    else
                    {
                        if (extensionName == ".bsp" || extensionName == ".py")
                        {
                            Console.WriteLine("Since file is " + extensionName + " There is no extracting to be done, skipping to next task.");
                            CreateList(managerDir + AddonName, AddonName);
                        }
                        else
                        {
                            using (ArchiveFile archiveFile = new ArchiveFile(FilePath)) {
                                archiveFile.Extract(managerDir + AddonName); // extract all
                            }

                            DirCheckLister(AddonName);
                        }
                    }
                    if (FilePath.Contains("Download"))
                    {
                        File.Delete(FilePath);
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine("An error occured in Extract: " + ex.Message);
                }
            });
            bw.RunWorkerAsync();
        }
Пример #31
0
 // if you want to extract all entries from the archive, use ArchiveFile.Extract
 // this is a lot more performant than calling Extract on each entry individually
 static void ExtractAll(string outputPath, ArchiveFile archiveFile)
 {
     Console.WriteLine("Extracting all entries to \".\\" + outputPath + "\"");
     archiveFile.Extract(outputPath, true);
 }