Skip to content

Commit

Permalink
Remove AzuraCastStationMountEntity
Browse files Browse the repository at this point in the history
  • Loading branch information
Sella-GH committed Jul 21, 2024
1 parent a497804 commit e80e109
Show file tree
Hide file tree
Showing 19 changed files with 78 additions and 1,355 deletions.
3 changes: 2 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,8 @@ dotnet_diagnostic.rcs1070.severity = suggestion
dotnet_diagnostic.rcs1071.severity = suggestion

# Convert 'if' to 'return' statement
dotnet_diagnostic.rcs1073.severity = suggestion
# This one is doubled
dotnet_diagnostic.rcs1073.severity = none

# Remove redundant constructor
dotnet_diagnostic.rcs1074.severity = suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,22 @@
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using AzzyBot.Bot.Services.Modules;
using AzzyBot.Bot.Utilities.Records.AzuraCast;
using AzzyBot.Core.Logging;
using AzzyBot.Core.Utilities.Encryption;
using AzzyBot.Data;
using AzzyBot.Data.Entities;
using DSharpPlus.Commands.Processors.SlashCommands;
using DSharpPlus.Commands.Processors.SlashCommands.ArgumentModifiers;
using Microsoft.Extensions.Logging;

namespace AzzyBot.Bot.Commands.Autocompletes;

public sealed class AzuraCastMountAutocomplete(DbActions dbActions) : IAutoCompleteProvider
public sealed class AzuraCastMountAutocomplete(ILogger<AzuraCastMountAutocomplete> logger, AzuraCastApiService azuraCast, DbActions dbActions) : IAutoCompleteProvider
{
private readonly ILogger<AzuraCastMountAutocomplete> _logger = logger;
private readonly AzuraCastApiService _azuraCast = azuraCast;
private readonly DbActions _dbActions = dbActions;

public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(AutoCompleteContext context)
Expand All @@ -25,29 +31,31 @@ public async ValueTask<IReadOnlyDictionary<string, object>> AutoCompleteAsync(Au
if (stationId == 0)
return results;

// TODO Solve this more clean and nicer when it's possible
IReadOnlyList<AzuraCastStationMountEntity> mountsInDb;
try
{
mountsInDb = await _dbActions.GetAzuraCastStationMountsAsync(context.Guild.Id, stationId);
if (mountsInDb.Count is 0)
return results;
}
catch (InvalidOperationException)
AzuraCastEntity? azuraCastEntity = await _dbActions.GetAzuraCastAsync(context.Guild.Id, false, false, true);
if (azuraCastEntity is null)
{
_logger.DatabaseAzuraCastNotFound(context.Guild.Id);
return results;
}

string search = context.UserInput;
foreach (AzuraCastStationMountEntity mount in mountsInDb)
bool hlsAdded = false;
AzuraStationRecord record = await _azuraCast.GetStationAsync(new(Crypto.Decrypt(azuraCastEntity.BaseUrl)), stationId);
foreach (AzuraStationMountRecord mount in record.Mounts)
{
if (results.Count == 25)
break;

if (!string.IsNullOrWhiteSpace(search) && !Crypto.Decrypt(mount.Name).Contains(search, StringComparison.OrdinalIgnoreCase))
if (!hlsAdded && record.HlsUrl is not null)
{
results.Add("HTTP Live Streaming", record.HlsUrl);
hlsAdded = true;
}

if (!string.IsNullOrWhiteSpace(search) && !mount.Name.Contains(search, StringComparison.OrdinalIgnoreCase))
continue;

results.Add(Crypto.Decrypt(mount.Name), mount.Id);
results.Add(mount.Name, mount.Url);
}

return results;
Expand Down
4 changes: 2 additions & 2 deletions src/AzzyBot-Next.Bot/Commands/AzuraCastCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ public async ValueTask UploadFilesAsync
_logger.CommandRequested(nameof(UploadFilesAsync), context.User.GlobalName);

AzuraCastEntity azuraCast = await _dbActions.GetAzuraCastAsync(context.Guild.Id) ?? throw new InvalidOperationException("AzuraCast is null");
AzuraCastStationEntity acStation = await _dbActions.GetAzuraCastStationAsync(context.Guild.Id, station, false, false, true) ?? throw new InvalidOperationException("Station is null");
AzuraCastStationEntity acStation = await _dbActions.GetAzuraCastStationAsync(context.Guild.Id, station, false, true) ?? throw new InvalidOperationException("Station is null");
string apiKey = (!string.IsNullOrWhiteSpace(acStation.ApiKey)) ? Crypto.Decrypt(acStation.ApiKey) : Crypto.Decrypt(azuraCast.AdminApiKey);
string baseUrl = Crypto.Decrypt(azuraCast.BaseUrl);

Expand Down Expand Up @@ -575,7 +575,7 @@ public async ValueTask GetNowPlayingAsync
_logger.CommandRequested(nameof(GetNowPlayingAsync), context.User.GlobalName);

AzuraCastEntity azuraCast = await _dbActions.GetAzuraCastAsync(context.Guild.Id) ?? throw new InvalidOperationException("AzuraCast is null");
AzuraCastStationEntity acStation = await _dbActions.GetAzuraCastStationAsync(context.Guild.Id, station, false, false, true) ?? throw new InvalidOperationException("Station is null");
AzuraCastStationEntity acStation = await _dbActions.GetAzuraCastStationAsync(context.Guild.Id, station, false, true) ?? throw new InvalidOperationException("Station is null");
string baseUrl = Crypto.Decrypt(azuraCast.BaseUrl);

AzuraNowPlayingDataRecord? nowPlaying = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class AzuraCastDiscordPermCheck(ILogger<AzuraCastDiscordPermCheck> logger
await context.DeferResponseAsync();

int stationId = Convert.ToInt32(context.Arguments.SingleOrDefault(o => o.Key.Name is "station" && o.Value is not null).Value, CultureInfo.InvariantCulture);
AzuraCastEntity? azuraCast = await _dbActions.GetAzuraCastAsync(context.Guild.Id, false, true, true, false, false, true);
AzuraCastEntity? azuraCast = await _dbActions.GetAzuraCastAsync(context.Guild.Id, false, true, true, false, true);
if (azuraCast is null)
{
_logger.DatabaseAzuraCastNotFound(context.Guild.Id);
Expand All @@ -50,11 +50,9 @@ public class AzuraCastDiscordPermCheck(ILogger<AzuraCastDiscordPermCheck> logger
case "azuracast start-station":
case "azuracast stop-station":
case "azuracast toggle-song-requests":
case "config add-azuracast-station-mount":
case "config modify-azuracast-station":
case "config modify-azuracast-station-checks":
case "config delete-azuracast-station":
case "config delete-azuracast-station-mount":
case "dj delete-song-request":
case "dj skip-song":
case "dj switch-playlist":
Expand Down Expand Up @@ -102,11 +100,9 @@ public class AzuraCastDiscordPermCheck(ILogger<AzuraCastDiscordPermCheck> logger
case "azuracast start-station":
case "azuracast stop-station":
case "azuracast toggle-song-requests":
case "config add-azuracast-station-mount":
case "config modify-azuracast-station":
case "config modify-azuracast-station-checks":
case "config delete-azuracast-station":
case "config delete-azuracast-station-mount":
isStationAdmin = userRoles.Contains(_botService.GetDiscordRole(guildId, station.Preferences.StationAdminRoleId));
break;

Expand Down
56 changes: 4 additions & 52 deletions src/AzzyBot-Next.Bot/Commands/ConfigCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ public async ValueTask AddAzuraCastStationAsync
[Description("Enter the name of the new station.")] string stationName,
[Description("Select the group that has the admin permissions on this station.")] DiscordRole adminGroup,
[Description("Select a channel to get music requests when a request is not found on the server."), ChannelTypes(DiscordChannelType.Text)] DiscordChannel requestsChannel,
[Description("Enable or disable the preference of HLS streams if you add an able mount point."), SlashChoiceProvider<BooleanEnableDisableStateProvider>] int hls,
[Description("Enable or disable the showing of the playlist in the nowplaying embed."), SlashChoiceProvider<BooleanEnableDisableStateProvider>] int showPlaylist,
[Description("Enable or disable the automatic check if files have been changed."), SlashChoiceProvider<BooleanEnableDisableStateProvider>] int fileChanges,
[Description("Select a channel where users are able to upload their own songs to your station."), ChannelTypes(DiscordChannelType.Text)] DiscordChannel? uploadChannel = null,
Expand Down Expand Up @@ -147,7 +146,7 @@ public async ValueTask AddAzuraCastStationAsync
return;
}

await _db.AddAzuraCastStationAsync(context.Guild.Id, station, stationName, adminGroup.Id, requestsChannel.Id, hls is 1, showPlaylist is 1, fileChanges is 1, uploadChannel?.Id, uploadPath, apiKey, djGroup?.Id);
await _db.AddAzuraCastStationAsync(context.Guild.Id, station, stationName, adminGroup.Id, requestsChannel.Id, showPlaylist is 1, fileChanges is 1, uploadChannel?.Id, uploadPath, apiKey, djGroup?.Id);

await context.DeleteResponseAsync();
await context.FollowupAsync("Your station was added successfully and private data has been encrypted.");
Expand All @@ -163,24 +162,6 @@ public async ValueTask AddAzuraCastStationAsync
await _backgroundService.StartAzuraCastBackgroundServiceAsync(AzuraCastChecks.CheckForFileChanges, context.Guild.Id, station);
}

[Command("add-azuracast-station-mount"), Description("Add an AzuraCast mount point to the selected station."), ModuleActivatedCheck(AzzyModules.AzuraCast), AzuraCastDiscordPermCheck([AzuraCastDiscordPerm.InstanceAdminGroup])]
public async ValueTask AddAzuraCastStationMountAsync
(
CommandContext context,
[Description("Choose the station you want to add the mount."), SlashAutoCompleteProvider<AzuraCastStationsAutocomplete>] int station,
[Description("Enter the mount point name.")] string mountName,
[Description("Enter the mount point stub.")] string mount
)
{
ArgumentNullException.ThrowIfNull(context, nameof(context));

_logger.CommandRequested(nameof(AddAzuraCastStationMountAsync), context.User.GlobalName);

await _db.AddAzuraCastStationMountPointAsync(station, mountName, mount);

await context.EditResponseAsync("Your mount point was added successfully.");
}

[Command("delete-azuracast"), Description("Delete the existing AzuraCast setup."), ModuleActivatedCheck(AzzyModules.AzuraCast), AzuraCastDiscordPermCheck([AzuraCastDiscordPerm.InstanceAdminGroup])]
public async ValueTask DeleteAzuraCastAsync(CommandContext context)
{
Expand Down Expand Up @@ -237,24 +218,6 @@ public async ValueTask DeleteAzuraCastStationAsync
await context.EditResponseAsync("Your station was deleted successfully.");
}

[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Needed in the mount autocomplete provider")]
[Command("delete-azuracast-station-mount"), Description("Delete an existing AzuraCast mount point from a station."), ModuleActivatedCheck(AzzyModules.AzuraCast), AzuraCastDiscordPermCheck([AzuraCastDiscordPerm.StationAdminGroup, AzuraCastDiscordPerm.InstanceAdminGroup])]
public async ValueTask DeleteAzuraCastStationMountAsync
(
CommandContext context,
[Description("Select the station of the mount point."), SlashAutoCompleteProvider<AzuraCastStationsAutocomplete>] int station,
[Description("Select the mount point you want to delete."), SlashAutoCompleteProvider<AzuraCastMountAutocomplete>] int mountId
)
{
ArgumentNullException.ThrowIfNull(context, nameof(context));

_logger.CommandRequested(nameof(DeleteAzuraCastStationMountAsync), context.User.GlobalName);

await _db.DeleteAzuraCastMountAsync(mountId);

await context.EditResponseAsync("Your mount point was deleted successfully.");
}

[Command("modify-azuracast"), Description("Modify the general AzuraCast settings."), ModuleActivatedCheck(AzzyModules.AzuraCast), AzuraCastDiscordPermCheck([AzuraCastDiscordPerm.InstanceAdminGroup])]
public async ValueTask UpdateAzuraCastAsync
(
Expand Down Expand Up @@ -359,7 +322,6 @@ public async ValueTask UpdateAzuraCastStationAsync
[Description("Modify the channel where users are able to upload their own songs to your station."), ChannelTypes(DiscordChannelType.Text)] DiscordChannel? uploadChannel = null,
[Description("Modify the channel to get music requests when a request is not found in the station."), ChannelTypes(DiscordChannelType.Text)] DiscordChannel? requestsChannel = null,
[Description("Modify the custom path where the user uploaded songs are stored. Like /Requests")] string? uploadPath = null,
[Description("Enable or disable the preference of HLS streams if you add an able mount point."), SlashChoiceProvider<BooleanEnableDisableStateProvider>] int hls = 0,
[Description("Enable or disable the showing of the playlist in the nowplaying embed."), SlashChoiceProvider<BooleanEnableDisableStateProvider>] int showPlaylist = 0
)
{
Expand All @@ -368,24 +330,14 @@ public async ValueTask UpdateAzuraCastStationAsync

_logger.CommandRequested(nameof(UpdateAzuraCastStationAsync), context.User.GlobalName);

if (stationId is null && stationName is null && apiKey is null && adminGroup is null && djGroup is null && uploadChannel is null && string.IsNullOrWhiteSpace(uploadPath) && requestsChannel is null && hls is 0 && showPlaylist is 0)
if (stationId is null && stationName is null && apiKey is null && adminGroup is null && djGroup is null && uploadChannel is null && string.IsNullOrWhiteSpace(uploadPath) && requestsChannel is null && showPlaylist is 0)
{
await context.RespondAsync("You have to provide at least one parameter to update.");
return;
}

bool? preferHls = null;
bool? showPlaylistInEmbed = null;

if (hls is 1)
{
preferHls = true;
}
else if (hls is 2)
{
preferHls = false;
}

if (showPlaylist is 1)
{
showPlaylistInEmbed = true;
Expand All @@ -398,8 +350,8 @@ public async ValueTask UpdateAzuraCastStationAsync
if (stationId.HasValue || !string.IsNullOrWhiteSpace(stationName) || !string.IsNullOrWhiteSpace(apiKey))
await _db.UpdateAzuraCastStationAsync(context.Guild.Id, station, stationId, stationName, apiKey);

if (adminGroup is not null || djGroup is not null || uploadChannel is not null || requestsChannel is not null || !string.IsNullOrWhiteSpace(uploadPath) || preferHls is not null || showPlaylistInEmbed is not null)
await _db.UpdateAzuraCastStationPreferencesAsync(context.Guild.Id, station, adminGroup?.Id, djGroup?.Id, uploadChannel?.Id, requestsChannel?.Id, uploadPath, preferHls, showPlaylistInEmbed);
if (adminGroup is not null || djGroup is not null || uploadChannel is not null || requestsChannel is not null || !string.IsNullOrWhiteSpace(uploadPath) || showPlaylistInEmbed is not null)
await _db.UpdateAzuraCastStationPreferencesAsync(context.Guild.Id, station, adminGroup?.Id, djGroup?.Id, uploadChannel?.Id, requestsChannel?.Id, uploadPath, showPlaylistInEmbed);

await context.DeleteResponseAsync();
await context.FollowupAsync("Your settings were saved successfully and private data has been encrypted.");
Expand Down
2 changes: 1 addition & 1 deletion src/AzzyBot-Next.Bot/Services/DiscordBotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public async Task RespondToChecksExceptionAsync(ChecksFailedException ex, SlashC
return;
}

AzuraCastEntity? azuraCast = await _db.GetAzuraCastAsync(context.Guild.Id, false, true, true, false, false, true);
AzuraCastEntity? azuraCast = await _db.GetAzuraCastAsync(context.Guild.Id, false, true, true, false, true);
if (azuraCast is null)
{
_logger.DatabaseAzuraCastNotFound(context.Guild.Id);
Expand Down
9 changes: 9 additions & 0 deletions src/AzzyBot-Next.Bot/Services/Modules/AzuraCastApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,15 @@ public async Task<AzuraSongDataRecord> GetSongInfoAsync(Uri baseUrl, string apiK
};
}

public Task<AzuraStationRecord> GetStationAsync(Uri baseUrl, int stationId)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(stationId, nameof(stationId));

string endpoint = $"{AzuraApiEndpoints.Station}/{stationId}";

return GetFromApiAsync<AzuraStationRecord>(baseUrl, endpoint);
}

public Task<AzuraAdminStationConfigRecord> GetStationAdminConfigAsync(Uri baseUrl, string apiKey, int stationId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(apiKey, nameof(apiKey));
Expand Down
10 changes: 0 additions & 10 deletions src/AzzyBot-Next.Bot/Services/Modules/CoreServiceHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ private async Task ReencryptDatabaseAsync()

List<AzuraCastEntity> azuraCast = await dbContext.AzuraCast.ToListAsync();
List<AzuraCastStationEntity> azuraCastStations = await dbContext.AzuraCastStations.ToListAsync();
List<AzuraCastStationMountEntity> AzuraCastStationMounts = await dbContext.AzuraCastStationMounts.ToListAsync();

try
{
Expand All @@ -104,15 +103,6 @@ private async Task ReencryptDatabaseAsync()
}
}

foreach (AzuraCastStationMountEntity entity in AzuraCastStationMounts)
{
entity.Mount = Crypto.Decrypt(entity.Mount);
entity.Mount = Crypto.Encrypt(entity.Mount, newEncryptionKey);

entity.Name = Crypto.Decrypt(entity.Name);
entity.Name = Crypto.Encrypt(entity.Name, newEncryptionKey);
}

await dbContext.SaveChangesAsync();
await transaction.CommitAsync();
}
Expand Down
6 changes: 1 addition & 5 deletions src/AzzyBot-Next.Bot/Utilities/EmbedBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -575,10 +575,8 @@ public static IReadOnlyList<DiscordEmbed> BuildGetSettingsAzuraEmbed(AzuraCastEn
string fileUploadChannel = (station.Preferences.FileUploadChannelId > 0) ? $"<#{station.Preferences.FileUploadChannelId}>" : "Not set";
string requestsChannel = (station.Preferences.RequestsChannelId > 0) ? $"<#{station.Preferences.RequestsChannelId}>" : "Not set";
string fileUploadPath = (!string.IsNullOrWhiteSpace(station.Preferences.FileUploadPath)) ? station.Preferences.FileUploadPath : "Not set";
string preferHls = Misc.ReadableBool(station.Preferences.PreferHls, ReadbleBool.EnabledDisabled);
string showPlaylist = Misc.ReadableBool(station.Preferences.ShowPlaylistInNowPlaying, ReadbleBool.EnabledDisabled);
string fileChanges = Misc.ReadableBool(station.Checks.FileChanges, ReadbleBool.EnabledDisabled);
string mounts = (station.Mounts.Count > 0) ? string.Join('\n', station.Mounts.Select(x => $"- {Crypto.Decrypt(x.Name)}: {Crypto.Decrypt(x.Mount)}")) : "No Mount Points added";

fields = new()
{
Expand All @@ -590,10 +588,8 @@ public static IReadOnlyList<DiscordEmbed> BuildGetSettingsAzuraEmbed(AzuraCastEn
["File Upload Channel"] = new(fileUploadChannel),
["Music Requests Channel"] = new(requestsChannel),
["File Upload Path"] = new(fileUploadPath),
["Prefer HLS Streaming"] = new(preferHls),
["Show Playlist In Now Playing"] = new(showPlaylist),
["Automatic Checks"] = new($"- File Changes: {fileChanges}"),
["Mount Points"] = new(mounts)
["Automatic Checks"] = new($"- File Changes: {fileChanges}")
};

embeds.Add(CreateBasicEmbed(stationTitle, string.Empty, DiscordColor.White, null, null, null, fields));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace AzzyBot.Bot.Utilities.Records.AzuraCast;

public sealed record AzuraStationRecord
{
[JsonPropertyName("id")]
public required int Id { get; init; }

[JsonPropertyName("shortcode")]
public required string Shortcode { get; init; }

[JsonPropertyName("mounts")]
public required IReadOnlyList<AzuraStationMountRecord> Mounts { get; init; }

[JsonPropertyName("hls_url")]
public Uri? HlsUrl { get; init; }
}

public sealed record AzuraStationMountRecord
{
[JsonPropertyName("name")]
public required string Name { get; init; }

[JsonPropertyName("url")]
public required Uri Url { get; init; }
}
Loading

0 comments on commit e80e109

Please sign in to comment.