using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Text;
namespace Titano.App.Infrastructure;
///
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report
/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included.
///
public static class DiagnosticsBundle
{
/// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into and returns its path.
public static Task CreateAsync(AppEnvironment environment, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) =>
Task.Run(() =>
{
var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip");
var temp = path + ".tmp";
using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create))
{
var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal);
using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false)))
{
writer.Write(Report(environment, extraLines));
}
if (Directory.Exists(environment.LogDirectory))
{
foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal))
{
ct.ThrowIfCancellationRequested();
var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal);
// The current log is open for writing: share the handle instead of copying the file.
using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var target = entry.Open();
source.CopyTo(target);
}
}
}
File.Move(temp, path, overwrite: true);
return path;
}, ct);
/// Plain-text environment report.
public static string Report(AppEnvironment environment, IEnumerable? extraLines = null)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}");
sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB");
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
if (extraLines is not null)
{
foreach (var line in extraLines) sb.AppendLine(line);
}
return sb.ToString();
}
}
///
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Titano created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
///
public static class CacheStore
{
public const string MarkerFile = ".titano-cache";
/// The cache folder in effect.
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// Creates the folder (if needed) and marks it as Titano's.
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time.");
}
/// True when is a Titano cache folder (safe to empty).
public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
/// Total bytes of the files in the cache (0 when missing).
public static long Size(string folder)
{
if (!Directory.Exists(folder)) return 0;
long total = 0;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
return total;
}
/// Deletes everything inside an owned cache folder except the marker; returns the bytes freed.
/// The folder is not a Titano cache folder.
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano cache folder: " + folder);
long freed = 0;
var root = new DirectoryInfo(folder);
foreach (var file in root.EnumerateFiles())
{
if (file.Name == MarkerFile) continue;
freed += TryDelete(file);
}
foreach (var directory in root.EnumerateDirectories())
{
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
try
{
directory.Delete(recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return freed;
}
private static long TryDelete(FileInfo file)
{
try
{
var length = file.Length;
file.Delete();
return length;
}
catch (IOException)
{
return 0; // in use (a render spilling right now)
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
}