diff --git a/server/RdtClient.Service/Services/QBittorrent.cs b/server/RdtClient.Service/Services/QBittorrent.cs index 4cd1513..95b5832 100644 --- a/server/RdtClient.Service/Services/QBittorrent.cs +++ b/server/RdtClient.Service/Services/QBittorrent.cs @@ -194,8 +194,6 @@ public class QBittorrent(ILogger logger, Settings settings, Authent var prio = 0; - Double downloadProgress = 0; - foreach (var torrent in allTorrents) { var downloadPath = savePath; @@ -218,36 +216,36 @@ public class QBittorrent(ILogger logger, Settings settings, Authent } } - Int64 bytesDone = 0; - Int64 bytesTotal = 0; - Int64 speed = 0; - Double rdProgress = 0; - try - { - rdProgress = (torrent.RdProgress ?? 0.0) / 100.0; - bytesTotal = torrent.RdSize ?? 1; - bytesDone = (Int64) (bytesTotal * rdProgress); - speed = torrent.RdSpeed ?? 0; - } - catch (Exception ex) - { - logger.LogError(ex, $""" - Error calculating progress: - RdProgress: {torrent.RdProgress} - RdSize: {torrent.RdSize} - RdSpeed: {torrent.RdSpeed} - """); - } + var rdProgress = Math.Clamp(torrent.RdProgress ?? 0.0, 0.0, 100.0) / 100.0; + var bytesTotal = torrent.RdSize ?? 0; + var speed = torrent.RdSpeed ?? 0; + var bytesDone = (Int64) (bytesTotal * rdProgress); - if (torrent.Downloads.Count > 0) + Double downloadProgress = 0; + if (torrent.Downloads is { Count: > 0 }) { - bytesDone = torrent.Downloads.Sum(m => m.BytesDone); - bytesTotal = torrent.Downloads.Sum(m => m.BytesTotal); + var dlBytesDone = torrent.Downloads.Sum(m => m.BytesDone); + var dlBytesTotal = torrent.Downloads.Sum(m => m.BytesTotal); speed = (Int32) torrent.Downloads.Average(m => m.Speed); - downloadProgress = bytesTotal > 0 ? (Double) bytesDone / bytesTotal : 0; + downloadProgress = bytesTotal > 0 ? Math.Clamp((Double) dlBytesDone / dlBytesTotal, 0.0, 1.0) : 0; } var progress = (rdProgress + downloadProgress) / 2.0; + var remaining = TimeSpan.Zero; + if (progress > 0.001 && progress < 1.0) + { + var startTime = torrent.Retry > torrent.Added ? torrent.Retry.Value : torrent.Added; + var elapsed = DateTimeOffset.UtcNow - startTime; + var elapsedTicks = Math.Max(0, elapsed.Ticks); + var totalEstimatedTime = TimeSpan.FromTicks((Int64)(elapsedTicks / progress)); + remaining = totalEstimatedTime - TimeSpan.FromTicks(elapsedTicks); + + // In case there is clock skew + if (remaining < TimeSpan.Zero) + { + remaining = TimeSpan.Zero; + } + } var result = new TorrentInfo { @@ -263,7 +261,7 @@ public class QBittorrent(ILogger logger, Settings settings, Authent Dlspeed = speed, Downloaded = bytesDone, DownloadedSession = bytesDone, - Eta = 0, + Eta = (Int64)remaining.TotalSeconds, FlPiecePrio = false, ForceStart = false, Hash = torrent.Hash,