forked from revenz/FileFlows
/
TempFileCleaner.cs
60 lines (54 loc) · 2.16 KB
/
TempFileCleaner.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
using FileFlows.ServerShared.Services;
namespace FileFlows.ServerShared.Workers;
/// <summary>
/// Worker to clean up temporary files
/// </summary>
public class TempFileCleaner:Worker
{
private string nodeAddress;
private readonly IWorkerThatUsesTempDirectories workerThatUsesTempDirectories;
/// <summary>
/// Constructs a temp file cleaner
/// <param name="nodeAddress">The name of the node</param>
/// <param name="workerThatUsesTempDirectories">The worker that uses temp directories, this is used to verify that a temp directory should not be removed while still in use</param>"
/// </summary>
public TempFileCleaner(string nodeAddress, IWorkerThatUsesTempDirectories workerThatUsesTempDirectories) : base(ScheduleType.Daily, 5)
{
this.nodeAddress = nodeAddress;
this.workerThatUsesTempDirectories = workerThatUsesTempDirectories;
Trigger();
}
/// <summary>
/// Executes the cleaner
/// </summary>
protected sealed override void Execute()
{
var service = NodeService.Load();
var node = string.IsNullOrWhiteSpace(nodeAddress)
? service.GetServerNodeAsync().Result
: service.GetByAddressAsync(nodeAddress).Result;
if (string.IsNullOrWhiteSpace(node?.TempPath))
return;
var tempDir = new DirectoryInfo(node.TempPath);
if (tempDir.Exists == false)
return;
Logger.Instance?.ILog("About to clean temporary directory: " + tempDir.FullName);
foreach (var dir in tempDir.GetDirectories())
{
if (workerThatUsesTempDirectories.IsTempDirectoryInUse(dir.Name))
continue;
if (dir.CreationTimeUtc < DateTime.UtcNow.AddDays(-1))
{
try
{
dir.Delete(recursive: true);
Logger.Instance.ILog($"Deleted directory '{dir.Name}' from temp directory");
}
catch (Exception ex)
{
Logger.Instance.WLog($"Failed to delete directory '{dir.Name}' from temp directory: " + ex.Message);
}
}
}
}
}