1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2024-10-17 09:42:45 +02:00
TweetDuck/Management/BrowserCache.cs

77 lines
1.8 KiB
C#

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TweetDuck.Management {
static class BrowserCache {
public static string CacheFolder => Path.Combine(Program.StoragePath, "Cache");
private static bool clearOnExit;
private static Timer autoClearTimer;
private static long CalculateCacheSize() {
return new DirectoryInfo(CacheFolder).EnumerateFiles().Select(file => {
try {
return file.Length;
} catch {
return 0L;
}
}).Sum();
}
public static void GetCacheSize(Action<Task<long>> callbackBytes) {
Task<long> task = new Task<long>(CalculateCacheSize);
task.ContinueWith(callbackBytes);
task.Start();
}
public static void RefreshTimer() {
bool shouldRun = Program.Config.System.ClearCacheAutomatically && !clearOnExit;
if (!shouldRun && autoClearTimer != null) {
autoClearTimer.Dispose();
autoClearTimer = null;
}
else if (shouldRun && autoClearTimer == null) {
autoClearTimer = new Timer(state => {
if (autoClearTimer != null) {
try {
if (CalculateCacheSize() >= Program.Config.System.ClearCacheThreshold * 1024L * 1024L) {
SetClearOnExit();
}
} catch (Exception) {
// TODO should probably log errors and report them at some point
}
}
}, null, TimeSpan.FromSeconds(30), TimeSpan.FromHours(4));
}
}
public static void SetClearOnExit() {
clearOnExit = true;
RefreshTimer();
}
public static void TryClearNow() {
try {
Directory.Delete(CacheFolder, true);
} catch {
// welp, too bad
}
}
public static void Exit() {
if (autoClearTimer != null) {
autoClearTimer.Dispose();
autoClearTimer = null;
}
if (clearOnExit) {
TryClearNow();
}
}
}
}