//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ 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
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
using Microsoft.Extensions.Options;
namespace slskd.Messaging.API
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Soulseek;
///
/// Rooms.
///
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("0")]
[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
public class RoomsController : ControllerBase
{
public RoomsController(
ISoulseekClient soulseekClient,
IRoomService roomService,
IStateMonitor applicationStateMonitor,
IOptionsSnapshot optionsSnapshot,
IRoomTracker tracker)
{
Client = soulseekClient;
ApplicationStateMonitor = applicationStateMonitor;
OptionsSnapshot = optionsSnapshot;
Tracker = tracker;
RoomService = roomService;
}
private IRoomService RoomService { get; }
private ISoulseekClient Client { get; }
private IStateMonitor ApplicationStateMonitor { get; }
private IRoomTracker Tracker { get; }
private IOptionsSnapshot OptionsSnapshot { get; }
///
/// Gets all rooms.
///
///
/// The request completed successfully.
[HttpGet("joined")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(Dictionary>), 200)]
public IActionResult GetAll()
{
if (Program.IsRelayAgent)
{
return Forbid();
}
return Ok(Tracker.Rooms.Keys);
}
///
/// Gets the specified room.
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpGet("joined/{roomName}")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(Room), 200)]
[ProducesResponseType(404)]
public IActionResult GetByRoomName([FromRoute, UrlEncoded] string roomName)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var room))
{
return Ok(MapRoomToRoomResponse(room));
}
return NotFound();
}
///
/// Sends a message to the specified room.
///
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpPost("joined/{roomName}/messages")]
[Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)]
[ProducesResponseType(201)]
[ProducesResponseType(404)]
public async Task SendMessage([FromRoute, UrlEncoded] string roomName, [FromBody] string message)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var _))
{
await Client.SendRoomMessageAsync(roomName, message);
return StatusCode(StatusCodes.Status201Created);
}
return NotFound();
}
///
/// Sets a ticker for the specified room.
///
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpPost("joined/{roomName}/ticker")]
[Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)]
[ProducesResponseType(201)]
[ProducesResponseType(404)]
public async Task SetTicker([FromRoute, UrlEncoded] string roomName, [FromBody] string message)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var _))
{
await Client.SetRoomTickerAsync(roomName, message);
return StatusCode(StatusCodes.Status201Created);
}
return NotFound();
}
///
/// Adds a member to a private room.
///
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpPost("joined/{roomName}/members")]
[Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)]
[ProducesResponseType(201)]
[ProducesResponseType(404)]
public async Task AddRoomMember([FromRoute, UrlEncoded] string roomName, [FromBody] string username)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var _))
{
await Client.AddPrivateRoomMemberAsync(roomName, username);
return StatusCode(StatusCodes.Status201Created);
}
return NotFound();
}
///
/// Gets the current list of users for the specified room.
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpGet("joined/{roomName}/users")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(IList), 200)]
[ProducesResponseType(404)]
public IActionResult GetUsersByRoomName([FromRoute, UrlEncoded] string roomName)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var room))
{
var response = room.Users
.Select(user => UserDataResponse.FromUserData(user, self: user.Username == ApplicationStateMonitor.CurrentValue.User.Username));
return Ok(response);
}
return NotFound();
}
///
/// Gets the current list of messages for the specified room.
///
///
///
/// The request completed successfully.
/// The specified roomName could not be found.
[HttpGet("joined/{roomName}/messages")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(IList), 200)]
[ProducesResponseType(404)]
public IActionResult GetMessagesByRoomName([FromRoute, UrlEncoded] string roomName)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.TryGet(roomName, out var room))
{
var response = room.Messages
.Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == ApplicationStateMonitor.CurrentValue.User.Username));
return Ok(response);
}
return NotFound();
}
///
/// Gets a list of rooms from the server.
///
///
[HttpGet("available")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(List), 200)]
public async Task GetRooms()
{
if (Program.IsRelayAgent)
{
return Forbid();
}
var list = await Client.GetRoomListAsync();
var response = new List();
response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r)));
response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true)));
response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true)));
foreach (var room in response)
{
room.IsModerated = list.ModeratedRoomNames.Contains(room.Name);
}
return Ok(response);
}
///
/// Joins a room.
///
///
///
/// The request completed successfully.
/// The room has already been joined.
[HttpPost("joined")]
[Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)]
[ProducesResponseType(typeof(Room), 201)]
[ProducesResponseType(304)]
public async Task JoinRoom([FromBody] string roomName)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (Tracker.Rooms.ContainsKey(roomName))
{
return Ok();
}
try
{
var roomData = await RoomService.JoinAsync(roomName);
var room = Room.FromRoomData(roomData);
return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room));
}
catch (Exception ex)
{
if (ex.InnerException is RoomJoinForbiddenException)
{
return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}");
}
throw;
}
}
///
/// Leaves a room.
///
///
///
/// The request completed successfully.
/// The room has not been joined.
[HttpDelete("joined/{roomName}")]
[Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
public async Task LeaveRoom([FromRoute, UrlEncoded] string roomName)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
if (!Tracker.Rooms.ContainsKey(roomName))
{
return StatusCode(StatusCodes.Status404NotFound);
}
await RoomService.LeaveAsync(roomName);
Tracker.TryRemove(roomName);
return StatusCode(StatusCodes.Status204NoContent);
}
private RoomResponse MapRoomToRoomResponse(Room room)
{
bool IsSelf(string username)
{
return username == ApplicationStateMonitor.CurrentValue.User.Username;
}
var response = RoomResponse.FromRoom(room);
response.Users = room.Users
.Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username)));
response.Messages = room.Messages
.Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username)));
return response;
}
}
}