Skip to content

Commit

Permalink
Merge pull request #1 from Neinndall/dev_v1.1.0.0
Browse files Browse the repository at this point in the history
Major Update v1.1.0.0
  • Loading branch information
Neinndall authored Dec 30, 2024
2 parents ff5f468 + 039fc7c commit 26ef77a
Show file tree
Hide file tree
Showing 18 changed files with 746 additions and 498 deletions.
6 changes: 3 additions & 3 deletions PBE_AssetsDownloader.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<ApplicationIcon>img\Icon.ico</ApplicationIcon>
<Version>1.0.0.0-Beta</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<Version>1.1.0.0-Beta</Version>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<LangVersion>latest</LangVersion>
<UseWindowsForms>true</UseWindowsForms>
Expand Down
2 changes: 1 addition & 1 deletion PBE_AssetsDownloader/Info/ApplicationInfos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Reflection;
using System.Windows.Forms;

namespace PBE_NewFileExtractor.Info
namespace PBE_AssetsDownloader.Info
{
public static class ApplicationInfos
{
Expand Down
60 changes: 33 additions & 27 deletions PBE_AssetsDownloader/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
using Serilog;
using System.Windows.Forms;
using Newtonsoft.Json;
using PBE_NewFileExtractor.UI;
using PBE_NewFileExtractor.Utils;
using PBE_NewFileExtractor.Services;
using PBE_AssetsDownloader.UI;
using PBE_AssetsDownloader.Utils;
using PBE_AssetsDownloader.Services;

namespace PBE_NewFileExtractor
namespace PBE_AssetsDownloader
{
static class Program
{
Expand All @@ -18,12 +18,12 @@ static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

// Iniciar el formulario principal
Application.Run(new MainForm());
}

public static async Task RunExtraction(string newHashesDirectory, string oldHashesDirectory, bool syncHashesWithCDTB, Action<string> logAction)
public static async Task<string> RunExtraction(string newHashesDirectory, string oldHashesDirectory, bool syncHashesWithCDTB, bool autoCopyHashes, Action<string> logAction)
{
// Configurar el logger
Log.Logger = new LoggerConfiguration()
Expand All @@ -32,38 +32,50 @@ public static async Task RunExtraction(string newHashesDirectory, string oldHash

try
{
// Crear instancia de DirectoriesCreator y AssetDownloader
var directoryCreator = new DirectoriesCreator();
await directoryCreator.CreateAllDirectoriesAsync();

var httpClient = new HttpClient();
var assetDownloader = new AssetDownloader(httpClient, directoryCreator);

// Crear todas las carpetas necesarias
await directoryCreator.CreateAllDirectoriesAsync().ConfigureAwait(false);

var requests = new Requests(httpClient, directoryCreator);


var comparator = new FilesComparator(
Path.Combine(newHashesDirectory, "hashes.game.txt"),
Path.Combine(oldHashesDirectory, "hashes.game.txt"),
Path.Combine(newHashesDirectory, "hashes.lcu.txt"),
Path.Combine(oldHashesDirectory, "hashes.lcu.txt"),
Path.Combine("Resources", "differences_game.txt"),
Path.Combine("Resources", "differences_lcu.txt")
);
// Obtener la ruta de Resources con timestamp
var resourcesPath = directoryCreator.ResourcesPath;

// Crear instancia de FilesComparator
var comparator = new FilesComparator();
comparator.HashesComparator(newHashesDirectory, oldHashesDirectory, resourcesPath);

// Mensajes de comparación
await comparator.CheckFilesDiffAsync();

// Crear una instancia de HashesManager para comparar hashes
var hashesManager = new HashesManager(oldHashesDirectory, newHashesDirectory);
var hashesManager = new HashesManager(oldHashesDirectory, newHashesDirectory, resourcesPath);
await hashesManager.CompareHashesAsync();

// Crear una instancia de Resources para descargar los assets
var resourcesDownloader = new Resources(new HttpClient());
var resourcesDownloader = new Resources(httpClient, directoryCreator); // Pasar directoryCreator aquí
await resourcesDownloader.DownloadAssetsAsync();

Log.Information("Download complete.");

// Crear una instancia de HashCopier para hacer el copiar de hashes si está activado
if (autoCopyHashes)
{
var hashCopier = new HashCopier();
return await hashCopier.CopyNewHashesToOlds(newHashesDirectory, oldHashesDirectory);
}

return "Hashes were not replaced because autoCopyHashes is disabled.";
}
catch (Exception ex)
{
Log.Fatal(ex, "An unexpected error has occurred.");
Log.Fatal(ex, "StackTrace: {0}", ex.StackTrace);
return "An error occurred during the process.";
}
finally
{
Expand All @@ -86,11 +98,5 @@ public void Emit(Serilog.Events.LogEvent logEvent)
_logAction(logEvent.RenderMessage());
}
}

// Guardar por si acaso
// public class AppSettings
// {
// public bool syncHashesWithCDTB { get; set; }
// }
}
}
}
182 changes: 117 additions & 65 deletions PBE_AssetsDownloader/Services/AssetDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,104 +4,156 @@
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using PBE_AssetsDownloader.Utils;

namespace PBE_NewFileExtractor.Services
namespace PBE_AssetsDownloader.Services
{
public class AssetDownloader
{
private readonly HttpClient _httpClient;
private readonly DirectoriesCreator _directoriesCreator; // Crea una instancia de DirectoriesCreator

public AssetDownloader(HttpClient httpClient)
// Lista de extensiones excluidas
private readonly List<string> _excludedExtensions = new()
{
".luabin", ".luabin64", ".preload", ".scb",
".sco", ".skl", ".mapgeo", ".subchunktoc", ".stringtable",
".anm"
};

public AssetDownloader(HttpClient httpClient, DirectoriesCreator directoriesCreator)
{
_httpClient = httpClient;
_directoriesCreator = directoriesCreator; // Inicializar el creador de directorios
}

public async Task<List<string>> DownloadAssets(IEnumerable<string> differences, string baseUrl, string downloadDirectory, Action<string> logAction)
private string AdjustUrlBasedOnRules(string url)
{
var notFoundUrls = new List<string>();

foreach (var line in differences)
// Cambiar extensión o ignorar según las reglas específicas
if (url.EndsWith(".dds") &&
(url.Contains("/loot/companions/") ||
url.Contains("2x_") ||
url.Contains("4x_") ||
url.Contains("tx_cm") ||
url.Contains("/particles/") ||
url.Contains("/clash/") ||
url.Contains("/skins/") ||
url.Contains("uiautoatlas") ||
url.Contains("/summonerbanners/") ||
url.Contains("/hud/") ||
url.Contains("/regalia/")))
{
var url = baseUrl + line.Split(' ').Skip(1).First();

// Si la URL termina en ".dds" y contiene patrones específicos, cambiar la extensión a ".png"
if (url.EndsWith(".dds") &&
(url.Contains("/loot/companions/") ||
url.Contains("2x_") ||
url.Contains("4x_") ||
url.Contains("tx_cm") ||
url.Contains("/particles/") ||
url.Contains("uiautoatlas") ||
url.Contains("/hud/")))
// Si contiene "/hud/" y termina en ".png", ignorar la URL
if (url.Contains("/hud/") && url.EndsWith(".png"))
{
// Si contiene "/hud/" y termina en ".png", ignorar la URL
if (url.Contains("/hud/") && url.EndsWith(".png"))
{
logAction($"Ignored: {url}");
continue;
}

// Si pasa las condiciones, cambiar la extensión a ".png"
url = Path.ChangeExtension(url, ".png");
return null; // Ignorar
}

// Si la URL contiene "_le." y termina en ".jpg", permitir la descarga
if (url.Contains("_le.") && url.EndsWith(".jpg"))
url = Path.ChangeExtension(url, ".png"); // Cambiar la extensión a ".png"
}
// Si contiene "/loot/companions/" y termina en ".png", ignorar la URL
if (url.Contains("/loot/companions/") && url.EndsWith(".png"))
{
return null; // Ignorar
}
// Si contiene "_le." y termina en ".dds", ignorar la URL
if (url.Contains("_le.") && url.EndsWith(".dds"))
{
return null; // Ignorar
}
// Si contiene "/summonericons/" y termina en ".dds"
if (url.Contains("/summonericons/") && url.EndsWith(".dds"))
{
// Si también contiene ".accessories_", procesarlo cambiando la extensión a .png
if (url.Contains(".accessories_"))
{
// Proceder con la descarga normal
url = Path.ChangeExtension(url, ".png"); // Cambiar la extensión a ".png"
}

// Si la URL contiene "_le." y termina en ".dds", no descargar
if (url.Contains("_le.") && url.EndsWith(".dds"))
else
{
logAction($"Ignored: {url}");
continue;
return null; // Ignorar el resto
}
}
// Si la url termina en .tex cambiar la extensión a png y descargar
if (url.EndsWith(".tex"))
{
url = Path.ChangeExtension(url, ".png"); // Cambiar la extensión a ".png"
}

return url;
}

public async Task<List<string>> DownloadAssets(IEnumerable<string> differences, string baseUrl, string downloadDirectory, Action<string> logAction, List<string> notFoundAssets)
{
// Lista para URLs no encontradas que se retorna al final
var NotFoundAssets = new List<string>();

// Asegurarse de que el directorio de descarga exista
if (!Directory.Exists(downloadDirectory))
{
Directory.CreateDirectory(downloadDirectory);
}

foreach (var line in differences)
{
var url = baseUrl + line.Split(' ').Skip(1).First();
var originalUrl = url;

// Si la URL acaba en ".tex" sustituir por ".png"
if (url.EndsWith(".tex"))
var extension = Path.GetExtension(url);

// Excluir extensiones para los assets (por si acaso no fue filtrado antes)
if (_excludedExtensions.Contains(extension))
{
// Modificar la extensión si termina en ".tex"
url = Path.ChangeExtension(url, ".png");
continue;
}

// Si la URL contiene "/loot/companions/" y termina en ".png", no se descargará
if (url.Contains("/loot/companions/") && url.EndsWith(".png"))
{
logAction($"Ignored: {url}");
// Funcion para ajustar los url con la extension adecuada segun criterios
url = AdjustUrlBasedOnRules(url);

if (string.IsNullOrEmpty(url)) {
continue;
}


try
{
var fileName = Path.GetFileName(url);
var filePath = Path.Combine(downloadDirectory, fileName);
var result = await DownloadFileAsync(url, downloadDirectory, logAction, NotFoundAssets, originalUrl);
if (!result) {
NotFoundAssets.Add(originalUrl);
}
}

var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
await using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await response.Content.CopyToAsync(fileStream);
}
return NotFoundAssets;
}

logAction($"Download: {fileName}");
}
else
private async Task<bool> DownloadFileAsync(string url, string downloadDirectory, Action<string> logAction, List<string> notFoundAssets, string originalUrl)
{
try
{
var fileName = Path.GetFileName(url);
var finalExtension = Path.GetExtension(fileName);

string extensionFolder = _directoriesCreator.CreateAssetTypeDirectory(finalExtension, fileName, url);
var filePath = Path.Combine(extensionFolder, fileName);

var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
await using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
logAction($"The asset was not found in: {url}");
notFoundUrls.Add(url);
await response.Content.CopyToAsync(fileStream);
}
logAction($"Download: {fileName}");
return true;
}
catch (Exception ex)
else
{
logAction($"Error trying to download asset from {url}: {ex.Message}");
notFoundUrls.Add(url);
notFoundAssets.Add(originalUrl);
return false;
}
}

return notFoundUrls;
catch (Exception)
{
notFoundAssets.Add(originalUrl);
return false;
}
}
}
}
}
Loading

0 comments on commit 26ef77a

Please sign in to comment.