-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheController.cs
94 lines (79 loc) · 2.84 KB
/
CacheController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// Cuboid (http://github.com/arjonagelhout/cuboid)
// Copyright (c) 2023 Arjo Nagelhout
//
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Cuboid.UI;
using Cuboid.Utils;
namespace Cuboid
{
/// <summary>
/// Responsible for calculating the cache size on disk and propagating clearing the cache
/// to classes that have a cache when the app is low on memory via the <see cref="OnClearCache"/> action.
/// </summary>
public class CacheController : MonoBehaviour
{
private static CacheController _instance;
public static CacheController Instance => _instance;
public Action OnClearCache;
private void Awake()
{
// Singleton implemention
if (_instance != null && _instance != this) { Destroy(this); } else { _instance = this; }
}
private void Start()
{
RecalculateCacheSizeOnDisk();
}
[System.NonSerialized]
public Binding<long> CacheSizeOnDiskInBytes = new Binding<long>(-1);
public void RecalculateCacheSizeOnDisk()
{
Task<long> task = CalculateCacheSizeOnDiskAsync();
task.ContinueWithOnMainThread((t) =>
{
if (t.IsCompletedSuccessfully)
{
CacheSizeOnDiskInBytes.Value = t.Result;
}
else
{
CacheSizeOnDiskInBytes.Value = -1;
}
});
}
private async Task<long> CalculateCacheSizeOnDiskAsync()
{
string cachePath = Constants.CacheDirectoryPath;
DirectoryInfo cacheDirectoryInfo = new DirectoryInfo(cachePath);
long sizeInBytes = await Task.Run(() => cacheDirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories).Sum(file => file.Length));
return sizeInBytes;
}
public void ClearCache()
{
OnClearCache?.Invoke();
string cachePath = Constants.CacheDirectoryPath;
long sizeBeforeCleaning = CacheSizeOnDiskInBytes.Value;
if (Directory.Exists(cachePath))
{
Directory.Delete(cachePath, recursive: true);
Directory.CreateDirectory(cachePath);
RecalculateCacheSizeOnDisk();
NotificationsController.Instance.OpenNotification(new Notification.Data()
{
Title = "Cleared cache on disk",
Description = "Cleared " + Utils.Utils.BytesToString(sizeBeforeCleaning),
Icon = Icons.Data.Info,
IconColor = Color.green,
DisplayDurationInSeconds = 2f
});
}
}
}
}