Performance improvements via Roslynator.

This commit is contained in:
Steven Hildreth 2020-01-27 21:44:13 -06:00
parent a5498ff7a7
commit 85dd7352c5
10 changed files with 761 additions and 794 deletions

View file

@ -32,7 +32,7 @@ namespace Roadie.Library.SearchEngines.Imaging
try
{
var request = BuildRequest(query, 1, "musicArtist");
var response = await _client.ExecuteTaskAsync<ITunesSearchResult>(request);
var response = await _client.ExecuteAsync<ITunesSearchResult>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
@ -116,7 +116,7 @@ namespace Roadie.Library.SearchEngines.Imaging
public async Task<OperationResult<IEnumerable<ReleaseSearchResult>>> PerformReleaseSearch(string artistName, string query, int resultsCount)
{
var request = BuildRequest(query, 1, "album");
var response = await _client.ExecuteTaskAsync<ITunesSearchResult>(request);
var response = await _client.ExecuteAsync<ITunesSearchResult>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)

View file

@ -40,7 +40,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Discogs
UserAgent = WebHelper.UserAgent
};
var response = await client.ExecuteTaskAsync<DiscogsResult>(request);
var response = await client.ExecuteAsync<DiscogsResult>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
@ -126,7 +126,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Discogs
var client = new RestClient("https://api.discogs.com/database");
client.UserAgent = WebHelper.UserAgent;
var response = await client.ExecuteTaskAsync<DiscogsResult>(request);
var response = await client.ExecuteAsync<DiscogsResult>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
@ -207,7 +207,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Discogs
Timeout = SafeParser.ToNumber<int>(Configuration.Integrations.DiscogsTimeout)
};
var response = await client.ExecuteTaskAsync<DiscogsReleaseSearchResult>(request);
var response = await client.ExecuteAsync<DiscogsReleaseSearchResult>(request);
if (response?.ResponseStatus == null || response.ResponseStatus == ResponseStatus.Error)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)

View file

@ -86,7 +86,7 @@ namespace Roadie.Library.MetaData.LastFm
};
var request = new RestRequest(Method.GET);
var client = new RestClient(BuildUrl("auth.getSession", parameters));
var responseXML = await client.ExecuteTaskAsync<string>(request);
var responseXML = await client.ExecuteAsync<string>(request);
var doc = new XmlDocument();
doc.LoadXml(responseXML.Content);
var sessionKey = doc.GetElementsByTagName("key")[0].InnerText;
@ -205,7 +205,7 @@ namespace Roadie.Library.MetaData.LastFm
{
var request = new RestRequest(Method.GET);
var client = new RestClient(string.Format("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key={0}&artist={1}&album={2}&format=xml", ApiKey.Key, artistName, query));
var responseData = await client.ExecuteTaskAsync<lfm>(request);
var responseData = await client.ExecuteAsync<lfm>(request);
ReleaseSearchResult result = null;

View file

@ -37,7 +37,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Spotify
var client = new RestClient("http://api.spotify.com/v1");
client.UserAgent = WebHelper.UserAgent;
var response = await client.ExecuteTaskAsync<SpotifyResult>(request);
var response = await client.ExecuteAsync<SpotifyResult>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
@ -104,7 +104,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Spotify
}
var client = new RestClient(string.Format("http://api.spotify.com/v1/albums/{0}", spotifyAlbum.id));
var albumResult = await client.ExecuteTaskAsync<AlbumResult>(request);
var albumResult = await client.ExecuteAsync<AlbumResult>(request);
if (albumResult != null && albumResult.Data != null)
{
var sa = albumResult.Data;
@ -213,7 +213,7 @@ namespace Roadie.Library.SearchEngines.MetaData.Spotify
var client = new RestClient(string.Format(
"http://api.spotify.com/v1/artists/{0}/albums?offset=0&limit=25&album_type=album&market=US",
spotifyId));
var artistAlbumsResponse = await client.ExecuteTaskAsync<Albums>(request);
var artistAlbumsResponse = await client.ExecuteAsync<Albums>(request);
result = artistAlbumsResponse != null && artistAlbumsResponse.Data != null
? artistAlbumsResponse.Data
: null;

View file

@ -10,7 +10,6 @@ using Roadie.Library.Encoding;
using Roadie.Library.Engines;
using Roadie.Library.Enums;
using Roadie.Library.Extensions;
using Roadie.Library.Identity;
using Roadie.Library.Imaging;
using Roadie.Library.MetaData.Audio;
using Roadie.Library.Models;
@ -71,7 +70,7 @@ namespace Roadie.Api.Services
FileDirectoryProcessorService = fileDirectoryProcessorService;
}
public async Task<OperationResult<Artist>> ById(Library.Models.Users.User roadieUser, Guid id, IEnumerable<string> includes)
public async Task<OperationResult<Artist>> ById(User roadieUser, Guid id, IEnumerable<string> includes)
{
var timings = new Dictionary<string, long>();
var tsw = new Stopwatch();
@ -82,19 +81,19 @@ namespace Roadie.Api.Services
var result = await CacheManager.GetAsync(cacheKey, async () =>
{
tsw.Restart();
var rr = await ArtistByIdAction(id, includes);
var rr = await ArtistByIdAction(id, includes).ConfigureAwait(false);
tsw.Stop();
timings.Add("ArtistByIdAction", tsw.ElapsedMilliseconds);
return rr;
}, data.Artist.CacheRegionUrn(id));
}, data.Artist.CacheRegionUrn(id)).ConfigureAwait(false);
if (result?.Data != null && roadieUser != null)
{
tsw.Restart();
var artist = await GetArtist(id);
var artist = await GetArtist(id).ConfigureAwait(false);
tsw.Stop();
timings.Add("getArtist", tsw.ElapsedMilliseconds);
tsw.Restart();
var userBookmarkResult = await BookmarkService.List(roadieUser, new PagedRequest(), false, BookmarkType.Artist);
var userBookmarkResult = await BookmarkService.List(roadieUser, new PagedRequest(), false, BookmarkType.Artist).ConfigureAwait(false);
if (userBookmarkResult.IsSuccess)
{
result.Data.UserBookmarked = userBookmarkResult?.Rows?.FirstOrDefault(x => x?.Bookmark?.Value == artist?.RoadieId.ToString()) != null;
@ -125,7 +124,7 @@ namespace Roadie.Api.Services
select cr).ToArray();
foreach (var comment in result.Data.Comments)
{
var userCommentReaction = userCommentReactions.FirstOrDefault(x => x.CommentId == comment.DatabaseId);
var userCommentReaction = Array.Find(userCommentReactions, x => x.CommentId == comment.DatabaseId);
comment.IsDisliked = userCommentReaction?.ReactionValue == CommentReaction.Dislike;
comment.IsLiked = userCommentReaction?.ReactionValue == CommentReaction.Like;
}
@ -155,10 +154,10 @@ namespace Roadie.Api.Services
if (artist != null)
{
DbContext.Artists.Remove(artist);
await DbContext.SaveChangesAsync();
if(deleteFolder)
await DbContext.SaveChangesAsync().ConfigureAwait(false);
if (deleteFolder)
{
// Delete all image files for Artist
// Delete all image files for Artist
foreach (var file in ImageHelper.ImageFilesInFolder(artist.ArtistFileFolder(Configuration), SearchOption.TopDirectoryOnly))
{
try
@ -175,8 +174,8 @@ namespace Roadie.Api.Services
var artistDir = new DirectoryInfo(artist.ArtistFileFolder(Configuration));
FolderPathHelper.DeleteEmptyFolders(artistDir.Parent);
}
await BookmarkService.RemoveAllBookmarksForItem(BookmarkType.Artist, artist.Id);
await UpdatePlaylistCountsForArtist(artist.Id, DateTime.UtcNow);
await BookmarkService.RemoveAllBookmarksForItem(BookmarkType.Artist, artist.Id).ConfigureAwait(false);
await UpdatePlaylistCountsForArtist(artist.Id, DateTime.UtcNow).ConfigureAwait(false);
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogWarning("User `{0}` deleted Artist `{1}]`", user, artist);
isSuccess = true;
@ -198,7 +197,7 @@ namespace Roadie.Api.Services
};
}
public async Task<Library.Models.Pagination.PagedResult<ArtistList>> List(Library.Models.Users.User roadieUser, PagedRequest request, bool? doRandomize = false, bool? onlyIncludeWithReleases = true)
public async Task<Library.Models.Pagination.PagedResult<ArtistList>> List(User roadieUser, PagedRequest request, bool? doRandomize = false, bool? onlyIncludeWithReleases = true)
{
var sw = new Stopwatch();
sw.Start();
@ -255,7 +254,9 @@ namespace Roadie.Api.Services
if (filter.StartsWith('"') && filter.EndsWith('"'))
{
isEqualFilter = true;
#pragma warning disable IDE0057 // Use range operator
request.Filter = filter.Substring(1, filter.Length - 2);
#pragma warning restore IDE0057 // Use range operator
}
}
var normalizedFilterValue = !string.IsNullOrEmpty(request.FilterValue)
@ -267,9 +268,9 @@ namespace Roadie.Api.Services
if (doRandomize ?? false)
{
var randomLimit = request.Limit ?? roadieUser?.RandomReleaseLimit ?? request.LimitValue;
randomArtistData = await DbContext.RandomArtistIds(roadieUser?.Id ?? -1, randomLimit, request.FilterFavoriteOnly, request.FilterRatedOnly);
randomArtistData = await DbContext.RandomArtistIds(roadieUser?.Id ?? -1, randomLimit, request.FilterFavoriteOnly, request.FilterRatedOnly).ConfigureAwait(false);
randomArtistIds = randomArtistData.Select(x => x.Value).ToArray();
rowCount = DbContext.Artists.Count();
rowCount = await DbContext.Artists.CountAsync().ConfigureAwait(false);
}
var result = (from a in DbContext.Artists
where !onlyWithReleases || a.ReleaseCount > 0
@ -314,11 +315,11 @@ namespace Roadie.Api.Services
});
ArtistList[] rows;
rowCount = rowCount ?? result.Count();
rowCount ??= result.Count();
if (doRandomize ?? false)
{
var resultData = await result.ToArrayAsync();
var resultData = await result.ToArrayAsync().ConfigureAwait(false);
rows = (from r in resultData
join ra in randomArtistData on r.DatabaseId equals ra.Value
orderby ra.Key
@ -328,7 +329,7 @@ namespace Roadie.Api.Services
else
{
string sortBy;
if (request.ActionValue == Library.Models.Users.User.ActionKeyUserRated)
if (request.ActionValue == User.ActionKeyUserRated)
{
sortBy = string.IsNullOrEmpty(request.Sort)
? request.OrderValue(new Dictionary<string, string> { { "Rating", "DESC" }, { "Artist.Text", "ASC" } })
@ -338,20 +339,20 @@ namespace Roadie.Api.Services
{
sortBy = request.OrderValue(new Dictionary<string, string> { { "SortName", "ASC" }, { "Artist.Text", "ASC" } });
}
rows = await result.OrderBy(sortBy).Skip(request.SkipValue).Take(request.LimitValue).ToArrayAsync();
rows = await result.OrderBy(sortBy).Skip(request.SkipValue).Take(request.LimitValue).ToArrayAsync().ConfigureAwait(false);
}
if (rows.Any() && roadieUser != null)
if (rows.Length > 0 && roadieUser != null)
{
var rowIds = rows.Select(x => x.DatabaseId).ToArray();
var userArtistRatings = await (from ua in DbContext.UserArtists
where ua.UserId == roadieUser.Id
where rowIds.Contains(ua.ArtistId)
select ua).ToArrayAsync();
where ua.UserId == roadieUser.Id
where rowIds.Contains(ua.ArtistId)
select ua).ToArrayAsync().ConfigureAwait(false);
foreach (var userArtistRating in userArtistRatings.Where(x => rows.Select(r => r.DatabaseId).Contains(x.ArtistId)))
{
var row = rows.FirstOrDefault(x => x.DatabaseId == userArtistRating.ArtistId);
var row = Array.Find(rows, x => x.DatabaseId == userArtistRating.ArtistId);
if (row != null)
{
row.UserRating = new UserArtist
@ -364,19 +365,16 @@ namespace Roadie.Api.Services
}
}
}
if (!string.IsNullOrEmpty(request.Filter) && rowCount == 0)
if (!string.IsNullOrEmpty(request.Filter) && rowCount == 0 && Configuration.RecordNoResultSearches)
{
if (Configuration.RecordNoResultSearches)
// Create request for no artist found
var req = new data.Request
{
// Create request for no artist found
var req = new data.Request
{
UserId = roadieUser?.Id,
Description = request.Filter
};
DbContext.Requests.Add(req);
await DbContext.SaveChangesAsync();
}
UserId = roadieUser?.Id,
Description = request.Filter
};
DbContext.Requests.Add(req);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
}
sw.Stop();
return new Library.Models.Pagination.PagedResult<ArtistList>
@ -392,9 +390,8 @@ namespace Roadie.Api.Services
/// <summary>
/// Merge one Artist into another one
/// </summary>
/// <param name="artistToMerge">The Artist to be merged</param>
/// <param name="artistToMergeInto">The Artist to merge into</param>
/// <returns></returns>
/// <param name="artistToMergeId">The Artist to be merged</param>
/// <param name="artistToMergeIntoId">The Artist to merge into</param>
public async Task<OperationResult<bool>> MergeArtists(Library.Identity.User user, Guid artistToMergeId, Guid artistToMergeIntoId)
{
var sw = new Stopwatch();
@ -423,7 +420,7 @@ namespace Roadie.Api.Services
try
{
var result = await MergeArtists(user, artistToMerge, mergeIntoArtist);
var result = await MergeArtists(user, artistToMerge, mergeIntoArtist).ConfigureAwait(false);
if (!result.IsSuccess)
{
CacheManager.ClearRegion(artistToMerge.CacheRegion);
@ -442,8 +439,8 @@ namespace Roadie.Api.Services
return new OperationResult<bool>
{
IsSuccess = !errors.Any(),
Data = !errors.Any(),
IsSuccess = errors.Count == 0,
Data = errors.Count == 0,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
@ -472,7 +469,7 @@ namespace Roadie.Api.Services
artistSearch = await ArtistLookupEngine.PerformMetaDataProvidersArtistSearch(new AudioMetaData
{
Artist = artist.Name
});
}).ConfigureAwait(false);
}
catch (Exception ex)
{
@ -482,11 +479,11 @@ namespace Roadie.Api.Services
if (artistSearch.IsSuccess)
{
// Do metadata search for Artist like if new Artist then set some overides and merge
var mergeResult = await MergeArtists(user, artistSearch.Data, artist);
var mergeResult = await MergeArtists(user, artistSearch.Data, artist).ConfigureAwait(false);
if (mergeResult.IsSuccess)
{
artist = mergeResult.Data;
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
sw.Stop();
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogTrace("Scanned RefreshArtistMetadata [{0}], OperationTime [{1}]",
@ -502,6 +499,7 @@ namespace Roadie.Api.Services
{
Logger.LogError(ex, ex.Serialize());
resultErrors.Add(ex);
result = false;
}
return new OperationResult<bool>
@ -544,9 +542,10 @@ namespace Roadie.Api.Services
if (artist.Releases != null)
{
foreach (var release in artist.Releases)
{
try
{
result = result && (await ReleaseService.ScanReleaseFolder(user, Guid.Empty, doJustInfo, release)).Data;
result = result && (await ReleaseService.ScanReleaseFolder(user, Guid.Empty, doJustInfo, release).ConfigureAwait(false)).Data;
releaseScannedCount++;
scannedArtistFolders.Add(release.ReleaseFileFolder(artistFolder));
}
@ -554,11 +553,12 @@ namespace Roadie.Api.Services
{
Logger.LogError(ex, ex.Serialize());
}
}
}
var artistImage = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistFolder), ImageType.Artist).FirstOrDefault();
if (artistImage != null)
{
// See if image file is valid image if not delete it
// See if image file is valid image if not delete it
if (ImageHelper.ConvertToJpegFormat(File.ReadAllBytes(artistImage.FullName)) == null)
{
artistImage.Delete();
@ -571,7 +571,7 @@ namespace Roadie.Api.Services
select d;
foreach (var folder in nonReleaseFolders)
{
await FileDirectoryProcessorService.Process(user, new DirectoryInfo(folder), doJustInfo);
await FileDirectoryProcessorService.Process(user, new DirectoryInfo(folder), doJustInfo).ConfigureAwait(false);
}
if (!doJustInfo)
{
@ -596,10 +596,7 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<Library.Models.Image>> SetReleaseImageByUrl(Library.Identity.User user, Guid id, string imageUrl)
{
return await SaveImageBytes(user, id, WebHelper.BytesForImageUrl(imageUrl));
}
public async Task<OperationResult<Library.Models.Image>> SetReleaseImageByUrl(Library.Identity.User user, Guid id, string imageUrl) => await SaveImageBytes(user, id, WebHelper.BytesForImageUrl(imageUrl)).ConfigureAwait(false);
public async Task<OperationResult<bool>> UpdateArtist(Library.Identity.User user, Artist model)
{
@ -695,7 +692,7 @@ namespace Roadie.Api.Services
File.WriteAllBytes(artistImageName, ImageHelper.ConvertToJpegFormat(artistImage));
}
if (model.NewSecondaryImagesData != null && model.NewSecondaryImagesData.Any())
if (model.NewSecondaryImagesData?.Any() == true)
{
// Additional images to add to artist
var looper = 0;
@ -721,7 +718,7 @@ namespace Roadie.Api.Services
}
}
if (model.Genres != null && model.Genres.Any())
if (model.Genres?.Any() == true)
{
// Remove existing Genres not in model list
foreach (var genre in artist.Genres.ToList())
@ -739,21 +736,23 @@ namespace Roadie.Api.Services
{
var g = DbContext.Genres.FirstOrDefault(x => x.RoadieId == genreId);
if (g != null)
{
artist.Genres.Add(new data.ArtistGenre
{
ArtistId = artist.Id,
GenreId = g.Id,
Genre = g
});
}
}
}
}
else if (model.Genres == null || !model.Genres.Any())
else if (model.Genres?.Any() != true)
{
artist.Genres.Clear();
}
if (model.AssociatedArtistsTokens != null && model.AssociatedArtistsTokens.Any())
if (model.AssociatedArtistsTokens?.Any() == true)
{
var associatedArtists = DbContext.ArtistAssociations.Include(x => x.AssociatedArtist)
.Where(x => x.ArtistId == artist.Id).ToList();
@ -776,21 +775,23 @@ namespace Roadie.Api.Services
{
var a = DbContext.Artists.FirstOrDefault(x => x.RoadieId == associatedArtistId);
if (a != null)
{
DbContext.ArtistAssociations.Add(new data.ArtistAssociation
{
ArtistId = artist.Id,
AssociatedArtistId = a.Id
});
}
}
}
}
else if (model.AssociatedArtistsTokens == null || !model.AssociatedArtistsTokens.Any())
else if (model.AssociatedArtistsTokens?.Any() != true)
{
var associatedArtists = DbContext.ArtistAssociations.Include(x => x.AssociatedArtist).Where(x => x.ArtistId == artist.Id || x.AssociatedArtistId == artist.Id).ToList();
DbContext.ArtistAssociations.RemoveRange(associatedArtists);
}
if (model.SimilarArtistsTokens != null && model.SimilarArtistsTokens.Any())
if (model.SimilarArtistsTokens?.Any() == true)
{
var similarArtists = DbContext.ArtistSimilar.Include(x => x.SimilarArtist)
.Where(x => x.ArtistId == artist.Id).ToList();
@ -812,21 +813,23 @@ namespace Roadie.Api.Services
{
var a = DbContext.Artists.FirstOrDefault(x => x.RoadieId == similarArtistId);
if (a != null)
{
DbContext.ArtistSimilar.Add(new data.ArtistSimilar
{
ArtistId = artist.Id,
SimilarArtistId = a.Id
});
}
}
}
}
else if (model.SimilarArtistsTokens == null || !model.SimilarArtistsTokens.Any())
else if (model.SimilarArtistsTokens?.Any() != true)
{
var similarArtists = DbContext.ArtistSimilar.Include(x => x.SimilarArtist).Where(x => x.ArtistId == artist.Id || x.SimilarArtistId == artist.Id).ToList();
DbContext.ArtistSimilar.RemoveRange(similarArtists);
}
artist.LastUpdated = now;
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
if (didRenameArtist)
{
// Many contributing artists do not have releases and will not have an empty Artist folder
@ -836,7 +839,7 @@ namespace Roadie.Api.Services
foreach (var mp3 in Directory.GetFiles(newArtistFolder, "*.mp3", SearchOption.AllDirectories))
{
var trackFileInfo = new FileInfo(mp3);
var audioMetaData = await AudioMetaDataHelper.GetInfo(trackFileInfo);
var audioMetaData = await AudioMetaDataHelper.GetInfo(trackFileInfo).ConfigureAwait(false);
if (audioMetaData != null)
{
audioMetaData.Artist = artist.Name;
@ -844,7 +847,7 @@ namespace Roadie.Api.Services
}
}
await ScanArtistReleasesFolders(user, artist.RoadieId, Configuration.LibraryFolder, false);
await ScanArtistReleasesFolders(user, artist.RoadieId, Configuration.LibraryFolder, false).ConfigureAwait(false);
}
}
@ -861,8 +864,8 @@ namespace Roadie.Api.Services
return new OperationResult<bool>
{
IsSuccess = !errors.Any(),
Data = !errors.Any(),
IsSuccess = errors.Count == 0,
Data = errors.Count == 0,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
@ -877,7 +880,7 @@ namespace Roadie.Api.Services
bytes = ms.ToArray();
}
return await SaveImageBytes(user, id, bytes);
return await SaveImageBytes(user, id, bytes).ConfigureAwait(false);
}
private async Task<OperationResult<Artist>> ArtistByIdAction(Guid id, IEnumerable<string> includes)
@ -889,14 +892,14 @@ namespace Roadie.Api.Services
sw.Start();
tsw.Restart();
var artist = await GetArtist(id);
var artist = await GetArtist(id).ConfigureAwait(false);
tsw.Stop();
timings.Add("getArtist", tsw.ElapsedMilliseconds);
if (artist == null) return new OperationResult<Artist>(true, $"Artist Not Found [{id}]");
tsw.Restart();
var result = artist.Adapt<Artist>();
result.BandStatus = result.BandStatus ?? BandStatus.Unknown.ToString();
result.BandStatus ??= nameof(BandStatus.Unknown);
result.BeginDate = result.BeginDate == null || result.BeginDate == DateTime.MinValue
? null
: result.BeginDate;
@ -913,11 +916,10 @@ namespace Roadie.Api.Services
result.Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, id);
result.MediumThumbnail = ImageHelper.MakeThumbnailImage(Configuration, HttpContext, id, "artist", Configuration.MediumImageSize.Width, Configuration.MediumImageSize.Height);
if (includes != null && includes.Any())
if (includes?.Any() == true)
{
tsw.Restart();
if(includes.Contains("genres"))
if (includes.Contains("genres"))
{
var artistGenreIds = artist.Genres.Select(x => x.GenreId).ToArray();
result.Genres = (await (from g in DbContext.Genres
@ -928,7 +930,7 @@ namespace Roadie.Api.Services
where rg.GenreId == g.Id
select rg.Id).Count()
where artistGenreIds.Contains(g.Id)
select new { g, releaseCount, artistCount }).ToListAsync())
select new { g, releaseCount, artistCount }).ToListAsync().ConfigureAwait(false))
.Select(x => GenreList.FromDataGenre(x.g,
ImageHelper.MakeGenreThumbnailImage(Configuration, HttpContext, x.g.RoadieId),
x.artistCount,
@ -937,10 +939,8 @@ namespace Roadie.Api.Services
tsw.Stop();
timings.Add("genres", tsw.ElapsedMilliseconds);
}
if (includes.Contains("releases"))
{
tsw.Restart();
@ -950,12 +950,13 @@ namespace Roadie.Api.Services
.Include("Medias.Tracks")
.Include("Medias.Tracks")
.Where(x => x.ArtistId == artist.Id)
.ToArrayAsync())
.ToArrayAsync().ConfigureAwait(false))
{
var releaseList = release.Adapt<ReleaseList>();
releaseList.Thumbnail = ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, release.RoadieId);
var dtoReleaseMedia = new List<ReleaseMediaList>();
if (includes.Contains("tracks"))
{
foreach (var releasemedia in release.Medias.OrderBy(x => x.MediaNumber).ToArray())
{
var dtoMedia = releasemedia.Adapt<ReleaseMediaList>();
@ -963,7 +964,7 @@ namespace Roadie.Api.Services
foreach (var t in await DbContext.Tracks
.Where(x => x.ReleaseMediaId == releasemedia.Id)
.OrderBy(x => x.TrackNumber)
.ToArrayAsync())
.ToArrayAsync().ConfigureAwait(false))
{
var track = t.Adapt<TrackList>();
ArtistList trackArtist = null;
@ -979,6 +980,8 @@ namespace Roadie.Api.Services
dtoMedia.Tracks = tracks;
dtoReleaseMedia.Add(dtoMedia);
}
}
releaseList.Media = dtoReleaseMedia;
dtoReleases.Add(releaseList);
}
@ -989,6 +992,7 @@ namespace Roadie.Api.Services
}
if (includes.Contains("stats"))
{
try
{
tsw.Restart();
@ -1027,6 +1031,7 @@ namespace Roadie.Api.Services
{
Logger.LogError(ex, $"Error Getting Statistics for Artist `{artist}`");
}
}
if (includes.Contains("images"))
{
@ -1035,7 +1040,7 @@ namespace Roadie.Api.Services
var artistImagesInFolder = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistFolder), ImageType.ArtistSecondary, SearchOption.TopDirectoryOnly);
if (artistImagesInFolder.Any())
{
result.Images = artistImagesInFolder.Select((x, i) => ImageHelper.MakeFullsizeSecondaryImage(Configuration, HttpContext, id, ImageType.ArtistSecondary, i));
result.Images = artistImagesInFolder.Select((_, i) => ImageHelper.MakeFullsizeSecondaryImage(Configuration, HttpContext, id, ImageType.ArtistSecondary, i));
}
tsw.Stop();
@ -1046,52 +1051,52 @@ namespace Roadie.Api.Services
{
tsw.Restart();
var associatedWithArtists = await (from aa in DbContext.ArtistAssociations
join a in DbContext.Artists on aa.AssociatedArtistId equals a.Id
where aa.ArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync();
join a in DbContext.Artists on aa.AssociatedArtistId equals a.Id
where aa.ArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync().ConfigureAwait(false);
var associatedArtists = await (from aa in DbContext.ArtistAssociations
join a in DbContext.Artists on aa.ArtistId equals a.Id
where aa.AssociatedArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync();
join a in DbContext.Artists on aa.ArtistId equals a.Id
where aa.AssociatedArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync().ConfigureAwait(false);
result.AssociatedArtists = associatedArtists.Union(associatedWithArtists, new ArtistListComparer()).OrderBy(x => x.SortName);
result.AssociatedArtistsTokens = result.AssociatedArtists.Select(x => x.Artist).ToArray();
tsw.Stop();
@ -1102,52 +1107,52 @@ namespace Roadie.Api.Services
{
tsw.Restart();
var similarWithArtists = await (from aa in DbContext.ArtistSimilar
join a in DbContext.Artists on aa.SimilarArtistId equals a.Id
where aa.ArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync();
join a in DbContext.Artists on aa.SimilarArtistId equals a.Id
where aa.ArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync().ConfigureAwait(false);
var similarArtists = await (from aa in DbContext.ArtistSimilar
join a in DbContext.Artists on aa.ArtistId equals a.Id
where aa.SimilarArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync();
join a in DbContext.Artists on aa.ArtistId equals a.Id
where aa.SimilarArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
Thumbnail = ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, a.RoadieId),
Rating = a.Rating,
Rank = (double?)a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArrayAsync().ConfigureAwait(false);
result.SimilarArtists = similarWithArtists.Union(similarArtists, new ArtistListComparer()).OrderBy(x => x.SortName);
result.SimilarArtistsTokens = result.SimilarArtists.Select(x => x.Artist).ToArray();
tsw.Stop();
@ -1161,7 +1166,7 @@ namespace Roadie.Api.Services
{
Limit = 100
};
var r = await CollectionService.List(null, collectionPagedRequest, artistId: artist.RoadieId);
var r = await CollectionService.List(null, collectionPagedRequest, artistId: artist.RoadieId).ConfigureAwait(false);
if (r.IsSuccess) result.CollectionsWithArtistReleases = r.Rows.ToArray();
tsw.Stop();
timings.Add("collections", tsw.ElapsedMilliseconds);
@ -1173,8 +1178,8 @@ namespace Roadie.Api.Services
var artistComments = await DbContext.Comments.Include(x => x.User)
.Where(x => x.ArtistId == artist.Id)
.OrderByDescending(x => x.CreatedDate)
.ToArrayAsync();
if (artistComments.Any())
.ToArrayAsync().ConfigureAwait(false);
if (artistComments.Length > 0)
{
var comments = new List<Comment>();
var commentIds = artistComments.Select(x => x.Id).ToArray();
@ -1208,7 +1213,7 @@ namespace Roadie.Api.Services
{
FilterToArtistId = artist.RoadieId
};
var r = await PlaylistService.List(pg);
var r = await PlaylistService.List(pg).ConfigureAwait(false);
if (r.IsSuccess)
{
result.PlaylistsWithArtistReleases = r.Rows.ToArray();
@ -1230,10 +1235,10 @@ namespace Roadie.Api.Services
if (artistContributingTracks?.Any() ?? false)
{
result.ArtistContributionReleases = (await (from r in DbContext.Releases.Include(x => x.Artist)
where artistContributingTracks.Contains(r.Id)
select r)
where artistContributingTracks.Contains(r.Id)
select r)
.OrderBy(x => x.Title)
.ToArrayAsync())
.ToArrayAsync().ConfigureAwait(false))
.Select(r => ReleaseList.FromDataRelease(r, r.Artist, HttpContext.BaseUrl, ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, r.Artist.RoadieId), ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, r.RoadieId)));
result.ArtistContributionReleases = result.ArtistContributionReleases.Any()
@ -1248,12 +1253,12 @@ namespace Roadie.Api.Services
{
tsw.Restart();
result.ArtistLabels = (await (from l in DbContext.Labels
join rl in DbContext.ReleaseLabels on l.Id equals rl.LabelId
join r in DbContext.Releases on rl.ReleaseId equals r.Id
where r.ArtistId == artist.Id
orderby l.SortName
select LabelList.FromDataLabel(l, ImageHelper.MakeLabelThumbnailImage(Configuration, HttpContext, l.RoadieId)))
.ToArrayAsync())
join rl in DbContext.ReleaseLabels on l.Id equals rl.LabelId
join r in DbContext.Releases on rl.ReleaseId equals r.Id
where r.ArtistId == artist.Id
orderby l.SortName
select LabelList.FromDataLabel(l, ImageHelper.MakeLabelThumbnailImage(Configuration, HttpContext, l.RoadieId)))
.ToArrayAsync().ConfigureAwait(false))
.GroupBy(x => x.Label.Value)
.Select(x => x.First())
.OrderBy(x => x.SortName)
@ -1275,29 +1280,6 @@ namespace Roadie.Api.Services
};
}
private OperationResult<data.Artist> GetByExternalIds(string musicBrainzId = null, string iTunesId = null, string amgId = null, string spotifyId = null)
{
var sw = new Stopwatch();
sw.Start();
var artist = (from a in DbContext.Artists
where a.MusicBrainzId != null && musicBrainzId != null && a.MusicBrainzId == musicBrainzId ||
a.ITunesId != null || iTunesId != null && a.ITunesId == iTunesId || a.AmgId != null ||
amgId != null && a.AmgId == amgId || a.SpotifyId != null ||
spotifyId != null && a.SpotifyId == spotifyId
select a).FirstOrDefault();
sw.Stop();
if (artist == null || !artist.IsValid)
Logger.LogTrace(
"ArtistFactory: Artist Not Found By External Ids: MusicbrainzId [{0}], iTunesIs [{1}], AmgId [{2}], SpotifyId [{3}]",
musicBrainzId, iTunesId, amgId, spotifyId);
return new OperationResult<data.Artist>
{
IsSuccess = artist != null,
OperationTime = sw.ElapsedMilliseconds,
Data = artist
};
}
private async Task<OperationResult<data.Artist>> MergeArtists(Library.Identity.User user, data.Artist artistToMerge, data.Artist artistToMergeInto)
{
SimpleContract.Requires<ArgumentNullException>(artistToMerge != null, "Invalid Artist");
@ -1312,21 +1294,21 @@ namespace Roadie.Api.Services
var artistToMergeFolder = artistToMerge.ArtistFileFolder(Configuration);
var artistToMergeIntoFolder = artistToMergeInto.ArtistFileFolder(Configuration);
artistToMergeInto.RealName = artistToMergeInto.RealName ?? artistToMerge.RealName;
artistToMergeInto.MusicBrainzId = artistToMergeInto.MusicBrainzId ?? artistToMerge.MusicBrainzId;
artistToMergeInto.ITunesId = artistToMergeInto.ITunesId ?? artistToMerge.ITunesId;
artistToMergeInto.AmgId = artistToMergeInto.AmgId ?? artistToMerge.AmgId;
artistToMergeInto.SpotifyId = artistToMergeInto.SpotifyId ?? artistToMerge.SpotifyId;
artistToMergeInto.Profile = artistToMergeInto.Profile ?? artistToMerge.Profile;
artistToMergeInto.BirthDate = artistToMergeInto.BirthDate ?? artistToMerge.BirthDate;
artistToMergeInto.BeginDate = artistToMergeInto.BeginDate ?? artistToMerge.BeginDate;
artistToMergeInto.EndDate = artistToMergeInto.EndDate ?? artistToMerge.EndDate;
artistToMergeInto.RealName ??= artistToMerge.RealName;
artistToMergeInto.MusicBrainzId ??= artistToMerge.MusicBrainzId;
artistToMergeInto.ITunesId ??= artistToMerge.ITunesId;
artistToMergeInto.AmgId ??= artistToMerge.AmgId;
artistToMergeInto.SpotifyId ??= artistToMerge.SpotifyId;
artistToMergeInto.Profile ??= artistToMerge.Profile;
artistToMergeInto.BirthDate ??= artistToMerge.BirthDate;
artistToMergeInto.BeginDate ??= artistToMerge.BeginDate;
artistToMergeInto.EndDate ??= artistToMerge.EndDate;
if (!string.IsNullOrEmpty(artistToMerge.ArtistType) && !artistToMerge.ArtistType.Equals("Other", StringComparison.OrdinalIgnoreCase))
{
artistToMergeInto.ArtistType = artistToMergeInto.ArtistType ?? artistToMerge.ArtistType;
artistToMergeInto.ArtistType ??= artistToMerge.ArtistType;
}
artistToMergeInto.BioContext = artistToMergeInto.BioContext ?? artistToMerge.BioContext;
artistToMergeInto.DiscogsId = artistToMergeInto.DiscogsId ?? artistToMerge.DiscogsId;
artistToMergeInto.BioContext ??= artistToMerge.BioContext;
artistToMergeInto.DiscogsId ??= artistToMerge.DiscogsId;
artistToMergeInto.Tags = artistToMergeInto.Tags.AddToDelimitedList(artistToMerge.Tags.ToListFromDelimited());
var altNames = artistToMerge.AlternateNames.ToListFromDelimited().ToList();
altNames.Add(artistToMerge.Name);
@ -1344,7 +1326,7 @@ namespace Roadie.Api.Services
var existingArtistGenres = DbContext.ArtistGenres.Where(x => x.ArtistId == artistToMergeInto.Id).ToArray();
foreach (var artistGenre in artistGenres)
{
var existing = existingArtistGenres.FirstOrDefault(x => x.GenreId == artistGenre.GenreId);
var existing = Array.Find(existingArtistGenres, x => x.GenreId == artistGenre.GenreId);
// If not exist then add new for artist to merge into
if (existing == null)
{
@ -1379,7 +1361,7 @@ namespace Roadie.Api.Services
}
}
// Secondary Artist images
if (artistToMergeSecondaryImages.Any())
if (artistToMergeSecondaryImages.Count > 0)
{
var looper = 0;
foreach (var artistSecondaryImage in artistToMergeSecondaryImages)
@ -1418,7 +1400,7 @@ namespace Roadie.Api.Services
var artistToMergeHasRelease = DbContext.Releases.FirstOrDefault(x => x.ArtistId == artistToMerge.Id && x.Title == artistRelease.Title);
if (artistToMergeHasRelease != null)
{
await ReleaseService.MergeReleases(user, artistRelease, artistToMergeHasRelease, false);
await ReleaseService.MergeReleases(user, artistRelease, artistToMergeHasRelease, false).ConfigureAwait(false);
}
else
{
@ -1435,11 +1417,11 @@ namespace Roadie.Api.Services
foreach (var release in DbContext.Releases.Include("Artist").Where(x => x.ArtistId == artistToMerge.Id).ToArray())
{
var originalReleaseFolder = release.ReleaseFileFolder(artistToMergeFolder);
await ReleaseService.UpdateRelease(user, release.Adapt<Release>(), originalReleaseFolder);
await ReleaseService.UpdateRelease(user, release.Adapt<Release>(), originalReleaseFolder).ConfigureAwait(false);
}
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
await Delete(user, artistToMerge, true);
await Delete(user, artistToMerge, true).ConfigureAwait(false);
result = true;
@ -1473,7 +1455,7 @@ namespace Roadie.Api.Services
File.WriteAllBytes(artistImage, imageBytes);
artist.LastUpdated = now;
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation($"SaveImageBytes `{artist}` By User `{user}`");
}
@ -1492,7 +1474,7 @@ namespace Roadie.Api.Services
return new OperationResult<Library.Models.Image>
{
IsSuccess = !errors.Any(),
IsSuccess = errors.Count == 0,
Data = ImageHelper.MakeThumbnailImage(Configuration, HttpContext, id, "artist", Configuration.MediumImageSize.Width, Configuration.MediumImageSize.Height, true),
OperationTime = sw.ElapsedMilliseconds,
Errors = errors

File diff suppressed because it is too large Load diff

View file

@ -11,7 +11,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using data = Roadie.Library.Data;
namespace Roadie.Api.Services
{
@ -209,9 +208,9 @@ namespace Roadie.Api.Services
year = SafeParser.ToNumber<int>(x.Key),
count = x.Count()
});
if (decadeInfos != null && decadeInfos.Any())
if (decadeInfos?.Any() == true)
{
var decadeInterval = 10;
const int decadeInterval = 10;
var startingDecade = (decadeInfos.Min(x => x.year) / 10) * 10;
var endingDecade = (decadeInfos.Max(x => x.year) / 10) * 10;
for (int decade = startingDecade; decade <= endingDecade; decade += decadeInterval)
@ -236,7 +235,5 @@ namespace Roadie.Api.Services
Data = result
});
}
}
}

View file

@ -10,7 +10,6 @@ using Roadie.Library.Data.Context;
using Roadie.Library.Encoding;
using Roadie.Library.Enums;
using Roadie.Library.Extensions;
using Roadie.Library.Identity;
using Roadie.Library.Imaging;
using Roadie.Library.MetaData.Audio;
using Roadie.Library.Models;
@ -56,7 +55,7 @@ namespace Roadie.Api.Services
public static long DetermineByteEndFromHeaders(IHeaderDictionary headers, long fileLength)
{
var defaultFileLength = fileLength - 1;
if (headers == null || !headers.Any(x => x.Key == "Range"))
if (headers?.Any(x => x.Key == "Range") != true)
{
return defaultFileLength;
}
@ -87,7 +86,7 @@ namespace Roadie.Api.Services
public static long DetermineByteStartFromHeaders(IHeaderDictionary headers)
{
if (headers == null || !headers.Any(x => x.Key == "Range"))
if (headers?.Any(x => x.Key == "Range") != true)
{
return 0;
}
@ -110,7 +109,7 @@ namespace Roadie.Api.Services
return result;
}
public async Task<OperationResult<Track>> ById(Library.Models.Users.User roadieUser, Guid id, IEnumerable<string> includes)
public async Task<OperationResult<Track>> ById(User roadieUser, Guid id, IEnumerable<string> includes)
{
var timings = new Dictionary<string, long>();
var tsw = new Stopwatch();
@ -121,27 +120,27 @@ namespace Roadie.Api.Services
var result = await CacheManager.GetAsync(cacheKey, async () =>
{
tsw.Restart();
var rr = await TrackByIdAction(id, includes);
var rr = await TrackByIdAction(id, includes).ConfigureAwait(false);
tsw.Stop();
timings.Add("TrackByIdAction", tsw.ElapsedMilliseconds);
return rr;
}, data.Track.CacheRegionUrn(id));
}, data.Track.CacheRegionUrn(id)).ConfigureAwait(false);
if (result?.Data != null && roadieUser != null)
{
tsw.Restart();
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
tsw.Stop();
timings.Add("getUser", tsw.ElapsedMilliseconds);
tsw.Restart();
var track = await GetTrack(id);
var track = await GetTrack(id).ConfigureAwait(false);
tsw.Stop();
timings.Add("getTrack", tsw.ElapsedMilliseconds);
result.Data.TrackPlayUrl = MakeTrackPlayUrl(user, HttpContext.BaseUrl, track.RoadieId);
tsw.Restart();
var userBookmarkResult = await BookmarkService.List(roadieUser, new PagedRequest(), false, BookmarkType.Track);
var userBookmarkResult = await BookmarkService.List(roadieUser, new PagedRequest(), false, BookmarkType.Track).ConfigureAwait(false);
if (userBookmarkResult.IsSuccess)
{
result.Data.UserBookmarked = userBookmarkResult?.Rows?.FirstOrDefault(x => x?.Bookmark?.Value == track?.RoadieId.ToString()) != null;
@ -175,8 +174,7 @@ namespace Roadie.Api.Services
select cr).ToArray();
foreach (var comment in result.Data.Comments)
{
var userCommentReaction =
userCommentReactions.FirstOrDefault(x => x.CommentId == comment.DatabaseId);
var userCommentReaction = Array.Find(userCommentReactions, x => x.CommentId == comment.DatabaseId);
comment.IsDisliked = userCommentReaction?.ReactionValue == CommentReaction.Dislike;
comment.IsLiked = userCommentReaction?.ReactionValue == CommentReaction.Like;
}
@ -197,7 +195,7 @@ namespace Roadie.Api.Services
};
}
public async Task<Library.Models.Pagination.PagedResult<TrackList>> List(PagedRequest request, Library.Models.Users.User roadieUser, bool? doRandomize = false, Guid? releaseId = null)
public async Task<Library.Models.Pagination.PagedResult<TrackList>> List(PagedRequest request, User roadieUser, bool? doRandomize = false, Guid? releaseId = null)
{
try
{
@ -226,17 +224,17 @@ namespace Roadie.Api.Services
if (request.FilterToPlaylistId.HasValue)
{
var playlistTrackInfos = await (from plt in DbContext.PlaylistTracks
join p in DbContext.Playlists on plt.PlayListId equals p.Id
join t in DbContext.Tracks on plt.TrackId equals t.Id
where p.RoadieId == request.FilterToPlaylistId.Value
orderby plt.ListNumber
select new
{
plt.ListNumber,
t.Id
}).ToArrayAsync();
join p in DbContext.Playlists on plt.PlayListId equals p.Id
join t in DbContext.Tracks on plt.TrackId equals t.Id
where p.RoadieId == request.FilterToPlaylistId.Value
orderby plt.ListNumber
select new
{
plt.ListNumber,
t.Id
}).ToArrayAsync().ConfigureAwait(false);
rowCount = playlistTrackInfos.Count();
rowCount = playlistTrackInfos.Length;
playListTrackPositions = playlistTrackInfos
.Skip(request.SkipValue)
.Take(request.LimitValue)
@ -254,16 +252,16 @@ namespace Roadie.Api.Services
request.Limit = roadieUser?.PlayerTrackLimit ?? 50;
collectionTrackIds = await (from cr in DbContext.CollectionReleases
join c in DbContext.Collections on cr.CollectionId equals c.Id
join r in DbContext.Releases on cr.ReleaseId equals r.Id
join rm in DbContext.ReleaseMedias on r.Id equals rm.ReleaseId
join t in DbContext.Tracks on rm.Id equals t.ReleaseMediaId
where c.RoadieId == request.FilterToCollectionId.Value
orderby cr.ListNumber, rm.MediaNumber, t.TrackNumber
select t.Id)
join c in DbContext.Collections on cr.CollectionId equals c.Id
join r in DbContext.Releases on cr.ReleaseId equals r.Id
join rm in DbContext.ReleaseMedias on r.Id equals rm.ReleaseId
join t in DbContext.Tracks on rm.Id equals t.ReleaseMediaId
where c.RoadieId == request.FilterToCollectionId.Value
orderby cr.ListNumber, rm.MediaNumber, t.TrackNumber
select t.Id)
.Skip(request.SkipValue)
.Take(request.LimitValue)
.ToArrayAsync();
.ToArrayAsync().ConfigureAwait(false);
}
IQueryable<int> topTrackids = null;
@ -287,7 +285,7 @@ namespace Roadie.Api.Services
if (doRandomize ?? false)
{
var randomLimit = roadieUser?.RandomReleaseLimit ?? request.LimitValue;
randomTrackData = await DbContext.RandomTrackIds(roadieUser?.Id ?? -1, randomLimit, request.FilterFavoriteOnly, request.FilterRatedOnly);
randomTrackData = await DbContext.RandomTrackIds(roadieUser?.Id ?? -1, randomLimit, request.FilterFavoriteOnly, request.FilterRatedOnly).ConfigureAwait(false);
randomTrackIds = randomTrackData.Select(x => x.Value).ToArray();
rowCount = DbContext.Releases.Count();
}
@ -325,7 +323,9 @@ namespace Roadie.Api.Services
if (filter.StartsWith('"') && filter.EndsWith('"'))
{
isEqualFilter = true;
#pragma warning disable IDE0057 // Use range operator
request.Filter = filter.Substring(1, filter.Length - 2);
#pragma warning restore IDE0057 // Use range operator
}
}
@ -440,17 +440,14 @@ namespace Roadie.Api.Services
}
};
if (!string.IsNullOrEmpty(request.FilterValue))
if (!string.IsNullOrEmpty(request.FilterValue) && request.FilterValue.StartsWith("#"))
{
if (request.FilterValue.StartsWith("#"))
{
// Find any releases by tags
var tagValue = request.FilterValue.Replace("#", "");
resultQuery = resultQuery.Where(x => x.ti.Tags != null && x.ti.Tags.Contains(tagValue));
}
// Find any releases by tags
var tagValue = request.FilterValue.Replace("#", "");
resultQuery = resultQuery.Where(x => x.ti.Tags != null && x.ti.Tags.Contains(tagValue));
}
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
var result = resultQuery.Select(x =>
new TrackList
{
@ -482,36 +479,33 @@ namespace Roadie.Api.Services
});
string sortBy = null;
rowCount = rowCount ?? result.Count();
rowCount ??= result.Count();
TrackList[] rows = null;
if (!doRandomize ?? false)
{
if (request.Action == Library.Models.Users.User.ActionKeyUserRated)
if (request.Action == User.ActionKeyUserRated)
{
sortBy = string.IsNullOrEmpty(request.Sort)
? request.OrderValue(new Dictionary<string, string> { { "UserTrack.Rating", "DESC" }, { "MediaNumber", "ASC" }, { "TrackNumber", "ASC" } })
: request.OrderValue();
}
else if (request.Sort == "Rating")
{
// The request is to sort tracks by Rating if the artist only has a few tracks rated then order by those then order by played (put most popular after top rated)
sortBy = request.OrderValue(new Dictionary<string, string> { { "Rating", request.Order }, { "PlayedCount", request.Order } });
}
else
{
if (request.Sort == "Rating")
{
// The request is to sort tracks by Rating if the artist only has a few tracks rated then order by those then order by played (put most popular after top rated)
sortBy = request.OrderValue(new Dictionary<string, string> { { "Rating", request.Order }, { "PlayedCount", request.Order } });
}
else
{
sortBy = string.IsNullOrEmpty(request.Sort)
? request.OrderValue(new Dictionary<string, string> { { "Release.Release.Text", "ASC" }, { "MediaNumber", "ASC" }, { "TrackNumber", "ASC" } })
: request.OrderValue();
}
sortBy = string.IsNullOrEmpty(request.Sort)
? request.OrderValue(new Dictionary<string, string> { { "Release.Release.Text", "ASC" }, { "MediaNumber", "ASC" }, { "TrackNumber", "ASC" } })
: request.OrderValue();
}
}
if (doRandomize ?? false)
{
var resultData = await result.ToArrayAsync();
var resultData = await result.ToArrayAsync().ConfigureAwait(false);
rows = (from r in resultData
join ra in randomTrackData on r.DatabaseId equals ra.Value
orderby ra.Key
@ -524,18 +518,18 @@ namespace Roadie.Api.Services
.OrderBy(sortBy)
.Skip(request.SkipValue)
.Take(request.LimitValue)
.ToArrayAsync();
.ToArrayAsync().ConfigureAwait(false);
}
if (rows.Any() && roadieUser != null)
if (rows.Length > 0 && roadieUser != null)
{
var rowIds = rows.Select(x => x.DatabaseId).ToArray();
var userTrackRatings = await (from ut in DbContext.UserTracks
where ut.UserId == roadieUser.Id
where rowIds.Contains(ut.TrackId)
select ut).ToArrayAsync();
where ut.UserId == roadieUser.Id
where rowIds.Contains(ut.TrackId)
select ut).ToArrayAsync().ConfigureAwait(false);
foreach (var userTrackRating in userTrackRatings)
{
var row = rows.FirstOrDefault(x => x.DatabaseId == userTrackRating.TrackId);
var row = Array.Find(rows, x => x.DatabaseId == userTrackRating.TrackId);
if (row != null)
{
row.UserRating = new UserTrack
@ -551,9 +545,9 @@ namespace Roadie.Api.Services
var releaseIds = rows.Select(x => x.Release.DatabaseId).Distinct().ToArray();
var userReleaseRatings = await (from ur in DbContext.UserReleases
where ur.UserId == roadieUser.Id
where releaseIds.Contains(ur.ReleaseId)
select ur).ToArrayAsync();
where ur.UserId == roadieUser.Id
where releaseIds.Contains(ur.ReleaseId)
select ur).ToArrayAsync().ConfigureAwait(false);
foreach (var userReleaseRating in userReleaseRatings)
{
foreach (var row in rows.Where(x => x.Release.DatabaseId == userReleaseRating.ReleaseId))
@ -563,12 +557,12 @@ namespace Roadie.Api.Services
}
var artistIds = rows.Select(x => x.Artist.DatabaseId).ToArray();
if (artistIds != null && artistIds.Any())
if (artistIds?.Any() == true)
{
var userArtistRatings = await (from ua in DbContext.UserArtists
where ua.UserId == roadieUser.Id
where artistIds.Contains(ua.ArtistId)
select ua).ToArrayAsync();
where ua.UserId == roadieUser.Id
where artistIds.Contains(ua.ArtistId)
select ua).ToArrayAsync().ConfigureAwait(false);
foreach (var userArtistRating in userArtistRatings)
{
foreach (var artistTrack in rows.Where(
@ -580,13 +574,13 @@ namespace Roadie.Api.Services
}
var trackArtistIds = rows.Where(x => x.TrackArtist != null).Select(x => x.TrackArtist.DatabaseId).ToArray();
if (trackArtistIds != null && trackArtistIds.Any())
if (trackArtistIds?.Any() == true)
{
var userTrackArtistRatings = await (from ua in DbContext.UserArtists
where ua.UserId == roadieUser.Id
where trackArtistIds.Contains(ua.ArtistId)
select ua).ToArrayAsync();
if (userTrackArtistRatings != null && userTrackArtistRatings.Any())
where ua.UserId == roadieUser.Id
where trackArtistIds.Contains(ua.ArtistId)
select ua).ToArrayAsync().ConfigureAwait(false);
if (userTrackArtistRatings?.Any() == true)
{
foreach (var userTrackArtistRating in userTrackArtistRatings)
{
@ -601,21 +595,21 @@ namespace Roadie.Api.Services
}
}
if (rows.Any())
if (rows.Length > 0)
{
var rowIds = rows.Select(x => x.DatabaseId).ToArray();
var favoriteUserTrackRatings = await (from ut in DbContext.UserTracks
where ut.IsFavorite ?? false
where rowIds.Contains(ut.TrackId)
select ut).ToArrayAsync();
where ut.IsFavorite ?? false
where rowIds.Contains(ut.TrackId)
select ut).ToArrayAsync().ConfigureAwait(false);
foreach (var row in rows)
{
row.FavoriteCount = favoriteUserTrackRatings.Where(x => x.TrackId == row.DatabaseId).Count();
row.FavoriteCount = favoriteUserTrackRatings.Count(x => x.TrackId == row.DatabaseId);
row.TrackNumber = playListTrackPositions.ContainsKey(row.DatabaseId) ? playListTrackPositions[row.DatabaseId] : row.TrackNumber;
}
}
if(playListTrackPositions.Any())
if (playListTrackPositions.Count > 0)
{
rows = rows.OrderBy(x => x.TrackNumber).ToArray();
}
@ -643,7 +637,7 @@ namespace Roadie.Api.Services
/// <summary>
/// Fast as possible check if exists and return minimum information on Track
/// </summary>
public OperationResult<Track> StreamCheckAndInfo(Library.Models.Users.User roadieUser, Guid id)
public OperationResult<Track> StreamCheckAndInfo(User roadieUser, Guid id)
{
var track = DbContext.Tracks.FirstOrDefault(x => x.RoadieId == id);
if (track == null)
@ -658,7 +652,7 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<TrackStreamInfo>> TrackStreamInfo(Guid trackId, long beginBytes, long endBytes, Library.Models.Users.User roadieUser)
public async Task<OperationResult<TrackStreamInfo>> TrackStreamInfo(Guid trackId, long beginBytes, long endBytes, User roadieUser)
{
var track = DbContext.Tracks.FirstOrDefault(x => x.RoadieId == trackId);
if (!(track?.IsValid ?? true))
@ -673,7 +667,7 @@ namespace Roadie.Api.Services
await AdminService.ScanRelease(new Library.Identity.User
{
Id = roadieUser.Id.Value
}, release.RoadieId, false, true);
}, release.RoadieId, false, true).ConfigureAwait(false);
track = DbContext.Tracks.FirstOrDefault(x => x.RoadieId == trackId);
}
else
@ -712,7 +706,7 @@ namespace Roadie.Api.Services
await AdminService.ScanRelease(new Library.Identity.User
{
Id = roadieUser.Id.Value
}, release.RoadieId, false, true);
}, release.RoadieId, false, true).ConfigureAwait(false);
}
track = DbContext.Tracks.FirstOrDefault(x => x.RoadieId == trackId);
@ -733,14 +727,12 @@ namespace Roadie.Api.Services
if (!trackFileInfo.Exists)
{
track.UpdateTrackMissingFile();
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
return new OperationResult<TrackStreamInfo>(
$"TrackStreamInfo: TrackId [{trackId}] Unable to Find Track [{trackFileInfo.FullName}]");
}
}
var disableCaching = true;
var contentDurationTimeSpan = TimeSpan.FromMilliseconds(track.Duration ?? 0);
var info = new TrackStreamInfo
{
@ -761,19 +753,11 @@ namespace Roadie.Api.Services
info.IsFullRequest = beginBytes == 0 && endBytes == trackFileInfo.Length - 1;
info.IsEndRangeRequest = beginBytes > 0 && endBytes != trackFileInfo.Length - 1;
info.LastModified = (track.LastUpdated ?? track.CreatedDate).ToString("R");
if (!disableCaching)
{
var cacheTimeout = 86400; // 24 hours
info.CacheControl = $"public, max-age={cacheTimeout.ToString()} ";
info.Expires = DateTime.UtcNow.AddMinutes(cacheTimeout).ToString("R");
info.Etag = track.Etag;
}
else
{
info.CacheControl = "no-store, must-revalidate, no-cache, max-age=0";
info.Pragma = "no-cache";
info.Expires = "Mon, 01 Jan 1990 00:00:00 GMT";
}
info.CacheControl = "no-store, must-revalidate, no-cache, max-age=0";
info.Pragma = "no-cache";
info.Expires = "Mon, 01 Jan 1990 00:00:00 GMT";
var bytesToRead = (int)(endBytes - beginBytes) + 1;
var trackBytes = new byte[bytesToRead];
using (var fs = trackFileInfo.OpenRead())
@ -797,9 +781,8 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> UpdateTrack(Library.Models.Users.User user, Track model)
public async Task<OperationResult<bool>> UpdateTrack(User user, Track model)
{
var didChangeTrack = false;
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
@ -829,7 +812,7 @@ namespace Roadie.Api.Services
track.MusicBrainzId = model.MusicBrainzId;
track.SpotifyId = model.SpotifyId;
track.Tags = model.TagsList.ToDelimitedList();
track.PartTitles = model.PartTitlesList == null || !model.PartTitlesList.Any()
track.PartTitles = model.PartTitlesList?.Any() != true
? null
: string.Join("\n", model.PartTitlesList);
@ -839,7 +822,7 @@ namespace Roadie.Api.Services
var artistId = SafeParser.ToGuid(model.TrackArtistToken.Value);
if (artistId.HasValue)
{
trackArtist = await GetArtist(artistId.Value);
trackArtist = await GetArtist(artistId.Value).ConfigureAwait(false);
if (trackArtist != null)
{
track.ArtistId = trackArtist.Id;
@ -851,16 +834,15 @@ namespace Roadie.Api.Services
track.ArtistId = null;
}
if(model.Credits == null || !model.Credits.Any())
if (model.Credits?.Any() != true)
{
// Delete all existing credits for track
var trackCreditsToDelete = (from c in DbContext.Credits
where c.TrackId == track.Id
select c).ToArray();
DbContext.Credits.RemoveRange(trackCreditsToDelete);
}
else if(model.Credits != null && model.Credits.Any())
else if (model.Credits?.Any() == true)
{
var trackCreditIds = model.Credits.Select(x => x.Id).ToArray();
// Delete any credits not given in model (removed by edit operation)
@ -870,12 +852,12 @@ namespace Roadie.Api.Services
select c).ToArray();
DbContext.Credits.RemoveRange(trackCreditsToDelete);
// Update any existing
foreach(var credit in model.Credits)
foreach (var credit in model.Credits)
{
var trackCredit = DbContext.Credits.FirstOrDefault(x => x.RoadieId == credit.Id);
if(trackCredit == null)
if (trackCredit == null)
{
// Add new
// Add new
trackCredit = new data.Credit
{
TrackId = track.Id,
@ -886,7 +868,7 @@ namespace Roadie.Api.Services
data.Artist artistForCredit = null;
if (credit.Artist != null)
{
artistForCredit = await GetArtist(credit.Artist.Id);
artistForCredit = await GetArtist(credit.Artist.Id).ConfigureAwait(false);
}
var creditCategory = DbContext.CreditCategory.FirstOrDefault(x => x.RoadieId.ToString() == credit.Category.Value);
trackCredit.CreditCategoryId = creditCategory.Id;
@ -917,10 +899,10 @@ namespace Roadie.Api.Services
File.Move(originalFilename, track.PathToTrack(Configuration));
}
track.LastUpdated = now;
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
var trackFileInfo = new FileInfo(track.PathToTrack(Configuration));
var audioMetaData = await AudioMetaDataHelper.GetInfo(trackFileInfo);
var audioMetaData = await AudioMetaDataHelper.GetInfo(trackFileInfo).ConfigureAwait(false);
if (audioMetaData != null)
{
audioMetaData.Title = track.Title;
@ -931,7 +913,7 @@ namespace Roadie.Api.Services
AudioMetaDataHelper.WriteTags(audioMetaData, trackFileInfo);
}
CacheManager.ClearRegion(track.CacheRegion);
Logger.LogInformation($"UpdateTrack `{track}` By User `{user}`: Edited Track [{didChangeTrack}]");
Logger.LogInformation($"UpdateTrack `{track}` By User `{user}`");
}
catch (Exception ex)
{
@ -943,8 +925,8 @@ namespace Roadie.Api.Services
return new OperationResult<bool>
{
IsSuccess = !errors.Any(),
Data = !errors.Any(),
IsSuccess = errors.Count == 0,
Data = errors.Count == 0,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
@ -959,7 +941,7 @@ namespace Roadie.Api.Services
sw.Start();
tsw.Restart();
var track = await GetTrack(id);
var track = await GetTrack(id).ConfigureAwait(false);
tsw.Stop();
timings.Add("getTrack", tsw.ElapsedMilliseconds);
@ -1004,24 +986,25 @@ namespace Roadie.Api.Services
timings.Add("trackArtist", tsw.ElapsedMilliseconds);
}
if (includes != null && includes.Any())
if (includes?.Any() == true)
{
if (includes.Contains("credits"))
{
tsw.Restart();
result.Credits = (await(from c in DbContext.Credits
join cc in DbContext.CreditCategory on c.CreditCategoryId equals cc.Id
join a in DbContext.Artists on c.ArtistId equals a.Id into agg
from a in agg.DefaultIfEmpty()
where c.TrackId == track.Id
select new { c, cc, a })
.ToListAsync())
result.Credits = (await (from c in DbContext.Credits
join cc in DbContext.CreditCategory on c.CreditCategoryId equals cc.Id
join a in DbContext.Artists on c.ArtistId equals a.Id into agg
from a in agg.DefaultIfEmpty()
where c.TrackId == track.Id
select new { c, cc, a })
.ToListAsync().ConfigureAwait(false))
.Select(x => new CreditList
{
Id = x.c.RoadieId,
Artist = x.a == null ? null : ArtistList.FromDataArtist(x.a, ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, x.a.RoadieId)),
Category = new DataToken {
Category = new DataToken
{
Text = x.cc.Name,
Value = x.cc.RoadieId.ToString()
},
@ -1045,7 +1028,7 @@ namespace Roadie.Api.Services
join ut in DbContext.UserTracks on t.Id equals ut.TrackId
where t.Id == track.Id
select ut).ToArray();
if (userTracks != null && userTracks.Any())
if (userTracks?.Any() == true)
{
result.Statistics.DislikedCount = userTracks.Count(x => x.IsDisliked ?? false);
result.Statistics.FavoriteCount = userTracks.Count(x => x.IsFavorite ?? false);
@ -1059,7 +1042,7 @@ namespace Roadie.Api.Services
tsw.Restart();
var trackComments = DbContext.Comments.Include(x => x.User).Where(x => x.TrackId == track.Id)
.OrderByDescending(x => x.CreatedDate).ToArray();
if (trackComments.Any())
if (trackComments.Length > 0)
{
var comments = new List<Comment>();
var commentIds = trackComments.Select(x => x.Id).ToArray();

View file

@ -10,7 +10,6 @@ using Roadie.Library.Data.Context;
using Roadie.Library.Encoding;
using Roadie.Library.Enums;
using Roadie.Library.Extensions;
using Roadie.Library.Identity;
using Roadie.Library.Imaging;
using Roadie.Library.MetaData.LastFm;
using Roadie.Library.Models.Pagination;
@ -49,30 +48,21 @@ namespace Roadie.Api.Services
{
UserManager = userManager;
LastFmHelper = lastFmHelper;
;
}
public async Task<OperationResult<models.Users.User>> ById(models.Users.User user, Guid id, IEnumerable<string> includes, bool isAccountSettingsEdit = false)
public async Task<OperationResult<User>> ById(User user, Guid id, IEnumerable<string> includes, bool isAccountSettingsEdit = false)
{
if (isAccountSettingsEdit)
if (isAccountSettingsEdit && user.UserId != id && !user.IsAdmin)
{
if (user.UserId != id && !user.IsAdmin)
return new OperationResult<User>("Access Denied")
{
var r = new OperationResult<models.Users.User>("Access Denied")
{
IsAccessDeniedResult = true
};
return r;
}
IsAccessDeniedResult = true
};
}
var sw = Stopwatch.StartNew();
sw.Start();
var cacheKey = string.Format("urn:user_by_id_operation:{0}:{1}", id, isAccountSettingsEdit);
var result = await CacheManager.GetAsync(cacheKey, async () =>
{
var rr = await UserByIdAction(id, includes);
return rr;
}, Library.Identity.User.CacheRegionUrn(id));
var result = await CacheManager.GetAsync(cacheKey, async () => await UserByIdAction(id, includes).ConfigureAwait(false), Library.Identity.User.CacheRegionUrn(id)).ConfigureAwait(false);
sw.Stop();
if (result?.Data != null)
{
@ -83,7 +73,7 @@ namespace Roadie.Api.Services
result.Data.ConcurrencyStamp = null;
}
}
return new OperationResult<models.Users.User>(result.Messages)
return new OperationResult<User>(result.Messages)
{
Data = result?.Data,
Errors = result?.Errors,
@ -93,7 +83,7 @@ namespace Roadie.Api.Services
};
}
public Task<Library.Models.Pagination.PagedResult<UserList>> List(PagedRequest request)
public Task<models.Pagination.PagedResult<UserList>> List(PagedRequest request)
{
var sw = new Stopwatch();
sw.Start();
@ -103,7 +93,7 @@ namespace Roadie.Api.Services
where ut.UserId == u.Id
select ut.LastPlayed).Max()
where request.FilterValue.Length == 0 ||
request.FilterValue.Length > 0 && u.UserName.Contains(request.FilterValue)
(request.FilterValue.Length > 0 && u.UserName.Contains(request.FilterValue))
select new UserList
{
DatabaseId = u.Id,
@ -132,7 +122,7 @@ namespace Roadie.Api.Services
: request.OrderValue();
rows = result.OrderBy(sortBy).Skip(request.SkipValue).Take(request.LimitValue).ToArray();
if (rows.Any())
if (rows.Length > 0)
{
foreach (var row in rows)
{
@ -147,22 +137,22 @@ namespace Roadie.Api.Services
.ToArray();
row.Statistics = new UserStatistics
{
RatedArtists = userArtists.Where(x => x.Rating > 0).Count(),
FavoritedArtists = userArtists.Where(x => x.IsFavorite ?? false).Count(),
DislikedArtists = userArtists.Where(x => x.IsDisliked ?? false).Count(),
RatedReleases = userReleases.Where(x => x.Rating > 0).Count(),
FavoritedReleases = userReleases.Where(x => x.IsFavorite ?? false).Count(),
DislikedReleases = userReleases.Where(x => x.IsDisliked ?? false).Count(),
RatedTracks = userTracks.Where(x => x.Rating > 0).Count(),
RatedArtists = userArtists.Count(x => x.Rating > 0),
FavoritedArtists = userArtists.Count(x => x.IsFavorite ?? false),
DislikedArtists = userArtists.Count(x => x.IsDisliked ?? false),
RatedReleases = userReleases.Count(x => x.Rating > 0),
FavoritedReleases = userReleases.Count(x => x.IsFavorite ?? false),
DislikedReleases = userReleases.Count(x => x.IsDisliked ?? false),
RatedTracks = userTracks.Count(x => x.Rating > 0),
PlayedTracks = userTracks.Where(x => x.PlayedCount.HasValue).Select(x => x.PlayedCount).Sum(),
FavoritedTracks = userTracks.Where(x => x.IsFavorite ?? false).Count(),
DislikedTracks = userTracks.Where(x => x.IsDisliked ?? false).Count()
FavoritedTracks = userTracks.Count(x => x.IsFavorite ?? false),
DislikedTracks = userTracks.Count(x => x.IsDisliked ?? false)
};
}
}
sw.Stop();
return Task.FromResult(new Library.Models.Pagination.PagedResult<UserList>
return Task.FromResult(new models.Pagination.PagedResult<UserList>
{
TotalCount = rowCount,
CurrentPage = request.PageValue,
@ -172,16 +162,16 @@ namespace Roadie.Api.Services
});
}
public async Task<OperationResult<bool>> DeleteAllBookmarks(models.Users.User roadieUser)
public async Task<OperationResult<bool>> DeleteAllBookmarks(User roadieUser)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
DbContext.Bookmarks.RemoveRange(DbContext.Bookmarks.Where(x => x.UserId == user.Id));
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
CacheManager.ClearRegion(user.CacheRegion);
@ -192,19 +182,20 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetArtistBookmark(Guid artistId, models.Users.User roadieUser, bool isBookmarked)
public async Task<OperationResult<bool>> SetArtistBookmark(Guid artistId, User roadieUser, bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var artist = await GetArtist(artistId);
var artist = await GetArtist(artistId).ConfigureAwait(false);
if (artist == null)
{
return new OperationResult<bool>(true, $"Invalid Artist [{artistId}]");
}
var result = await SetBookmark(user, BookmarkType.Artist, artist.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Artist, artist.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(artist.CacheRegion);
@ -215,49 +206,49 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetArtistDisliked(Guid artistId, models.Users.User roadieUser, bool isDisliked)
public async Task<OperationResult<bool>> SetArtistDisliked(Guid artistId, User roadieUser, bool isDisliked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleArtistDisliked(artistId, user, isDisliked);
return await ToggleArtistDisliked(artistId, user, isDisliked).ConfigureAwait(false);
}
public async Task<OperationResult<bool>> SetArtistFavorite(Guid artistId, models.Users.User roadieUser, bool isFavorite)
public async Task<OperationResult<bool>> SetArtistFavorite(Guid artistId, User roadieUser, bool isFavorite)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleArtistFavorite(artistId, user, isFavorite);
return await ToggleArtistFavorite(artistId, user, isFavorite).ConfigureAwait(false);
}
public async Task<OperationResult<short>> SetArtistRating(Guid artistId, models.Users.User roadieUser, short rating)
public async Task<OperationResult<short>> SetArtistRating(Guid artistId, User roadieUser, short rating)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<short>(true, $"Invalid User [{roadieUser}]");
}
return await SetArtistRating(artistId, user, rating);
return await SetArtistRating(artistId, user, rating).ConfigureAwait(false);
}
public async Task<OperationResult<bool>> SetCollectionBookmark(Guid collectionId, models.Users.User roadieUser, bool isBookmarked)
public async Task<OperationResult<bool>> SetCollectionBookmark(Guid collectionId, User roadieUser, bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var collection = await GetCollection(collectionId);
var collection = await GetCollection(collectionId).ConfigureAwait(false);
if (collection == null)
{
return new OperationResult<bool>(true, $"Invalid Collection [{collectionId}]");
}
var result = await SetBookmark(user, BookmarkType.Collection, collection.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Collection, collection.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(collection.CacheRegion);
@ -268,19 +259,19 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetLabelBookmark(Guid labelId, models.Users.User roadieUser, bool isBookmarked)
public async Task<OperationResult<bool>> SetLabelBookmark(Guid labelId, User roadieUser, bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var label = await GetLabel(labelId);
var label = await GetLabel(labelId).ConfigureAwait(false);
if (label == null)
{
return new OperationResult<bool>(true, $"Invalid Label [{labelId}]");
}
var result = await SetBookmark(user, BookmarkType.Label, label.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Label, label.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(label.CacheRegion);
@ -291,20 +282,20 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetPlaylistBookmark(Guid playlistId, models.Users.User roadieUser,
public async Task<OperationResult<bool>> SetPlaylistBookmark(Guid playlistId, User roadieUser,
bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var playlist = await GetPlaylist(playlistId);
var playlist = await GetPlaylist(playlistId).ConfigureAwait(false);
if (playlist == null)
{
return new OperationResult<bool>(true, $"Invalid Playlist [{playlistId}]");
}
await SetBookmark(user, BookmarkType.Playlist, playlist.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Playlist, playlist.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(playlist.CacheRegion);
@ -315,19 +306,19 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetReleaseBookmark(Guid releaseid, models.Users.User roadieUser, bool isBookmarked)
public async Task<OperationResult<bool>> SetReleaseBookmark(Guid releaseid, User roadieUser, bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var release = await GetRelease(releaseid);
var release = await GetRelease(releaseid).ConfigureAwait(false);
if (release == null)
{
return new OperationResult<bool>(true, $"Invalid Release [{releaseid}]");
}
await SetBookmark(user, BookmarkType.Release, release.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Release, release.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(release.CacheRegion);
@ -338,49 +329,49 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetReleaseDisliked(Guid releaseId, models.Users.User roadieUser, bool isDisliked)
public async Task<OperationResult<bool>> SetReleaseDisliked(Guid releaseId, User roadieUser, bool isDisliked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleReleaseDisliked(releaseId, user, isDisliked);
return await ToggleReleaseDisliked(releaseId, user, isDisliked).ConfigureAwait(false);
}
public async Task<OperationResult<bool>> SetReleaseFavorite(Guid releaseId, models.Users.User roadieUser, bool isFavorite)
public async Task<OperationResult<bool>> SetReleaseFavorite(Guid releaseId, User roadieUser, bool isFavorite)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleReleaseFavorite(releaseId, user, isFavorite);
return await ToggleReleaseFavorite(releaseId, user, isFavorite).ConfigureAwait(false);
}
public async Task<OperationResult<short>> SetReleaseRating(Guid releaseId, models.Users.User roadieUser, short rating)
public async Task<OperationResult<short>> SetReleaseRating(Guid releaseId, User roadieUser, short rating)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<short>(true, $"Invalid User [{roadieUser}]");
}
return await base.SetReleaseRating(releaseId, user, rating);
return await SetReleaseRating(releaseId, user, rating).ConfigureAwait(false);
}
public async Task<OperationResult<bool>> SetTrackBookmark(Guid trackId, models.Users.User roadieUser, bool isBookmarked)
public async Task<OperationResult<bool>> SetTrackBookmark(Guid trackId, User roadieUser, bool isBookmarked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
var track = await GetTrack(trackId);
var track = await GetTrack(trackId).ConfigureAwait(false);
if (track == null)
{
return new OperationResult<bool>(true, $"Invalid Track [{trackId}]");
}
await SetBookmark(user, BookmarkType.Track, track.Id, isBookmarked);
await SetBookmark(user, BookmarkType.Track, track.Id, isBookmarked).ConfigureAwait(false);
CacheManager.ClearRegion(track.CacheRegion);
@ -391,31 +382,31 @@ namespace Roadie.Api.Services
};
}
public async Task<OperationResult<bool>> SetTrackDisliked(Guid trackId, models.Users.User roadieUser, bool isDisliked)
public async Task<OperationResult<bool>> SetTrackDisliked(Guid trackId, User roadieUser, bool isDisliked)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleTrackDisliked(trackId, user, isDisliked);
return await ToggleTrackDisliked(trackId, user, isDisliked).ConfigureAwait(false);
}
public async Task<OperationResult<bool>> SetTrackFavorite(Guid trackId, models.Users.User roadieUser, bool isFavorite)
public async Task<OperationResult<bool>> SetTrackFavorite(Guid trackId, User roadieUser, bool isFavorite)
{
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
if (user == null)
{
return new OperationResult<bool>(true, $"Invalid User [{roadieUser}]");
}
return await ToggleTrackFavorite(trackId, user, isFavorite);
return await ToggleTrackFavorite(trackId, user, isFavorite).ConfigureAwait(false);
}
public async Task<OperationResult<short>> SetTrackRating(Guid trackId, models.Users.User roadieUser, short rating)
public async Task<OperationResult<short>> SetTrackRating(Guid trackId, User roadieUser, short rating)
{
var timings = new Dictionary<string, long>();
var sw = Stopwatch.StartNew();
var user = await GetUser(roadieUser.UserId);
var user = await GetUser(roadieUser.UserId).ConfigureAwait(false);
sw.Stop();
timings.Add("GetUser", sw.ElapsedMilliseconds);
@ -424,7 +415,7 @@ namespace Roadie.Api.Services
return new OperationResult<short>(true, $"Invalid User [{roadieUser}]");
}
sw.Start();
var result = await base.SetTrackRating(trackId, user, rating);
var result = await SetTrackRating(trackId, user, rating).ConfigureAwait(false);
sw.Stop();
timings.Add("SetTrackRating", sw.ElapsedMilliseconds);
@ -434,19 +425,21 @@ namespace Roadie.Api.Services
return result;
}
public async Task<OperationResult<bool>> UpdateIntegrationGrant(Guid userId, string integrationName,
string token)
public async Task<OperationResult<bool>> UpdateIntegrationGrant(Guid userId, string integrationName, string token)
{
var user = DbContext.Users.FirstOrDefault(x => x.RoadieId == userId);
if (user == null)
{
return new OperationResult<bool>(true, $"User Not Found [{userId}]");
}
if (integrationName == "lastfm") return await UpdateLastFMSessionKey(user, token);
if (integrationName == "lastfm")
{
return await UpdateLastFMSessionKey(user, token).ConfigureAwait(false);
}
throw new NotImplementedException();
}
public async Task<OperationResult<bool>> UpdateProfile(models.Users.User userPerformingUpdate, models.Users.User userBeingUpdatedModel)
public async Task<OperationResult<bool>> UpdateProfile(User userPerformingUpdate, User userBeingUpdatedModel)
{
var user = DbContext.Users.FirstOrDefault(x => x.RoadieId == userBeingUpdatedModel.UserId);
if (user == null)
@ -455,11 +448,10 @@ namespace Roadie.Api.Services
}
if (user.Id != userPerformingUpdate.Id && !userPerformingUpdate.IsAdmin)
{
var r = new OperationResult<bool>("Access Denied")
return new OperationResult<bool>("Access Denied")
{
IsAccessDeniedResult = true
};
return r;
}
// Check concurrency stamp
if (user.ConcurrencyStamp != userBeingUpdatedModel.ConcurrencyStamp)
@ -509,12 +501,9 @@ namespace Roadie.Api.Services
user.ConcurrencyStamp = Guid.NewGuid().ToString();
user.DefaultRowsPerPage = userBeingUpdatedModel.DefaultRowsPerPage;
if (didChangeName)
if (didChangeName && File.Exists(oldPathToImage))
{
if (File.Exists(oldPathToImage))
{
File.Move(oldPathToImage, user.PathToImage(Configuration));
}
File.Move(oldPathToImage, user.PathToImage(Configuration));
}
if (!string.IsNullOrEmpty(userBeingUpdatedModel.AvatarData))
@ -529,20 +518,24 @@ namespace Roadie.Api.Services
}
}
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
if (!string.IsNullOrEmpty(userBeingUpdatedModel.Password) &&
!string.IsNullOrEmpty(userBeingUpdatedModel.PasswordConfirmation))
{
if (userBeingUpdatedModel.Password != userBeingUpdatedModel.PasswordConfirmation)
{
return new OperationResult<bool>
{
Errors = new List<Exception> { new Exception("Password does not match confirmation") }
};
var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user);
}
var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);
var identityResult =
await UserManager.ResetPasswordAsync(user, resetToken, userBeingUpdatedModel.Password);
await UserManager.ResetPasswordAsync(user, resetToken, userBeingUpdatedModel.Password).ConfigureAwait(false);
if (!identityResult.Succeeded)
{
return new OperationResult<bool>
{
Errors = identityResult.Errors != null
@ -550,6 +543,7 @@ namespace Roadie.Api.Services
new Exception($"Code [{x.Code}], Description [{x.Description}]"))
: new List<Exception> { new Exception("Unable to reset password") }
};
}
}
CacheManager.ClearRegion(Library.Identity.User.CacheRegionUrn(user.RoadieId));
@ -574,7 +568,7 @@ namespace Roadie.Api.Services
if (bookmark != null)
{
DbContext.Bookmarks.Remove(bookmark);
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
}
}
else
@ -589,8 +583,8 @@ namespace Roadie.Api.Services
BookmarkType = bookmarktype,
CreatedDate = DateTime.UtcNow,
Status = Statuses.Ok
});
await DbContext.SaveChangesAsync();
}).ConfigureAwait(false);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
}
}
@ -605,19 +599,22 @@ namespace Roadie.Api.Services
private async Task<OperationResult<bool>> UpdateLastFMSessionKey(Library.Identity.User user, string token)
{
var lastFmSessionKeyResult = await LastFmHelper.GetSessionKeyForUserToken(token);
var lastFmSessionKeyResult = await LastFmHelper.GetSessionKeyForUserToken(token).ConfigureAwait(false);
if (!lastFmSessionKeyResult.IsSuccess)
return new OperationResult<bool>(false, $"Unable to Get LastFM Session Key For Token [{token}]");
// Check concurrency stamp
if (user.ConcurrencyStamp != user.ConcurrencyStamp)
{
return new OperationResult<bool>
{
Errors = new List<Exception> { new Exception("User data is stale.") }
};
}
user.LastFMSessionKey = lastFmSessionKeyResult.Data;
user.LastUpdated = DateTime.UtcNow;
user.ConcurrencyStamp = Guid.NewGuid().ToString();
await DbContext.SaveChangesAsync();
await DbContext.SaveChangesAsync().ConfigureAwait(false);
CacheManager.ClearRegion(Library.Identity.User.CacheRegionUrn(user.RoadieId));
@ -630,103 +627,100 @@ namespace Roadie.Api.Services
};
}
private async Task<OperationResult<models.Users.User>> UserByIdAction(Guid id, IEnumerable<string> includes)
private async Task<OperationResult<User>> UserByIdAction(Guid id, IEnumerable<string> includes)
{
var timings = new Dictionary<string, long>();
var tsw = new Stopwatch();
tsw.Restart();
var user = await GetUser(id);
var user = await GetUser(id).ConfigureAwait(false);
tsw.Stop();
timings.Add("getUser", tsw.ElapsedMilliseconds);
if (user == null)
{
return new OperationResult<models.Users.User>(true, string.Format("User Not Found [{0}]", id));
return new OperationResult<User>(true, string.Format("User Not Found [{0}]", id));
}
tsw.Restart();
var model = user.Adapt<models.Users.User>();
var model = user.Adapt<User>();
model.MediumThumbnail = ImageHelper.MakeThumbnailImage(Configuration, HttpContext, id, "user", Configuration.MediumImageSize.Width, Configuration.MediumImageSize.Height);
model.IsAdmin = user.UserRoles?.Any(x => x.Role?.NormalizedName == "ADMIN") ?? false;
model.IsEditor = model.IsAdmin ? true : user.UserRoles?.Any(x => x.Role?.NormalizedName == "EDITOR") ?? false;
model.IsEditor = model.IsAdmin || (user.UserRoles?.Any(x => x.Role?.NormalizedName == "EDITOR") ?? false);
tsw.Stop();
timings.Add("adapt", tsw.ElapsedMilliseconds);
if (includes != null && includes.Any())
if (includes?.Any() == true && includes.Contains("stats"))
{
if (includes.Contains("stats"))
{
tsw.Restart();
var userArtists = DbContext.UserArtists.Include(x => x.Artist).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserArtist[0];
var userReleases = DbContext.UserReleases.Include(x => x.Release).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserRelease[0];
var userTracks = DbContext.UserTracks.Include(x => x.Track).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserTrack[0];
tsw.Restart();
var userArtists = DbContext.UserArtists.Include(x => x.Artist).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserArtist[0];
var userReleases = DbContext.UserReleases.Include(x => x.Release).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserRelease[0];
var userTracks = DbContext.UserTracks.Include(x => x.Track).Where(x => x.UserId == user.Id).ToArray() ?? new data.UserTrack[0];
var mostPlayedArtist = await DbContext.MostPlayedArtist(user.Id);
var mostPlayedRelease = await DbContext.MostPlayedRelease(user.Id);
var lastPlayedTrack = await GetTrack((await DbContext.MostPlayedTrack(user.Id))?.RoadieId ?? Guid.Empty);
var mostPlayedTrack = await GetTrack((await DbContext.LastPlayedTrack(user.Id))?.RoadieId ?? Guid.Empty);
model.Statistics = new UserStatistics
{
LastPlayedTrack = lastPlayedTrack == null
? null
: models.TrackList.FromDataTrack(
MakeTrackPlayUrl(user, HttpContext.BaseUrl, lastPlayedTrack.RoadieId),
lastPlayedTrack,
lastPlayedTrack.ReleaseMedia.MediaNumber,
lastPlayedTrack.ReleaseMedia.Release,
lastPlayedTrack.ReleaseMedia.Release.Artist,
lastPlayedTrack.TrackArtist,
HttpContext.BaseUrl,
ImageHelper.MakeTrackThumbnailImage(Configuration, HttpContext, lastPlayedTrack.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, lastPlayedTrack.ReleaseMedia.Release.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, lastPlayedTrack.ReleaseMedia.Release.Artist.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, lastPlayedTrack.TrackArtist == null
? null
: (Guid?)lastPlayedTrack.TrackArtist.RoadieId)),
MostPlayedArtist = mostPlayedArtist == null
? null
: models.ArtistList.FromDataArtist(mostPlayedArtist,
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedArtist.RoadieId)),
MostPlayedRelease = mostPlayedRelease == null
? null
: ReleaseList.FromDataRelease(mostPlayedRelease,
mostPlayedRelease.Artist,
HttpContext.BaseUrl,
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedRelease.Artist.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, mostPlayedRelease.RoadieId)),
MostPlayedTrack = mostPlayedTrack == null
? null
: models.TrackList.FromDataTrack(
MakeTrackPlayUrl(user, HttpContext.BaseUrl, mostPlayedTrack.RoadieId),
mostPlayedTrack,
mostPlayedTrack.ReleaseMedia.MediaNumber,
mostPlayedTrack.ReleaseMedia.Release,
mostPlayedTrack.ReleaseMedia.Release.Artist,
mostPlayedTrack.TrackArtist,
HttpContext.BaseUrl,
ImageHelper.MakeTrackThumbnailImage(Configuration, HttpContext, mostPlayedTrack.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, mostPlayedTrack.ReleaseMedia.Release.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedTrack.ReleaseMedia.Release.Artist.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedTrack.TrackArtist == null
? null
: (Guid?)mostPlayedTrack.TrackArtist.RoadieId)),
RatedArtists = userArtists.Where(x => x.Rating > 0).Count(),
FavoritedArtists = userArtists.Where(x => x.IsFavorite ?? false).Count(),
DislikedArtists = userArtists.Where(x => x.IsDisliked ?? false).Count(),
RatedReleases = userReleases.Where(x => x.Rating > 0).Count(),
FavoritedReleases = userReleases.Where(x => x.IsFavorite ?? false).Count(),
DislikedReleases = userReleases.Where(x => x.IsDisliked ?? false).Count(),
RatedTracks = userTracks.Where(x => x.Rating > 0).Count(),
PlayedTracks = userTracks.Where(x => x.PlayedCount.HasValue).Select(x => x.PlayedCount).Sum(),
FavoritedTracks = userTracks.Where(x => x.IsFavorite ?? false).Count(),
DislikedTracks = userTracks.Where(x => x.IsDisliked ?? false).Count()
};
tsw.Stop();
timings.Add("stats", tsw.ElapsedMilliseconds);
}
var mostPlayedArtist = await DbContext.MostPlayedArtist(user.Id).ConfigureAwait(false);
var mostPlayedRelease = await DbContext.MostPlayedRelease(user.Id).ConfigureAwait(false);
var lastPlayedTrack = await GetTrack((await DbContext.MostPlayedTrack(user.Id).ConfigureAwait(false))?.RoadieId ?? Guid.Empty).ConfigureAwait(false);
var mostPlayedTrack = await GetTrack((await DbContext.LastPlayedTrack(user.Id).ConfigureAwait(false))?.RoadieId ?? Guid.Empty).ConfigureAwait(false);
model.Statistics = new UserStatistics
{
LastPlayedTrack = lastPlayedTrack == null
? null
: models.TrackList.FromDataTrack(
MakeTrackPlayUrl(user, HttpContext.BaseUrl, lastPlayedTrack.RoadieId),
lastPlayedTrack,
lastPlayedTrack.ReleaseMedia.MediaNumber,
lastPlayedTrack.ReleaseMedia.Release,
lastPlayedTrack.ReleaseMedia.Release.Artist,
lastPlayedTrack.TrackArtist,
HttpContext.BaseUrl,
ImageHelper.MakeTrackThumbnailImage(Configuration, HttpContext, lastPlayedTrack.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, lastPlayedTrack.ReleaseMedia.Release.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, lastPlayedTrack.ReleaseMedia.Release.Artist.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, lastPlayedTrack.TrackArtist == null
? null
: (Guid?)lastPlayedTrack.TrackArtist.RoadieId)),
MostPlayedArtist = mostPlayedArtist == null
? null
: models.ArtistList.FromDataArtist(mostPlayedArtist,
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedArtist.RoadieId)),
MostPlayedRelease = mostPlayedRelease == null
? null
: ReleaseList.FromDataRelease(mostPlayedRelease,
mostPlayedRelease.Artist,
HttpContext.BaseUrl,
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedRelease.Artist.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, mostPlayedRelease.RoadieId)),
MostPlayedTrack = mostPlayedTrack == null
? null
: models.TrackList.FromDataTrack(
MakeTrackPlayUrl(user, HttpContext.BaseUrl, mostPlayedTrack.RoadieId),
mostPlayedTrack,
mostPlayedTrack.ReleaseMedia.MediaNumber,
mostPlayedTrack.ReleaseMedia.Release,
mostPlayedTrack.ReleaseMedia.Release.Artist,
mostPlayedTrack.TrackArtist,
HttpContext.BaseUrl,
ImageHelper.MakeTrackThumbnailImage(Configuration, HttpContext, mostPlayedTrack.RoadieId),
ImageHelper.MakeReleaseThumbnailImage(Configuration, HttpContext, mostPlayedTrack.ReleaseMedia.Release.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedTrack.ReleaseMedia.Release.Artist.RoadieId),
ImageHelper.MakeArtistThumbnailImage(Configuration, HttpContext, mostPlayedTrack.TrackArtist == null
? null
: (Guid?)mostPlayedTrack.TrackArtist.RoadieId)),
RatedArtists = userArtists.Count(x => x.Rating > 0),
FavoritedArtists = userArtists.Count(x => x.IsFavorite ?? false),
DislikedArtists = userArtists.Count(x => x.IsDisliked ?? false),
RatedReleases = userReleases.Count(x => x.Rating > 0),
FavoritedReleases = userReleases.Count(x => x.IsFavorite ?? false),
DislikedReleases = userReleases.Count(x => x.IsDisliked ?? false),
RatedTracks = userTracks.Count(x => x.Rating > 0),
PlayedTracks = userTracks.Where(x => x.PlayedCount.HasValue).Select(x => x.PlayedCount).Sum(),
FavoritedTracks = userTracks.Count(x => x.IsFavorite ?? false),
DislikedTracks = userTracks.Count(x => x.IsDisliked ?? false)
};
tsw.Stop();
timings.Add("stats", tsw.ElapsedMilliseconds);
}
Logger.LogInformation($"ByIdAction: User `{ user }`: includes [{includes.ToCSV()}], timings: [{ timings.ToTimings() }]");
return new OperationResult<models.Users.User>
return new OperationResult<User>
{
IsSuccess = true,
Data = model

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB