This commit is contained in:
Lani Aung
2024-09-15 20:15:11 -06:00
parent a8d3afd2a8
commit de9c6e6e92
11 changed files with 394 additions and 467 deletions
+131 -131
View File
@@ -13,153 +13,153 @@ using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp;
using Configuration = fxl.codes.kisekae.Entities.Configuration;
namespace fxl.codes.kisekae.Services
namespace fxl.codes.kisekae.Services;
public class DatabaseService
{
public class DatabaseService
private readonly ConfigurationReaderService _configurationReaderService;
private readonly IDbContextFactory<KisekaeContext> _contextFactory;
private readonly FileParserService _fileParserService;
private readonly ILogger<DatabaseService> _logger;
private readonly IsolatedStorageFile _storage;
public DatabaseService(ILogger<DatabaseService> logger,
ConfigurationReaderService configurationReaderService,
FileParserService fileParserService,
IDbContextFactory<KisekaeContext> contextFactory)
{
private readonly ConfigurationReaderService _configurationReaderService;
private readonly IDbContextFactory<KisekaeContext> _contextFactory;
_logger = logger;
_configurationReaderService = configurationReaderService;
_fileParserService = fileParserService;
_contextFactory = contextFactory;
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
private readonly FileParserService _fileParserService;
private readonly ILogger<DatabaseService> _logger;
private readonly IsolatedStorageFile _storage;
public IEnumerable<Kisekae> GetAll()
{
using var context = _contextFactory.CreateDbContext();
return context.KisekaeSets
.Include(x => x.Configurations)
.ToArray();
}
public DatabaseService(ILogger<DatabaseService> logger,
ConfigurationReaderService configurationReaderService,
FileParserService fileParserService,
IDbContextFactory<KisekaeContext> contextFactory)
public Configuration GetConfig(int id)
{
using var context = _contextFactory.CreateDbContext();
return context.Configurations
.Include(x => x.Cels).ThenInclude(x => x.Render)
.Include(x => x.Cels).ThenInclude(x => x.Cel)
.Include(x => x.Cels).ThenInclude(x => x.Positions)
.Include(x => x.Kisekae).ThenInclude(x => x.Palettes).ThenInclude(x => x.Colors)
.AsSplitQuery()
.FirstOrDefault(x => x.Id == id);
}
public async Task StoreToDatabase(IFormFile file)
{
var memoryStream = await GetAsMemoryStream(file);
var checksum = Convert.ToBase64String(SHA256.HashData(memoryStream.GetBuffer()));
memoryStream.Position = 0; // Reset for re-read
await using var context = await _contextFactory.CreateDbContextAsync();
var existing = await context.KisekaeSets
.FirstOrDefaultAsync(x => string.Equals(x.FileName, file.FileName)
|| string.Equals(x.CheckSum, checksum));
if (existing != null) context.KisekaeSets.Remove(existing);
await context.SaveChangesAsync();
await _fileParserService.UnzipLzh(file, memoryStream);
var directory = Path.GetFileNameWithoutExtension(file.FileName);
var kisekae = new Kisekae
{
_logger = logger;
_configurationReaderService = configurationReaderService;
_fileParserService = fileParserService;
_contextFactory = contextFactory;
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
FileName = file.FileName,
CheckSum = checksum
};
public IEnumerable<Kisekae> GetAll()
var filenames = _storage.GetFileNames($"{Path.Combine(directory, "*")}");
await SetInnerFiles(kisekae, directory, filenames);
var backgroundColors = new Dictionary<Configuration, int>();
foreach (var config in kisekae.Configurations)
_configurationReaderService.ReadConfiguration(config,
backgroundColors,
kisekae.Cels.ToDictionary(x => x.FileName.ToLowerInvariant()),
kisekae.Palettes.ToDictionary(x => x.FileName.ToLowerInvariant()));
SetPaletteColors(kisekae.Palettes);
foreach (var (config, colorIndex) in backgroundColors)
config.BackgroundColorHex = kisekae.Palettes.First()?.Colors[colorIndex].Hex ?? Color.White.ToHex();
foreach (var celConfig in kisekae.Configurations.SelectMany(config => config.Cels))
_fileParserService.RenderCel(celConfig);
await context.AddAsync(kisekae);
await context.SaveChangesAsync();
}
private async Task SetInnerFiles(Kisekae kisekae, string directory, IEnumerable<string> filenames)
{
foreach (var filename in filenames)
{
using var context = _contextFactory.CreateDbContext();
return context.KisekaeSets
.Include(x => x.Configurations)
.ToArray();
}
await using var reader = _storage.OpenFile(Path.Combine(directory, filename), FileMode.Open);
if (!reader.CanRead) throw new InvalidDataException();
public Configuration GetConfig(int id)
{
using var context = _contextFactory.CreateDbContext();
return context.Configurations
.Include(x => x.Cels).ThenInclude(x => x.Render)
.Include(x => x.Cels).ThenInclude(x => x.Cel)
.Include(x => x.Cels).ThenInclude(x => x.Positions)
.Include(x => x.Kisekae).ThenInclude(x => x.Palettes).ThenInclude(x => x.Colors)
.AsSplitQuery()
.FirstOrDefault(x => x.Id == id);
}
var bytes = new byte[reader.Length];
reader.Read(bytes, 0, bytes.Length);
public async void StoreToDatabase(IFormFile file)
{
var memoryStream = await GetAsMemoryStream(file);
var checksum = Convert.ToBase64String(SHA256.HashData(memoryStream.GetBuffer()));
memoryStream.Position = 0; // Reset for re-read
await using var context = await _contextFactory.CreateDbContextAsync();
var existing = await context.KisekaeSets
.FirstOrDefaultAsync(x => string.Equals(x.FileName, file.FileName)
|| string.Equals(x.CheckSum, checksum));
if (existing != null) context.KisekaeSets.Remove(existing);
await context.SaveChangesAsync();
_fileParserService.UnzipLzh(file, memoryStream);
var directory = Path.GetFileNameWithoutExtension(file.FileName);
var kisekae = new Kisekae
switch (Path.GetExtension(filename).ToLower())
{
FileName = file.FileName,
CheckSum = checksum
};
var filenames = _storage.GetFileNames($"{Path.Combine(directory, "*")}");
await SetInnerFiles(kisekae, directory, filenames);
var backgroundColors = new Dictionary<Configuration, int>();
foreach (var config in kisekae.Configurations)
_configurationReaderService.ReadConfiguration(config,
backgroundColors,
kisekae.Cels.ToDictionary(x => x.FileName.ToLowerInvariant()),
kisekae.Palettes.ToDictionary(x => x.FileName.ToLowerInvariant()));
SetPaletteColors(kisekae.Palettes);
foreach (var (config, colorIndex) in backgroundColors)
config.BackgroundColorHex = kisekae.Palettes.First()?.Colors[colorIndex].Hex ?? Color.White.ToHex();
foreach (var celConfig in kisekae.Configurations.SelectMany(config => config.Cels))
_fileParserService.RenderCel(celConfig);
await context.AddAsync(kisekae);
await context.SaveChangesAsync();
}
private async Task SetInnerFiles(Kisekae kisekae, string directory, IEnumerable<string> filenames)
{
foreach (var filename in filenames)
{
await using var reader = _storage.OpenFile(Path.Combine(directory, filename), FileMode.Open);
if (!reader.CanRead) throw new InvalidDataException();
var bytes = new byte[reader.Length];
reader.Read(bytes, 0, bytes.Length);
switch (Path.GetExtension(filename).ToLower())
{
case ".cel":
kisekae.Cels.Add(new Cel
{
FileName = filename,
Data = bytes
});
break;
case ".cnf":
kisekae.Configurations.Add(new Configuration
{
Name = filename,
Data = Encoding.ASCII.GetString(bytes)
});
break;
case ".kcf":
kisekae.Palettes.Add(new Palette
{
FileName = filename,
Data = bytes
});
break;
}
}
}
private void SetPaletteColors(IEnumerable<Palette> palettes)
{
foreach (var palette in palettes)
{
var colors = _fileParserService.ParsePalette(palette, out var groups, out var colorsPerGroup);
for (var groupIndex = 0; groupIndex < groups; groupIndex++)
for (var colorIndex = 0; colorIndex < colorsPerGroup; colorIndex++)
{
var color = colors[groupIndex * colorsPerGroup + colorIndex];
palette.Colors.Add(new PaletteColor
case ".cel":
kisekae.Cels.Add(new Cel
{
Group = groupIndex,
Hex = color.ToHex()
FileName = filename,
Data = bytes
});
}
break;
case ".cnf":
kisekae.Configurations.Add(new Configuration
{
Name = filename,
Data = Encoding.ASCII.GetString(bytes)
});
break;
case ".kcf":
kisekae.Palettes.Add(new Palette
{
FileName = filename,
Data = bytes
});
break;
}
}
}
private static async Task<MemoryStream> GetAsMemoryStream(IFormFile file)
private void SetPaletteColors(IEnumerable<Palette> palettes)
{
foreach (var palette in palettes)
{
var stream = new MemoryStream();
await file.CopyToAsync(stream);
return stream;
var colors = _fileParserService.ParsePalette(palette, out var groups, out var colorsPerGroup);
for (var groupIndex = 0; groupIndex < groups; groupIndex++)
for (var colorIndex = 0; colorIndex < colorsPerGroup; colorIndex++)
{
var color = colors[groupIndex * colorsPerGroup + colorIndex];
palette.Colors.Add(new PaletteColor
{
Group = groupIndex,
Hex = color.ToHex()
});
}
}
}
private static async Task<MemoryStream> GetAsMemoryStream(IFormFile file)
{
var stream = new MemoryStream();
await file.CopyToAsync(stream);
return stream;
}
}