roadie/Roadie.Api.Services/ArtistService.cs

1464 lines
72 KiB
C#
Raw Normal View History

2018-11-06 22:59:48 +00:00
using Mapster;
2018-12-26 21:18:51 +00:00
using Microsoft.AspNetCore.Http;
2018-11-06 22:59:48 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
2018-12-05 16:04:21 +00:00
using Newtonsoft.Json;
2018-11-06 04:31:25 +00:00
using Roadie.Library;
using Roadie.Library.Caching;
using Roadie.Library.Configuration;
using Roadie.Library.Encoding;
2018-12-27 17:37:17 +00:00
using Roadie.Library.Engines;
2018-11-06 22:59:48 +00:00
using Roadie.Library.Enums;
using Roadie.Library.Extensions;
2019-07-07 03:16:33 +00:00
using Roadie.Library.Identity;
2018-12-26 21:18:51 +00:00
using Roadie.Library.Imaging;
2018-12-27 17:37:17 +00:00
using Roadie.Library.MetaData.Audio;
using Roadie.Library.MetaData.FileName;
using Roadie.Library.MetaData.ID3Tags;
using Roadie.Library.MetaData.LastFm;
2018-11-06 04:31:25 +00:00
using Roadie.Library.Models;
using Roadie.Library.Models.Pagination;
2018-11-06 22:59:48 +00:00
using Roadie.Library.Models.Releases;
using Roadie.Library.Models.Statistics;
using Roadie.Library.Models.Users;
2019-01-08 22:40:26 +00:00
using Roadie.Library.Processors;
2018-11-06 22:59:48 +00:00
using Roadie.Library.Utility;
2018-11-06 04:31:25 +00:00
using System;
using System.Collections.Generic;
2018-11-06 21:55:31 +00:00
using System.Diagnostics;
2018-12-26 21:18:51 +00:00
using System.IO;
2018-11-06 22:59:48 +00:00
using System.Linq;
2018-11-14 14:00:08 +00:00
using System.Linq.Dynamic.Core;
2018-11-06 04:31:25 +00:00
using System.Threading.Tasks;
using data = Roadie.Library.Data;
2019-01-08 22:40:26 +00:00
using mb = Roadie.Library.MetaData.MusicBrainz;
2018-11-06 04:31:25 +00:00
namespace Roadie.Api.Services
{
public class ArtistService : ServiceBase, IArtistService
{
2018-12-27 17:37:17 +00:00
private IArtistLookupEngine ArtistLookupEngine { get; }
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
private IAudioMetaDataHelper AudioMetaDataHelper { get; }
2019-06-30 22:14:36 +00:00
private IBookmarkService BookmarkService { get; }
private ICollectionService CollectionService { get; }
2018-12-27 17:37:17 +00:00
private IFileNameHelper FileNameHelper { get; }
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
private IID3TagsHelper ID3TagsHelper { get; }
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
private ILabelLookupEngine LabelLookupEngine { get; }
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
private ILastFmHelper LastFmHelper { get; }
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
private mb.IMusicBrainzProvider MusicBrainzProvider { get; }
2019-06-30 22:14:36 +00:00
private IPlaylistService PlaylistService { get; }
2018-12-27 17:37:17 +00:00
private IReleaseLookupEngine ReleaseLookupEngine { get; }
2019-07-07 03:16:33 +00:00
private IReleaseService ReleaseService { get; }
private IFileDirectoryProcessorService FileDirectoryProcessorService { get; }
public ArtistService(IRoadieSettings configuration,
IHttpEncoder httpEncoder,
2019-06-30 22:14:36 +00:00
IHttpContext httpContext,
data.IRoadieDbContext dbContext,
ICacheManager cacheManager,
ILogger<ArtistService> logger,
ICollectionService collectionService,
IPlaylistService playlistService,
2019-07-07 03:16:33 +00:00
IBookmarkService bookmarkService,
IReleaseService releaseService,
IArtistLookupEngine artistLookupEngine,
mb.IMusicBrainzProvider musicBrainzProvider,
ILastFmHelper lastFmHelper,
IFileNameHelper fileNameHelper,
IID3TagsHelper id3tagsHelper,
IAudioMetaDataHelper audioMetaDataHelper,
IReleaseLookupEngine releaseLookupEngine,
ILabelLookupEngine labelLookupEngine,
IFileDirectoryProcessorService fileDirectoryProcessorService
2019-06-30 22:14:36 +00:00
)
2018-12-27 17:37:17 +00:00
: base(configuration, httpEncoder, dbContext, cacheManager, logger, httpContext)
2018-11-06 04:31:25 +00:00
{
2019-06-30 22:14:36 +00:00
CollectionService = collectionService;
PlaylistService = playlistService;
BookmarkService = bookmarkService;
2019-07-07 03:16:33 +00:00
MusicBrainzProvider = musicBrainzProvider;
LastFmHelper = lastFmHelper;
FileNameHelper = fileNameHelper;
ID3TagsHelper = id3tagsHelper;
ArtistLookupEngine = artistLookupEngine;
LabelLookupEngine = labelLookupEngine;
ReleaseLookupEngine = releaseLookupEngine;
AudioMetaDataHelper = audioMetaDataHelper;
ReleaseService = releaseService;
FileDirectoryProcessorService = fileDirectoryProcessorService;
2018-11-06 04:31:25 +00:00
}
2018-11-14 03:19:28 +00:00
public async Task<OperationResult<Artist>> ById(User roadieUser, Guid id, IEnumerable<string> includes)
2018-11-06 04:31:25 +00:00
{
2018-12-05 16:04:21 +00:00
var timings = new Dictionary<string, long>();
var tsw = new Stopwatch();
2018-11-06 21:55:31 +00:00
var sw = Stopwatch.StartNew();
sw.Start();
2019-06-30 22:14:36 +00:00
var cacheKey = $"urn:artist_by_id_operation:{id}:{(includes == null ? "0" : string.Join("|", includes))}";
var result = await CacheManager.GetAsync(cacheKey, async () =>
{
2018-12-05 16:04:21 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
var rr = await ArtistByIdAction(id, includes);
2018-12-05 16:04:21 +00:00
tsw.Stop();
timings.Add("ArtistByIdAction", tsw.ElapsedMilliseconds);
return rr;
2018-11-11 16:20:33 +00:00
}, data.Artist.CacheRegionUrn(id));
if (result?.Data != null && roadieUser != null)
2018-11-14 03:19:28 +00:00
{
2018-12-05 16:04:21 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
var artist = GetArtist(id);
2018-12-05 16:04:21 +00:00
tsw.Stop();
timings.Add("GetArtist", tsw.ElapsedMilliseconds);
tsw.Restart();
2019-06-30 22:14:36 +00:00
var userBookmarkResult =
await BookmarkService.List(roadieUser, new PagedRequest(), false, BookmarkType.Artist);
2018-12-05 16:04:21 +00:00
if (userBookmarkResult.IsSuccess)
2019-06-30 22:14:36 +00:00
result.Data.UserBookmarked =
userBookmarkResult?.Rows?.FirstOrDefault(x => x.Bookmark.Value == artist.RoadieId.ToString()) !=
null;
2018-12-05 16:04:21 +00:00
tsw.Stop();
timings.Add("userBookmarkResult", tsw.ElapsedMilliseconds);
tsw.Restart();
2019-06-30 22:14:36 +00:00
var userArtist =
DbContext.UserArtists.FirstOrDefault(x => x.ArtistId == artist.Id && x.UserId == roadieUser.Id);
2018-11-14 03:19:28 +00:00
if (userArtist != null)
2018-11-14 14:00:08 +00:00
result.Data.UserRating = new UserArtist
{
IsDisliked = userArtist.IsDisliked ?? false,
IsFavorite = userArtist.IsFavorite ?? false,
Rating = userArtist.Rating
};
2018-12-05 16:04:21 +00:00
tsw.Stop();
timings.Add("userArtist", tsw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
if (result.Data.Comments.Any())
2019-06-28 21:24:32 +00:00
{
tsw.Restart();
var commentIds = result.Data.Comments.Select(x => x.DatabaseId).ToArray();
2019-06-30 22:14:36 +00:00
var userCommentReactions = (from cr in DbContext.CommentReactions
2019-06-28 21:24:32 +00:00
where commentIds.Contains(cr.CommentId)
where cr.UserId == roadieUser.Id
select cr).ToArray();
2019-06-30 22:14:36 +00:00
foreach (var comment in result.Data.Comments)
2019-06-28 21:24:32 +00:00
{
2019-06-30 22:14:36 +00:00
var userCommentReaction =
userCommentReactions.FirstOrDefault(x => x.CommentId == comment.DatabaseId);
2019-06-28 21:24:32 +00:00
comment.IsDisliked = userCommentReaction?.ReactionValue == CommentReaction.Dislike;
comment.IsLiked = userCommentReaction?.ReactionValue == CommentReaction.Like;
}
2019-06-30 22:14:36 +00:00
2019-06-28 21:24:32 +00:00
tsw.Stop();
timings.Add("commentReactions", tsw.ElapsedMilliseconds);
}
2018-11-14 03:19:28 +00:00
}
2019-06-30 22:14:36 +00:00
sw.Stop();
2018-12-05 16:04:21 +00:00
timings.Add("operation", sw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
Logger.LogDebug("ById Timings: id [{0}], includes [{1}], timings [{3}]", id, includes,
JsonConvert.SerializeObject(timings));
return new OperationResult<Artist>(result.Messages)
2018-11-06 21:55:31 +00:00
{
2018-11-11 01:11:58 +00:00
Data = result?.Data,
Errors = result?.Errors,
IsNotFoundResult = result?.IsNotFoundResult ?? false,
2018-11-11 01:11:58 +00:00
IsSuccess = result?.IsSuccess ?? false,
OperationTime = sw.ElapsedMilliseconds
};
}
public async Task<OperationResult<bool>> Delete(ApplicationUser user, data.Artist artist)
2019-07-07 03:16:33 +00:00
{
var isSuccess = false;
try
{
if (artist != null)
2019-07-07 03:16:33 +00:00
{
DbContext.Artists.Remove(artist);
2019-07-07 03:16:33 +00:00
await DbContext.SaveChangesAsync();
// TODO delete artist folder if empty?
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation(string.Format("x DeleteArtist [{0}]", artist.Id));
2019-07-07 03:16:33 +00:00
isSuccess = true;
}
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Serialize());
return new OperationResult<bool>
{
Errors = new Exception[1] { ex }
};
}
return new OperationResult<bool>
{
IsSuccess = isSuccess,
Data = isSuccess
};
}
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
};
}
2019-06-30 22:14:36 +00:00
public async Task<Library.Models.Pagination.PagedResult<ArtistList>> List(User roadieUser, PagedRequest request,
2019-07-07 03:16:33 +00:00
bool? doRandomize = false, bool? onlyIncludeWithReleases = true)
2018-11-06 04:31:25 +00:00
{
2018-11-14 14:00:08 +00:00
var sw = new Stopwatch();
sw.Start();
2018-11-21 18:19:38 +00:00
2019-06-23 15:45:45 +00:00
IQueryable<int> favoriteArtistIds = null;
2019-01-08 22:40:26 +00:00
if (request.FilterFavoriteOnly)
2019-06-30 22:14:36 +00:00
favoriteArtistIds = from a in DbContext.Artists
join ua in DbContext.UserArtists on a.Id equals ua.ArtistId
where ua.IsFavorite ?? false
where roadieUser == null || ua.UserId == roadieUser.Id
select a.Id;
2019-06-23 15:45:45 +00:00
IQueryable<int> labelArtistIds = null;
2019-01-08 22:40:26 +00:00
if (request.FilterToLabelId.HasValue)
2019-06-30 22:14:36 +00:00
labelArtistIds = (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
2018-12-09 23:30:55 +00:00
where l.RoadieId == request.FilterToLabelId
select r.ArtistId)
2019-06-30 22:14:36 +00:00
.Distinct();
2019-06-23 15:45:45 +00:00
IQueryable<int> genreArtistIds = null;
2018-12-30 04:34:32 +00:00
var isFilteredToGenre = false;
2019-06-30 22:14:36 +00:00
if (!string.IsNullOrEmpty(request.Filter) &&
request.Filter.StartsWith(":genre", StringComparison.OrdinalIgnoreCase))
2018-12-30 04:34:32 +00:00
{
var genreFilter = request.Filter.Replace(":genre ", "");
2019-06-30 22:14:36 +00:00
genreArtistIds = (from ag in DbContext.ArtistGenres
join g in DbContext.Genres on ag.GenreId equals g.Id
2018-12-30 04:34:32 +00:00
where g.Name.Contains(genreFilter)
select ag.ArtistId)
2019-06-30 22:14:36 +00:00
.Distinct();
2018-12-30 04:34:32 +00:00
isFilteredToGenre = true;
request.Filter = null;
}
2019-06-30 22:14:36 +00:00
var onlyWithReleases = onlyIncludeWithReleases ?? true;
2019-03-10 16:55:21 +00:00
var isEqualFilter = false;
2019-05-29 22:25:40 +00:00
if (!string.IsNullOrEmpty(request.FilterValue))
2019-03-10 16:55:21 +00:00
{
var filter = request.FilterValue;
// if filter string is wrapped in quotes then is an exact not like search, e.g. "Diana Ross" should not return "Diana Ross & The Supremes"
if (filter.StartsWith('"') && filter.EndsWith('"'))
{
isEqualFilter = true;
request.Filter = filter.Substring(1, filter.Length - 2);
}
}
2019-06-30 22:14:36 +00:00
var normalizedFilterValue = !string.IsNullOrEmpty(request.FilterValue)
? request.FilterValue.ToAlphanumericName()
: null;
var result = (from a in DbContext.Artists
where !onlyWithReleases || a.ReleaseCount > 0
where request.FilterToArtistId == null || a.RoadieId == request.FilterToArtistId
where request.FilterMinimumRating == null || a.Rating >= request.FilterMinimumRating.Value
where request.FilterValue == "" || a.Name.Contains(request.FilterValue) || a.SortName.Contains(request.FilterValue) || a.AlternateNames.Contains(request.FilterValue) || a.AlternateNames.Contains(normalizedFilterValue)
where !isEqualFilter || a.Name.Equals(request.FilterValue) || a.SortName.Equals(request.FilterValue) || a.AlternateNames.Equals(request.FilterValue) || a.AlternateNames.Equals(normalizedFilterValue)
2019-06-30 22:14:36 +00:00
where !request.FilterFavoriteOnly || favoriteArtistIds.Contains(a.Id)
where request.FilterToLabelId == null || labelArtistIds.Contains(a.Id)
where !isFilteredToGenre || genreArtistIds.Contains(a.Id)
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
2019-06-30 22:14:36 +00:00
Thumbnail = MakeArtistThumbnailImage(a.RoadieId),
Rating = a.Rating,
2019-01-23 16:50:36 +00:00
Rank = a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
2018-12-01 18:05:24 +00:00
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).Distinct();
2018-11-06 04:31:25 +00:00
2019-06-30 22:14:36 +00:00
ArtistList[] rows;
2018-11-14 14:00:08 +00:00
var rowCount = result.Count();
if (doRandomize ?? false)
{
2018-12-01 18:05:24 +00:00
var randomLimit = roadieUser?.RandomReleaseLimit ?? 100;
request.Limit = request.LimitValue > randomLimit ? randomLimit : request.LimitValue;
2019-03-06 01:18:21 +00:00
rows = result.OrderBy(x => x.RandomSortId).Skip(request.SkipValue).Take(request.LimitValue).ToArray();
2018-11-14 14:00:08 +00:00
}
else
{
2019-06-30 22:14:36 +00:00
string sortBy;
2018-11-14 14:00:08 +00:00
if (request.ActionValue == User.ActionKeyUserRated)
{
sortBy = string.IsNullOrEmpty(request.Sort)
? request.OrderValue(new Dictionary<string, string> { { "Rating", "DESC" }, { "Artist.Text", "ASC" } })
2019-06-30 22:14:36 +00:00
: request.OrderValue();
}
2018-11-14 14:00:08 +00:00
else
{
sortBy = request.OrderValue(new Dictionary<string, string> {{"SortName", "ASC"}, {"Artist.Text", "ASC"}});
}
2018-11-14 14:00:08 +00:00
rows = result.OrderBy(sortBy).Skip(request.SkipValue).Take(request.LimitValue).ToArray();
}
2019-06-30 22:14:36 +00:00
if (rows.Any() && roadieUser != null)
2018-11-14 14:00:08 +00:00
{
2018-12-08 19:47:19 +00:00
var rowIds = rows.Select(x => x.DatabaseId).ToArray();
2019-06-30 22:14:36 +00:00
var userArtistRatings = (from ua in DbContext.UserArtists
2019-01-08 22:40:26 +00:00
where ua.UserId == roadieUser.Id
where rowIds.Contains(ua.ArtistId)
select ua).ToArray();
2018-12-08 19:47:19 +00:00
2019-06-30 22:14:36 +00:00
foreach (var userArtistRating in userArtistRatings.Where(x =>
rows.Select(r => r.DatabaseId).Contains(x.ArtistId)))
2018-11-14 14:00:08 +00:00
{
var row = rows.FirstOrDefault(x => x.DatabaseId == userArtistRating.ArtistId);
if (row != null)
2018-11-14 14:00:08 +00:00
row.UserRating = new UserArtist
{
IsDisliked = userArtistRating.IsDisliked ?? false,
IsFavorite = userArtistRating.IsFavorite ?? false,
2018-11-25 20:43:52 +00:00
Rating = userArtistRating.Rating,
RatedDate = userArtistRating.LastUpdated ?? userArtistRating.CreatedDate
2018-11-14 14:00:08 +00:00
};
}
}
2019-06-30 22:14:36 +00:00
2018-11-14 14:00:08 +00:00
sw.Stop();
2019-05-29 22:25:40 +00:00
if (!string.IsNullOrEmpty(request.Filter) && rowCount == 0)
2019-06-23 15:45:45 +00:00
if (Configuration.RecordNoResultSearches)
2019-01-30 03:16:49 +00:00
{
2019-06-23 15:45:45 +00:00
// Create request for no artist found
var req = new data.Request
{
UserId = roadieUser?.Id,
Description = request.Filter
};
2019-06-30 22:14:36 +00:00
DbContext.Requests.Add(req);
await DbContext.SaveChangesAsync();
2019-06-23 15:45:45 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-30 03:16:49 +00:00
return new Library.Models.Pagination.PagedResult<ArtistList>
2018-11-14 14:00:08 +00:00
{
TotalCount = rowCount,
CurrentPage = request.PageValue,
TotalPages = (int)Math.Ceiling((double)rowCount / request.LimitValue),
OperationTime = sw.ElapsedMilliseconds,
Rows = rows
2019-01-30 03:16:49 +00:00
};
2018-11-06 04:31:25 +00:00
}
2018-12-26 21:18:51 +00:00
2019-07-07 03:16:33 +00:00
/// <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>
public async Task<OperationResult<bool>> MergeArtists(ApplicationUser user, Guid artistToMergeId, Guid artistToMergeIntoId)
2019-05-29 22:25:40 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var artistToMerge = DbContext.Artists
.Include(x => x.Genres)
.Include("Genres.Genre")
.FirstOrDefault(x => x.RoadieId == artistToMergeId);
2019-05-29 22:25:40 +00:00
if (artistToMerge == null)
{
2019-06-30 22:14:36 +00:00
Logger.LogWarning("MergeArtists Unknown Artist [{0}]", artistToMergeId);
return new OperationResult<bool>(true, $"Artist Not Found [{artistToMergeId}]");
2019-05-29 22:25:40 +00:00
}
2019-06-30 22:14:36 +00:00
var mergeIntoArtist = DbContext.Artists
.Include(x => x.Genres)
.Include("Genres.Genre")
.FirstOrDefault(x => x.RoadieId == artistToMergeIntoId);
2019-05-29 22:25:40 +00:00
if (mergeIntoArtist == null)
{
2019-06-30 22:14:36 +00:00
Logger.LogWarning("MergeArtists Unknown Artist [{0}]", artistToMergeIntoId);
return new OperationResult<bool>(true, $"Artist Not Found [{artistToMergeIntoId}]");
2019-05-29 22:25:40 +00:00
}
try
{
2019-07-07 03:16:33 +00:00
var result = await MergeArtists(user, artistToMerge, mergeIntoArtist);
2019-05-29 22:25:40 +00:00
if (!result.IsSuccess)
{
2019-06-30 22:14:36 +00:00
CacheManager.ClearRegion(artistToMerge.CacheRegion);
CacheManager.ClearRegion(mergeIntoArtist.CacheRegion);
Logger.LogInformation("MergeArtists `{0}` => `{1}`, By User `{2}`", artistToMerge, mergeIntoArtist,
user);
2019-05-29 22:25:40 +00:00
}
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
2019-05-29 22:25:40 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-05-29 22:25:40 +00:00
sw.Stop();
return new OperationResult<bool>
{
IsSuccess = !errors.Any(),
Data = !errors.Any(),
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2019-07-07 03:16:33 +00:00
async Task<OperationResult<data.Artist>> MergeArtists(ApplicationUser user, data.Artist artistToMerge, data.Artist artistToMergeInto)
{
SimpleContract.Requires<ArgumentNullException>(artistToMerge != null, "Invalid Artist");
SimpleContract.Requires<ArgumentNullException>(artistToMergeInto != null, "Invalid Artist");
var result = false;
var now = DateTime.UtcNow;
var sw = new Stopwatch();
sw.Start();
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.Thumbnail = artistToMergeInto.Thumbnail ?? artistToMerge.Thumbnail;
artistToMergeInto.Profile = artistToMergeInto.Profile ?? artistToMerge.Profile;
artistToMergeInto.BirthDate = artistToMergeInto.BirthDate ?? artistToMerge.BirthDate;
artistToMergeInto.BeginDate = artistToMergeInto.BeginDate ?? artistToMerge.BeginDate;
artistToMergeInto.EndDate = artistToMergeInto.EndDate ?? artistToMerge.EndDate;
2019-07-07 03:16:33 +00:00
if (!string.IsNullOrEmpty(artistToMerge.ArtistType) && !artistToMerge.ArtistType.Equals("Other", StringComparison.OrdinalIgnoreCase))
{
artistToMergeInto.ArtistType = artistToMergeInto.ArtistType ?? artistToMerge.ArtistType;
2019-07-07 03:16:33 +00:00
}
artistToMergeInto.BioContext = artistToMergeInto.BioContext ?? artistToMerge.BioContext;
artistToMergeInto.DiscogsId = artistToMergeInto.DiscogsId ?? artistToMerge.DiscogsId;
2019-07-07 03:16:33 +00:00
artistToMergeInto.Tags = artistToMergeInto.Tags.AddToDelimitedList(artistToMerge.Tags.ToListFromDelimited());
var altNames = artistToMerge.AlternateNames.ToListFromDelimited().ToList();
altNames.Add(artistToMerge.Name);
altNames.Add(artistToMerge.SortName);
artistToMergeInto.AlternateNames = artistToMergeInto.AlternateNames.AddToDelimitedList(altNames);
artistToMergeInto.URLs = artistToMergeInto.URLs.AddToDelimitedList(artistToMerge.URLs.ToListFromDelimited());
artistToMergeInto.ISNI = artistToMergeInto.ISNI.AddToDelimitedList(artistToMerge.ISNI.ToListFromDelimited());
artistToMergeInto.LastUpdated = now;
try
{
var artistGenres = DbContext.ArtistGenres.Where(x => x.ArtistId == artistToMerge.Id).ToArray();
if (artistGenres != null)
{
var existingArtistGenres = DbContext.ArtistGenres.Where(x => x.ArtistId == artistToMergeInto.Id).ToArray();
2019-07-07 03:16:33 +00:00
foreach (var artistGenre in artistGenres)
{
var existing = existingArtistGenres.FirstOrDefault(x => x.GenreId == artistGenre.GenreId);
// If not exist then add new for artist to merge into
if (existing == null)
{
DbContext.ArtistGenres.Add(new data.ArtistGenre
{
ArtistId = artistToMergeInto.Id,
GenreId = artistGenre.GenreId
});
}
2019-07-07 03:16:33 +00:00
}
}
var artistImages = DbContext.Images.Where(x => x.ArtistId == artistToMerge.Id).ToArray();
if (artistImages != null)
{
foreach (var artistImage in artistImages)
{
artistImage.ArtistId = artistToMergeInto.Id;
}
}
try
{
// Move any Artist and Artist Secondary images from ArtistToMerge into ArtistToMergeInto folder
if (Directory.Exists(artistToMergeFolder))
{
var artistToMergeImages = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistToMergeFolder), ImageType.Artist);
var artistToMergeSecondaryImages = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistToMergeFolder), ImageType.ArtistSecondary).ToList();
// Primary Artist image
if (artistToMergeImages.Any())
{
// If the ArtistToMergeInto already has a primary image then the ArtistToMerge primary image becomes a secondary image
var artistToMergeIntoPrimaryImage = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistToMergeIntoFolder), ImageType.Artist).FirstOrDefault();
if (artistToMergeIntoPrimaryImage != null)
{
artistToMergeSecondaryImages.Add(artistToMergeImages.First());
}
else
{
var artistImageFilename = Path.Combine(artistToMergeIntoFolder, ImageHelper.ArtistImageFilename);
artistToMergeImages.First().MoveTo(artistImageFilename);
}
}
// Secondary Artist images
if (artistToMergeSecondaryImages.Any())
{
var looper = 0;
foreach (var artistSecondaryImage in artistToMergeSecondaryImages)
{
var artistImageFilename = Path.Combine(artistToMergeIntoFolder, string.Format(ImageHelper.ArtistSecondaryImageFilename, looper.ToString("00")));
while (File.Exists(artistImageFilename))
{
looper++;
artistImageFilename = Path.Combine(artistToMergeIntoFolder, string.Format(ImageHelper.ArtistSecondaryImageFilename, looper.ToString("00")));
}
artistSecondaryImage.MoveTo(artistImageFilename);
}
}
}
}
catch (Exception ex)
{
Logger.LogError(ex, "MergeArtists: Error Moving Artist Primary and Secondary Images");
}
2019-07-07 03:16:33 +00:00
var userArtists = DbContext.UserArtists.Where(x => x.ArtistId == artistToMerge.Id).ToArray();
if (artistImages != null)
{
foreach (var userArtist in userArtists)
{
userArtist.ArtistId = artistToMergeInto.Id;
}
}
var artistTracks = DbContext.Tracks.Where(x => x.ArtistId == artistToMerge.Id).ToArray();
if (artistTracks != null)
{
foreach (var artistTrack in artistTracks)
{
artistTrack.ArtistId = artistToMergeInto.Id;
}
}
var artistReleases = DbContext.Releases.Where(x => x.ArtistId == artistToMerge.Id).ToArray();
if (artistReleases != null)
{
foreach (var artistRelease in artistReleases)
{
// See if there is already a release by the same name for the artist to merge into, if so then merge releases
var artistToMergeHasRelease = DbContext.Releases.FirstOrDefault(x => x.ArtistId == artistToMerge.Id && x.Title == artistRelease.Title);
if (artistToMergeHasRelease != null)
{
await ReleaseService.MergeReleases(user, artistRelease, artistToMergeHasRelease, false);
}
else
{
artistRelease.ArtistId = artistToMerge.Id;
}
}
}
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToString());
}
foreach (var release in DbContext.Releases.Include("Artist").Where(x => x.ArtistId == artistToMerge.Id).ToArray())
{
var originalReleaseFolder = release.ReleaseFileFolder(artistToMergeFolder);
2019-07-07 03:16:33 +00:00
await ReleaseService.UpdateRelease(user, release.Adapt<Release>(), originalReleaseFolder);
}
await DbContext.SaveChangesAsync();
2019-07-07 03:16:33 +00:00
await Delete(user, artistToMerge);
result = true;
sw.Stop();
return new OperationResult<data.Artist>
{
Data = artistToMergeInto,
IsSuccess = result,
OperationTime = sw.ElapsedMilliseconds
};
}
public async Task<OperationResult<bool>> RefreshArtistMetadata(ApplicationUser user, Guid artistId)
{
SimpleContract.Requires<ArgumentOutOfRangeException>(artistId != Guid.Empty, "Invalid ArtistId");
var result = true;
var resultErrors = new List<Exception>();
var sw = new Stopwatch();
sw.Start();
try
{
var artist = DbContext.Artists.FirstOrDefault(x => x.RoadieId == artistId);
if (artist == null)
{
Logger.LogWarning("Unable To Find Artist [{0}]", artistId);
return new OperationResult<bool>();
}
OperationResult<data.Artist> artistSearch = null;
try
{
artistSearch = await ArtistLookupEngine.PerformMetaDataProvidersArtistSearch(new AudioMetaData
{
Artist = artist.Name
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Serialize());
}
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);
if (mergeResult.IsSuccess)
{
artist = mergeResult.Data;
await DbContext.SaveChangesAsync();
sw.Stop();
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation("Scanned RefreshArtistMetadata [{0}], OperationTime [{1}]",
artist.ToString(), sw.ElapsedMilliseconds);
}
else
{
sw.Stop();
}
}
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Serialize());
resultErrors.Add(ex);
}
return new OperationResult<bool>
{
Data = result,
IsSuccess = result,
Errors = resultErrors,
OperationTime = sw.ElapsedMilliseconds
};
}
public async Task<OperationResult<Image>> SetReleaseImageByUrl(ApplicationUser user, Guid id, string imageUrl)
2018-12-26 21:18:51 +00:00
{
2019-06-30 22:14:36 +00:00
return await SaveImageBytes(user, id, WebHelper.BytesForImageUrl(imageUrl));
2019-01-08 22:40:26 +00:00
}
2019-07-07 03:16:33 +00:00
public async Task<OperationResult<bool>> UpdateArtist(ApplicationUser user, Artist model)
2018-12-27 17:37:17 +00:00
{
var didRenameArtist = false;
var didChangeThumbnail = false;
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var artist = DbContext.Artists
.Include(x => x.Genres)
.Include("Genres.Genre")
.FirstOrDefault(x => x.RoadieId == model.Id);
2018-12-27 17:37:17 +00:00
if (artist == null)
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Artist Not Found [{model.Id}]");
2018-12-27 17:37:17 +00:00
try
{
var now = DateTime.UtcNow;
2019-07-07 03:16:33 +00:00
var originalArtistFolder = artist.ArtistFileFolder(Configuration);
2019-06-23 15:45:45 +00:00
var specialArtistName = model.Name.ToAlphanumericName();
var alt = new List<string>(model.AlternateNamesList);
if (!model.AlternateNamesList.Contains(specialArtistName, StringComparer.OrdinalIgnoreCase))
{
2019-06-23 15:45:45 +00:00
alt.Add(specialArtistName);
}
2019-06-23 15:45:45 +00:00
artist.AlternateNames = alt.ToDelimitedList();
2019-02-05 03:53:31 +00:00
artist.ArtistType = model.ArtistType;
2018-12-27 17:37:17 +00:00
artist.AmgId = model.AmgId;
artist.BeginDate = model.BeginDate;
artist.BioContext = model.BioContext;
artist.BirthDate = model.BirthDate;
artist.DiscogsId = model.DiscogsId;
artist.EndDate = model.EndDate;
artist.IsLocked = model.IsLocked;
2018-12-27 21:56:40 +00:00
artist.ISNI = model.ISNIList.ToDelimitedList();
2018-12-27 17:37:17 +00:00
artist.ITunesId = model.ITunesId;
artist.MusicBrainzId = model.MusicBrainzId;
artist.Name = model.Name;
artist.Profile = model.Profile;
artist.Rating = model.Rating;
artist.RealName = model.RealName;
artist.SortName = model.SortName;
artist.SpotifyId = model.SpotifyId;
artist.Status = SafeParser.ToEnum<Statuses>(model.Status);
artist.Tags = model.TagsList.ToDelimitedList();
artist.URLs = model.URLsList.ToDelimitedList();
2019-07-07 03:16:33 +00:00
var newArtistFolder = artist.ArtistFileFolder(Configuration);
2018-12-27 17:37:17 +00:00
if (!newArtistFolder.Equals(originalArtistFolder, StringComparison.OrdinalIgnoreCase))
{
didRenameArtist = true;
if (Directory.Exists(originalArtistFolder))
{
// Rename artist folder to reflect new artist name
Logger.LogTrace("Moving Artist From Folder [{0}] To [{1}]", originalArtistFolder, newArtistFolder);
Directory.Move(originalArtistFolder, newArtistFolder);
}
2018-12-27 17:37:17 +00:00
}
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
var artistImage = ImageHelper.ImageDataFromUrl(model.NewThumbnailData);
if (artistImage != null)
{
// Save unaltered image to cover file
2019-05-23 03:10:59 +00:00
var artistImageName = Path.Combine(newArtistFolder, ImageHelper.ArtistImageFilename);
2019-07-25 15:43:11 +00:00
File.WriteAllBytes(artistImageName, ImageHelper.ConvertToJpegFormat(artistImage));
2018-12-27 17:37:17 +00:00
// Resize to store in database as thumbnail
2019-07-25 15:43:11 +00:00
artist.Thumbnail = ImageHelper.ResizeToThumbnail(artistImage, Configuration);
2018-12-27 17:37:17 +00:00
didChangeThumbnail = true;
}
2019-05-29 22:25:40 +00:00
if (model.NewSecondaryImagesData != null && model.NewSecondaryImagesData.Any())
2019-05-23 03:10:59 +00:00
{
// Additional images to add to artist
var looper = 0;
foreach (var newSecondaryImageData in model.NewSecondaryImagesData)
{
var artistSecondaryImage = ImageHelper.ImageDataFromUrl(newSecondaryImageData);
if (artistSecondaryImage != null)
{
// Ensure is jpeg first
artistSecondaryImage = ImageHelper.ConvertToJpegFormat(artistSecondaryImage);
2019-07-13 12:28:27 +00:00
var artistImageFilename = Path.Combine(newArtistFolder,string.Format(ImageHelper.ArtistSecondaryImageFilename, looper.ToString("00")));
while (File.Exists(artistImageFilename))
2019-05-23 03:10:59 +00:00
{
looper++;
2019-07-13 12:28:27 +00:00
artistImageFilename = Path.Combine(newArtistFolder,string.Format(ImageHelper.ArtistSecondaryImageFilename, looper.ToString("00")));
2019-05-23 03:10:59 +00:00
}
2019-06-30 22:14:36 +00:00
File.WriteAllBytes(artistImageFilename, artistSecondaryImage);
2019-05-23 03:10:59 +00:00
}
2019-06-30 22:14:36 +00:00
2019-05-23 03:10:59 +00:00
looper++;
}
}
2018-12-27 17:37:17 +00:00
if (model.Genres != null && model.Genres.Any())
{
// Remove existing Genres not in model list
foreach (var genre in artist.Genres.ToList())
{
var doesExistInModel = model.Genres.Any(x => SafeParser.ToGuid(x.Value) == genre.Genre.RoadieId);
2019-06-30 22:14:36 +00:00
if (!doesExistInModel) artist.Genres.Remove(genre);
2018-12-27 17:37:17 +00:00
}
// Add new Genres in model not in data
foreach (var genre in model.Genres)
{
var genreId = SafeParser.ToGuid(genre.Value);
var doesExistInData = artist.Genres.Any(x => x.Genre.RoadieId == genreId);
if (!doesExistInData)
{
2019-06-30 22:14:36 +00:00
var g = DbContext.Genres.FirstOrDefault(x => x.RoadieId == genreId);
2018-12-27 17:37:17 +00:00
if (g != null)
artist.Genres.Add(new data.ArtistGenre
{
ArtistId = artist.Id,
GenreId = g.Id,
2019-07-07 03:16:33 +00:00
Genre = g
2018-12-27 17:37:17 +00:00
});
}
}
}
else if (model.Genres == null || !model.Genres.Any())
{
artist.Genres.Clear();
}
if (model.AssociatedArtistsTokens != null && model.AssociatedArtistsTokens.Any())
{
2019-06-30 22:14:36 +00:00
var associatedArtists = DbContext.ArtistAssociations.Include(x => x.AssociatedArtist)
.Where(x => x.ArtistId == artist.Id).ToList();
2018-12-27 17:37:17 +00:00
// Remove existing AssociatedArtists not in model list
foreach (var associatedArtist in associatedArtists)
{
2019-06-30 22:14:36 +00:00
var doesExistInModel = model.AssociatedArtistsTokens.Any(x =>
SafeParser.ToGuid(x.Value) == associatedArtist.AssociatedArtist.RoadieId);
if (!doesExistInModel) DbContext.ArtistAssociations.Remove(associatedArtist);
2018-12-27 17:37:17 +00:00
}
// Add new AssociatedArtists in model not in data
foreach (var associatedArtist in model.AssociatedArtistsTokens)
{
var associatedArtistId = SafeParser.ToGuid(associatedArtist.Value);
2019-06-30 22:14:36 +00:00
var doesExistInData =
associatedArtists.Any(x => x.AssociatedArtist.RoadieId == associatedArtistId);
2018-12-27 17:37:17 +00:00
if (!doesExistInData)
{
2019-06-30 22:14:36 +00:00
var a = DbContext.Artists.FirstOrDefault(x => x.RoadieId == associatedArtistId);
2018-12-27 17:37:17 +00:00
if (a != null)
2019-06-30 22:14:36 +00:00
DbContext.ArtistAssociations.Add(new data.ArtistAssociation
2018-12-27 17:37:17 +00:00
{
ArtistId = artist.Id,
AssociatedArtistId = a.Id
});
}
}
}
else if (model.AssociatedArtistsTokens == null || !model.AssociatedArtistsTokens.Any())
{
var associatedArtists = DbContext.ArtistAssociations.Include(x => x.AssociatedArtist).Where(x => x.ArtistId == artist.Id || x.AssociatedArtistId == artist.Id).ToList();
DbContext.ArtistAssociations.RemoveRange(associatedArtists);
}
2019-07-07 03:16:33 +00:00
if (model.SimilarArtistsTokens != null && model.SimilarArtistsTokens.Any())
{
var similarArtists = DbContext.ArtistSimilar.Include(x => x.SimilarArtist)
.Where(x => x.ArtistId == artist.Id).ToList();
// Remove existing AssociatedArtists not in model list
foreach (var similarArtist in similarArtists)
{
var doesExistInModel = model.SimilarArtistsTokens.Any(x =>
SafeParser.ToGuid(x.Value) == similarArtist.SimilarArtist.RoadieId);
if (!doesExistInModel) DbContext.ArtistSimilar.Remove(similarArtist);
}
// Add new SimilarArtists in model not in data
foreach (var similarArtist in model.SimilarArtistsTokens)
{
var similarArtistId = SafeParser.ToGuid(similarArtist.Value);
var doesExistInData = similarArtists.Any(x => x.SimilarArtist.RoadieId == similarArtistId);
if (!doesExistInData)
{
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())
{
var similarArtists = DbContext.ArtistSimilar.Include(x => x.SimilarArtist).Where(x => x.ArtistId == artist.Id || x.SimilarArtistId == artist.Id).ToList();
DbContext.ArtistSimilar.RemoveRange(similarArtists);
2018-12-27 17:37:17 +00:00
}
if (model.Images != null && model.Images.Any())
{
// TODO
}
artist.LastUpdated = now;
2019-06-30 22:14:36 +00:00
await DbContext.SaveChangesAsync();
2019-01-08 22:40:26 +00:00
if (didRenameArtist)
{
// Many contributing artists do not have releases and will not have an empty Artist folder
if (Directory.Exists(newArtistFolder))
2018-12-27 20:42:51 +00:00
{
// Update artist tracks to have new artist name in ID3 metadata
foreach (var mp3 in Directory.GetFiles(newArtistFolder, "*.mp3", SearchOption.AllDirectories))
2018-12-27 20:42:51 +00:00
{
var trackFileInfo = new FileInfo(mp3);
var audioMetaData = await AudioMetaDataHelper.GetInfo(trackFileInfo);
if (audioMetaData != null)
{
audioMetaData.Artist = artist.Name;
AudioMetaDataHelper.WriteTags(audioMetaData, trackFileInfo);
}
2018-12-27 20:42:51 +00:00
}
2019-06-30 22:14:36 +00:00
await ScanArtistReleasesFolders(user, artist.RoadieId, Configuration.LibraryFolder, false);
}
2018-12-27 17:37:17 +00:00
}
2019-06-30 22:14:36 +00:00
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation(
$"UpdateArtist `{artist}` By User `{user}`: Renamed Artist [{didRenameArtist}], Uploaded new image [{didChangeThumbnail}]");
2018-12-27 17:37:17 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
2018-12-27 17:37:17 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2018-12-27 17:37:17 +00:00
sw.Stop();
return new OperationResult<bool>
{
IsSuccess = !errors.Any(),
Data = !errors.Any(),
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2019-07-07 03:16:33 +00:00
public async Task<OperationResult<Image>> UploadArtistImage(ApplicationUser user, Guid id, IFormFile file)
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
var bytes = new byte[0];
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
bytes = ms.ToArray();
}
2019-06-30 22:14:36 +00:00
return await SaveImageBytes(user, id, bytes);
2019-01-08 22:40:26 +00:00
}
2018-12-27 17:37:17 +00:00
2019-01-08 22:40:26 +00:00
private async Task<OperationResult<Artist>> ArtistByIdAction(Guid id, IEnumerable<string> includes)
{
var timings = new Dictionary<string, long>();
var tsw = new Stopwatch();
var sw = Stopwatch.StartNew();
2018-12-27 17:37:17 +00:00
sw.Start();
2019-01-08 22:40:26 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
var artist = GetArtist(id);
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("getArtist", tsw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
if (artist == null) return new OperationResult<Artist>(true, $"Artist Not Found [{id}]");
2019-01-08 22:40:26 +00:00
tsw.Restart();
var result = artist.Adapt<Artist>();
2019-01-26 04:44:07 +00:00
result.BandStatus = result.BandStatus ?? BandStatus.Unknown.ToString();
2019-06-30 22:14:36 +00:00
result.BeginDate = result.BeginDate == null || result.BeginDate == DateTime.MinValue
? null
: result.BeginDate;
2019-01-08 22:40:26 +00:00
result.EndDate = result.EndDate == null || result.EndDate == DateTime.MinValue ? null : result.EndDate;
2019-06-30 22:14:36 +00:00
result.BirthDate = result.BirthDate == null || result.BirthDate == DateTime.MinValue
? null
: result.BirthDate;
result.RankPosition = result.Rank > 0
? SafeParser.ToNumber<int?>(DbContext.Artists.Count(x => x.Rank > result.Rank) + 1)
: null;
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("adaptArtist", tsw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
result.Thumbnail = MakeArtistThumbnailImage(id);
result.MediumThumbnail = MakeThumbnailImage(id, "artist", Configuration.MediumImageSize.Width,
Configuration.MediumImageSize.Height);
2019-01-08 22:40:26 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
result.Genres = artist.Genres.Select(x => new DataToken
{ Text = x.Genre.Name, Value = x.Genre.RoadieId.ToString() });
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("genres", tsw.ElapsedMilliseconds);
if (includes != null && includes.Any())
{
if (includes.Contains("releases"))
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
var dtoReleases = new List<ReleaseList>();
2019-06-30 22:14:36 +00:00
foreach (var release in DbContext.Releases.Include("Medias").Include("Medias.Tracks")
.Include("Medias.Tracks").Where(x => x.ArtistId == artist.Id).ToArray())
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
var releaseList = release.Adapt<ReleaseList>();
2019-06-30 22:14:36 +00:00
releaseList.Thumbnail = MakeReleaseThumbnailImage(release.RoadieId);
2019-01-08 22:40:26 +00:00
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>();
var tracks = new List<TrackList>();
2019-06-30 22:14:36 +00:00
foreach (var t in DbContext.Tracks.Where(x => x.ReleaseMediaId == releasemedia.Id)
.OrderBy(x => x.TrackNumber).ToArray())
2019-01-08 22:40:26 +00:00
{
var track = t.Adapt<TrackList>();
ArtistList trackArtist = null;
if (t.ArtistId.HasValue)
{
2019-06-30 22:14:36 +00:00
var ta = DbContext.Artists.FirstOrDefault(x => x.Id == t.ArtistId.Value);
2019-01-08 22:40:26 +00:00
if (ta != null)
2019-06-30 22:14:36 +00:00
trackArtist = ArtistList.FromDataArtist(ta,
MakeArtistThumbnailImage(ta.RoadieId));
2019-01-08 22:40:26 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
track.TrackArtist = trackArtist;
tracks.Add(track);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
dtoMedia.Tracks = tracks;
dtoReleaseMedia.Add(dtoMedia);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
releaseList.Media = dtoReleaseMedia;
dtoReleases.Add(releaseList);
2018-12-27 17:37:17 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
result.Releases = dtoReleases;
2018-12-27 17:37:17 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("stats"))
2019-02-25 02:26:54 +00:00
try
2019-01-08 22:40:26 +00:00
{
2019-02-25 02:26:54 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
var artistTracks = from r in DbContext.Releases
join rm in DbContext.ReleaseMedias on r.Id equals rm.ReleaseId
join t in DbContext.Tracks on rm.Id equals t.ReleaseMediaId
where r.ArtistId == artist.Id || t.ArtistId == artist.Id
select new
{
t.Id,
size = t.FileSize,
time = t.Duration,
isMissing = t.Hash == null
};
2019-02-25 02:26:54 +00:00
var validCartistTracks = artistTracks.Where(x => !x.isMissing);
2019-06-30 22:14:36 +00:00
var trackTime = validCartistTracks.Sum(x => (long?)x.time);
2019-02-25 02:26:54 +00:00
result.Statistics = new CollectionStatistics
{
FileSize = artistTracks.Sum(x => (long?)x.size).ToFileSize(),
2019-06-30 22:14:36 +00:00
MissingTrackCount = artistTracks.Count(x => x.isMissing),
2019-02-25 02:26:54 +00:00
ReleaseCount = artist.ReleaseCount,
2019-06-30 22:14:36 +00:00
ReleaseMediaCount = (from r in DbContext.Releases
join rm in DbContext.ReleaseMedias on r.Id equals rm.ReleaseId
2019-02-25 02:26:54 +00:00
where r.ArtistId == artist.Id
select rm.Id).Count(),
2019-06-30 22:14:36 +00:00
TrackTime = validCartistTracks.Any()
? new TimeInfo((decimal)trackTime).ToFullFormattedString()
: "--:--",
2019-02-25 02:26:54 +00:00
TrackCount = validCartistTracks.Count(),
TrackPlayedCount = artist.PlayedCount
};
tsw.Stop();
timings.Add("stats", tsw.ElapsedMilliseconds);
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex, $"Error Getting Statistics for Artist `{artist}`");
2019-02-25 02:26:54 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("images"))
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
tsw.Restart();
2019-06-30 22:14:36 +00:00
result.Images = DbContext.Images.Where(x => x.ArtistId == artist.Id)
.Select(x => MakeFullsizeImage(x.RoadieId, x.Caption)).ToArray();
2019-02-10 00:19:26 +00:00
2019-07-07 03:16:33 +00:00
var artistFolder = artist.ArtistFileFolder(Configuration);
2019-06-30 22:14:36 +00:00
var artistImagesInFolder = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistFolder),
ImageType.ArtistSecondary, SearchOption.TopDirectoryOnly);
2019-02-10 00:19:26 +00:00
if (artistImagesInFolder.Any())
2019-06-30 22:14:36 +00:00
result.Images = result.Images.Concat(artistImagesInFolder.Select((x, i) =>
MakeFullsizeSecondaryImage(id, ImageType.ArtistSecondary, i)));
2019-02-10 00:19:26 +00:00
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("images", tsw.ElapsedMilliseconds);
2018-12-27 17:37:17 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("associatedartists"))
{
tsw.Restart();
2019-06-30 22:14:36 +00:00
var associatedWithArtists = (from aa in DbContext.ArtistAssociations
join a in DbContext.Artists on aa.AssociatedArtistId equals a.Id
2019-01-08 22:40:26 +00:00
where aa.ArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
2019-06-30 22:14:36 +00:00
Thumbnail = MakeArtistThumbnailImage(a.RoadieId),
2019-01-08 22:40:26 +00:00
Rating = a.Rating,
2019-01-23 16:50:36 +00:00
Rank = a.Rank,
2019-01-08 22:40:26 +00:00
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArray();
2018-12-27 17:37:17 +00:00
2019-06-30 22:14:36 +00:00
var associatedArtists = (from aa in DbContext.ArtistAssociations
join a in DbContext.Artists on aa.ArtistId equals a.Id
2019-01-08 22:40:26 +00:00
where aa.AssociatedArtistId == artist.Id
select new ArtistList
{
DatabaseId = a.Id,
Id = a.RoadieId,
Artist = new DataToken
{
Text = a.Name,
Value = a.RoadieId.ToString()
},
2019-06-30 22:14:36 +00:00
Thumbnail = MakeArtistThumbnailImage(a.RoadieId),
2019-01-08 22:40:26 +00:00
Rating = a.Rating,
2019-01-23 16:50:36 +00:00
Rank = a.Rank,
2019-01-08 22:40:26 +00:00
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArray();
2019-06-30 22:14:36 +00:00
result.AssociatedArtists = associatedArtists.Union(associatedWithArtists, new ArtistListComparer())
.OrderBy(x => x.SortName);
2019-01-08 22:40:26 +00:00
result.AssociatedArtistsTokens = result.AssociatedArtists.Select(x => x.Artist).ToArray();
tsw.Stop();
timings.Add("associatedartists", tsw.ElapsedMilliseconds);
}
2019-06-30 22:14:36 +00:00
if (includes.Contains("similarartists"))
{
tsw.Restart();
var similarWithArtists = (from aa in DbContext.ArtistSimilar
2019-07-07 03:16:33 +00:00
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 = MakeArtistThumbnailImage(a.RoadieId),
Rating = a.Rating,
Rank = a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArray();
var similarArtists = (from aa in DbContext.ArtistSimilar
2019-07-07 03:16:33 +00:00
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 = MakeArtistThumbnailImage(a.RoadieId),
Rating = a.Rating,
Rank = a.Rank,
CreatedDate = a.CreatedDate,
LastUpdated = a.LastUpdated,
LastPlayed = a.LastPlayed,
PlayedCount = a.PlayedCount,
ReleaseCount = a.ReleaseCount,
TrackCount = a.TrackCount,
SortName = a.SortName
}).ToArray();
result.SimilarArtists = similarWithArtists.Union(similarArtists, new ArtistListComparer())
.OrderBy(x => x.SortName);
result.SimilarArtistsTokens = result.SimilarArtists.Select(x => x.Artist).ToArray();
tsw.Stop();
timings.Add("similarartists", tsw.ElapsedMilliseconds);
}
2019-01-08 22:40:26 +00:00
if (includes.Contains("collections"))
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
tsw.Restart();
var collectionPagedRequest = new PagedRequest
2018-12-27 17:37:17 +00:00
{
2019-01-08 22:40:26 +00:00
Limit = 100
};
2019-06-30 22:14:36 +00:00
var r = await CollectionService.List(null,
collectionPagedRequest, artistId: artist.RoadieId);
if (r.IsSuccess) result.CollectionsWithArtistReleases = r.Rows.ToArray();
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("collections", tsw.ElapsedMilliseconds);
}
2019-06-30 22:14:36 +00:00
if (includes.Contains("comments"))
2019-06-28 21:24:32 +00:00
{
tsw.Restart();
2019-06-30 22:14:36 +00:00
var artistComments = DbContext.Comments.Include(x => x.User).Where(x => x.ArtistId == artist.Id)
.OrderByDescending(x => x.CreatedDate).ToArray();
if (artistComments.Any())
2019-06-28 21:24:32 +00:00
{
var comments = new List<Comment>();
var commentIds = artistComments.Select(x => x.Id).ToArray();
2019-06-30 22:14:36 +00:00
var userCommentReactions = (from cr in DbContext.CommentReactions
2019-06-28 21:24:32 +00:00
where commentIds.Contains(cr.CommentId)
select cr).ToArray();
foreach (var artistComment in artistComments)
{
var comment = artistComment.Adapt<Comment>();
comment.DatabaseId = artistComment.Id;
2019-06-30 22:14:36 +00:00
comment.User = UserList.FromDataUser(artistComment.User,
MakeUserThumbnailImage(artistComment.User.RoadieId));
comment.DislikedCount = userCommentReactions.Count(x =>
x.CommentId == artistComment.Id && x.ReactionValue == CommentReaction.Dislike);
comment.LikedCount = userCommentReactions.Count(x =>
x.CommentId == artistComment.Id && x.ReactionValue == CommentReaction.Like);
2019-06-28 21:24:32 +00:00
comments.Add(comment);
2019-06-30 22:14:36 +00:00
}
2019-06-28 21:24:32 +00:00
result.Comments = comments;
}
2019-06-30 22:14:36 +00:00
2019-06-28 21:24:32 +00:00
tsw.Stop();
timings.Add("comments", tsw.ElapsedMilliseconds);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("playlists"))
{
tsw.Restart();
var pg = new PagedRequest
{
FilterToArtistId = artist.RoadieId
};
2019-06-30 22:14:36 +00:00
var r = await PlaylistService.List(pg);
if (r.IsSuccess) result.PlaylistsWithArtistReleases = r.Rows.ToArray();
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("playlists", tsw.ElapsedMilliseconds);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("contributions"))
{
tsw.Restart();
2019-06-30 22:14:36 +00:00
result.ArtistContributionReleases = (from t in DbContext.Tracks
join rm in DbContext.ReleaseMedias on t.ReleaseMediaId equals rm.Id
join r in DbContext.Releases.Include(x => x.Artist) on rm.ReleaseId equals r.Id
2019-01-08 22:40:26 +00:00
where t.ArtistId == artist.Id
2019-06-30 22:14:36 +00:00
group r by r.Id
into rr
2019-01-08 22:40:26 +00:00
select rr)
2019-06-30 22:14:36 +00:00
.ToArray()
.Select(rr => rr.First())
.Select(r => ReleaseList.FromDataRelease(r, r.Artist, HttpContext.BaseUrl,
MakeArtistThumbnailImage(r.Artist.RoadieId), MakeReleaseThumbnailImage(r.RoadieId)))
.ToArray().OrderBy(x => x.Release.Text).ToArray();
result.ArtistContributionReleases = result.ArtistContributionReleases.Any()
? result.ArtistContributionReleases
: null;
2019-01-08 22:40:26 +00:00
tsw.Stop();
timings.Add("contributions", tsw.ElapsedMilliseconds);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
if (includes.Contains("labels"))
{
tsw.Restart();
2019-06-30 22:14:36 +00:00
result.ArtistLabels = (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
2019-01-08 22:40:26 +00:00
where r.ArtistId == artist.Id
orderby l.SortName
2019-06-30 22:14:36 +00:00
select LabelList.FromDataLabel(l, MakeLabelThumbnailImage(l.RoadieId)))
.ToArray()
.GroupBy(x => x.Label.Value).Select(x => x.First()).OrderBy(x => x.SortName)
.ThenBy(x => x.Label.Text).ToArray();
2019-01-08 22:40:26 +00:00
result.ArtistLabels = result.ArtistLabels.Any() ? result.ArtistLabels : null;
tsw.Stop();
timings.Add("labels", tsw.ElapsedMilliseconds);
2018-12-27 17:37:17 +00:00
}
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
sw.Stop();
timings.Add("operation", sw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
Logger.LogDebug("ArtistByIdAction Timings: id [{0}], includes [{1}], timings [{3}]", id, includes,
JsonConvert.SerializeObject(timings));
2019-01-08 22:40:26 +00:00
return new OperationResult<Artist>
2018-12-27 17:37:17 +00:00
{
Data = result,
2019-01-08 22:40:26 +00:00
IsSuccess = result != null,
2018-12-27 17:37:17 +00:00
OperationTime = sw.ElapsedMilliseconds
};
}
2019-07-07 03:16:33 +00:00
private async Task<OperationResult<Image>> SaveImageBytes(ApplicationUser user, Guid id, byte[] imageBytes)
2018-12-26 21:18:51 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var artist = DbContext.Artists.FirstOrDefault(x => x.RoadieId == id);
if (artist == null) return new OperationResult<Image>(true, $"Artist Not Found [{id}]");
2018-12-26 21:18:51 +00:00
try
{
var now = DateTime.UtcNow;
artist.Thumbnail = imageBytes;
if (artist.Thumbnail != null)
{
2018-12-27 21:56:40 +00:00
// Ensure artist folder exists
2019-07-07 03:16:33 +00:00
var artistFolder = artist.ArtistFileFolder(Configuration);
2019-01-08 22:40:26 +00:00
if (!Directory.Exists(artistFolder))
2018-12-27 21:56:40 +00:00
{
Directory.CreateDirectory(artistFolder);
2019-06-30 22:14:36 +00:00
Logger.LogInformation("Created Artist Folder [0] for `artist`", artistFolder, artist);
2019-01-08 22:40:26 +00:00
}
2018-12-27 21:56:40 +00:00
2018-12-26 21:18:51 +00:00
// Save unaltered image to artist file
2019-02-10 00:19:26 +00:00
var artistImage = Path.Combine(artistFolder, ImageHelper.ArtistImageFilename);
2019-07-25 15:43:11 +00:00
File.WriteAllBytes(artistImage, ImageHelper.ConvertToJpegFormat(imageBytes));
2018-12-26 21:18:51 +00:00
// Resize to store in database as thumbnail
2019-07-25 15:43:11 +00:00
artist.Thumbnail = ImageHelper.ResizeToThumbnail(artist.Thumbnail, Configuration);
2018-12-26 21:18:51 +00:00
}
2019-06-30 22:14:36 +00:00
2018-12-26 21:18:51 +00:00
artist.LastUpdated = now;
2019-06-30 22:14:36 +00:00
await DbContext.SaveChangesAsync();
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation($"SaveImageBytes `{artist}` By User `{user}`");
2018-12-26 21:18:51 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
2018-12-26 21:18:51 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2018-12-26 21:18:51 +00:00
sw.Stop();
2019-06-30 22:14:36 +00:00
return new OperationResult<Image>
2018-12-26 21:18:51 +00:00
{
IsSuccess = !errors.Any(),
2019-06-30 22:14:36 +00:00
Data = MakeThumbnailImage(id, "artist", Configuration.MediumImageSize.Width,
Configuration.MediumImageSize.Height, true),
2018-12-26 21:18:51 +00:00
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2019-06-30 22:14:36 +00:00
2019-07-07 03:16:33 +00:00
public async Task<OperationResult<bool>> ScanArtistReleasesFolders(ApplicationUser user, Guid artistId, string destinationFolder, bool doJustInfo)
2019-06-30 22:14:36 +00:00
{
SimpleContract.Requires<ArgumentOutOfRangeException>(artistId != Guid.Empty, "Invalid ArtistId");
var result = true;
var resultErrors = new List<Exception>();
var sw = new Stopwatch();
sw.Start();
try
{
var artist = DbContext.Artists
.Include("Releases")
.Include("Releases.Labels")
.FirstOrDefault(x => x.RoadieId == artistId);
if (artist == null)
{
Logger.LogWarning("Unable To Find Artist [{0}]", artistId);
return new OperationResult<bool>();
}
var releaseScannedCount = 0;
2019-07-07 03:16:33 +00:00
var artistFolder = artist.ArtistFileFolder(Configuration);
if (!Directory.Exists(artistFolder))
{
Logger.LogDebug($"ScanArtistReleasesFolders: ArtistFolder Not Found [{ artistFolder }] For Artist `{ artist }`");
return new OperationResult<bool>();
}
2019-06-30 22:14:36 +00:00
var scannedArtistFolders = new List<string>();
// Scan known releases for changes
if (artist.Releases != null)
{
2019-06-30 22:14:36 +00:00
foreach (var release in artist.Releases)
try
{
2019-07-07 03:16:33 +00:00
result = result && (await ReleaseService.ScanReleaseFolder(user, Guid.Empty, doJustInfo, release)).Data;
2019-06-30 22:14:36 +00:00
releaseScannedCount++;
scannedArtistFolders.Add(release.ReleaseFileFolder(artistFolder));
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Serialize());
}
}
2019-06-30 22:14:36 +00:00
// Any folder found in Artist folder not already scanned scan
var nonReleaseFolders = from d in Directory.EnumerateDirectories(artistFolder)
where !(from r in scannedArtistFolders select r).Contains(d)
orderby d
select d;
foreach (var folder in nonReleaseFolders)
2019-07-07 03:16:33 +00:00
{
await FileDirectoryProcessorService.Process(user, new DirectoryInfo(folder), doJustInfo);
}
if (!doJustInfo)
{
Services.FileDirectoryProcessorService.DeleteEmptyFolders(new DirectoryInfo(artistFolder), Logger);
}
2019-06-30 22:14:36 +00:00
// Always update artist image if artist image is found on an artist rescan
var imageFiles = ImageHelper.ImageFilesInFolder(artistFolder, SearchOption.AllDirectories);
if (imageFiles != null && imageFiles.Any())
{
2019-07-25 15:43:11 +00:00
var i = new FileInfo(imageFiles.First());
2019-06-30 22:14:36 +00:00
var iName = i.Name.ToLower().Trim();
2019-07-25 15:43:11 +00:00
if (ImageHelper.IsArtistImage(i))
2019-06-30 22:14:36 +00:00
{
// Read image and convert to jpeg
2019-07-25 15:43:11 +00:00
artist.Thumbnail = ImageHelper.ResizeToThumbnail(File.ReadAllBytes(i.FullName), Configuration);
2019-06-30 22:14:36 +00:00
artist.LastUpdated = DateTime.UtcNow;
await DbContext.SaveChangesAsync();
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation("Update Thumbnail using Artist File [{0}]", iName);
}
}
sw.Stop();
CacheManager.ClearRegion(artist.CacheRegion);
Logger.LogInformation("Scanned Artist [{0}], Releases Scanned [{1}], OperationTime [{2}]", artist.ToString(), releaseScannedCount, sw.ElapsedMilliseconds);
2019-06-30 22:14:36 +00:00
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Serialize());
resultErrors.Add(ex);
}
return new OperationResult<bool>
{
Data = result,
IsSuccess = result,
Errors = resultErrors,
OperationTime = sw.ElapsedMilliseconds
};
}
2018-11-06 04:31:25 +00:00
}
}