roadie/Roadie.Api.Services/AdminService.cs

1195 lines
54 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Identity;
2018-12-14 03:52:14 +00:00
using Microsoft.AspNetCore.SignalR;
2018-12-17 21:26:24 +00:00
using Microsoft.EntityFrameworkCore;
2018-12-14 03:52:14 +00:00
using Microsoft.Extensions.Logging;
using Roadie.Api.Hubs;
using Roadie.Library;
using Roadie.Library.Caching;
using Roadie.Library.Configuration;
2019-11-17 14:10:17 +00:00
using Roadie.Library.Data.Context;
2018-12-14 03:52:14 +00:00
using Roadie.Library.Encoding;
2018-12-15 22:35:20 +00:00
using Roadie.Library.Engines;
2018-12-14 03:52:14 +00:00
using Roadie.Library.Enums;
using Roadie.Library.Extensions;
2018-12-14 03:52:14 +00:00
using Roadie.Library.Identity;
2019-05-23 03:10:59 +00:00
using Roadie.Library.Imaging;
2019-06-30 22:14:36 +00:00
using Roadie.Library.Models.Collections;
2018-12-14 03:52:14 +00:00
using Roadie.Library.Processors;
using Roadie.Library.Utility;
2018-12-17 21:26:24 +00:00
using System;
using System.Collections.Generic;
2018-12-14 03:52:14 +00:00
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using data = Roadie.Library.Data;
namespace Roadie.Api.Services
{
public class AdminService : ServiceBase, IAdminService
{
private IArtistLookupEngine ArtistLookupEngine { get; }
2019-06-30 22:14:36 +00:00
private IArtistService ArtistService { get; }
private IBookmarkService BookmarkService { get; }
2019-06-30 22:14:36 +00:00
2018-12-15 23:22:02 +00:00
private IEventMessageLogger EventMessageLogger { get; }
2019-06-30 22:14:36 +00:00
private IFileDirectoryProcessorService FileDirectoryProcessorService { get; }
2018-12-15 22:35:20 +00:00
private IGenreService GenreService { get; }
private ILabelService LabelService { get; }
2018-12-15 23:22:02 +00:00
private IReleaseLookupEngine ReleaseLookupEngine { get; }
2019-07-21 04:35:12 +00:00
2019-07-07 03:16:33 +00:00
private IReleaseService ReleaseService { get; }
protected IHubContext<ScanActivityHub> ScanActivityHub { get; }
public AdminService(
IRoadieSettings configuration,
IHttpEncoder httpEncoder,
IHttpContext httpContext,
IRoadieDbContext context,
ICacheManager cacheManager,
ILogger<ArtistService> logger,
IHubContext<ScanActivityHub> scanActivityHub,
IFileDirectoryProcessorService fileDirectoryProcessorService,
IArtistService artistService,
IReleaseService releaseService,
IArtistLookupEngine artistLookupEngine,
IReleaseLookupEngine releaseLookupEngine,
ILabelService labelService,
IGenreService genreService,
IBookmarkService bookmarkService)
2018-12-14 03:52:14 +00:00
: base(configuration, httpEncoder, context, cacheManager, logger, httpContext)
{
2019-06-30 22:14:36 +00:00
ScanActivityHub = scanActivityHub;
2019-07-07 03:16:33 +00:00
EventMessageLogger = new EventMessageLogger<AdminService>();
2019-06-30 22:14:36 +00:00
EventMessageLogger.Messages += EventMessageLogger_Messages;
2019-07-07 03:16:33 +00:00
ArtistService = artistService;
ReleaseService = releaseService;
LabelService = labelService;
2019-08-02 20:59:24 +00:00
GenreService = genreService;
2019-11-10 23:54:15 +00:00
ArtistLookupEngine = artistLookupEngine;
2019-07-21 04:35:12 +00:00
ReleaseLookupEngine = releaseLookupEngine;
FileDirectoryProcessorService = fileDirectoryProcessorService;
2019-11-28 17:38:26 +00:00
BookmarkService = bookmarkService;
2018-12-14 23:38:48 +00:00
}
private void EventMessageLogger_Messages(object sender, EventMessage e) => Task.WaitAll(LogAndPublishAsync(e.Message, e.Level));
2022-01-21 21:52:35 +00:00
private Task LogAndPublishAsync(string message, LogLevel level = LogLevel.Trace)
{
switch (level)
{
case LogLevel.Trace:
Logger.LogTrace(message);
break;
case LogLevel.Debug:
Logger.LogDebug(message);
break;
case LogLevel.Information:
Logger.LogInformation(message);
break;
case LogLevel.Warning:
Logger.LogWarning(message);
break;
case LogLevel.Critical:
Logger.LogCritical(message);
break;
}
2022-01-21 21:52:35 +00:00
return ScanActivityHub.Clients.All.SendAsync("SendSystemActivityAsync", level, message);
}
private async Task<OperationResult<bool>> ScanFolderAsync(User user, DirectoryInfo d, bool isReadOnly, bool doDeleteFiles = true)
{
var sw = new Stopwatch();
sw.Start();
long processedFiles = 0;
2022-01-21 21:52:35 +00:00
await LogAndPublishAsync($"*\\ Processing Folder: [{d.FullName}]").ConfigureAwait(false);
long processedFolders = 0;
foreach (var folder in Directory.EnumerateDirectories(d.FullName).ToArray())
{
var directoryProcessResult = await FileDirectoryProcessorService.ProcessAsync(user: user,
folder: new DirectoryInfo(folder),
doJustInfo: isReadOnly,
doDeleteFiles: doDeleteFiles).ConfigureAwait(false);
processedFolders++;
processedFiles += SafeParser.ToNumber<int>(directoryProcessResult.AdditionalData["ProcessedFiles"]);
2022-01-21 21:52:35 +00:00
await LogAndPublishAsync($"*+ Processing Folder: [{folder}]").ConfigureAwait(false);
}
CacheManager.Clear();
if (!isReadOnly)
{
Services.FileDirectoryProcessorService.DeleteEmptyFolders(d, Logger);
}
sw.Stop();
var newScanHistory = new data.ScanHistory
{
UserId = user.Id,
NewArtists = FileDirectoryProcessorService.AddedArtistIds.Count(),
NewReleases = FileDirectoryProcessorService.AddedReleaseIds.Count(),
NewTracks = FileDirectoryProcessorService.AddedTrackIds.Count(),
TimeSpanInSeconds = (int)sw.Elapsed.TotalSeconds
};
DbContext.ScanHistories.Add(newScanHistory);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2022-01-21 21:52:35 +00:00
await LogAndPublishAsync($"*/ Completed! Processed Folders [{processedFolders}], Processed Files [{processedFiles}], New Artists [{ newScanHistory.NewArtists }], New Releases [{ newScanHistory.NewReleases }], New Tracks [{ newScanHistory.NewTracks }] : Elapsed Time [{sw.Elapsed}]").ConfigureAwait(false);
return new OperationResult<bool>
{
Data = true,
IsSuccess = true,
OperationTime = sw.ElapsedMilliseconds
};
}
public async Task<OperationResult<bool>> DeleteArtistAsync(User user, Guid artistId, bool deleteFolder)
2019-05-23 03:10:59 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var artist = await DbContext.Artists.FirstOrDefaultAsync(x => x.RoadieId == artistId).ConfigureAwait(false);
2019-05-23 03:10:59 +00:00
if (artist == null)
{
await LogAndPublishAsync($"DeleteArtist Unknown Artist [{artistId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Artist Not Found [{artistId}]");
2019-05-23 03:10:59 +00:00
}
2019-06-30 22:14:36 +00:00
2019-05-23 03:10:59 +00:00
try
{
var result = await ArtistService.DeleteAsync(user, artist, deleteFolder).ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
if (!result.IsSuccess)
{
2019-05-29 22:25:40 +00:00
return new OperationResult<bool>
{
Errors = result.Errors
};
}
2019-05-23 03:10:59 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting artist.").ConfigureAwait(false);
2019-05-23 03:10:59 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-05-23 03:10:59 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteArtist `{artist}`, By User `{user}`", LogLevel.Information).ConfigureAwait(false);
2019-05-23 03:10:59 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-05-23 03:10:59 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteArtistReleasesAsync(User user, Guid artistId, bool doDeleteFiles = false)
2019-01-08 22:40:26 +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 == artistId);
2019-01-08 22:40:26 +00:00
if (artist == null)
{
await LogAndPublishAsync($"DeleteArtistReleases Unknown Artist [{artistId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Artist Not Found [{artistId}]");
2019-01-08 22:40:26 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
try
{
await ReleaseService.DeleteReleasesAsync(user, DbContext.Releases.Where(x => x.ArtistId == artist.Id).Select(x => x.RoadieId).ToArray(), doDeleteFiles).ConfigureAwait(false);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2019-01-08 22:40:26 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting artist.").ConfigureAwait(false);
2019-01-08 22:40:26 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteArtistReleases `{artist}`, By User `{user}`", LogLevel.Information).ConfigureAwait(false);
2019-01-08 22:40:26 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-01-08 22:40:26 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteArtistSecondaryImageAsync(User user, Guid artistId, int index)
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var artist = DbContext.Artists.FirstOrDefault(x => x.RoadieId == artistId);
if (artist == null)
{
await LogAndPublishAsync($"DeleteArtistSecondaryImage Unknown Artist [{artistId}]", LogLevel.Warning).ConfigureAwait(false);
return new OperationResult<bool>(true, $"Artist Not Found [{artistId}]");
}
try
{
var artistFolder = artist.ArtistFileFolder(Configuration);
var artistImagesInFolder = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(artistFolder), ImageType.ArtistSecondary, SearchOption.TopDirectoryOnly);
var artistImageFilename = artistImagesInFolder.Skip(index).FirstOrDefault();
if (artistImageFilename.Exists)
{
artistImageFilename.Delete();
}
CacheManager.ClearRegion(artist.CacheRegion);
}
catch (Exception ex)
{
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting artist secondary image.").ConfigureAwait(false);
errors.Add(ex);
}
sw.Stop();
await LogAndPublishAsync($"DeleteArtistSecondaryImage `{artist}` Index [{index}], By User `{user}`", LogLevel.Information).ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteGenreAsync(User user, Guid genreId)
2019-08-02 20:59:24 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var genre = DbContext.Genres.FirstOrDefault(x => x.RoadieId == genreId);
if (genre == null)
{
await LogAndPublishAsync($"DeleteLabel Unknown Genre [{genreId}]", LogLevel.Warning).ConfigureAwait(false);
2019-08-02 20:59:24 +00:00
return new OperationResult<bool>(true, $"Genre Not Found [{genreId}]");
}
try
{
await GenreService.DeleteAsync(user, genreId).ConfigureAwait(false);
2019-08-02 20:59:24 +00:00
CacheManager.ClearRegion(genre.CacheRegion);
}
catch (Exception ex)
{
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting Genre.").ConfigureAwait(false);
2019-08-02 20:59:24 +00:00
errors.Add(ex);
}
sw.Stop();
await LogAndPublishAsync($"DeleteGenre `{genre}`, By User `{user}`", LogLevel.Information).ConfigureAwait(false);
2019-08-02 20:59:24 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-08-02 20:59:24 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteLabelAsync(User user, Guid labelId)
2019-01-08 22:40:26 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var label = DbContext.Labels.FirstOrDefault(x => x.RoadieId == labelId);
if (label == null)
2019-01-08 22:40:26 +00:00
{
await LogAndPublishAsync($"DeleteLabel Unknown Label [{labelId}]", LogLevel.Warning).ConfigureAwait(false);
return new OperationResult<bool>(true, $"Label Not Found [{labelId}]");
2019-01-08 22:40:26 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
try
{
await LabelService.DeleteAsync(user, labelId).ConfigureAwait(false);
CacheManager.ClearRegion(label.CacheRegion);
2019-01-08 22:40:26 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting Label.").ConfigureAwait(false);
2019-01-08 22:40:26 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteLabel `{label}`, By User `{user}`", LogLevel.Information).ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-05-29 22:25:40 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteReleaseAsync(User user, Guid releaseId, bool? doDeleteFiles)
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 release = DbContext.Releases.Include(x => x.Artist).FirstOrDefault(x => x.RoadieId == releaseId);
2019-05-29 22:25:40 +00:00
try
{
if (release == null)
{
await LogAndPublishAsync($"DeleteRelease Unknown Release [{releaseId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Release Not Found [{releaseId}]");
2019-05-29 22:25:40 +00:00
}
await ReleaseService.DeleteAsync(user, release, doDeleteFiles ?? false).ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting release.").ConfigureAwait(false);
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();
await LogAndPublishAsync($"DeleteRelease `{release}`, By User `{user}`", LogLevel.Information).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
CacheManager.Clear();
2019-01-08 22:40:26 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-01-08 22:40:26 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteReleaseSecondaryImageAsync(User user, Guid releaseId, int index)
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var release = DbContext.Releases.Include(x => x.Artist).FirstOrDefault(x => x.RoadieId == releaseId);
if (release == null)
{
await LogAndPublishAsync($"DeleteReleaseSecondaryImage Unknown Release [{releaseId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Release Not Found [{releaseId}]");
}
2019-06-30 22:14:36 +00:00
try
{
2019-08-06 13:50:25 +00:00
var releaseFolder = release.ReleaseFileFolder(release.Artist.ArtistFileFolder(Configuration));
var releaseImagesInFolder = ImageHelper.FindImageTypeInDirectory(new DirectoryInfo(releaseFolder), ImageType.ReleaseSecondary, SearchOption.TopDirectoryOnly);
var releaseImageFilename = releaseImagesInFolder.Skip(index).FirstOrDefault();
2019-08-06 13:50:25 +00:00
if (releaseImageFilename.Exists)
{
releaseImageFilename.Delete();
}
2019-06-30 22:14:36 +00:00
CacheManager.ClearRegion(release.CacheRegion);
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting release secondary image.").ConfigureAwait(false);
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteReleaseSecondaryImage `{release}` Index [{index}], By User `{user}`", LogLevel.Information).ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteTracksAsync(User user, IEnumerable<Guid> trackIds, bool? doDeleteFile)
2019-02-06 03:22:38 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
foreach (var trackId in trackIds)
2019-02-06 03:22:38 +00:00
{
var track = DbContext.Tracks.Include(x => x.ReleaseMedia)
.Include(x => x.ReleaseMedia.Release)
.Include(x => x.ReleaseMedia.Release.Artist)
.FirstOrDefault(x => x.RoadieId == trackId);
try
2019-02-06 03:22:38 +00:00
{
if (track == null)
{
await LogAndPublishAsync($"DeleteTracks Unknown Track [{trackId}]", LogLevel.Warning).ConfigureAwait(false);
return new OperationResult<bool>(true, $"Track Not Found [{trackId}]");
}
2019-06-30 22:14:36 +00:00
DbContext.Tracks.Remove(track);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
if (doDeleteFile ?? false)
2019-02-06 03:22:38 +00:00
{
string trackPath = null;
try
2019-02-06 03:22:38 +00:00
{
trackPath = track.PathToTrack(Configuration);
if (File.Exists(trackPath))
{
File.Delete(trackPath);
Logger.LogWarning($"x For Track `{track}`, Deleted File [{trackPath}]");
}
var trackThumbnailName = track.PathToTrackThumbnail(Configuration);
if (File.Exists(trackThumbnailName))
{
File.Delete(trackThumbnailName);
Logger.LogWarning($"x For Track `{track}`, Deleted Thumbnail File [{trackThumbnailName}]");
}
2019-02-06 03:22:38 +00:00
}
catch (Exception ex)
2019-05-11 03:07:45 +00:00
{
Logger.LogError(ex, $"Error Deleting File [{trackPath}] For Track [{track.Id}] Exception [{ex.Serialize()}]");
2019-05-11 03:07:45 +00:00
}
2019-02-06 03:22:38 +00:00
}
await ReleaseService.ScanReleaseFolderAsync(user, track.ReleaseMedia.Release.RoadieId, false, track.ReleaseMedia.Release).ConfigureAwait(false);
await BookmarkService.RemoveAllBookmarksForItemAsync(BookmarkType.Track, track.Id).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting track.").ConfigureAwait(false);
errors.Add(ex);
2019-02-06 03:22:38 +00:00
}
2019-06-30 22:14:36 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteTracks `{track}`, By User `{user}`", LogLevel.Warning).ConfigureAwait(false);
2019-02-06 03:22:38 +00:00
}
2019-06-30 22:14:36 +00:00
CacheManager.Clear();
2019-02-06 03:22:38 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-02-06 03:22:38 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> DeleteUserAsync(User applicationUser, Guid userId)
2019-01-08 22:40:26 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var user = DbContext.Users.FirstOrDefault(x => x.RoadieId == userId);
2019-05-29 22:25:40 +00:00
if (user.Id == applicationUser.Id)
{
var ex = new Exception("User cannot self.");
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting user.").ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-01-08 22:40:26 +00:00
try
{
2019-05-29 22:25:40 +00:00
if (user == null)
2019-01-08 22:40:26 +00:00
{
await LogAndPublishAsync($"DeleteUser Unknown User [{userId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"User Not Found [{userId}]");
2019-01-08 22:40:26 +00:00
}
2019-06-30 22:14:36 +00:00
DbContext.Users.Remove(user);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
var userImageFilename = user.PathToImage(Configuration);
if (File.Exists(userImageFilename))
{
File.Delete(userImageFilename);
}
2019-01-08 22:40:26 +00:00
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
await LogAndPublishAsync("Error deleting user.").ConfigureAwait(false);
2019-01-08 22:40:26 +00:00
errors.Add(ex);
}
2019-05-29 22:25:40 +00:00
2019-01-08 22:40:26 +00:00
sw.Stop();
await LogAndPublishAsync($"DeleteUser `{user}`, By User `{user}`", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
CacheManager.Clear();
2019-01-08 22:40:26 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-01-08 22:40:26 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2018-12-15 16:53:14 +00:00
/// <summary>
/// This is a very simple way to seed the database or setup configuration when the first (who becomes "Admin") user registers
2018-12-15 16:53:14 +00:00
/// </summary>
public async Task<OperationResult<bool>> DoInitialSetupAsync(User user, UserManager<User> userManager)
2018-12-15 16:53:14 +00:00
{
var sw = new Stopwatch();
sw.Start();
// Create user roles
2019-11-28 17:38:26 +00:00
DbContext.UserRoles.Add(new UserRole
2018-12-15 16:53:14 +00:00
{
2019-11-28 17:38:26 +00:00
Id = 1,
Status = (short)Statuses.Ok,
CreatedDate = DateTime.UtcNow,
IsLocked = false,
RoadieId = Guid.NewGuid().ToString(),
2018-12-15 16:53:14 +00:00
Name = "Admin",
Description = "Users with Administrative (full) access",
NormalizedName = "ADMIN"
});
2019-11-28 17:38:26 +00:00
DbContext.UserRoles.Add(new UserRole
2018-12-15 16:53:14 +00:00
{
2019-11-28 17:38:26 +00:00
Id = 2,
Status = (short)Statuses.Ok,
CreatedDate = DateTime.UtcNow,
IsLocked = false,
RoadieId = Guid.NewGuid().ToString(),
2018-12-15 16:53:14 +00:00
Name = "Editor",
Description = "Users who have Edit Permissions",
NormalizedName = "EDITOR"
});
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2018-12-15 16:53:14 +00:00
// Add given user to Admin role
await userManager.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
2018-12-15 16:53:14 +00:00
// Create special system artists of 'Sound Tracks' and 'Various Artists'
2019-06-30 22:14:36 +00:00
DbContext.Artists.Add(new data.Artist
2018-12-15 16:53:14 +00:00
{
2019-06-30 22:14:36 +00:00
AlternateNames =
"Sound Track|Film Sound Track|Film Sound Tracks|Les Sound Track|Motion Picture Soundtrack|Original Motion Picture SoundTrack|Original Motion Picture SoundTracks|Original Cast Album|Original Soundtrack|Soundtracks|SoundTrack|soundtracks|Original Cast|Original Cast Soundtrack|Motion Picture Cast Recording|Cast Recording",
2018-12-15 16:53:14 +00:00
ArtistType = "Meta",
2019-06-30 22:14:36 +00:00
BioContext =
"A soundtrack, also written sound track, can be recorded music accompanying and synchronized to the images of a motion picture, book, television program or video game; a commercially released soundtrack album of music as featured in the soundtrack of a film or TV show; or the physical area of a film that contains the synchronized recorded sound.",
2018-12-15 16:53:14 +00:00
Name = "Sound Tracks",
SortName = "Sound Tracks",
Status = Statuses.Ok,
2019-06-30 22:14:36 +00:00
Tags =
"movie and television soundtracks|video game soundtracks|book soundstracks|composite|compilations",
2018-12-15 16:53:14 +00:00
URLs = "https://en.wikipedia.org/wiki/Soundtrack"
});
2019-06-30 22:14:36 +00:00
DbContext.Artists.Add(new data.Artist
2018-12-15 16:53:14 +00:00
{
AlternateNames = "Various Artists|Various BNB artist|variousartist|va",
ArtistType = "Meta",
2019-06-30 22:14:36 +00:00
BioContext =
"Songs included on a compilation album may be previously released or unreleased, usually from several separate recordings by either one or several performers. If by one artist, then generally the tracks were not originally intended for release together as a single work, but may be collected together as a greatest hits album or box set. If from several performers, there may be a theme, topic, or genre which links the tracks, or they may have been intended for release as a single work—such as a tribute album. When the tracks are by the same recording artist, the album may be referred to as a retrospective album or an anthology. Compilation albums may employ traditional product bundling strategies",
2018-12-15 16:53:14 +00:00
Name = "Various Artists",
SortName = "Various Artist",
Status = Statuses.Ok,
2018-12-15 23:22:02 +00:00
Tags = "compilations|various",
2018-12-15 16:53:14 +00:00
URLs = "https://en.wikipedia.org/wiki/Compilation_album"
});
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2018-12-15 16:53:14 +00:00
return new OperationResult<bool>
{
Data = true,
IsSuccess = true,
OperationTime = sw.ElapsedMilliseconds
};
}
public Task<OperationResult<Dictionary<string, List<string>>>> MissingCollectionReleasesAsync(User user)
2018-12-17 21:26:24 +00:00
{
2019-05-29 22:25:40 +00:00
var sw = Stopwatch.StartNew();
2018-12-17 21:26:24 +00:00
sw.Start();
2019-05-29 22:25:40 +00:00
var missingData = new Dictionary<string, List<string>>();
2018-12-17 21:26:24 +00:00
2019-06-30 22:14:36 +00:00
foreach (var collection in DbContext.Collections.Where(x => x.Status != Statuses.Complete))
2018-12-17 21:26:24 +00:00
{
2019-06-30 22:14:36 +00:00
var collectionReleases = from cr in DbContext.CollectionReleases
where cr.CollectionId == collection.Id
select cr;
data.PositionArtistRelease[] pars = null;
2019-05-29 22:25:40 +00:00
try
{
pars = collection.PositionArtistReleases().ToArray();
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
missingData.Add($"CSV Error [{collection.Name}]", new List<string> { ex.Message });
2019-05-29 22:25:40 +00:00
continue;
}
2019-06-30 22:14:36 +00:00
2019-05-29 22:25:40 +00:00
foreach (var par in pars)
{
var cr = collectionReleases.FirstOrDefault(x => x.ListNumber == par.Position);
if (cr == null)
{
// If artist is already in result then add missing album to artist, if not then add artist then add missing album
2019-08-06 13:50:25 +00:00
if (!missingData.ContainsKey(par.Artist))
{
missingData.Add(par.Artist, new List<string>());
}
2019-06-30 22:14:36 +00:00
var r = $"[{collection.Name}]:[{par.Release}]";
2019-05-29 22:25:40 +00:00
missingData[par.Artist].Add(r);
}
}
2018-12-17 21:26:24 +00:00
}
2019-06-30 22:14:36 +00:00
2018-12-17 21:26:24 +00:00
sw.Stop();
2019-05-29 22:25:40 +00:00
return Task.FromResult(new OperationResult<Dictionary<string, List<string>>>
2018-12-19 20:23:10 +00:00
{
Data = missingData.OrderBy(x => x.Value.Count).ToDictionary(x => x.Key, x => x.Value),
2019-05-29 22:25:40 +00:00
IsSuccess = true,
OperationTime = sw.ElapsedMilliseconds
2018-12-19 20:23:10 +00:00
});
2018-12-17 21:26:24 +00:00
}
2022-01-18 22:52:02 +00:00
public void PerformStartUpTasks()
{
var sw = Stopwatch.StartNew();
#region Setup Configured storage folders
try
{
if (!Directory.Exists(Configuration.LibraryFolder))
{
Directory.CreateDirectory(Configuration.LibraryFolder);
Logger.LogInformation($"Created Library Folder [{Configuration.LibraryFolder }]");
}
2019-11-21 14:44:05 +00:00
if (!Directory.Exists(Configuration.InboundFolder))
{
Directory.CreateDirectory(Configuration.InboundFolder);
Logger.LogInformation($"Created Inbound Folder [{Configuration.InboundFolder }]");
}
if (!Directory.Exists(Configuration.UserImageFolder))
{
Directory.CreateDirectory(Configuration.UserImageFolder);
Logger.LogInformation($"Created User Image Folder [{Configuration.UserImageFolder }]");
}
if (!Directory.Exists(Configuration.GenreImageFolder))
{
Directory.CreateDirectory(Configuration.GenreImageFolder);
Logger.LogInformation($"Created Genre Image Folder [{Configuration.GenreImageFolder }]");
}
if (!Directory.Exists(Configuration.PlaylistImageFolder))
{
Directory.CreateDirectory(Configuration.PlaylistImageFolder);
Logger.LogInformation($"Created Playlist Image Folder [{Configuration.PlaylistImageFolder }]");
}
if (!Directory.Exists(Configuration.CollectionImageFolder))
{
Directory.CreateDirectory(Configuration.CollectionImageFolder);
Logger.LogInformation($"Created Collection Image Folder [{Configuration.CollectionImageFolder }]");
}
if (!Directory.Exists(Configuration.LabelImageFolder))
{
Directory.CreateDirectory(Configuration.LabelImageFolder);
Logger.LogInformation($"Created Label Image Folder [{Configuration.LabelImageFolder}]");
}
if (Configuration.DbContextToUse != DbContexts.MySQL)
2019-11-28 17:38:26 +00:00
{
if (!Directory.Exists(Configuration.FileDatabaseOptions.DatabaseFolder))
{
Directory.CreateDirectory(Configuration.FileDatabaseOptions.DatabaseFolder);
Logger.LogInformation($"Created File Database Folder [{Configuration.FileDatabaseOptions.DatabaseFolder}]");
}
else
{
Logger.LogInformation($"Administration Information: DatabaseFolder [{ Configuration.FileDatabaseOptions.DatabaseFolder }], Size [{ GetDirectorySize(Configuration.FileDatabaseOptions.DatabaseFolder) }] ");
}
2019-11-28 17:38:26 +00:00
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error setting up storage folders. Ensure application has create folder permissions.");
throw;
}
#endregion Setup Configured storage folders
sw.Stop();
Logger.LogInformation($"Administration Information: LibraryFolder [{ Configuration.LibraryFolder }]");
Logger.LogInformation($"Administration Information: InboundFolder [{ Configuration.InboundFolder }]");
Logger.LogInformation($"Administration startup tasks completed, elapsed time [{ sw.ElapsedMilliseconds }]");
}
private static long GetDirectorySize(string folderPath)
{
DirectoryInfo di = new DirectoryInfo(folderPath);
return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}
public async Task<OperationResult<bool>> ScanAllCollectionsAsync(User user, bool isReadOnly = false, bool doPurgeFirst = false)
2019-01-22 00:04:58 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var collections = await DbContext.Collections.Where(x => x.IsLocked == false).ToArrayAsync().ConfigureAwait(false);
2019-06-23 15:45:45 +00:00
var updatedReleaseIds = new List<int>();
2019-05-29 22:25:40 +00:00
foreach (var collection in collections)
{
2019-01-27 23:34:33 +00:00
try
2019-01-22 00:04:58 +00:00
{
var result = await ScanCollectionAsync(user, collection.RoadieId, isReadOnly, doPurgeFirst, false).ConfigureAwait(false);
2019-08-06 13:50:25 +00:00
if (!result.IsSuccess)
{
errors.AddRange(result.Errors);
}
2019-06-23 15:45:45 +00:00
updatedReleaseIds.AddRange((int[])result.AdditionalData["updatedReleaseIds"]);
2019-01-27 23:34:33 +00:00
}
catch (Exception ex)
{
await LogAndPublishAsync(ex.ToString(), LogLevel.Error).ConfigureAwait(false);
2019-01-27 23:34:33 +00:00
errors.Add(ex);
2019-01-22 00:04:58 +00:00
}
}
2019-06-30 22:14:36 +00:00
2019-08-06 13:50:25 +00:00
foreach (var updatedReleaseId in updatedReleaseIds.Distinct())
{
await UpdateReleaseRank(updatedReleaseId).ConfigureAwait(false);
2019-08-06 13:50:25 +00:00
}
2019-01-22 00:04:58 +00:00
sw.Stop();
await LogAndPublishAsync($"ScanAllCollections, By User `{user}`, Updated Release Count [{updatedReleaseIds.Distinct().Count()}], ElapsedTime [{sw.ElapsedMilliseconds}]", LogLevel.Warning).ConfigureAwait(false);
2019-01-22 00:04:58 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-01-22 00:04:58 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> ScanArtistAsync(User user, Guid artistId, bool isReadOnly = false)
{
var sw = Stopwatch.StartNew();
2019-03-09 16:33:19 +00:00
2019-05-29 22:25:40 +00:00
var errors = new List<Exception>();
2019-06-30 22:14:36 +00:00
var artist = DbContext.Artists.FirstOrDefault(x => x.RoadieId == artistId);
2019-05-29 22:25:40 +00:00
if (artist == null)
2019-03-09 16:33:19 +00:00
{
await LogAndPublishAsync($"ScanArtist Unknown Artist [{artistId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Artist Not Found [{artistId}]");
2019-05-29 22:25:40 +00:00
}
2019-06-30 22:14:36 +00:00
2019-05-29 22:25:40 +00:00
try
{
await ArtistService.ScanArtistReleasesFoldersAsync(user, artist.RoadieId, Configuration.LibraryFolder, isReadOnly).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
CacheManager.ClearRegion(artist.CacheRegion);
2019-05-29 22:25:40 +00:00
}
catch (Exception ex)
{
await LogAndPublishAsync(ex.ToString(), LogLevel.Error).ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
errors.Add(ex);
2019-03-09 16:33:19 +00:00
}
2019-06-30 22:14:36 +00:00
2019-03-09 16:33:19 +00:00
sw.Stop();
2019-06-30 22:14:36 +00:00
DbContext.ScanHistories.Add(new data.ScanHistory
2019-03-09 16:33:19 +00:00
{
2019-05-29 22:25:40 +00:00
UserId = user.Id,
ForArtistId = artist.Id,
2019-06-30 22:14:36 +00:00
NewReleases = ReleaseLookupEngine.AddedReleaseIds.Count(),
2019-07-07 03:16:33 +00:00
NewTracks = ReleaseService.AddedTrackIds.Count(),
2019-05-29 22:25:40 +00:00
TimeSpanInSeconds = (int)sw.Elapsed.TotalSeconds
2019-03-09 16:33:19 +00:00
});
await DbContext.SaveChangesAsync().ConfigureAwait(false);
await UpdateArtistRank(artist.Id, true).ConfigureAwait(false);
2019-05-29 22:25:40 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-05-29 22:25:40 +00:00
AdditionalData = new Dictionary<string, object> { { "artistAverage", artist.Rating } },
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
2019-03-09 16:33:19 +00:00
}
2019-01-22 00:04:58 +00:00
public async Task<OperationResult<bool>> ScanArtistsAsync(User user, IEnumerable<Guid> artistIds, bool isReadOnly = false)
{
var sw = Stopwatch.StartNew();
var errors = new List<Exception>();
foreach (var artistId in artistIds)
{
var result = await ScanArtistAsync(user, artistId, isReadOnly).ConfigureAwait(false);
if (!result.IsSuccess && (result.Errors?.Any() ?? false))
{
errors.AddRange(result.Errors);
}
}
sw.Stop();
await LogAndPublishAsync($"** Completed! ScanArtists: Artist Count [{ artistIds.Count() }], Elapsed Time [{sw.Elapsed}]").ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> ScanCollectionAsync(User user, Guid collectionId, bool isReadOnly = false, bool doPurgeFirst = false, bool doUpdateRanks = true)
2019-01-18 23:00:44 +00:00
{
var sw = new Stopwatch();
sw.Start();
2019-06-23 15:45:45 +00:00
var releaseIdsInCollection = new List<int>();
var updatedReleaseIds = new List<int>();
2019-01-18 23:00:44 +00:00
var errors = new List<Exception>();
var collection = await DbContext.Collections.FirstOrDefaultAsync(x => x.RoadieId == collectionId).ConfigureAwait(false);
2019-01-18 23:00:44 +00:00
if (collection == null)
{
await LogAndPublishAsync($"ScanCollection Unknown Collection [{collectionId}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
return new OperationResult<bool>(true, $"Collection Not Found [{collectionId}]");
2019-01-18 23:00:44 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-18 23:00:44 +00:00
try
{
if (doPurgeFirst)
{
await LogAndPublishAsync($"ScanCollection Purging Collection [{collectionId}]", LogLevel.Warning).ConfigureAwait(false);
var crs = await DbContext.CollectionReleases.Where(x => x.CollectionId == collection.Id).ToArrayAsync().ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
DbContext.CollectionReleases.RemoveRange(crs);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2019-01-18 23:00:44 +00:00
}
2019-06-30 22:14:36 +00:00
var collectionMissingRecords = DbContext.CollectionMissings.Where(x => x.CollectionId == collection.Id);
DbContext.CollectionMissings.RemoveRange(collectionMissingRecords);
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
2019-01-18 23:00:44 +00:00
var par = collection.PositionArtistReleases();
if (par != null)
{
var now = DateTime.UtcNow;
foreach (var csvRelease in par)
2019-05-29 22:25:40 +00:00
{
IEnumerable<data.Artist> artistsMatchingName = Enumerable.Empty<data.Artist>();
data.Release release = null;
2019-11-10 23:54:15 +00:00
var isArtistNameDbKey = csvRelease.Artist.StartsWith(Roadie.Library.Data.Collection.DatabaseIdKey);
int? artistId = isArtistNameDbKey ? SafeParser.ToNumber<int?>(csvRelease.Artist.Replace(Roadie.Library.Data.Collection.DatabaseIdKey, string.Empty)) : null;
if (artistId.HasValue)
2019-01-18 23:00:44 +00:00
{
var artist = DbContext.Artists.FirstOrDefault(x => x.Id == artistId.Value);
if (artist != null)
{
artistsMatchingName = new data.Artist[] { artist };
}
2019-11-10 23:54:15 +00:00
}
else
{
artistsMatchingName = await ArtistLookupEngine.DatabaseQueryForArtistName(csvRelease.Artist).ConfigureAwait(false);
if (artistsMatchingName?.Any() != true)
{
await LogAndPublishAsync($"CSV Position [{ csvRelease.Position }] Unable To Find Artist [{csvRelease.Artist}]", LogLevel.Warning).ConfigureAwait(false);
csvRelease.Status = Statuses.Missing;
await DbContext.CollectionMissings.AddAsync(new data.CollectionMissing
{
CollectionId = collection.Id,
Position = csvRelease.Position,
Artist = csvRelease.Artist,
Release = csvRelease.Release
}).ConfigureAwait(false);
continue;
}
else if (artistsMatchingName.Count() > 1)
{
await LogAndPublishAsync($"CSV Position [{ csvRelease.Position }] Found [{ artistsMatchingName.Count() }] Artists by [{csvRelease.Artist}]", LogLevel.Information).ConfigureAwait(false);
}
2019-11-10 23:54:15 +00:00
}
foreach (var artist in artistsMatchingName)
2019-11-10 23:54:15 +00:00
{
var isReleaseNameDbKey = csvRelease.Release.StartsWith(Roadie.Library.Data.Collection.DatabaseIdKey);
int? releaseId = isReleaseNameDbKey ? SafeParser.ToNumber<int?>(csvRelease.Release.Replace(Roadie.Library.Data.Collection.DatabaseIdKey, string.Empty)) : null;
if (releaseId.HasValue)
2019-06-30 22:14:36 +00:00
{
release = await DbContext.Releases.FirstOrDefaultAsync(x => x.Id == releaseId.Value).ConfigureAwait(false);
}
else
{
release = await ReleaseLookupEngine.DatabaseQueryForReleaseTitle(artist, csvRelease.Release).ConfigureAwait(false);
}
if (release != null)
{
break;
}
2019-01-18 23:00:44 +00:00
}
2019-06-30 22:14:36 +00:00
if (release == null)
2019-01-18 23:00:44 +00:00
{
await LogAndPublishAsync($"CSV Position [{ csvRelease.Position }] Unable To Find Release [{csvRelease.Release}], for Artist [{csvRelease.Artist}]", LogLevel.Warning).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
csvRelease.Status = Statuses.Missing;
await DbContext.CollectionMissings.AddAsync(new data.CollectionMissing
2019-06-30 22:14:36 +00:00
{
CollectionId = collection.Id,
IsArtistFound = true,
Position = csvRelease.Position,
2019-11-10 23:54:15 +00:00
Artist = csvRelease.Artist,
Release = csvRelease.Release
}).ConfigureAwait(false);
continue;
2019-05-29 22:25:40 +00:00
}
2019-06-30 22:14:36 +00:00
var isInCollection = await DbContext.CollectionReleases.FirstOrDefaultAsync(x =>
2019-06-30 22:14:36 +00:00
x.CollectionId == collection.Id &&
x.ListNumber == csvRelease.Position &&
x.ReleaseId == release.Id)
.ConfigureAwait(false);
2019-06-23 15:45:45 +00:00
var updated = false;
// Found in Database but not in collection add to Collection
if (isInCollection == null)
2019-01-18 23:00:44 +00:00
{
await DbContext.CollectionReleases.AddAsync(new data.CollectionRelease
2019-01-18 23:00:44 +00:00
{
CollectionId = collection.Id,
ReleaseId = release.Id,
2019-06-30 22:14:36 +00:00
ListNumber = csvRelease.Position
}).ConfigureAwait(false);
2019-06-23 15:45:45 +00:00
updated = true;
2019-01-18 23:00:44 +00:00
}
// If Item in Collection is at different List number update CollectionRelease
else if (isInCollection.ListNumber != csvRelease.Position)
2019-01-18 23:00:44 +00:00
{
isInCollection.LastUpdated = now;
isInCollection.ListNumber = csvRelease.Position;
2019-06-23 15:45:45 +00:00
updated = true;
}
2019-06-30 22:14:36 +00:00
2019-08-06 13:50:25 +00:00
if (updated && !updatedReleaseIds.Any(x => x == release.Id))
{
updatedReleaseIds.Add(release.Id);
}
2019-06-23 15:45:45 +00:00
releaseIdsInCollection.Add(release.Id);
2019-01-18 23:00:44 +00:00
}
2019-06-30 22:14:36 +00:00
2019-01-26 20:55:58 +00:00
collection.LastUpdated = now;
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
var dto = new CollectionList
2019-01-18 23:00:44 +00:00
{
2019-01-26 20:55:58 +00:00
CollectionCount = collection.CollectionCount,
2019-06-30 22:14:36 +00:00
CollectionFoundCount = (from cr in DbContext.CollectionReleases
2019-01-26 20:55:58 +00:00
where cr.CollectionId == collection.Id
select cr.CollectionId).Count()
};
if (dto.PercentComplete == 100)
{
2019-01-27 05:05:43 +00:00
// Lock so future implicit scans dont happen, with DB RI when releases are deleted they are removed from collection
2019-01-26 20:55:58 +00:00
collection.IsLocked = true;
collection.Status = Statuses.Complete;
}
2019-01-27 05:05:43 +00:00
else
{
collection.Status = Statuses.Incomplete;
}
2019-06-30 22:14:36 +00:00
var collectionReleasesToRemove = await (from cr in DbContext.CollectionReleases
where cr.CollectionId == collection.Id
where !releaseIdsInCollection.Contains(cr.ReleaseId)
select cr).ToArrayAsync().ConfigureAwait(false);
if (collectionReleasesToRemove.Length > 0)
2019-06-23 15:45:45 +00:00
{
await LogAndPublishAsync($"Removing [{collectionReleasesToRemove.Length}] Stale Release Records from Collection.", LogLevel.Information).ConfigureAwait(false);
2019-06-30 22:14:36 +00:00
DbContext.CollectionReleases.RemoveRange(collectionReleasesToRemove);
2019-06-23 15:45:45 +00:00
}
2019-06-30 22:14:36 +00:00
await DbContext.SaveChangesAsync().ConfigureAwait(false);
2019-06-23 15:45:45 +00:00
if (doUpdateRanks)
2019-08-06 13:50:25 +00:00
{
2019-06-30 22:14:36 +00:00
foreach (var updatedReleaseId in updatedReleaseIds)
2019-08-06 13:50:25 +00:00
{
await UpdateReleaseRank(updatedReleaseId).ConfigureAwait(false);
2019-08-06 13:50:25 +00:00
}
}
2019-06-30 22:14:36 +00:00
CacheManager.ClearRegion(collection.CacheRegion);
2019-01-18 23:00:44 +00:00
}
}
catch (Exception ex)
{
2019-06-30 22:14:36 +00:00
Logger.LogError(ex);
2019-01-18 23:00:44 +00:00
errors.Add(ex);
}
2019-06-30 22:14:36 +00:00
2019-01-18 23:00:44 +00:00
sw.Stop();
Logger.LogWarning($"RescanCollection `{collection}`, By User `{user}`, ElapsedTime [{sw.ElapsedMilliseconds}]");
2019-01-18 23:00:44 +00:00
return new OperationResult<bool>
{
2019-06-23 15:45:45 +00:00
AdditionalData = new Dictionary<string, object> { { "updatedReleaseIds", updatedReleaseIds.ToArray() } },
IsSuccess = errors.Count == 0,
2019-01-18 23:00:44 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public Task<OperationResult<bool>> ScanInboundFolderAsync(User user, bool isReadOnly = false) => ScanFolderAsync(user, new DirectoryInfo(Configuration.InboundFolder), isReadOnly);
2019-01-08 22:40:26 +00:00
public Task<OperationResult<bool>> ScanLibraryFolderAsync(User user, bool isReadOnly = false) => ScanFolderAsync(user, new DirectoryInfo(Configuration.LibraryFolder), isReadOnly, false);
2019-01-08 22:40:26 +00:00
public async Task<OperationResult<bool>> ScanReleaseAsync(User user, Guid releaseId, bool isReadOnly = false, bool wasDoneForInvalidTrackPlay = false)
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
var release = DbContext.Releases
.Include(x => x.Artist)
.Include(x => x.Labels)
.FirstOrDefault(x => x.RoadieId == releaseId);
if (release == null)
{
await LogAndPublishAsync($"ScanRelease Unknown Release [{releaseId}]", LogLevel.Warning).ConfigureAwait(false);
return new OperationResult<bool>(true, $"Release Not Found [{releaseId}]");
}
try
{
await ReleaseService.ScanReleaseFolderAsync(user, release.RoadieId, isReadOnly, release).ConfigureAwait(false);
}
catch (Exception ex)
{
await LogAndPublishAsync(ex.ToString(), LogLevel.Error).ConfigureAwait(false);
errors.Add(ex);
}
sw.Stop();
DbContext.ScanHistories.Add(new data.ScanHistory
{
UserId = user.Id,
ForReleaseId = release.Id,
NewTracks = ReleaseService.AddedTrackIds.Count(),
TimeSpanInSeconds = (int)sw.Elapsed.TotalSeconds
});
await DbContext.SaveChangesAsync().ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> ScanLastGiveNumberOfReleasesAsync(User user, int count, bool isReadOnly = false, bool wasDoneForInvalidTrackPlay = false)
{
var sw = Stopwatch.StartNew();
var errors = new List<Exception>();
var releaseIds = await DbContext.Releases.OrderByDescending(x => x.CreatedDate).Select(x => x.RoadieId).Take(count).ToListAsync().ConfigureAwait(false);
foreach (var releaseId in releaseIds)
{
var result = await ScanReleaseAsync(user, releaseId, isReadOnly, wasDoneForInvalidTrackPlay).ConfigureAwait(false);
if (!result.IsSuccess && (result.Errors?.Any() ?? false))
{
errors.AddRange(result.Errors);
}
}
sw.Stop();
await LogAndPublishAsync($"** Completed! ScanLastGiveNumberOfReleasesAsync: Release Count [{ releaseIds.Count() }], Elapsed Time [{sw.Elapsed}]").ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> ScanReleasesAsync(User user, IEnumerable<Guid> releaseIds, bool isReadOnly = false, bool wasDoneForInvalidTrackPlay = false)
2019-08-06 13:50:25 +00:00
{
var sw = Stopwatch.StartNew();
var errors = new List<Exception>();
foreach (var releaseId in releaseIds)
{
var result = await ScanReleaseAsync(user, releaseId, isReadOnly, wasDoneForInvalidTrackPlay).ConfigureAwait(false);
if (!result.IsSuccess && (result.Errors?.Any() ?? false))
2019-08-06 13:50:25 +00:00
{
errors.AddRange(result.Errors);
2019-08-06 13:50:25 +00:00
}
}
sw.Stop();
await LogAndPublishAsync($"** Completed! ScanReleases: Release Count [{ releaseIds.Count() }], Elapsed Time [{sw.Elapsed}]").ConfigureAwait(false);
2019-08-06 13:50:25 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2019-08-06 13:50:25 +00:00
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
public async Task<OperationResult<bool>> UpdateInviteTokenUsedAsync(Guid? tokenId)
2018-12-17 21:26:24 +00:00
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
if (tokenId == null)
2018-12-17 21:26:24 +00:00
{
return new OperationResult<bool>(true, $"Invalid Invite TokenId [{tokenId}]");
2018-12-17 21:26:24 +00:00
}
var token = DbContext.InviteTokens.FirstOrDefault(x => x.RoadieId == tokenId);
if (token == null)
{
return new OperationResult<bool>(true, $"Invite Token Not Found [{tokenId}]");
}
token.Status = Statuses.Complete;
token.LastUpdated = DateTime.UtcNow;
await DbContext.SaveChangesAsync().ConfigureAwait(false);
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2019-06-30 22:14:36 +00:00
public async Task<OperationResult<bool>> ValidateInviteTokenAsync(Guid? tokenId)
{
var sw = new Stopwatch();
sw.Start();
var errors = new List<Exception>();
if (tokenId == null)
2018-12-17 21:26:24 +00:00
{
return new OperationResult<bool>(true, $"Invalid Invite TokenId [{tokenId}]");
2018-12-17 21:26:24 +00:00
}
var token = DbContext.InviteTokens.FirstOrDefault(x => x.RoadieId == tokenId);
if (token == null)
2018-12-17 21:26:24 +00:00
{
return new OperationResult<bool>(true, $"Invite Token Not Found [{tokenId}]");
2018-12-17 21:26:24 +00:00
}
if (token.ExpiresDate < DateTime.UtcNow || token.Status == Statuses.Expired)
2018-12-19 20:23:10 +00:00
{
token.Status = Statuses.Expired;
token.LastUpdated = DateTime.UtcNow;
await DbContext.SaveChangesAsync().ConfigureAwait(false);
return new OperationResult<bool>(true, $"Invite Token [{tokenId}] Expired [{ token.ExpiresDate }]");
}
if (token.Status == Statuses.Complete)
{
return new OperationResult<bool>(true, $"Invite Token [{tokenId}] Already Used");
}
2018-12-17 21:26:24 +00:00
return new OperationResult<bool>
{
IsSuccess = errors.Count == 0,
2018-12-17 21:26:24 +00:00
Data = true,
OperationTime = sw.ElapsedMilliseconds,
Errors = errors
};
}
2018-12-14 03:52:14 +00:00
}
2018-12-15 23:22:02 +00:00
}