New Webserver and WebApp (#942)

* Replace the WCF webserver with an ASP.NET Core webserver (VocaluxeWeb)

- New project VocaluxeWeb: ASP.NET Core 2.3 (Kestrel) on .NET Framework 4.8.1, HTTP or HTTPS
  with a self-signed certificate, REST API (/api/v1) with Swagger, live events (Server-Sent Events)
- Access to the game only through IVocaluxeRemote; requests run on the main thread once per frame
- Sessions with roles (guest, player, admin) and configurable permissions, PINs hashed with PBKDF2
- Queue as a playlist with requesters and singers, fair order (one song per person and round)
- Admin: settings, server status, logged-in devices, activate/deactivate and delete profiles
- Profile pictures: own photo or one of the Vocaluxe avatars
- Game: WebApp queue screen (song options, playlist group) to start the next song with the chosen
  singers, return to it after singing, warning when the webserver is off, remote keyboard
- Old WCF server, WebserverInitalConfig and URL reservations removed; libraries moved to libs/managed
- Unit tests for PIN hashing, settings and permissions, queue order and device names
- AppVeyor: Visual Studio 2022 image and Node.js 24 (the build compiles the WebApp)
- Documentation in VocaluxeWeb/README.md

* New WebApp (Vue 3, TypeScript, Vite) replacing the old jQuery Mobile website

- Login with profile and PIN, create profiles
- Songs with search, filters, sorting and 30 second previews
- Queue: add songs with game mode, audio and singers, edit, reorder, start in the game
- Playlists: create, edit, add to the queue
- Now playing with live updates, remote control and keyboard
- Players: own profile with picture (photo or Vocaluxe avatar), roles for admins
- Admin settings: permissions, server status, devices, profiles
- Help page, responsive layout for phones, tablets and desktops, light and dark mode
- Texts in WebApp/src/locales/en.json, translated with Transifex
- Old website and PhoneGap config removed

---------

Co-authored-by: Florian Ostertag <flokuep@users.noreply.github.com>
This commit is contained in:
McSchneidarandFlorian Ostertag authored and GitHub committed 2026-10-26 05:40:11 +01:00
1 parent e3e9d1d6ae
commit 336d08040e
186 files changed
+14971 -6988

No files matched your search

+187
View File
@@ -0,0 +1,187 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Hosting;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
[Route("api/v1/admin")]
[RequireAdmin]
public sealed class AdminController : ApiControllerBase
{
private readonly CWebSettingsStore _Settings;
private readonly CQueueService _Queue;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly IVocaluxeRemote _Remote;
private readonly CSessionStore _Sessions;
private readonly CLiveEvents _Events;
private readonly CWebHost _Host;
public AdminController(CWebSettingsStore settings, CQueueService queue, CMainThreadDispatcher dispatcher, IVocaluxeRemote remote, CSessionStore sessions,
CLiveEvents events, CWebHost host)
{
_Settings = settings;
_Queue = queue;
_Dispatcher = dispatcher;
_Remote = remote;
_Sessions = sessions;
_Events = events;
_Host = host;
}
[HttpGet("settings")]
public ActionResult<AdminSettingsDto> GetSettings()
{
return _ToDto(_Settings.Current);
}
[HttpPut("settings")]
public async Task<ActionResult<AdminSettingsDto>> UpdateSettings([FromBody] AdminSettingsDto request)
{
_Settings.Update(s =>
{
s.AllowProfileCreation = request.AllowProfileCreation.Value;
s.QueuePlaylistName = request.QueuePlaylistName.Trim();
s.GuestPermissions = request.GuestPermissions.Distinct().ToList();
s.PlayerPermissions = request.PlayerPermissions.Distinct().ToList();
});
await _Dispatcher.InvokeAsync(_Queue.EnsurePlaylist);
return _ToDto(_Settings.Current);
}
/// Address, HTTPS and connected WebApps. The port is set in config.xml, HTTPS in the game (Options - Server).
[HttpGet("status")]
public ActionResult<AdminStatusDto> GetStatus()
{
return new AdminStatusDto
{
Version = _Remote.Version,
Address = _Host.Address?.AbsoluteUri ?? "",
Port = _Host.Port,
Https = _Host.UseHttps,
ConnectedClients = _Events.ClientCount
};
}
/// All profiles, including inactive ones.
[HttpGet("profiles")]
public async Task<ActionResult<IList<ProfileDto>>> GetProfiles()
{
var profiles = await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles());
return profiles.Select(ToDto).ToList();
}
/// Activates or deactivates a profile. Inactive profiles can't log in; their devices are logged out.
[HttpPut("profiles/{id}/active")]
public async Task<ActionResult<ProfileDto>> SetActive(Guid id, [FromBody] ActiveDto request)
{
if (id == CurrentSession.ProfileId && !request.Active.Value)
{
return Problem(StatusCodes.Status400BadRequest, "You cannot deactivate your own profile.");
}
var profile = await _Find(id);
if (profile == null)
{
return Problem(StatusCodes.Status404NotFound, "Profile not found.");
}
await _Dispatcher.InvokeAsync(() => _Remote.UpdateProfile(id, new ProfileChange { IsActive = request.Active.Value }));
if (!request.Active.Value)
{
_Sessions.RemoveProfile(id);
}
return ToDto(await _Find(id));
}
/// Deletes a profile in the game (including its file) and logs out its devices.
[HttpDelete("profiles/{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> DeleteProfile(Guid id)
{
if (id == CurrentSession.ProfileId)
{
return Problem(StatusCodes.Status400BadRequest, "You cannot delete your own profile.");
}
if (await _Find(id) == null)
{
return Problem(StatusCodes.Status404NotFound, "Profile not found.");
}
await _Dispatcher.InvokeAsync(() => _Remote.DeleteProfile(id));
_Sessions.RemoveProfile(id);
return NoContent();
}
/// Devices that are logged in.
[HttpGet("sessions")]
public ActionResult<IList<AdminSessionDto>> GetSessions()
{
return _Sessions.List().Select(s => new AdminSessionDto
{
Id = s.Id,
Profile = new ProfileRefDto { Id = s.ProfileId, Name = s.ProfileName },
Role = s.Role,
Device = CUserAgent.Describe(s.UserAgent),
RemoteAddress = s.RemoteAddress,
LastSeen = s.LastSeen,
IsCurrent = s.Id == CurrentSession.Id
}).ToList();
}
/// Logs out a device.
[HttpDelete("sessions/{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult DeleteSession(string id)
{
if (id == CurrentSession.Id)
{
return Problem(StatusCodes.Status400BadRequest, "Use logout to log out this device.");
}
return _Sessions.RemoveById(id) ? NoContent() : (IActionResult)Problem(StatusCodes.Status404NotFound, "Session not found.");
}
private async Task<RemoteProfile> _Find(Guid id)
{
return (await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles())).FirstOrDefault(p => p.Id == id);
}
private static AdminSettingsDto _ToDto(CWebSettings settings)
{
return new AdminSettingsDto
{
AllowProfileCreation = settings.AllowProfileCreation,
QueuePlaylistName = settings.QueuePlaylistName,
GuestPermissions = settings.GuestPermissions,
PlayerPermissions = settings.PlayerPermissions
};
}
}
}
+119
View File
@@ -0,0 +1,119 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
[ApiController]
[Produces("application/json")]
public abstract class ApiControllerBase : ControllerBase
{
internal const string SessionItemKey = "vlx.session";
/// The logged in session; set for actions with <see cref="RequireSessionAttribute" />.
protected CSession CurrentSession => HttpContext.Items[SessionItemKey] as CSession;
protected bool HasPermission(EPermission permission)
{
var session = CurrentSession;
var settings = HttpContext.RequestServices.GetRequiredService<CWebSettingsStore>().Current;
return session != null && settings.GetPermissions(session.Role).Contains(permission);
}
protected ObjectResult Problem(int status, string title)
{
return new ObjectResult(new ProblemDetails { Status = status, Title = title }) { StatusCode = status, ContentTypes = { "application/problem+json" } };
}
public static ProfileDto ToDto(RemoteProfile profile)
{
return new ProfileDto
{
Id = profile.Id,
Name = profile.Name,
Role = profile.Role,
HasPin = profile.PinHash != null,
HasAvatar = !string.IsNullOrEmpty(profile.AvatarPath),
Difficulty = profile.Difficulty,
IsActive = profile.IsActive
};
}
}
/// The request needs a logged in profile and, optionally, a permission. Admins have all permissions.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class RequireSessionAttribute : Attribute, IAuthorizationFilter
{
private readonly EPermission? _Permission;
public RequireSessionAttribute() { }
public RequireSessionAttribute(EPermission permission)
{
_Permission = permission;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var services = context.HttpContext.RequestServices;
var session = services.GetRequiredService<CSessionStore>().Get(context.HttpContext);
if (session == null)
{
context.Result = _Problem(StatusCodes.Status401Unauthorized, "Please log in.");
return;
}
context.HttpContext.Items[ApiControllerBase.SessionItemKey] = session;
if (_Permission.HasValue && !services.GetRequiredService<CWebSettingsStore>().Current.GetPermissions(session.Role).Contains(_Permission.Value))
{
context.Result = _Problem(StatusCodes.Status403Forbidden, "You are not allowed to do this.");
}
}
private static ObjectResult _Problem(int status, string title)
{
return new ObjectResult(new ProblemDetails { Status = status, Title = title }) { StatusCode = status, ContentTypes = { "application/problem+json" } };
}
}
/// Only admins.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class RequireAdminAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var session = context.HttpContext.RequestServices.GetRequiredService<CSessionStore>().Get(context.HttpContext);
if (session == null || session.Role != ERemoteRole.Admin)
{
var status = session == null ? StatusCodes.Status401Unauthorized : StatusCodes.Status403Forbidden;
context.Result = new ObjectResult(new ProblemDetails { Status = status, Title = "Admins only." }) { StatusCode = status, ContentTypes = { "application/problem+json" } };
return;
}
context.HttpContext.Items[ApiControllerBase.SessionItemKey] = session;
}
}
}
+68
View File
@@ -0,0 +1,68 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// Avatars that come with Vocaluxe, to choose from when changing the profile picture.
[Route("api/v1/avatars")]
public sealed class AvatarsController : ApiControllerBase
{
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CImageService _Images;
public AvatarsController(IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CImageService images)
{
_Remote = remote;
_Dispatcher = dispatcher;
_Images = images;
}
[HttpGet]
[RequireSession]
public async Task<ActionResult<IList<AvatarDto>>> GetAll()
{
var avatars = await _Dispatcher.InvokeAsync(() => _Remote.GetAvatars());
return avatars.Select(a => new AvatarDto { Id = a.Id }).ToList();
}
/// The avatar as JPEG. No login needed.
[HttpGet("{id}")]
[Produces("image/jpeg")]
[ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
public async Task<IActionResult> GetImage(int id, [FromQuery] int size = 200)
{
var avatar = (await _Dispatcher.InvokeAsync(() => _Remote.GetAvatars())).FirstOrDefault(a => a.Id == id);
var file = _Images.GetScaled(avatar?.Path, size, out var etag);
if (file == null)
{
return NotFound();
}
return CImageResult.Create(this, file, etag);
}
}
}
+62
View File
@@ -0,0 +1,62 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// Turns unhandled exceptions into ProblemDetails responses.
sealed class CExceptionFilter : IExceptionFilter
{
private readonly Action<Exception> _OnError;
public CExceptionFilter(Action<Exception> onError)
{
_OnError = onError;
}
public void OnException(ExceptionContext context)
{
ProblemDetails problem;
if (context.Exception is TimeoutException)
{
problem = new ProblemDetails { Status = StatusCodes.Status503ServiceUnavailable, Title = "Vocaluxe is busy, please try again." };
}
else if (context.Exception is CQueueService.CForbiddenException)
{
problem = new ProblemDetails { Status = StatusCodes.Status403Forbidden, Title = "You are not allowed to do this." };
}
else if (context.Exception is ArgumentOutOfRangeException || context.Exception is KeyNotFoundException)
{
problem = new ProblemDetails { Status = StatusCodes.Status404NotFound, Title = "Not found." };
}
else
{
_OnError?.Invoke(context.Exception);
problem = new ProblemDetails { Status = StatusCodes.Status500InternalServerError, Title = "Internal server error." };
}
context.Result = new ObjectResult(problem) { StatusCode = problem.Status, ContentTypes = { "application/problem+json" } };
context.ExceptionHandled = true;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using Microsoft.AspNetCore.Mvc;
namespace VocaluxeWeb.Api
{
static class CImageResult
{
/// Serves a cached JPEG with ETag, so browsers only download it once.
public static IActionResult Create(ControllerBase controller, string file, string etag)
{
var response = controller.Response;
response.Headers["Cache-Control"] = "public, max-age=86400";
response.Headers["ETag"] = etag;
if (controller.Request.Headers["If-None-Match"] == etag)
{
return controller.StatusCode(304);
}
return controller.PhysicalFile(file, "image/jpeg");
}
}
}
+59
View File
@@ -0,0 +1,59 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// Live events as Server-Sent Events (use EventSource in the browser).
/// Events: "state" (StateDto), "queue" (QueueEntryDto[]), "notification" (NotificationDto).
/// The current state and queue are sent right after connecting.
[Route("api/v1/events")]
[RequireSession]
public sealed class EventsController : ApiControllerBase
{
private readonly CLiveEvents _Events;
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CSongLibrary _Songs;
private readonly CQueueService _Queue;
private readonly CSessionStore _Sessions;
public EventsController(CLiveEvents events, IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CSongLibrary songs, CQueueService queue, CSessionStore sessions)
{
_Events = events;
_Remote = remote;
_Dispatcher = dispatcher;
_Songs = songs;
_Queue = queue;
_Sessions = sessions;
}
[HttpGet]
[Produces("text/event-stream")]
public async Task Stream()
{
var state = await _Songs.CreateStateAsync(await _Dispatcher.InvokeAsync(() => _Remote.GetState()));
var queue = await _Queue.GetAsync();
await _Events.StreamAsync(Response, new (string, object)[] { ("state", state), ("queue", queue) }, () => _Sessions.Get(HttpContext) != null,
HttpContext.RequestAborted);
}
}
}
+52
View File
@@ -0,0 +1,52 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
namespace VocaluxeWeb.Api
{
/// Remote keyboard.
[Route("api/v1/input")]
[RequireSession(EPermission.UseKeyboard)]
public sealed class InputController : ApiControllerBase
{
private readonly IVocaluxeRemote _Remote;
public InputController(IVocaluxeRemote remote)
{
_Remote = remote;
}
[HttpPost("key")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult SendKey([FromBody] KeyDto request)
{
_Remote.SendKey(request.Key.Value);
return NoContent();
}
[HttpPost("text")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult SendText([FromBody] TextDto request)
{
_Remote.SendText(request.Text);
return NoContent();
}
}
}
+218
View File
@@ -0,0 +1,218 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// The game's playlists. The queue playlist is not listed here, see /queue.
[Route("api/v1/playlists")]
[RequireSession]
public sealed class PlaylistsController : ApiControllerBase
{
private const string _PlaylistNotFound = "Playlist not found.";
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CSongLibrary _Songs;
private readonly CWebSettingsStore _Settings;
public PlaylistsController(IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CSongLibrary songs, CWebSettingsStore settings)
{
_Remote = remote;
_Dispatcher = dispatcher;
_Songs = songs;
_Settings = settings;
}
[HttpGet]
public async Task<ActionResult<IList<PlaylistSummaryDto>>> GetAll()
{
var queueName = _Settings.Current.QueuePlaylistName;
var playlists = await _Dispatcher.InvokeAsync(() => _Remote.GetPlaylists());
return playlists.Where(p => p.Name != queueName)
.OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase)
.Select(p => new PlaylistSummaryDto { Id = p.Id, Name = p.Name, SongCount = p.Entries.Count })
.ToList();
}
[HttpGet("{id}")]
public async Task<ActionResult<PlaylistDto>> Get(int id)
{
var playlist = await _Find(id);
return playlist == null ? Problem(StatusCodes.Status404NotFound, _PlaylistNotFound) : await _ToDto(playlist);
}
[HttpPost]
[RequireSession(EPermission.EditPlaylists)]
public async Task<ActionResult<PlaylistDto>> Create([FromBody] PlaylistNameDto request)
{
var name = request.Name.Trim();
var invalid = _CheckName(name);
if (invalid != null)
{
return invalid;
}
var id = await _Dispatcher.InvokeAsync(() => _Remote.CreatePlaylist(name));
return await _ToDto(await _Find(id));
}
[HttpPut("{id}")]
[RequireSession(EPermission.EditPlaylists)]
public async Task<ActionResult<PlaylistDto>> Rename(int id, [FromBody] PlaylistNameDto request)
{
if (await _Find(id) == null)
{
return Problem(StatusCodes.Status404NotFound, _PlaylistNotFound);
}
var name = request.Name.Trim();
var invalid = _CheckName(name);
if (invalid != null)
{
return invalid;
}
await _Dispatcher.InvokeAsync(() => _Remote.RenamePlaylist(id, name));
return await _ToDto(await _Find(id));
}
[HttpDelete("{id}")]
[RequireSession(EPermission.DeletePlaylists)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Delete(int id)
{
if (await _Find(id) == null)
{
return Problem(StatusCodes.Status404NotFound, _PlaylistNotFound);
}
await _Dispatcher.InvokeAsync(() => _Remote.DeletePlaylist(id));
return NoContent();
}
[HttpPost("{id}/songs")]
[RequireSession(EPermission.EditPlaylists)]
public async Task<ActionResult<PlaylistDto>> AddSong(int id, [FromBody] SongRefDto request)
{
if (await _Songs.GetAsync(request.SongId.Value) == null)
{
return Problem(StatusCodes.Status404NotFound, "Song not found.");
}
return await _Change(id, entries =>
{
var position = Math.Min(request.Position ?? entries.Count, entries.Count);
entries.Insert(position, new RemotePlaylistEntry { SongId = request.SongId.Value });
});
}
[HttpDelete("{id}/songs/{position}")]
[RequireSession(EPermission.EditPlaylists)]
public Task<ActionResult<PlaylistDto>> RemoveSong(int id, int position)
{
return _Change(id, entries =>
{
if (position < 0 || position >= entries.Count)
{
throw new KeyNotFoundException("No song at this position");
}
entries.RemoveAt(position);
});
}
[HttpPut("{id}/songs/{position}/position")]
[RequireSession(EPermission.EditPlaylists)]
public Task<ActionResult<PlaylistDto>> MoveSong(int id, int position, [FromBody] PositionDto request)
{
return _Change(id, entries =>
{
if (position < 0 || position >= entries.Count)
{
throw new KeyNotFoundException("No song at this position");
}
var entry = entries[position];
entries.RemoveAt(position);
entries.Insert(Math.Min(request.Position.Value, entries.Count), entry);
});
}
/// Reads, changes and saves the playlist in one step on the main thread.
private async Task<ActionResult<PlaylistDto>> _Change(int id, Action<List<RemotePlaylistEntry>> change)
{
var queueName = _Settings.Current.QueuePlaylistName;
var playlist = await _Dispatcher.InvokeAsync(() =>
{
var current = _Remote.GetPlaylists().FirstOrDefault(p => p.Id == id && p.Name != queueName);
if (current == null)
{
return null;
}
var entries = current.Entries.ToList();
change(entries);
_Remote.SetPlaylistEntries(id, entries);
current.Entries = entries;
return current;
});
return playlist == null ? Problem(StatusCodes.Status404NotFound, _PlaylistNotFound) : await _ToDto(playlist);
}
/// The name of the queue playlist can't be used for other playlists.
private ObjectResult _CheckName(string name)
{
if (name.Length == 0)
{
return Problem(StatusCodes.Status400BadRequest, "Please enter a name.");
}
return string.Equals(name, _Settings.Current.QueuePlaylistName, StringComparison.OrdinalIgnoreCase)
? Problem(StatusCodes.Status409Conflict, "This name is reserved for the queue.")
: null;
}
private async Task<RemotePlaylist> _Find(int id)
{
var queueName = _Settings.Current.QueuePlaylistName;
return (await _Dispatcher.InvokeAsync(() => _Remote.GetPlaylists())).FirstOrDefault(p => p.Id == id && p.Name != queueName);
}
private async Task<ActionResult<PlaylistDto>> _ToDto(RemotePlaylist playlist)
{
var songs = new List<PlaylistEntryDto>(playlist.Entries.Count);
for (var i = 0; i < playlist.Entries.Count; i++)
{
songs.Add(new PlaylistEntryDto { Position = i, Song = await _Songs.GetDtoAsync(playlist.Entries[i].SongId) });
}
return new PlaylistDto { Id = playlist.Id, Name = playlist.Name, Songs = songs };
}
}
}
+222
View File
@@ -0,0 +1,222 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
[Route("api/v1/profiles")]
public sealed class ProfilesController : ApiControllerBase
{
private const int _MaxAvatarUpload = 15 * 1024 * 1024;
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CSessionStore _Sessions;
private readonly CWebSettingsStore _Settings;
private readonly CImageService _Images;
public ProfilesController(IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CSessionStore sessions, CWebSettingsStore settings, CImageService images)
{
_Remote = remote;
_Dispatcher = dispatcher;
_Sessions = sessions;
_Settings = settings;
_Images = images;
}
/// All active profiles, for the "Who are you?" page. No login needed.
[HttpGet]
public async Task<ActionResult<IList<ProfileDto>>> GetAll()
{
var profiles = await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles());
return profiles.Where(p => p.IsActive).Select(ToDto).ToList();
}
/// The avatar as JPEG. No login needed.
[HttpGet("{id}/avatar")]
[Produces("image/jpeg")]
[ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAvatar(Guid id, [FromQuery] int size = 200)
{
var profile = await _Find(id);
var file = _Images.GetScaled(profile?.AvatarPath, size, out var etag);
if (file == null)
{
return NotFound();
}
return CImageResult.Create(this, file, etag);
}
/// Creates a profile. Allowed without login if profile creation is enabled in the settings.
[HttpPost]
[ProducesResponseType(typeof(ProfileDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status403Forbidden)]
public async Task<ActionResult<ProfileDto>> Create([FromBody] ProfileCreateDto request)
{
var settings = _Settings.Current;
var session = _Sessions.Get(HttpContext);
var allowed = session != null
? settings.GetPermissions(session.Role).Contains(EPermission.CreateProfiles)
: settings.AllowProfileCreation;
if (!allowed)
{
return Problem(StatusCodes.Status403Forbidden, "Creating profiles is not allowed.");
}
var change = new ProfileChange { Name = request.Name.Trim(), Difficulty = request.Difficulty ?? 0, Role = ERemoteRole.Player };
if (!string.IsNullOrEmpty(request.Pin))
{
CPinHasher.Hash(request.Pin, out change.PinHash, out change.PinSalt);
}
var id = await _Dispatcher.InvokeAsync(() => _Remote.CreateProfile(change));
return ToDto(await _Find(id));
}
/// Changes name, difficulty or PIN.
[HttpPut("{id}")]
[RequireSession]
public async Task<ActionResult<ProfileDto>> Update(Guid id, [FromBody] ProfileUpdateDto request)
{
if (!_CanEdit(id))
{
return Problem(StatusCodes.Status403Forbidden, "You are not allowed to edit this profile.");
}
var change = new ProfileChange { Name = request.Name?.Trim(), Difficulty = request.Difficulty };
if (request.Pin != null)
{
if (request.Pin.Length == 0)
{
change.ClearPin = true;
}
else if (request.Pin.Length < 4)
{
return Problem(StatusCodes.Status400BadRequest, "The PIN needs at least 4 characters.");
}
else
{
CPinHasher.Hash(request.Pin, out change.PinHash, out change.PinSalt);
}
}
return await _Apply(id, change);
}
/// Sets a new avatar. The body is the picture (JPEG or PNG), it is cropped to a square.
[HttpPut("{id}/avatar")]
[RequireSession]
[Consumes("image/jpeg", "image/png", "image/webp", "application/octet-stream")]
public async Task<ActionResult<ProfileDto>> UpdateAvatar(Guid id)
{
if (!_CanEdit(id))
{
return Problem(StatusCodes.Status403Forbidden, "You are not allowed to edit this profile.");
}
byte[] jpeg;
try
{
using (var buffer = new MemoryStream())
{
await Request.Body.CopyToAsync(buffer);
if (buffer.Length == 0 || buffer.Length > _MaxAvatarUpload)
{
return Problem(StatusCodes.Status400BadRequest, "Please send a picture up to 15 MB.");
}
jpeg = CImageService.CreateAvatar(buffer.ToArray());
}
}
catch (ArgumentException)
{
return Problem(StatusCodes.Status400BadRequest, "This picture format is not supported.");
}
return await _Apply(id, new ProfileChange { AvatarJpeg = jpeg });
}
/// Uses one of the avatars of the game, see GET /api/v1/avatars.
[HttpPut("{id}/game-avatar")]
[RequireSession]
public async Task<ActionResult<ProfileDto>> SelectAvatar(Guid id, [FromBody] AvatarSelectDto request)
{
if (!_CanEdit(id))
{
return Problem(StatusCodes.Status403Forbidden, "You are not allowed to edit this profile.");
}
var avatars = await _Dispatcher.InvokeAsync(() => _Remote.GetAvatars());
if (avatars.All(a => a.Id != request.AvatarId.Value))
{
return Problem(StatusCodes.Status404NotFound, "Avatar not found.");
}
return await _Apply(id, new ProfileChange { AvatarId = request.AvatarId });
}
/// Changes the role of a profile (admins only). Logs out the devices of that profile.
[HttpPut("{id}/role")]
[RequireAdmin]
public async Task<ActionResult<ProfileDto>> UpdateRole(Guid id, [FromBody] RoleUpdateDto request)
{
if (id == CurrentSession.ProfileId && request.Role.Value != ERemoteRole.Admin)
{
return Problem(StatusCodes.Status400BadRequest, "You cannot remove your own admin role.");
}
var result = await _Apply(id, new ProfileChange { Role = request.Role });
_Sessions.RemoveProfile(id);
return result;
}
private bool _CanEdit(Guid id)
{
return HasPermission(EPermission.EditAllProfiles) || (id == CurrentSession.ProfileId && HasPermission(EPermission.EditOwnProfile));
}
private async Task<ActionResult<ProfileDto>> _Apply(Guid id, ProfileChange change)
{
if (await _Find(id) == null)
{
return Problem(StatusCodes.Status404NotFound, "Profile not found.");
}
await _Dispatcher.InvokeAsync(() => _Remote.UpdateProfile(id, change));
var profile = await _Find(id);
_Sessions.UpdateProfileName(id, profile.Name);
return ToDto(profile);
}
private async Task<RemoteProfile> _Find(Guid id)
{
return (await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles())).FirstOrDefault(p => p.Id == id);
}
}
}
+239
View File
@@ -0,0 +1,239 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// Song wishes. Everybody gets one song per round. Entries can be changed and removed by their requester
/// or by people allowed to manage the queue; only admins can clear the whole queue.
[Route("api/v1/queue")]
[RequireSession]
public sealed class QueueController : ApiControllerBase
{
public const int MaxPlayers = 6;
private readonly CQueueService _Queue;
private readonly CSongLibrary _Songs;
private readonly CLiveEvents _Events;
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
public QueueController(CQueueService queue, CSongLibrary songs, CLiveEvents events, IVocaluxeRemote remote, CMainThreadDispatcher dispatcher)
{
_Queue = queue;
_Songs = songs;
_Events = events;
_Remote = remote;
_Dispatcher = dispatcher;
}
[HttpGet]
public async Task<ActionResult<IList<QueueEntryDto>>> Get()
{
return Ok(await _Queue.GetAsync());
}
/// Wishes a song. Without game mode the first mode the song supports is used.
[HttpPost]
[RequireSession(EPermission.AddToQueue)]
public async Task<ActionResult<IList<QueueEntryDto>>> Add([FromBody] QueueAddDto request)
{
var song = await _Songs.GetAsync(request.SongId.Value);
if (song == null)
{
return Problem(StatusCodes.Status404NotFound, "Song not found.");
}
var dto = CSongLibrary.ToDto(song);
var gameMode = request.GameMode ?? dto.GameModes.DefaultIfEmpty(ESongGameMode.Normal).First();
var audioMode = request.AudioMode ?? ESongAudioMode.Normal;
var error = _Validate(dto, gameMode, audioMode);
var players = await _ResolvePlayers(request.PlayerIds);
if (error != null || players == null)
{
return Problem(StatusCodes.Status400BadRequest, error ?? "Unknown players.");
}
var result = await _Queue.AddAsync(dto.Id, gameMode, audioMode, players, CurrentSession);
_Events.Publish("notification", new NotificationDto
{
Type = "queueAdded",
Profile = new ProfileRefDto { Id = CurrentSession.ProfileId, Name = CurrentSession.ProfileName },
Song = dto
});
return Ok(result);
}
/// Adds the songs of a playlist (all or the given positions) to the queue, keeping their game and audio mode.
[HttpPost("import")]
[RequireSession(EPermission.AddToQueue)]
public async Task<ActionResult<IList<QueueEntryDto>>> Import([FromBody] QueueImportDto request)
{
var playlist = (await _Dispatcher.InvokeAsync(() => _Remote.GetPlaylists())).FirstOrDefault(p => p.Id == request.PlaylistId.Value);
if (playlist == null)
{
return Problem(StatusCodes.Status404NotFound, "Playlist not found.");
}
var entries = request.Positions == null
? playlist.Entries.ToList()
: request.Positions.Where(p => p >= 0 && p < playlist.Entries.Count).Distinct().Select(p => playlist.Entries[p]).ToList();
if (entries.Count == 0)
{
return Problem(StatusCodes.Status400BadRequest, "No songs to add.");
}
var result = await _Queue.AddManyAsync(entries, CurrentSession);
var first = await _Songs.GetDtoAsync(entries[0].SongId);
_Events.Publish("notification", new NotificationDto
{
Type = entries.Count == 1 ? "queueAdded" : "queueAddedMany",
Profile = new ProfileRefDto { Id = CurrentSession.ProfileId, Name = CurrentSession.ProfileName },
Song = first,
Count = entries.Count
});
return Ok(result);
}
/// Starts singing this entry in the game right away, with its singers. Fails with 409 while the game is busy (e.g. singing).
[HttpPost("{id}/start")]
[RequireSession(EPermission.StartSongs)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<ActionResult<IList<QueueEntryDto>>> Start(string id)
{
var entry = (await _Queue.GetAsync()).FirstOrDefault(e => e.Id == id);
if (entry == null)
{
return Problem(StatusCodes.Status404NotFound, "Queue entry not found.");
}
var started = await _Dispatcher.InvokeAsync(() =>
{
var index = _Queue.IndexOf(id);
if (index < 0)
{
return false;
}
var result = _Remote.StartSong(new RemoteStartRequest
{
SongId = entry.Song.Id,
GameMode = (int)entry.GameMode,
AudioMode = (int)entry.AudioMode,
PlayerIds = entry.Players.Select(p => p.Id).ToList()
});
//With player selection the entry stays until singing really starts (the selection can be cancelled)
if (result == ERemoteStartResult.Singing)
{
_Queue.MarkStarted(index);
}
return result != ERemoteStartResult.Busy;
});
if (!started)
{
return Problem(StatusCodes.Status409Conflict, "Vocaluxe cannot start a song right now.");
}
return Ok(await _Queue.GetAsync());
}
/// Changes game mode, audio mode or players of a wish.
[HttpPut("{id}")]
public async Task<ActionResult<IList<QueueEntryDto>>> Update(string id, [FromBody] QueueUpdateDto request)
{
var entry = (await _Queue.GetAsync()).FirstOrDefault(e => e.Id == id);
if (entry == null)
{
return Problem(StatusCodes.Status404NotFound, "Queue entry not found.");
}
var error = _Validate(entry.Song, request.GameMode ?? entry.GameMode, request.AudioMode ?? entry.AudioMode);
var players = request.PlayerIds == null ? null : await _ResolvePlayers(request.PlayerIds);
if (error != null || (request.PlayerIds != null && players == null))
{
return Problem(StatusCodes.Status400BadRequest, error ?? "Unknown players.");
}
return Ok(await _Queue.UpdateAsync(id, request.GameMode, request.AudioMode, players, CurrentSession, HasPermission(EPermission.ManageQueue)));
}
[HttpDelete("{id}")]
public async Task<ActionResult<IList<QueueEntryDto>>> Remove(string id)
{
return Ok(await _Queue.RemoveAsync(id, CurrentSession, HasPermission(EPermission.ManageQueue)));
}
[HttpPut("{id}/position")]
[RequireSession(EPermission.ManageQueue)]
public async Task<ActionResult<IList<QueueEntryDto>>> Move(string id, [FromBody] PositionDto request)
{
return Ok(await _Queue.MoveAsync(id, request.Position.Value));
}
/// Removes all wishes (admins only).
[HttpDelete]
[RequireAdmin]
public async Task<ActionResult<IList<QueueEntryDto>>> Clear()
{
return Ok(await _Queue.ClearAsync());
}
private static string _Validate(SongDto song, ESongGameMode gameMode, ESongAudioMode audioMode)
{
if (song.GameModes.Count > 0 && !song.GameModes.Contains(gameMode))
{
return "The song does not support this game mode.";
}
if (audioMode != ESongAudioMode.Normal && !song.AudioModes.Contains(audioMode))
{
return "The song does not support this audio mode.";
}
return null;
}
/// The profiles with the given ids, or null if one is unknown or there are too many.
private async Task<List<ProfileRefDto>> _ResolvePlayers(IList<Guid> ids)
{
if (ids == null || ids.Count == 0)
{
return new List<ProfileRefDto>();
}
if (ids.Count > MaxPlayers)
{
return null;
}
var profiles = await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles());
var result = ids.Distinct().Select(id => profiles.FirstOrDefault(p => p.Id == id)).ToList();
return result.Contains(null) ? null : result.Select(p => new ProfileRefDto { Id = p.Id, Name = p.Name }).ToList();
}
}
}
+64
View File
@@ -0,0 +1,64 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
[Route("api/v1")]
public sealed class ServerController : ApiControllerBase
{
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CWebSettingsStore _Settings;
private readonly CSongLibrary _Songs;
public ServerController(IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CWebSettingsStore settings, CSongLibrary songs)
{
_Remote = remote;
_Dispatcher = dispatcher;
_Settings = settings;
_Songs = songs;
}
/// Name and version of the server and how logging in works.
[HttpGet("server")]
public ActionResult<ServerInfoDto> GetServerInfo()
{
var settings = _Settings.Current;
return new ServerInfoDto
{
Name = "Vocaluxe",
Version = _Remote.Version,
AllowProfileCreation = settings.AllowProfileCreation,
QueuePlaylistName = settings.QueuePlaylistName
};
}
/// Current state of the game.
[HttpGet("state")]
[RequireSession]
public async Task<ActionResult<StateDto>> GetState()
{
return await _Songs.CreateStateAsync(await _Dispatcher.InvokeAsync(() => _Remote.GetState()));
}
}
}
+115
View File
@@ -0,0 +1,115 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Dispatching;
using VocaluxeWeb.Remote;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
/// Logging in by picking a profile ("Who are you?"), with PIN if the profile has one.
[Route("api/v1/session")]
public sealed class SessionController : ApiControllerBase
{
private readonly IVocaluxeRemote _Remote;
private readonly CMainThreadDispatcher _Dispatcher;
private readonly CSessionStore _Sessions;
private readonly CWebSettingsStore _Settings;
public SessionController(IVocaluxeRemote remote, CMainThreadDispatcher dispatcher, CSessionStore sessions, CWebSettingsStore settings)
{
_Remote = remote;
_Dispatcher = dispatcher;
_Sessions = sessions;
_Settings = settings;
}
/// The current session.
[HttpGet]
[RequireSession]
public async Task<ActionResult<SessionDto>> Get()
{
var session = CurrentSession;
var profile = (await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles())).FirstOrDefault(p => p.Id == session.ProfileId);
if (profile == null || !profile.IsActive)
{
_Sessions.Remove(HttpContext);
return Problem(StatusCodes.Status401Unauthorized, "Please log in.");
}
session.Role = profile.Role;
session.ProfileName = profile.Name;
return CreateDto(profile, _Settings.Current);
}
/// Logs in as the given profile.
[HttpPost]
[ProducesResponseType(typeof(SessionDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status403Forbidden)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests)]
public async Task<ActionResult<SessionDto>> Create([FromBody] SessionCreateDto request)
{
if (_Sessions.IsLocked(request.ProfileId.Value))
{
return Problem(StatusCodes.Status429TooManyRequests, "Too many wrong PINs, please wait a moment.");
}
var profile = (await _Dispatcher.InvokeAsync(() => _Remote.GetProfiles())).FirstOrDefault(p => p.Id == request.ProfileId.Value);
if (profile == null || !profile.IsActive)
{
return Problem(StatusCodes.Status404NotFound, "Profile not found.");
}
if (profile.PinHash != null)
{
if (!CPinHasher.Verify(request.Pin ?? "", profile.PinHash, profile.PinSalt))
{
_Sessions.RegisterFailedLogin(profile.Id);
return Problem(StatusCodes.Status403Forbidden, "Wrong PIN.");
}
if (CPinHasher.NeedsUpgrade(profile.PinSalt))
{
CPinHasher.Hash(request.Pin, out var hash, out var salt);
await _Dispatcher.InvokeAsync(() => _Remote.UpdateProfile(profile.Id, new ProfileChange { PinHash = hash, PinSalt = salt }));
}
}
_Sessions.Create(HttpContext, profile.Id, profile.Name, profile.Role);
return CreateDto(profile, _Settings.Current);
}
/// Logs out this device.
[HttpDelete]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult Delete()
{
_Sessions.Remove(HttpContext);
return NoContent();
}
internal static SessionDto CreateDto(RemoteProfile profile, CWebSettings settings)
{
return new SessionDto { Profile = ToDto(profile), Permissions = settings.GetPermissions(profile.Role).ToList() };
}
}
}
+130
View File
@@ -0,0 +1,130 @@
#region license
// This file is part of Vocaluxe.
//
// Vocaluxe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Vocaluxe 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VocaluxeWeb.Contracts;
using VocaluxeWeb.Services;
namespace VocaluxeWeb.Api
{
[Route("api/v1/songs")]
[RequireSession]
public sealed class SongsController : ApiControllerBase
{
private readonly CSongLibrary _Songs;
private readonly CImageService _Images;
public SongsController(CSongLibrary songs, CImageService images)
{
_Songs = songs;
_Images = images;
}
/// Searches the song library. All words of the query must appear in artist, title or edition.
[HttpGet]
public async Task<ActionResult<SongPageDto>> Search([FromQuery] SongSearchDto request)
{
return await _Songs.SearchAsync(new CSongQuery
{
Text = request.Query,
Language = request.Language,
Genre = request.Genre,
Decade = request.Decade,
Duet = request.Duet,
Sort = request.Sort,
Page = request.Page,
PageSize = request.PageSize
});
}
/// Available languages, genres and decades with the number of songs, for filters.
[HttpGet("facets")]
public async Task<ActionResult<SongFacetsDto>> GetFacets()
{
return await _Songs.GetFacetsAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<SongDto>> Get(int id)
{
var song = await _Songs.GetAsync(id);
if (song == null)
{
return Problem(StatusCodes.Status404NotFound, "Song not found.");
}
return CSongLibrary.ToDto(song);
}
/// The audio file of the song, for previews. Supports range requests, so the browser can jump to the preview start.
[HttpGet("{id}/audio")]
[Produces("audio/mpeg", "audio/ogg", "audio/mp4", "audio/wav", "audio/flac")]
[ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAudio(int id)
{
var song = await _Songs.GetAsync(id);
if (string.IsNullOrEmpty(song?.AudioPath) || !System.IO.File.Exists(song.AudioPath))
{
return NotFound();
}
Response.Headers["Cache-Control"] = "private, max-age=3600";
return PhysicalFile(song.AudioPath, _GetAudioType(song.AudioPath), true);
}
private static string _GetAudioType(string path)
{
switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
{
case ".ogg":
case ".oga":
case ".opus":
return "audio/ogg";
case ".m4a":
case ".mp4":
case ".aac":
return "audio/mp4";
case ".wav":
return "audio/wav";
case ".flac":
return "audio/flac";
case ".webm":
return "audio/webm";
default:
return "audio/mpeg";
}
}
/// The cover as JPEG, scaled to fit the given size (96, 200 or 400).
[HttpGet("{id}/cover")]
[Produces("image/jpeg")]
[ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
public async Task<IActionResult> GetCover(int id, [FromQuery] int size = 200)
{
var song = await _Songs.GetAsync(id);
var file = _Images.GetScaled(song?.CoverPath, size, out var etag);
if (file == null)
{
return NotFound();
}
return CImageResult.Create(this, file, etag);
}
}
}