-
-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathCompactor.cs
More file actions
182 lines (136 loc) · 5.95 KB
/
Compactor.cs
File metadata and controls
182 lines (136 loc) · 5.95 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using CompactGUI.Logging.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32.SafeHandles;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Enumeration;
using System.Runtime.InteropServices;
using Windows.Win32;
namespace CompactGUI.Core;
public sealed class Compactor : ICompressor, IDisposable
{
private readonly string workingDirectory;
private readonly HashSet<string> excludedFileExtensions;
private readonly WOFCompressionAlgorithm wofCompressionAlgorithm;
private IntPtr compressionInfoPtr;
private UInt32 compressionInfoSize;
private long totalProcessedBytes = 0;
private readonly SemaphoreSlim pauseSemaphore = new SemaphoreSlim(1, 2);
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private ILogger<Compactor> _logger;
private Analyser _analyser;
public Compactor(string folderPath, WOFCompressionAlgorithm compressionLevel, string[] excludedFileTypes, Analyser analyser, ILogger<Compactor>? logger = null)
{
workingDirectory = folderPath;
excludedFileExtensions = new HashSet<string>(excludedFileTypes);
wofCompressionAlgorithm = compressionLevel;
_logger = logger ?? NullLogger<Compactor>.Instance;
_analyser = analyser;
InitializeCompressionInfoPointer();
}
private void InitializeCompressionInfoPointer()
{
var _EFInfo = new WOFHelper.WOF_FILE_COMPRESSION_INFO_V1 { Algorithm = (UInt32)wofCompressionAlgorithm, Flags = 0 };
compressionInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(_EFInfo));
compressionInfoSize = (UInt32)Marshal.SizeOf(_EFInfo);
Marshal.StructureToPtr(_EFInfo, compressionInfoPtr, true);
}
public async Task<bool> RunAsync(List<string> filesList, IProgress<CompressionProgress> progressMonitor = null, int maxParallelism = 1)
{
if(cancellationTokenSource.IsCancellationRequested) { return false; }
CompactorLog.BuildingWorkingFilesList(_logger, workingDirectory);
var workingFiles = await BuildWorkingFilesList().ConfigureAwait(false);
long totalFilesSize = workingFiles.Sum((f) => f.UncompressedSize);
totalProcessedBytes = 0;
var sw = Stopwatch.StartNew();
if (maxParallelism <= 0) maxParallelism = Environment.ProcessorCount;
ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = maxParallelism, CancellationToken = cancellationTokenSource.Token };
CompactorLog.StartingCompression(_logger, workingDirectory, wofCompressionAlgorithm.ToString(), maxParallelism);
try
{
await Parallel.ForEachAsync(workingFiles, parallelOptions,
(file, ctx) =>
{
ctx.ThrowIfCancellationRequested();
return new ValueTask(PauseAndProcessFile(file, totalFilesSize, cancellationTokenSource.Token, progressMonitor));
}).ConfigureAwait(false);
}
catch (OperationCanceledException){
CompactorLog.CompressionCanceled(_logger);
return false;
}
catch (Exception ex){
CompactorLog.CompressionFailed(_logger, ex.Message);
return false;
}
finally { sw.Stop();}
CompactorLog.CompressionCompleted(_logger, Math.Round(sw.Elapsed.TotalSeconds, 3));
return true;
}
private async Task PauseAndProcessFile(FileDetails file, long totalFilesSize, CancellationToken token, IProgress<CompressionProgress> progressMonitor)
{
CompactorLog.ProcessingFile(_logger, file.FileName, file.UncompressedSize);
await pauseSemaphore.WaitAsync(token).ConfigureAwait(false);
pauseSemaphore.Release();
var res = WOFCompressFile(file.FileName);
Interlocked.Add(ref totalProcessedBytes, file.UncompressedSize);
progressMonitor?.Report(new CompressionProgress((int)((double)totalProcessedBytes / totalFilesSize * 100.0), file.FileName));
}
private unsafe int? WOFCompressFile(string filePath)
{
try
{
using (SafeFileHandle fs = File.OpenHandle(filePath))
{
return PInvoke.WofSetFileDataLocation(fs, (uint)WOFHelper.WOF_PROVIDER_FILE, compressionInfoPtr.ToPointer(), compressionInfoSize);
}
}
catch (Exception ex)
{
CompactorLog.FileCompressionFailed(_logger, filePath, ex.Message);
return null;
}
}
public async Task<IEnumerable<FileDetails>> BuildWorkingFilesList()
{
uint clusterSize = SharedMethods.GetClusterSize(workingDirectory);
var analysedFiles = await _analyser.GetAnalysedFilesAsync(cancellationTokenSource.Token);
var filesList = analysedFiles?
.Where(fl =>
fl.CompressionMode != wofCompressionAlgorithm
&& fl.UncompressedSize > clusterSize
&& fl.FileInfo != null && !excludedFileExtensions.Contains(fl.FileInfo.Extension)
)
.Select(fl => new FileDetails(fl.FileName, fl.UncompressedSize))
.ToList();
return filesList;
}
public void Pause()
{
CompactorLog.CompressionPaused(_logger);
pauseSemaphore.Wait(cancellationTokenSource.Token);
}
public void Resume()
{
if (pauseSemaphore.CurrentCount == 0) pauseSemaphore.Release();
CompactorLog.CompressionResumed(_logger);
}
public void Cancel()
{
Resume();
cancellationTokenSource.Cancel();
}
public void Dispose()
{
cancellationTokenSource?.Dispose();
pauseSemaphore?.Dispose();
if (compressionInfoPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(compressionInfoPtr);
compressionInfoPtr = IntPtr.Zero;
}
}
public readonly record struct FileDetails(string FileName, long UncompressedSize);
}