From ad3008c64a3f8c34632f570733ba133d12d2ae63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Sep 2023 16:18:37 -0500 Subject: implement download pruning --- src/slskd/Transfers/Downloads/DownloadService.cs | 41 ++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 685bcb43..fc18b506 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -476,6 +476,47 @@ namespace slskd.Transfers.Downloads } } + /// + /// Removes downloads older than the specified . + /// + /// The age after which downloads are eligible for pruning, in hours. + /// An optional, additional state by which downloads are filtered for pruning. + /// The number of pruned downloads. + public int Prune(int age, TransferStates state = TransferStates.Completed) + { + if (!state.HasFlag(TransferStates.Completed)) + { + throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(state)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + + var expired = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed) + .Where(t => t.EndedAt.HasValue && (DateTime.UtcNow - t.EndedAt.Value).Hours >= age) + .Where(t => t.State.HasFlag(state)) + .ToList(); + + foreach (var tx in expired) + { + tx.Removed = true; + } + + var pruned = context.SaveChanges(); + + Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, state); + return pruned; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message); + throw; + } + } + /// /// Removes the download matching the specified . /// -- cgit v1.2.3