2025-01-29 22:52:27 -06:00
|
|
|
using System;
|
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
|
|
|
|
|
namespace LANCommander.SDK;
|
|
|
|
|
|
|
|
|
|
public class FileTransferMonitor : IDisposable
|
|
|
|
|
{
|
|
|
|
|
private readonly Stopwatch _stopwatch;
|
|
|
|
|
|
|
|
|
|
private long _lastBytesTransferred;
|
|
|
|
|
private long _totalBytes;
|
|
|
|
|
private double _smoothedTransferRate;
|
|
|
|
|
|
|
|
|
|
private const double SmoothingFactor = 0.1;
|
|
|
|
|
private const double RateLimit = 0.5;
|
|
|
|
|
|
|
|
|
|
public FileTransferMonitor(long totalBytes)
|
|
|
|
|
{
|
|
|
|
|
_stopwatch = Stopwatch.StartNew();
|
|
|
|
|
_totalBytes = totalBytes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool CanUpdate()
|
|
|
|
|
{
|
2025-02-04 02:34:31 -06:00
|
|
|
return _stopwatch.Elapsed.TotalSeconds > RateLimit;
|
2025-01-29 22:52:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Update(long bytesTransferred)
|
|
|
|
|
{
|
|
|
|
|
if (!_stopwatch.IsRunning)
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
var bytesSinceLastUpdate = bytesTransferred - _lastBytesTransferred;
|
|
|
|
|
var currentSpeed = bytesSinceLastUpdate / _stopwatch.Elapsed.TotalSeconds;
|
|
|
|
|
|
|
|
|
|
if (_smoothedTransferRate == 0)
|
|
|
|
|
_smoothedTransferRate = currentSpeed;
|
|
|
|
|
else
|
|
|
|
|
_smoothedTransferRate = (_smoothedTransferRate * (1 - SmoothingFactor)) + (currentSpeed * SmoothingFactor);
|
|
|
|
|
|
|
|
|
|
_lastBytesTransferred = bytesTransferred;
|
|
|
|
|
_stopwatch.Restart();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public long GetBytesTransferred() => _lastBytesTransferred;
|
2025-01-29 23:02:59 -06:00
|
|
|
public long GetSpeed() => (long)_smoothedTransferRate;
|
2025-01-29 22:52:27 -06:00
|
|
|
|
|
|
|
|
public TimeSpan GetTimeRemaining()
|
|
|
|
|
{
|
|
|
|
|
if (_smoothedTransferRate <= 0)
|
|
|
|
|
return TimeSpan.Zero;
|
2025-02-04 02:34:31 -06:00
|
|
|
|
|
|
|
|
double secondsRemaining;
|
2025-01-29 22:52:27 -06:00
|
|
|
|
|
|
|
|
var remainingBytes = _totalBytes - _lastBytesTransferred;
|
2025-02-04 02:34:31 -06:00
|
|
|
|
|
|
|
|
if (_smoothedTransferRate > 0)
|
|
|
|
|
secondsRemaining = remainingBytes / _smoothedTransferRate;
|
|
|
|
|
else
|
|
|
|
|
secondsRemaining = 0;
|
2025-01-29 22:52:27 -06:00
|
|
|
|
|
|
|
|
return TimeSpan.FromSeconds(secondsRemaining);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
2025-02-04 02:34:31 -06:00
|
|
|
//_stopwatch.Stop();
|
2025-01-29 22:52:27 -06:00
|
|
|
}
|
|
|
|
|
}
|