aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--docs/config.md63
-rw-r--r--src/slskd/Events/API/EventsController.cs73
-rw-r--r--src/slskd/Events/Types/Events.cs12
3 files changed, 136 insertions, 12 deletions
diff --git a/docs/config.md b/docs/config.md
index 8ac29622..9d17974f 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -923,7 +923,58 @@ retention:
# Integrations
-## Webhooks
+## User-Defined
+
+User-defined integrations allow users to configure external applications to receive data from slskd as things happen internally. slskd uses an internal [event bus](https://www.akamai.com/glossary/what-is-an-event-bus) over which event data is sent from application logic to whatever destination(s) users choose.
+
+The number and type of events will change as the application matures, but each event should have some minimal properties:
+
+|Name|Description|
+|-|-|
+|Id|The unique ID for the event. Events may be delivered to external consumers more than once; use this property to de-duplicate them.|
+|Timestamp|The time (UTC) at which the event was raised. Events can arrive out of chronological order; use this property to determine if that has taken place.|
+|Version|The event version, used to disambiguate event shapes if a breaking change is made to the data in the future.|
+|Type|The event type. Use this to determine what other data will be included. See: [Events.cs](https://github.com/slskd/slskd/blob/master/src/slskd/Events/Types/Events.cs).|
+
+Here's an example of what a `DownloadFileComplete` event (at the time of this writing; review Events.cs!) looks like:
+
+```json
+{
+ "type": "DownloadFileComplete",
+ "version": 0,
+ "localFilename": "asdfasfdasfdlocal.file",
+ "remoteFilename": "asdfasfdasfdremote.file",
+ "transfer": {
+ "id": "00000000-0000-0000-0000-000000000000",
+ "direction": "Download",
+ "size": 0,
+ "startOffset": 0,
+ "state": "None",
+ "requestedAt": "0001-01-01T00:00:00",
+ "bytesTransferred": 0,
+ "averageSpeed": 0,
+ "bytesRemaining": 0,
+ "percentComplete": 0
+ },
+ "id": "973bed18-8516-4b7d-ab24-e13888385237",
+ "timestamp": "2024-11-28T00:54:13.8939864Z"
+}
+```
+
+Users developing integrations can use the internal `RaiseEvent` HTTP endpoint to create sample events and put them on the bus. This will help test integrations end to end without having to take action within the application, but be aware; using this endpoint after testing is complete is not a good idea!
+
+Here's an example cURL command for the endpoint:
+
+```bash
+curl --location 'localhost:5030/api/v0/events/downloadfilecomplete' \
+ --header 'Content-Type: application/json' \
+ --header 'X-API-Key: <an API key from your config>' \
+ --data '"asdfasfdasfd"'
+```
+
+The data passed is a 'disambiguator' that's prepended to sample data. This helps differentiate between different event instances.
+
+### Webhooks
Webhooks (outbound HTTP requests) can be configured to be called when application events are raised. Webhooks are given a name (useful for troubleshooting!), a list of triggering events, a `call` configuration that defines the HTTP request to be made, and timeout and retry configuration.
@@ -958,7 +1009,7 @@ integration:
attempts: 3
```
-## User-Defined Scripts
+### Scripts
User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script.
@@ -981,7 +1032,11 @@ integration:
run: cmd.exe echo $DATA >> event_log.txt # Windows
```
-## FTP
+## System-Defined
+
+System-defined integrations are part of the application logic. Users can configure settings, but don't have any control over behavior.
+
+### FTP
Files can be uploaded to a remote FTP server upon completion. Files are uploaded to the server and remote path specified using the directory and filename with which they were downloaded; the FTP will match the layout of the local disk.
@@ -1018,7 +1073,7 @@ integration:
retry_attempts: 3
```
-## Pushbullet
+### Pushbullet
Pushbullet notifications can be sent when a private message is sent, or the current user's username is mentioned in a chat room. Notifications are prefixed with a user-definable string to differentiate these notifications from others.
diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs
index 46afa5c7..c0aa92f0 100644
--- a/src/slskd/Events/API/EventsController.cs
+++ b/src/slskd/Events/API/EventsController.cs
@@ -19,44 +19,54 @@ namespace slskd.Events.API;
using System;
using System.Collections.Generic;
+using System.Linq;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
+using slskd.Transfers;
/// <summary>
/// Events.
/// </summary>
[Route("api/v{version:apiVersion}/[controller]")]
-[ApiVersion("0")]
[ApiController]
+[ApiVersion("0")]
[Produces("application/json")]
[Consumes("application/json")]
public class EventsController : ControllerBase
{
public EventsController(
- EventService eventService)
+ EventService eventService,
+ EventBus eventBus)
{
Events = eventService;
+ EventBus = eventBus;
}
private EventService Events { get; }
+ private EventBus EventBus { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<EventsController>();
/// <summary>
- /// Retrieves a paginated list of past <see cref="Event"/> records.
+ /// Retrieves a paginated list of past event records.
/// </summary>
/// <param name="offset">The offset (number of records) at which to start the requested page.</param>
/// <param name="limit">The page size.</param>
/// <returns>The list of <see cref="Event"/> records.</returns>
+ /// <response code="400">The offset is less than zero, or if the limit is less than or equal to zero.</response>
+ /// <response code="401">Authentication credentials are omitted.</response>
+ /// <response code="403">Authentication is valid but not sufficient to access this endpoint.</response>
+ /// <response code="500">An unexpected error is encountered.</response>
+ /// <response code="200">The request completed successfully.</response>
[HttpGet("", Name = nameof(GetEvents))]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(401)]
[ProducesResponseType(403)]
- [ProducesResponseType(typeof(IEnumerable<EventRecord>), 200)]
[ProducesResponseType(typeof(string), 500)]
+ [ProducesResponseType(typeof(IEnumerable<EventRecord>), 200)]
public IActionResult GetEvents([FromQuery] int offset = 0, [FromQuery] int limit = 100)
{
if (offset < 0)
@@ -84,4 +94,59 @@ public class EventsController : ControllerBase
throw;
}
}
+
+ /// <summary>
+ /// Raises a sample event of the specified type.
+ /// </summary>
+ /// <param name="type">The type of event to raise.</param>
+ /// <param name="disambiguator">An optional string used to disambiguate generated events.</param>
+ /// <returns>The randomly generated event that was raised.</returns>
+ /// <response code="400">The specified type is not a valid event type.</response>
+ /// <response code="401">Authentication credentials are omitted.</response>
+ /// <response code="403">Authentication is valid but not sufficient to access this endpoint.</response>
+ /// <response code="500">An unexpected error is encountered.</response>
+ /// <response code="201">The request completed successfully.</response>
+ [HttpPost("{type}", Name = nameof(RaiseEvent))]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(401)]
+ [ProducesResponseType(403)]
+ [ProducesResponseType(typeof(string), 500)]
+ [ProducesResponseType(typeof(Event), 201)]
+ public IActionResult RaiseEvent([FromRoute] string type, [FromBody] string disambiguator)
+ {
+ if (!Enum.TryParse<EventType>(type, ignoreCase: true, out var eventType))
+ {
+ var names = Enum.GetNames(typeof(EventType))
+ .Where(n => n != EventType.Any.ToString() && n != EventType.None.ToString());
+
+ return BadRequest($"Unknown event type '{type}'; must be one of {string.Join(", ", names)}");
+ }
+
+ if (eventType is EventType.None || eventType is EventType.Any)
+ {
+ return BadRequest($"Event type '{type}' can not be raised");
+ }
+
+ try
+ {
+ var d = disambiguator;
+
+ Event @event = eventType switch
+ {
+ EventType.DownloadFileComplete => new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() },
+ EventType.DownloadDirectoryComplete => new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" },
+ EventType.Noop => new NoopEvent(),
+ _ => throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."),
+ };
+
+ EventBus.Raise(@event);
+ return StatusCode(201, @event);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to raise event {Type}: {Message}", eventType, ex.Message);
+ throw;
+ }
+ }
} \ No newline at end of file
diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs
index e4274e39..fc9397ea 100644
--- a/src/slskd/Events/Types/Events.cs
+++ b/src/slskd/Events/Types/Events.cs
@@ -34,19 +34,22 @@ public abstract record Event
public Guid Id { get; } = Guid.NewGuid();
public DateTime Timestamp { get; init; } = DateTime.UtcNow;
public abstract EventType Type { get; }
+ public abstract int Version { get; }
}
public sealed record DownloadFileCompleteEvent : Event
{
- public override EventType Type => EventType.DownloadFileComplete;
- public string LocalFilename { get; init; }
- public string RemoteFilename { get; init; }
- public Transfer Transfer { get; init; }
+ public override EventType Type { get; } = EventType.DownloadFileComplete;
+ public override int Version { get; } = 0;
+ public required string LocalFilename { get; init; }
+ public required string RemoteFilename { get; init; }
+ public required Transfer Transfer { get; init; }
}
public sealed record DownloadDirectoryCompleteEvent : Event
{
public override EventType Type => EventType.DownloadDirectoryComplete;
+ public override int Version { get; } = 0;
public string LocalDirectoryName { get; init; }
public string RemoteDirectoryName { get; init; }
public string Username { get; init; }
@@ -55,4 +58,5 @@ public sealed record DownloadDirectoryCompleteEvent : Event
public sealed record NoopEvent : Event
{
public override EventType Type => EventType.Noop;
+ public override int Version { get; } = 0;
} \ No newline at end of file