aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Events/API/EventsController.cs
blob: 603d07d596eb9f628f17966e504b83f584ca9f8b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// <copyright file="EventsController.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ Copyright (c) JP Dillingham.
//   │
//   │ 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, version 3.
//   │
//   │ 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/.
//   │
//   │ This program is distributed with Additional Terms pursuant to Section 7
//   │ of the AGPLv3.  See the LICENSE file in the root directory of this
//   │ project for the complete terms and conditions.
//   │
//   │ https://slskd.org
//   │
//   ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
//   │ SPDX-FileCopyrightText: JP Dillingham
//   │ SPDX-License-Identifier: AGPL-3.0-only
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

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.Messaging;
using slskd.Transfers;

/// <summary>
///     Events.
/// </summary>
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("0")]
[Produces("application/json")]
[Consumes("application/json")]
public class EventsController : ControllerBase
{
    public EventsController(
        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 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(string), 500)]
    [ProducesResponseType(typeof(IEnumerable<EventRecord>), 200)]
    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");
        }

        try
        {
            var eventRecords = Events.Get(offset, limit);
            var count = Events.Count();

            Response.Headers.Append("X-Total-Count", count.ToString());

            return Ok(eventRecords);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "Failed to list events: {Message}", ex.Message);
            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;

            // each event must be raised using its concrete type so that the correct subscribers are invoked
            switch (eventType)
            {
                case EventType.DownloadFileComplete:
                    var downloadFileComplete = new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() };
                    EventBus.Raise(downloadFileComplete);
                    @event = downloadFileComplete;
                    break;
                case EventType.DownloadDirectoryComplete:
                    var downloadDirectoryComplete = new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" };
                    EventBus.Raise(downloadDirectoryComplete);
                    @event = downloadDirectoryComplete;
                    break;
                case EventType.UploadFileComplete:
                    var uploadFileComplete = new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() };
                    EventBus.Raise(uploadFileComplete);
                    @event = uploadFileComplete;
                    break;
                case EventType.PrivateMessageReceived:
                    var privateMessageReceived = new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } };
                    EventBus.Raise(privateMessageReceived);
                    @event = privateMessageReceived;
                    break;
                case EventType.RoomMessageReceived:
                    var roomMessageReceived = new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } };
                    EventBus.Raise(roomMessageReceived);
                    @event = roomMessageReceived;
                    break;
                case EventType.Noop:
                    var noop = new NoopEvent();
                    EventBus.Raise(noop);
                    @event = noop;
                    break;
                default:
                    throw new SlskdException($"Event type {eventType} is an enum member but is not handled.  Please submit an issue on GitHub.");
            }

            return StatusCode(201, @event);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "Failed to raise event {Type}: {Message}", eventType, ex.Message);
            throw;
        }
    }
}