diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-10-06 18:06:22 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-10-06 18:06:22 -0500 |
| commit | bac18981efba4daa4e4668dd382b7fbed8765636 (patch) | |
| tree | 86307843bd193b5eb5750e254e231dc3751d1f40 | |
| parent | 3fb1176c9788d2de5527df282702aefb0497a0ec (diff) | |
| parent | 5dea82dbd647cdc28c89a1d37e168d3a47abeea7 (diff) | |
| download | slskd-bac18981efba4daa4e4668dd382b7fbed8765636.tar.gz | |
Merge pull request #1215 from slskd/tasks
Add 'Events'
| -rw-r--r-- | config/slskd.example.yml | 2 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 7 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Events/API/EventsController.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Events/EventBus.cs | 158 | ||||
| -rw-r--r-- | src/slskd/Events/EventService.cs | 128 | ||||
| -rw-r--r-- | src/slskd/Events/EventsDbContext.cs | 40 | ||||
| -rw-r--r-- | src/slskd/Events/Types/EventRecord.cs | 84 | ||||
| -rw-r--r-- | src/slskd/Events/Types/Events.cs | 41 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Transfers/Types/Transfer.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Transfers/Types/Upload.cs | 2 | ||||
| -rw-r--r-- | src/web/src/components/System/Events/index.jsx | 118 | ||||
| -rw-r--r-- | src/web/src/components/System/System.css | 16 | ||||
| -rw-r--r-- | src/web/src/components/System/System.jsx | 14 | ||||
| -rw-r--r-- | src/web/src/lib/events.js | 10 |
17 files changed, 745 insertions, 23 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 5f028582..4b4f0996 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -168,7 +168,7 @@ # files: # complete: 20160 # 2 weeks # incomplete: 43200 # 30 days -# logs: 259200 # 180 days +# logs: 180 # days # logger: # disk: false # no_color: false diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9723db58..d441160e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -40,6 +40,7 @@ namespace slskd using Serilog.Events; using slskd.Configuration; using slskd.Core.API; + using slskd.Events; using slskd.Files; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -97,6 +98,7 @@ namespace slskd IShareService shareService, IPushbulletService pushbulletService, IRelayService relayService, + EventService eventService, IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) { @@ -144,6 +146,8 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); + Events = eventService; + Transfers = transferService; BrowseTracker = browseTracker; Pushbullet = pushbulletService; @@ -223,6 +227,7 @@ namespace slskd private IHubContext<LogsHub> LogHub { get; set; } private IUserService Users { get; set; } private IShareService Shares { get; set; } + private EventService Events { get; } private IRelayService Relay { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; } @@ -1650,4 +1655,4 @@ namespace slskd } } } -} +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cad58817..0f86ff62 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2215,4 +2215,4 @@ namespace slskd } } } -} +}
\ No newline at end of file diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs new file mode 100644 index 00000000..e9780fad --- /dev/null +++ b/src/slskd/Events/API/EventsController.cs @@ -0,0 +1,66 @@ +// <copyright file="EventsController.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events.API; + +using Asp.Versioning; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Serilog; + +/// <summary> +/// Events. +/// </summary> +[Route("api/v{version:apiVersion}/[controller]")] +[ApiVersion("0")] +[ApiController] +[Produces("application/json")] +[Consumes("application/json")] +public class EventsController : ControllerBase +{ + public EventsController( + EventService eventService) + { + Events = eventService; + } + + private EventService Events { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<EventsController>(); + + [HttpGet("")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult GetEvents([FromQuery] int offset = 0, [FromQuery] int limit = 100) + { + if (offset < 0) + { + return BadRequest("Offset must be greater than or equal to zero."); + } + + if (limit <= 0) + { + return BadRequest("Limit must be greater than zero"); + } + + var events = Events.Get(offset, limit); + var count = Events.Count(); + + Response.Headers.Append("X-Total-Count", count.ToString()); + + return Ok(events); + } +}
\ No newline at end of file diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs new file mode 100644 index 00000000..e5552d2d --- /dev/null +++ b/src/slskd/Events/EventBus.cs @@ -0,0 +1,158 @@ +// <copyright file="EventBus.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Serilog; + +/// <summary> +/// The event bus supporting interoperability and ancillary functions. +/// </summary> +/// <remarks> +/// <para> +/// This "bus" is meant to mimic an event bus you'd find in a distributed system; fire and forget. If an +/// Exception is encountered while an event is being raised, it will be logged and swallowed. +/// </para> +/// <para> +/// It is also intended to be used *ONLY* for ancillary and/or third party logic that isn't part of the +/// core application. The core application should continue to use regular old C# events and method calls +/// to communicate within and among modules. +/// </para> +/// <para> +/// This design was chosen over built-in C# events to give greater control over how events are dispatched, +/// and bound. +/// </para> +/// </remarks> +public class EventBus +{ + /// <summary> + /// Initializes a new instance of the <see cref="EventBus"/> class. + /// </summary> + /// <param name="eventService"/> + public EventBus(EventService eventService) + { + Events = eventService; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<EventBus>(); + private EventService Events { get; } + + /// <summary> + /// Gets the internal list of event subscriptions. + /// </summary> + /// <remarks> + /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to + /// support unsubscribing. + /// </remarks> + private ConcurrentDictionary<Type, ConcurrentDictionary<string, object>> Subscriptions { get; } = new(); + + /// <summary> + /// Raises an event. + /// </summary> + /// <param name="data">The event data.</param> + /// <typeparam name="T">The Type of the event.</typeparam> + public virtual void Raise<T>(T data) + where T : Event + { + Log.Debug("Handling {Type}: {Data}", typeof(T), data); + + // save the event to the database before broadcasting to consumers + Events.Add(EventRecord.From<T>(data)); + + // broadcast the event in a fire-and-forget fashion + // we don't need to wait for anything, just need to kick off the tasks + // if something throws it will be logged and the consumer can figure it out + if (Subscriptions.TryGetValue(typeof(T), out var subscribers)) + { + Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); + + // we don't care about any of these tasks; contractually we are only obligated to invoke them + _ = Task.WhenAll(subscribers.Select(subscriber => + Task.Run(() => (subscriber.Value as Func<T, Task>)(data)) + .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); + } + else + { + Log.Debug("No subscribers for {Type}", typeof(T)); + } + } + + /// <summary> + /// Subscribes a <paramref name="subscriber"/>'s <paramref name="callback"/> to an event. + /// </summary> + /// <param name="subscriber">The unique name of the subscriber.</param> + /// <param name="callback">The callback function to execute when an event is raised.</param> + /// <typeparam name="T">The Type of the event.</typeparam> + /// <exception cref="ArgumentException">Thrown if the specified <paramref name="subscriber"/> is null or whitespace.</exception> + /// <exception cref="ArgumentNullException">Thrown if the specified <paramref name="callback"/> is null.</exception> + public virtual void Subscribe<T>(string subscriber, Func<T, Task> callback) + where T : Event + { + ArgumentException.ThrowIfNullOrWhiteSpace(subscriber); + + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + Subscriptions.AddOrUpdate( + key: typeof(T), + addValue: new ConcurrentDictionary<string, object>( + new Dictionary<string, object> { [subscriber] = callback }), + updateValueFactory: (_, subscribers) => + { + subscribers.AddOrUpdate( + key: subscriber, + addValue: callback, + updateValueFactory: (_, existingSubscription) => + { + if (existingSubscription is not null) + { + Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); + } + + return callback; + }); + + return subscribers; + }); + + Log.Debug("Subscribed {Name} to {Type}", subscriber, typeof(T)); + } + + /// <summary> + /// Unsubscribes a <paramref name="subscriber"/> from an event. + /// </summary> + /// <remarks> + /// Will not throw if a subscription doesn't exist. + /// </remarks> + /// <typeparam name="T">The Type of the event.</typeparam> + /// <param name="subscriber">The unique name of the subscriber.</param> + public virtual void Unsubscribe<T>(string subscriber) + where T : Event + { + if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) + { + subscriptions.TryRemove(subscriber, out _); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs new file mode 100644 index 00000000..d6f1a3f5 --- /dev/null +++ b/src/slskd/Events/EventService.cs @@ -0,0 +1,128 @@ +// <copyright file="EventService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// <summary> +/// Manages events. +/// </summary> +public class EventService +{ + /// <summary> + /// Initializes a new instance of the <see cref="EventService"/> class. + /// </summary> + /// <param name="contextFactory"></param> + public EventService(IDbContextFactory<EventsDbContext> contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory<EventsDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<EventService>(); + + /// <summary> + /// Gets list of events, optionally applying the specified <paramref name="offset"/> and <paramref name="limit"/>. + /// </summary> + /// <param name="offset">The beginning offset for the page.</param> + /// <param name="limit">The page size limit.</param> + /// <returns>The retrieved list.</returns> + /// <exception cref="ArgumentOutOfRangeException">Thrown when the specified <paramref name="offset"/> is less than zero.</exception> + /// <exception cref="ArgumentOutOfRangeException">Thrown when the specified <paramref name="limit"/> is zero.</exception> + public virtual IReadOnlyCollection<EventRecord> Get(int offset = 0, int limit = int.MaxValue) + { + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be greater than or equal to zero"); + } + + if (limit <= 0) + { + throw new ArgumentOutOfRangeException(nameof(limit), "Limit must be greater than zero"); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + + var events = context.Events + .OrderByDescending(e => e.Timestamp) + .Skip(offset) + .Take(limit) + .ToList(); + + return events; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get event records with options {Options}: {Message}", new { offset, limit }, ex.Message); + throw; + } + } + + /// <summary> + /// Gets the total number of events. + /// </summary> + /// <returns>The total number of events.</returns> + public virtual int Count() + { + try + { + using var context = ContextFactory.CreateDbContext(); + var count = context.Events.Count(); + return count; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to count event records: {Message}", ex.Message); + throw; + } + } + + /// <summary> + /// Adds the specified event <paramref name="eventRecord"/>. + /// </summary> + /// <remarks> + /// To ensure proper construction of the record, use <see cref="EventRecord.From"/>. + /// </remarks> + /// <param name="eventRecord">The record to add.</param> + /// <exception cref="ArgumentNullException">Thrown when the specified record is null.</exception> + public virtual void Add(EventRecord eventRecord) + { + if (eventRecord is null) + { + throw new ArgumentNullException(nameof(eventRecord)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + context.Add(eventRecord); + context.SaveChanges(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to add event record: {Message}", ex.Message); + throw; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs new file mode 100644 index 00000000..9acbc9a4 --- /dev/null +++ b/src/slskd/Events/EventsDbContext.cs @@ -0,0 +1,40 @@ +// <copyright file="EventsDbContext.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using Microsoft.EntityFrameworkCore; + +public class EventsDbContext : DbContext +{ + public EventsDbContext(DbContextOptions<EventsDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<EventRecord> Events { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity<EventRecord>() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + } +}
\ No newline at end of file diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs new file mode 100644 index 00000000..11825c09 --- /dev/null +++ b/src/slskd/Events/Types/EventRecord.cs @@ -0,0 +1,84 @@ +// <copyright file="EventRecord.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; + +[Index(nameof(Timestamp))] +[Index(nameof(Type))] +public record EventRecord +{ + public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public string Type { get; private set; } + public string Data { get; init; } + [Key] + public Guid Id { get; private set; } + + private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = false, + }; + + /// <summary> + /// Converts the specified event <paramref name="e"/> into an instance of <see cref="EventRecord"/> + /// for the purpose of database storage. + /// </summary> + /// <remarks> + /// The <see cref="Data"/> property contains the event-specific data serialized as json, applying + /// standard formatting such as camel cased property names and null value omission. This is important so that + /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, + /// but standardizing json is a good practice. + /// </remarks> + /// <param name="e">The Event to convert.</param> + /// <typeparam name="T">The specific type of the Event.</typeparam> + /// <returns>The converted EventRecord.</returns> + public static EventRecord From<T>(Event e) + where T : Event + { + // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' + var type = e.GetType().Name.Split('.').TakeLast(1).First(); + type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix + + // construct the data for the record by serializing the event and removing redundant properties + var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); + var data = JsonNode.Parse(json).AsObject(); + data.Remove(nameof(Timestamp).ToLower()); + data.Remove(nameof(Type).ToLower()); + data.Remove(nameof(Id).ToLower()); + data.Remove(nameof(Data).ToLower()); + + return new EventRecord + { + Timestamp = e.Timestamp, + Type = type, + Id = e.Id, + Data = data.ToJsonString(JsonSerializerOptions), + }; + } +}
\ No newline at end of file diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs new file mode 100644 index 00000000..20ec3f9f --- /dev/null +++ b/src/slskd/Events/Types/Events.cs @@ -0,0 +1,41 @@ +// <copyright file="Events.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using slskd.Transfers; + +public abstract record Event +{ + public Guid Id { get; } = Guid.NewGuid(); + public DateTime Timestamp { get; init; } = DateTime.UtcNow; +} + +public sealed record DownloadFileCompleteEvent : Event +{ + public string LocalFilename { get; init; } + public string RemoteFilename { get; init; } + public Transfer Transfer { get; init; } +} + +public sealed record DownloadDirectoryCompleteEvent : Event +{ + public string LocalDirectoryName { get; init; } + public string RemoteDirectoryName { get; init; } + public string Username { get; init; } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d47d3d91..6392385f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -39,7 +39,6 @@ namespace slskd using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -57,6 +56,7 @@ namespace slskd using slskd.Configuration; using slskd.Core.API; using slskd.Cryptography; + using slskd.Events; using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; @@ -558,17 +558,26 @@ namespace slskd if (OptionsAtStartup.Flags.Volatile) { - services.AddDbContext<SearchDbContext>($"Data Source=file:search?mode=memory;Cache=shared;Pooling=True;"); - services.AddDbContext<TransfersDbContext>($"Data Source=file:transfers?mode=memory;Cache=shared;Pooling=True;"); - services.AddDbContext<MessagingDbContext>($"Data Source=file:messaging?mode=memory;Cache=shared;Pooling=True;"); + static string MemoryConnectionString(string name) => $"Data Source=file:{name}?mode=memory;Cache=shared;Pooling=True;"; + + services.AddDbContext<SearchDbContext>(MemoryConnectionString("search")); + services.AddDbContext<TransfersDbContext>(MemoryConnectionString("transfers")); + services.AddDbContext<MessagingDbContext>(MemoryConnectionString("messaging")); + services.AddDbContext<EventsDbContext>(MemoryConnectionString("events")); } else { - services.AddDbContext<SearchDbContext>($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); - services.AddDbContext<TransfersDbContext>($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); - services.AddDbContext<MessagingDbContext>($"Data Source={Path.Combine(DataDirectory, "messaging.db")};Cache=shared;Pooling=True;"); + static string DiskConnectionString(string name) => $"Data Source={Path.Combine(DataDirectory, $"{name}.db")};Cache=shared;Pooling=True;"; + + services.AddDbContext<SearchDbContext>(DiskConnectionString("search")); + services.AddDbContext<TransfersDbContext>(DiskConnectionString("transfers")); + services.AddDbContext<MessagingDbContext>(DiskConnectionString("messaging")); + services.AddDbContext<EventsDbContext>(DiskConnectionString("events")); } + services.AddSingleton<EventService>(); + services.AddSingleton<EventBus>(); + services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); @@ -631,7 +640,7 @@ namespace slskd .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() - .WithExposedHeaders("X-URL-Base"))); + .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); services.AddSystemMetrics(); using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 32903bf9..37df355c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -29,6 +29,7 @@ namespace slskd.Transfers.Downloads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Events; using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; @@ -122,7 +123,8 @@ namespace slskd.Transfers.Downloads IDbContextFactory<TransfersDbContext> contextFactory, FileService fileService, IRelayService relayService, - IFTPService ftpClient) + IFTPService ftpClient, + EventBus eventBus) { Client = soulseekClient; OptionsMonitor = optionsMonitor; @@ -130,6 +132,7 @@ namespace slskd.Transfers.Downloads Files = fileService; FTP = ftpClient; Relay = relayService; + EventBus = eventBus; } private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); @@ -140,6 +143,7 @@ namespace slskd.Transfers.Downloads private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } + private EventBus EventBus { get; } /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. @@ -281,7 +285,7 @@ namespace slskd.Transfers.Downloads { transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer); })); @@ -312,25 +316,54 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); - // this would be the ideal place to hook in a generic post-download task processor for now, we'll - // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could - // argue both ways for that being the correct behavior. revisit this later. + var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + var finalFilename = Files.MoveFile( sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), + destinationDirectory: destinationDirectory, overwrite: false, deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file to {Destination}", finalFilename); + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory if (OptionsMonitor.CurrentValue.Relay.Enabled) { _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } + EventBus.Raise(new DownloadFileCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, + }); + + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); + + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) { _ = FTP.UploadAsync(finalFilename); @@ -342,7 +375,7 @@ namespace slskd.Transfers.Downloads transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Cancelled; - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); throw; @@ -355,7 +388,7 @@ namespace slskd.Transfers.Downloads transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Errored; - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); throw; diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 1797adcd..ddb3e017 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -29,6 +29,10 @@ namespace slskd.Transfers public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; init; } + + /// <summary> + /// Gets the remote filename. + /// </summary> public string Filename { get; init; } public long Size { get; set; } public long StartOffset { get; init; } diff --git a/src/slskd/Transfers/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs index bc2b69b1..9dbd6696 100644 --- a/src/slskd/Transfers/Types/Upload.cs +++ b/src/slskd/Transfers/Types/Upload.cs @@ -30,4 +30,4 @@ namespace slskd.Transfers public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); public string Username { get; set; } } -} +}
\ No newline at end of file diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx new file mode 100644 index 00000000..7f708908 --- /dev/null +++ b/src/web/src/components/System/Events/index.jsx @@ -0,0 +1,118 @@ +import { list } from '../../../lib/events'; +import { LoaderSegment } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { Icon, Pagination, Popup, Table } from 'semantic-ui-react'; + +const PER_PAGE = 10; + +const replaceHyphensWithNonBreakingEquivalent = (string) => + string?.replaceAll('-', '‑'); + +const Events = () => { + const [page, setPage] = useState(1); + const [totalPages, setTotalPages] = useState(0); + const [loading, setLoading] = useState(false); + const [events, setEvents] = useState([]); + + const fetch = async () => { + setLoading(true); + + const { events: items, totalCount } = await list({ + limit: PER_PAGE, + offset: (page - 1) * PER_PAGE, + }); + + const tp = Math.ceil(totalCount / PER_PAGE); + + setEvents(items); + setTotalPages(Number.isNaN(tp) ? 0 : tp); + setLoading(false); + + return items; + }; + + const paginationChanged = ({ activePage }) => { + if (activePage >= 1) { + setPage(activePage); + } + }; + + useEffect(() => { + fetch(); + }, [page]); // eslint-disable-line react-hooks/exhaustive-deps + + if (loading) { + return <LoaderSegment />; + } + + return ( + <> + <div className="header-buttons"> + <Pagination + activePage={page} + className="header-buttons" + onPageChange={(event, data) => paginationChanged({ ...data })} + totalPages={totalPages} + /> + </div> + <Table + className="events-table, unstackable" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell className="events-list-id">Id</Table.HeaderCell> + <Table.HeaderCell className="events-list-timestamp"> + Timestamp + </Table.HeaderCell> + <Table.HeaderCell className="events-list-type"> + Type + </Table.HeaderCell> + <Table.HeaderCell className="events-list-data"> + Data + </Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body className="events-table-body"> + {events?.length === 0 ? ( + <Table.Row> + <Table.Cell + colSpan={99} + style={{ + opacity: 0.5, + padding: '10px !important', + textAlign: 'center', + }} + > + No events + </Table.Cell> + </Table.Row> + ) : ( + events.map((event) => ( + <Table.Row key={event.id}> + <Table.Cell> + <Popup + content={event.id} + on="hover" + style={{ fontFamily: 'monospace', width: '400px' }} + trigger={<Icon name="info circle" />} + wide="very" + /> + </Table.Cell> + <Table.Cell> + {replaceHyphensWithNonBreakingEquivalent(event.timestamp)} + </Table.Cell> + <Table.Cell>{event.type}</Table.Cell> + <Table.Cell className="events-table-data"> + {JSON.stringify(JSON.parse(event.data), null, 2)} + </Table.Cell> + </Table.Row> + )) + )} + </Table.Body> + </Table> + </> + ); +}; + +export default Events; diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index ded0449a..a3a2c83a 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -8,11 +8,11 @@ margin-bottom: 16px; } -.logs-table { +.logs-table, .events-table { font-size: smaller; } -.logs-table-body { +.logs-table-body, .events-table-body { font-family: monospace; } @@ -20,6 +20,18 @@ word-break: break-all; } +.events-list-id { + width: 0px; /* shrink to fit */ +} + +.events-list-timestamp { + width: 0px; /* shrink to fit */ +} + +.events-list-type { + width: 0px; /* shrink to fit */ +} + .logs { min-height: 100px; } diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx index 8746cefe..2dbd9d91 100644 --- a/src/web/src/components/System/System.jsx +++ b/src/web/src/components/System/System.jsx @@ -1,6 +1,7 @@ import './System.css'; import { Switch } from '../Shared'; import Data from './Data'; +import Events from './Events'; import Files from './Files'; import Info from './Info'; import Logs from './Logs'; @@ -122,6 +123,19 @@ const System = ({ options = {}, state = {}, theme }) => { }, { menuItem: { + content: 'Events', + icon: 'calendar check', + key: 'events', + }, + render: () => ( + <Tab.Pane className="full-height"> + <Events /> + </Tab.Pane> + ), + route: 'events', + }, + { + menuItem: { content: 'Logs', icon: 'file outline', key: 'logs', diff --git a/src/web/src/lib/events.js b/src/web/src/lib/events.js new file mode 100644 index 00000000..9f16a66f --- /dev/null +++ b/src/web/src/lib/events.js @@ -0,0 +1,10 @@ +import api from './api'; + +export const list = async ({ offset, limit }) => { + const response = await api.get(`/events?offset=${offset}&limit=${limit}`); + + const events = response.data; + const totalCount = response.headers['x-total-count']; + + return { events, totalCount }; +}; |
