Skip to content

Commit

Permalink
add decade filter
Browse files Browse the repository at this point in the history
  • Loading branch information
th0mk committed Apr 10, 2024
1 parent e2a5ab6 commit 422244a
Show file tree
Hide file tree
Showing 14 changed files with 250 additions and 40 deletions.
51 changes: 51 additions & 0 deletions src/FMBot.Bot/AutoCompleteHandlers/DecadeAutoComplete.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Interactions;
using FMBot.Bot.Extensions;

namespace FMBot.Bot.AutoCompleteHandlers;

public class DecadeAutoComplete : AutocompleteHandler
{
private readonly List<string> _allPossibleCombinations;
public DecadeAutoComplete()
{
this._allPossibleCombinations = new List<string>();

for (var i = 2020; i >= 1900; i -= 10)
{
this._allPossibleCombinations.Add($"{i}");
}
}

public override async Task<AutocompletionResult> GenerateSuggestionsAsync(IInteractionContext context,
IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter, IServiceProvider services)
{
var results = new List<string>();

if (autocompleteInteraction?.Data?.Current?.Value == null ||
string.IsNullOrWhiteSpace(autocompleteInteraction?.Data?.Current?.Value.ToString()))
{
results
.ReplaceOrAddToList(this._allPossibleCombinations.Take(12).ToList());
}
else
{
var searchValue = autocompleteInteraction.Data.Current.Value.ToString();

results.ReplaceOrAddToList(this._allPossibleCombinations
.Where(w => w.StartsWith(searchValue, StringComparison.OrdinalIgnoreCase))
.Take(6));

results.ReplaceOrAddToList(this._allPossibleCombinations
.Where(w => w.Contains(searchValue, StringComparison.OrdinalIgnoreCase))
.Take(5));
}

return await Task.FromResult(
AutocompletionResult.FromSuccess(results.Select(s => new AutocompleteResult($"{s}s", s))));
}
}
14 changes: 12 additions & 2 deletions src/FMBot.Bot/Builders/AlbumBuilders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,7 @@ public class AlbumBuilders
return response;
}

if (topListSettings.ReleaseYearFilter.HasValue && timeSettings.TimePeriod == TimePeriod.AllTime)
if ((topListSettings.ReleaseYearFilter.HasValue || topListSettings.ReleaseDecadeFilter.HasValue) && timeSettings.TimePeriod == TimePeriod.AllTime)
{
var topAllTimeDb = await this._albumService.GetUserAllTimeTopAlbums(userSettings.UserId);
if (topAllTimeDb.Count > 1000)
Expand All @@ -1136,7 +1136,11 @@ public class AlbumBuilders

if (topListSettings.ReleaseYearFilter.HasValue)
{
albums.Content.TopAlbums = await this._albumService.FilterAlbumToReleaseDate(albums.Content?.TopAlbums, topListSettings.ReleaseYearFilter.Value);
albums.Content.TopAlbums = await this._albumService.FilterAlbumToReleaseYear(albums.Content?.TopAlbums, topListSettings.ReleaseYearFilter.Value);
}
else if (topListSettings.ReleaseDecadeFilter.HasValue)
{
albums.Content.TopAlbums = await this._albumService.FilterAlbumToReleaseDecade(albums.Content?.TopAlbums, topListSettings.ReleaseDecadeFilter.Value);
}

if (mode == ResponseMode.Image)
Expand Down Expand Up @@ -1229,6 +1233,12 @@ public class AlbumBuilders
footer.Append($"Filtering to albums released in {topListSettings.ReleaseYearFilter.Value}");
}

if (topListSettings.ReleaseDecadeFilter.HasValue)
{
footer.AppendLine();
footer.Append($"Filtering to albums released in the {topListSettings.ReleaseDecadeFilter.Value}s");
}

if (rnd == 1 && !topListSettings.Billboard)
{
footer.AppendLine();
Expand Down
19 changes: 16 additions & 3 deletions src/FMBot.Bot/Builders/ChartBuilders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public class ChartBuilders
extraAlbums = chartSettings.Height;
}

var albums = await this._dataSourceFactory.GetTopAlbumsAsync(userSettings.UserNameLastFm, chartSettings.TimeSettings, chartSettings.ReleaseYearFilter.HasValue ? 1000 : 250);
var albums = await this._dataSourceFactory.GetTopAlbumsAsync(userSettings.UserNameLastFm, chartSettings.TimeSettings, chartSettings.ReleaseYearFilter.HasValue || chartSettings.ReleaseDecadeFilter.HasValue ? 1000 : 250);

if (albums.Content?.TopAlbums == null || albums.Content.TopAlbums.Count < chartSettings.ImagesNeeded)
{
Expand All @@ -92,7 +92,7 @@ public class ChartBuilders
return response;
}

if (chartSettings.ReleaseYearFilter.HasValue && chartSettings.TimeSettings.TimePeriod == TimePeriod.AllTime)
if ((chartSettings.ReleaseYearFilter.HasValue || chartSettings.ReleaseDecadeFilter.HasValue) && chartSettings.TimeSettings.TimePeriod == TimePeriod.AllTime)
{
var topAllTimeDb = await this._albumService.GetUserAllTimeTopAlbums(userSettings.UserId);
if (topAllTimeDb.Count > 1000)
Expand All @@ -107,7 +107,7 @@ public class ChartBuilders
topAlbums = await this._albumService.FillMissingAlbumCovers(topAlbums);
if (chartSettings.ReleaseYearFilter.HasValue)
{
topAlbums = await this._albumService.FilterAlbumToReleaseDate(topAlbums, chartSettings.ReleaseYearFilter.Value);
topAlbums = await this._albumService.FilterAlbumToReleaseYear(topAlbums, chartSettings.ReleaseYearFilter.Value);

if (topAlbums.Count < chartSettings.ImagesNeeded)
{
Expand All @@ -118,6 +118,19 @@ public class ChartBuilders
return response;
}
}
else if (chartSettings.ReleaseDecadeFilter.HasValue)
{
topAlbums = await this._albumService.FilterAlbumToReleaseDecade(topAlbums, chartSettings.ReleaseDecadeFilter.Value);

if (topAlbums.Count < chartSettings.ImagesNeeded)
{
response.Text = $"Sorry, you haven't listened to enough albums released in the {chartSettings.ReleaseDecadeFilter}s ({topAlbums.Count} of required {chartSettings.ImagesNeeded}) to generate a chart.\n" +
$"Please try a smaller chart, a different year or a bigger time period ({Constants.CompactTimePeriodList})";
response.ResponseType = ResponseType.Text;
response.CommandResponse = CommandResponse.WrongInput;
return response;
}
}

var imagesToRequest = chartSettings.ImagesNeeded + extraAlbums;
topAlbums = topAlbums.Take(imagesToRequest).ToList();
Expand Down
1 change: 1 addition & 0 deletions src/FMBot.Bot/Models/ChartModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public int Width
public bool RainbowSortingEnabled { get; set; }

public int? ReleaseYearFilter { get; set; }
public int? ReleaseDecadeFilter { get; set; }

public bool ContainsNsfw { get; set; }
public int? CensoredItems { get; set; }
Expand Down
4 changes: 3 additions & 1 deletion src/FMBot.Bot/Models/TopListModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,21 @@ public TopListSettings(EmbedSize embedSize)
this.EmbedSize = embedSize;
}

public TopListSettings(EmbedSize embedSize, bool billboard, bool discogs = false, int? year = null)
public TopListSettings(EmbedSize embedSize, bool billboard, bool discogs = false, int? year = null, int? decade = null)
{
this.EmbedSize = embedSize;
this.Billboard = billboard;
this.Discogs = discogs;
this.ReleaseYearFilter = year;
this.ReleaseDecadeFilter = decade;
}

public EmbedSize EmbedSize { get; set; }
public bool Billboard { get; set; }
public bool Discogs { get; set; }
public string NewSearchValue { get; set; }
public int? ReleaseYearFilter { get; set; }
public int? ReleaseDecadeFilter { get; set; }

public TopListType Type { get; set; }
}
Expand Down
65 changes: 45 additions & 20 deletions src/FMBot.Bot/Services/AlbumService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,29 +309,63 @@ public async Task<List<TopAlbum>> FillMissingAlbumCovers(List<TopAlbum> topAlbum

var albums = await this._albumEnrichment.AddMissingAlbumCoversAsync(request);

foreach (var topAlbum in topAlbums.Where(w => w.AlbumCoverUrl == null))
{
var album = albums.Albums.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.AlbumCoverUrl) &&
f.AlbumName == topAlbum.AlbumName &&
f.ArtistName == topAlbum.ArtistName);
var albumDict = albums.Albums
.Where(a => !string.IsNullOrWhiteSpace(a.AlbumCoverUrl))
.GroupBy(a => (a.AlbumName.ToLower(), a.ArtistName.ToLower()))
.ToDictionary(
g => g.Key,
g => g.First(f => f.AlbumCoverUrl != null)
);

if (album != null)
foreach (var topAlbum in topAlbums)
{
if (topAlbum.AlbumCoverUrl == null)
{
topAlbum.AlbumCoverUrl = album.AlbumCoverUrl;
}
var key = (topAlbum.AlbumName.ToLower(), topAlbum.ArtistName.ToLower());
if (albumDict.TryGetValue(key, out var coverUrl))
{
topAlbum.AlbumCoverUrl = coverUrl.AlbumCoverUrl;
}
}
}

return topAlbums;
}

public async Task<List<TopAlbum>> FilterAlbumToReleaseDate(List<TopAlbum> topAlbums, int year)
public async Task<List<TopAlbum>> FilterAlbumToReleaseYear(List<TopAlbum> topAlbums, int year)
{
await EnrichTopAlbums(topAlbums);

var yearStart = new DateTime(year, 1, 1);
var yearEnd = yearStart.AddYears(1).AddSeconds(-1);
return topAlbums
.Where(w => w.ReleaseDate.HasValue &&
w.ReleaseDate.Value >= yearStart &&
w.ReleaseDate.Value <= yearEnd)
.ToList();
}

public async Task<List<TopAlbum>> FilterAlbumToReleaseDecade(List<TopAlbum> topAlbums, int decade)
{
await EnrichTopAlbums(topAlbums);

var decadeStart = new DateTime(decade, 1, 1);
var decadeEnd = decadeStart.AddYears(10).AddSeconds(-1);
return topAlbums
.Where(w => w.ReleaseDate.HasValue &&
w.ReleaseDate.Value >= decadeStart &&
w.ReleaseDate.Value <= decadeEnd)
.ToList();
}

private async Task EnrichTopAlbums(IReadOnlyCollection<TopAlbum> list)
{
var minTimestamp = Timestamp.FromDateTime(DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc));
var request = new AlbumReleaseDateRequest
{
Albums =
{
topAlbums.Select(s => new AlbumWithDate
list.Select(s => new AlbumWithDate
{
ArtistName = s.ArtistName,
AlbumName = s.AlbumName,
Expand All @@ -348,7 +382,7 @@ public async Task<List<TopAlbum>> FilterAlbumToReleaseDate(List<TopAlbum> topAlb
.GroupBy(a => (a.AlbumName.ToLower(), a.ArtistName.ToLower()))
.ToDictionary(g => g.Key, g => g.ToList());

foreach (var topAlbum in topAlbums.Where(w => w.ReleaseDate == null))
foreach (var topAlbum in list.Where(w => w.ReleaseDate == null))
{
var key = (topAlbum.AlbumName.ToLower(), topAlbum.ArtistName.ToLower());

Expand All @@ -362,15 +396,6 @@ public async Task<List<TopAlbum>> FilterAlbumToReleaseDate(List<TopAlbum> topAlb
}
}
}


var yearStart = new DateTime(year, 1, 1);
var yearEnd = yearStart.AddYears(1).AddSeconds(-1);
return topAlbums
.Where(w => w.ReleaseDate.HasValue &&
w.ReleaseDate.Value >= yearStart &&
w.ReleaseDate.Value <= yearEnd)
.ToList();
}

public async Task<Album> GetAlbumForId(int albumId)
Expand Down
73 changes: 70 additions & 3 deletions src/FMBot.Bot/Services/ChartService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ private static void AddClassicTitleToChartImage(SKBitmap chartImage, TopAlbum al
}

public ChartSettings SetSettings(ChartSettings currentChartSettings, string[] extraOptions,
UserSettingsModel userSettings, bool aoty = false)
UserSettingsModel userSettings, bool aoty = false, bool aotd = false)
{
var chartSettings = currentChartSettings;
chartSettings.CustomOptionsEnabled = false;
Expand Down Expand Up @@ -574,6 +574,42 @@ private static void AddClassicTitleToChartImage(SKBitmap chartImage, TopAlbum al
chartSettings.CustomOptionsEnabled = true;
}

if (aotd)
{
var aotdFound = false;
foreach (var option in extraOptions)
{
var cleaned = option
.Replace("d:", "", StringComparison.OrdinalIgnoreCase)
.Replace("decade:", "", StringComparison.OrdinalIgnoreCase)
.TrimEnd('s')
.TrimEnd('S');

if (int.TryParse(cleaned, out var year))
{
if (year < 100)
{
year += year < 30 ? 2000 : 1900;
}

year = (year / 10) * 10;

if (year <= DateTime.UtcNow.Year && year >= 1900)
{
chartSettings.CustomOptionsEnabled = true;
chartSettings.ReleaseDecadeFilter = year;
aotdFound = true;
}
}
}
if (!aotdFound)
{
chartSettings.ReleaseDecadeFilter = (DateTime.UtcNow.Year / 10) * 10;
}

chartSettings.CustomOptionsEnabled = true;
}

foreach (var option in extraOptions)
{
if (option.StartsWith("r:", StringComparison.OrdinalIgnoreCase) ||
Expand All @@ -583,16 +619,43 @@ private static void AddClassicTitleToChartImage(SKBitmap chartImage, TopAlbum al
.Replace("r:", "", StringComparison.OrdinalIgnoreCase)
.Replace("released:", "", StringComparison.OrdinalIgnoreCase);

if (int.TryParse(yearString, out var year) && year <= DateTime.UtcNow.Year && year >= 1900)
var year = SettingService.GetYear(yearString);
if (year != null)
{
chartSettings.CustomOptionsEnabled = true;
chartSettings.ReleaseYearFilter = year;
aoty = true;
}
}
if (option.StartsWith("d:", StringComparison.OrdinalIgnoreCase) ||
option.StartsWith("decade:", StringComparison.OrdinalIgnoreCase))
{
var yearString = option
.Replace("d:", "", StringComparison.OrdinalIgnoreCase)
.Replace("decade:", "", StringComparison.OrdinalIgnoreCase)
.TrimEnd('s')
.TrimEnd('S');

if (int.TryParse(yearString, out var year))
{
if (year < 100)
{
year += year < 30 ? 2000 : 1900;
}

year = (year / 10) * 10;

if (year <= DateTime.UtcNow.Year && year >= 1900)
{
chartSettings.CustomOptionsEnabled = true;
chartSettings.ReleaseDecadeFilter = year;
aotd = true;
}
}
}
}

var timeSettings = SettingService.GetTimePeriod(optionsAsString, aoty ? TimePeriod.AllTime : TimePeriod.Weekly, timeZone: userSettings.TimeZone);
var timeSettings = SettingService.GetTimePeriod(optionsAsString, aoty || aotd ? TimePeriod.AllTime : TimePeriod.Weekly, timeZone: userSettings.TimeZone);

chartSettings.TimeSettings = timeSettings;
chartSettings.TimespanString = timeSettings.Description;
Expand Down Expand Up @@ -632,6 +695,10 @@ public static string AddSettingsToDescription(ChartSettings chartSettings, strin
{
embedDescription += $"- Filtering to albums released in {chartSettings.ReleaseYearFilter.Value}\n";
}
if (chartSettings.ReleaseDecadeFilter.HasValue)
{
embedDescription += $"- Filtering to albums released in the {chartSettings.ReleaseDecadeFilter.Value}s\n";
}
if (chartSettings.SkipWithoutImage)
{
embedDescription += $"- {multiple} without images skipped\n";
Expand Down
Loading

0 comments on commit 422244a

Please sign in to comment.