86 lines
2.8 KiB
C#
86 lines
2.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
using BetterEN5.Services;
|
|
|
|
namespace BetterEN5
|
|
{
|
|
public class InkAutoSaveService
|
|
{
|
|
private static readonly string SettingsPath = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
|
"BetterEN5", "ink-settings.json");
|
|
|
|
public async Task StartAsync()
|
|
{
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
var settings = LoadSettings();
|
|
if (settings != null && settings.AutoSaveEnabled)
|
|
{
|
|
var dir = settings.SaveDirectory;
|
|
if (!string.IsNullOrEmpty(dir))
|
|
{
|
|
if (!Directory.Exists(dir))
|
|
Directory.CreateDirectory(dir);
|
|
var timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
|
|
var filePath = Path.Combine(dir, $"ink-auto-{timestamp}.ink.json");
|
|
var inkService = new InkService();
|
|
await inkService.ExportInkAsync(filePath);
|
|
|
|
var retentionMinutes = settings.AutoSaveIntervalMinutes * 2;
|
|
CleanOldFiles(dir, TimeSpan.FromMinutes(retentionMinutes > 0 ? retentionMinutes : 10));
|
|
}
|
|
}
|
|
}
|
|
catch { }
|
|
|
|
var intervalMinutes = LoadSettings()?.AutoSaveIntervalMinutes ?? 5;
|
|
await Task.Delay(TimeSpan.FromMinutes(Math.Max(1, intervalMinutes)));
|
|
}
|
|
}
|
|
|
|
private static InkAutoSaveSettings? LoadSettings()
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(SettingsPath))
|
|
{
|
|
var json = File.ReadAllText(SettingsPath);
|
|
return JsonSerializer.Deserialize<InkAutoSaveSettings>(json);
|
|
}
|
|
}
|
|
catch { }
|
|
return null;
|
|
}
|
|
|
|
private static void CleanOldFiles(string dir, TimeSpan maxAge)
|
|
{
|
|
try
|
|
{
|
|
if (!Directory.Exists(dir)) return;
|
|
foreach (var file in Directory.GetFiles(dir, "ink-auto-*.ink.json"))
|
|
{
|
|
try
|
|
{
|
|
if (DateTime.Now - File.GetCreationTime(file) > maxAge)
|
|
File.Delete(file);
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
|
|
public class InkAutoSaveSettings
|
|
{
|
|
public bool AutoSaveEnabled { get; set; }
|
|
public int AutoSaveIntervalMinutes { get; set; } = 5;
|
|
public string SaveDirectory { get; set; } = "";
|
|
}
|
|
}
|