From fbdd590393206d5fa6679a7b5c6e2ca6637bc724 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 16:10:27 -0500 Subject: remove TransferTracker --- src/slskd/Application.cs | 88 ----------- src/slskd/Program.cs | 1 - src/slskd/Transfers/ITransferTracker.cs | 66 --------- src/slskd/Transfers/TransferTracker.cs | 209 --------------------------- src/slskd/Transfers/Uploads/UploadService.cs | 13 +- 5 files changed, 3 insertions(+), 374 deletions(-) delete mode 100644 src/slskd/Transfers/ITransferTracker.cs delete mode 100644 src/slskd/Transfers/TransferTracker.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b4dfccaa..409b9aaf 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -75,7 +75,6 @@ namespace slskd IManagedState state, ISoulseekClient soulseekClient, IConnectionWatchdog connectionWatchdog, - ITransferTracker transferTracker, ITransferService transferService, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -100,7 +99,6 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); - TransferTracker = transferTracker; Transfers = transferService; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; @@ -157,7 +155,6 @@ namespace slskd private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } - private ITransferTracker TransferTracker { get; set; } private ITransferService Transfers { get; init; } private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } @@ -580,91 +577,6 @@ namespace slskd return dir; } - /// - /// Invoked upon a remote request to download a file. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The filename of the requested file. - /// (for example purposes) the ITransferTracker used to track progress. - /// A Task representing the asynchronous operation. - /// - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// - /// - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// - private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - // remote clients might sometimes re-request downloads to check the status. don't try to add the download again - // if it is already tracked. - if (await Transfers.Uploads.ExistsAsync(t => t.Username == username && t.Filename == filename)) - { - return; - } - - _ = endpoint; - string localFilename; - FileInfo fileInfo = default; - - Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); - - try - { - localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); - - fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - throw new NotFoundException(); - } - } - catch (NotFoundException) - { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); - throw new DownloadEnqueueException($"File not shared."); - } - - // create a new cancellation token source so that we can cancel the upload from the UI. - var cts = new CancellationTokenSource(); - var topts = new TransferOptions( - stateChanged: (e) => - { - tracker.AddOrUpdate(e.Transfer, cts); - - if (e.Transfer.State.HasFlag(TransferStates.Queued)) - { - Transfers.Uploads.Queue.Enqueue(e.Transfer.Username, e.Transfer.Filename); - } - }, - progressUpdated: (e) => tracker.AddOrUpdate(e.Transfer, cts), - governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx.Username, req, ct), - reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx.Username, att, grant, act), - slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx.Username, tx.Filename), - slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx.Username, tx.Filename)); - - // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and - // uploads would be handled separately. - _ = Task.Run(async () => - { - // users with uploads must be watched so that we can keep informed of their - // online status, privileges, and statistics. this is so that we can accurately - // determine their effective group. - if (!Users.IsWatched(username)) - { - await Users.WatchAsync(username); - } - - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => - { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); - }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - } - private async Task OptionsMonitor_OnChange(Options newOptions) { // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently. diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ac5bf99b..64a16076 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,6 @@ namespace slskd services.AddDbContext("search.db"); services.AddDbContext("transfers.db"); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs deleted file mode 100644 index e25539f7..00000000 --- a/src/slskd/Transfers/ITransferTracker.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Transfers -{ - using System.Collections.Concurrent; - using System.Threading; - using Soulseek; - - /// - /// Tracks transfers. - /// - public interface ITransferTracker - { - /// - /// Tracked transfers. - /// - ConcurrentDictionary>> Transfers { get; } - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource); - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - void TryRemove(TransferDirection direction, string username, string id = null); - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); - - /// - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// - /// - /// - /// - /// - bool Contains(TransferDirection direction, string username, string filename); - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs deleted file mode 100644 index d809e792..00000000 --- a/src/slskd/Transfers/TransferTracker.cs +++ /dev/null @@ -1,209 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Transfers -{ - using System.Collections.Concurrent; - using System.Linq; - using System.Threading; - using Soulseek; - - /// - /// Transfer extensions. - /// - public static class TransferTrackerExtensions - { - /// - /// Filters a Transfer collection by user. - /// - /// - /// - /// - public static ConcurrentDictionary FromUser( - this ConcurrentDictionary> directedTransfers, - string username) - { - directedTransfers.TryGetValue(username, out var transfers); - return transfers ?? new ConcurrentDictionary(); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary> directedTransfers) - { - return directedTransfers.Select(u => new - { - Username = u.Key, - Directories = u.Value.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), - }); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary userTransfers) - { - return userTransfers.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); - } - - /// - /// Filters a Transfer collection by direction. - /// - /// - /// - /// - public static ConcurrentDictionary> WithDirection( - this ConcurrentDictionary>> allTransfers, - TransferDirection direction) - { - allTransfers.TryGetValue(direction, out var transfers); - return transfers ?? new ConcurrentDictionary>(); - } - - /// - /// Retrieves a Transfer from a Transfer collection by id. - /// - /// - /// - /// - public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( - this ConcurrentDictionary userTransfers, - string id) - { - userTransfers.TryGetValue(id, out var transfer); - return transfer; - } - } - - /// - /// Tracks transfers. - /// - public class TransferTracker : ITransferTracker - { - /// - /// Initializes a new instance of the class. - /// - public TransferTracker() - { - Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); - Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); - } - - /// - /// Gets tracked transfers. - /// - public ConcurrentDictionary>> Transfers { get; private set; } = - new ConcurrentDictionary>>(); - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - public void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - Transfers.TryGetValue(transfer.Direction, out var direction); - - direction.AddOrUpdate(transfer.Username, GetNewDictionaryForUser(transfer, cancellationTokenSource), (user, dict) => - { - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - dict.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, cancellationTokenSource)); - return dict; - }); - } - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) - { - transfer = default; - - if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) - { - return true; - } - - return false; - } - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - public void TryRemove(TransferDirection direction, string username, string id = null) - { - Transfers.TryGetValue(direction, out var directionDict); - - if (string.IsNullOrEmpty(id)) - { - directionDict.TryRemove(username, out _); - } - else - { - directionDict.TryGetValue(username, out var userDict); - userDict.TryRemove(id, out _); - - if (userDict.IsEmpty) - { - directionDict.TryRemove(username, out _); - } - } - } - - /// - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// - /// - /// - /// - /// - public bool Contains(TransferDirection direction, string username, string filename) - { - if (Transfers.TryGetValue(direction, out var directionDict) && directionDict.TryGetValue(username, out var userDict)) - { - return userDict.Values.Any(record => record.Transfer.Filename == filename); - } - - return false; - } - - private ConcurrentDictionary GetNewDictionaryForUser(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - var r = new ConcurrentDictionary(); - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - r.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, record.CancellationTokenSource)); - return r; - } - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index af490174..319b4306 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -43,14 +43,12 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, - ITransferTracker transferTracker, IDbContextFactory contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; ContextFactory = contextFactory; - Tracker = transferTracker; Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); @@ -72,7 +70,6 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private ISoulseekClient Client { get; set; } - private ITransferTracker Tracker { get; set; } /// /// Enqueues the requested file. @@ -92,7 +89,7 @@ namespace slskd.Transfers.Uploads string localFilename; FileInfo fileInfo = default; - Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); + Log.Information("[{Context}] {Username} requested {Filename}]", "UPLOAD REQUESTED", username, filename); try { @@ -107,7 +104,7 @@ namespace slskd.Transfers.Uploads } catch (NotFoundException) { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); + Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename); throw new DownloadEnqueueException($"File not shared."); } @@ -156,8 +153,6 @@ namespace slskd.Transfers.Uploads // todo: broadcast _ = UpdateAndSaveChangesAsync(transfer); - Tracker.AddOrUpdate(args.Transfer, cts); - if (args.Transfer.State.HasFlag(TransferStates.Queued)) { Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); @@ -165,8 +160,6 @@ namespace slskd.Transfers.Uploads }, progressUpdated: (args) => rateLimiter.Invoke(() => { - Tracker.AddOrUpdate(args.Transfer, cts); - transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast _ = UpdateAndSaveChangesAsync(transfer); @@ -192,7 +185,7 @@ namespace slskd.Transfers.Uploads await UpdateAndSaveChangesAsync(transfer); }).ContinueWith(t => { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget } -- cgit v1.2.3