86 lines
3 KiB
C#
86 lines
3 KiB
C#
using System.IO.Compression;
|
|
using System.Text;
|
|
using GhostImageManager.Models;
|
|
|
|
namespace GhostImageManager.Services;
|
|
|
|
public class ImageExportService
|
|
{
|
|
public byte[] ExportToCsv(List<GhostImage> images)
|
|
{
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("Dateiname;Relativer Pfad;URL;Größe Bytes;Größe;Dimensionen;Letzte Änderung;Verwaist;Verwendet in Posts");
|
|
|
|
foreach (var image in images)
|
|
{
|
|
var posts = string.Join(" | ", image.UsedInPosts.Select(p => $"{p.Title} ({(p.IsFeatureImage ? "Feature" : "Content")})"));
|
|
sb.AppendLine($"{EscapeCsv(image.FileName)};{EscapeCsv(image.RelativePath)};{EscapeCsv(image.Url)};{image.FileSize};{image.FormattedFileSize};{image.Dimensions};{image.LastModified:yyyy-MM-dd HH:mm};{image.IsOrphaned};{EscapeCsv(posts)}");
|
|
}
|
|
|
|
return Encoding.UTF8.GetBytes(sb.ToString());
|
|
}
|
|
|
|
public byte[] ExportToTxt(List<GhostImage> images)
|
|
{
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("Ghost Image Export");
|
|
sb.AppendLine($"Erstellt am: {DateTime.Now:yyyy-MM-dd HH:mm}");
|
|
sb.AppendLine($"Anzahl Bilder: {images.Count}");
|
|
sb.AppendLine($"Verwaiste Bilder: {images.Count(i => i.IsOrphaned)}");
|
|
sb.AppendLine(new string('-', 80));
|
|
|
|
foreach (var image in images)
|
|
{
|
|
sb.AppendLine($"Datei: {image.FileName}");
|
|
sb.AppendLine($"URL: {image.Url}");
|
|
sb.AppendLine($"Pfad: {image.RelativePath}");
|
|
sb.AppendLine($"Verwaist: {(image.IsOrphaned ? "Ja" : "Nein")}");
|
|
if (image.UsedInPosts.Any())
|
|
{
|
|
sb.AppendLine("Verwendet in:");
|
|
foreach (var post in image.UsedInPosts)
|
|
{
|
|
sb.AppendLine($" - {post.Title} ({(post.IsFeatureImage ? "Feature" : "Content")})");
|
|
}
|
|
}
|
|
sb.AppendLine();
|
|
}
|
|
|
|
return Encoding.UTF8.GetBytes(sb.ToString());
|
|
}
|
|
|
|
public async Task<byte[]> ExportToZipAsync(List<GhostImage> images)
|
|
{
|
|
using var ms = new MemoryStream();
|
|
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
|
|
{
|
|
foreach (var image in images)
|
|
{
|
|
if (!File.Exists(image.FilePath))
|
|
continue;
|
|
|
|
var entry = archive.CreateEntry(image.RelativePath.Replace("/", "\\"));
|
|
await using (var entryStream = entry.Open())
|
|
{
|
|
await using var fileStream = File.OpenRead(image.FilePath);
|
|
await fileStream.CopyToAsync(entryStream);
|
|
}
|
|
}
|
|
}
|
|
|
|
return ms.ToArray();
|
|
}
|
|
|
|
private static string EscapeCsv(string value)
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
return "";
|
|
|
|
if (value.Contains(';') || value.Contains('"') || value.Contains('\n'))
|
|
{
|
|
return $"\"{value.Replace("\"", "\"\"")}\"";
|
|
}
|
|
|
|
return value;
|
|
}
|
|
}
|