Made the search page all async goodness #278

This commit is contained in:
tidusjar 2016-05-27 22:04:25 +01:00
parent 05b219a351
commit 03ce361183
13 changed files with 432 additions and 183 deletions

View file

@ -92,7 +92,7 @@ namespace PlexRequests.UI.Modules
EmailNotificationSettings = email;
Get["/"] = parameters => RequestLoad();
Get["/", true] = async (x, ct) => await RequestLoad();
Get["movie/{searchTerm}", true] = async (x, ct) => await SearchMovie((string)x.searchTerm);
Get["tv/{searchTerm}", true] = async (x, ct) => await SearchTvShow((string)x.searchTerm);
@ -102,12 +102,12 @@ namespace PlexRequests.UI.Modules
Get["movie/upcoming", true] = async (x, ct) => await UpcomingMovies();
Get["movie/playing", true] = async (x, ct) => await CurrentlyPlayingMovies();
Post["request/movie"] = parameters => RequestMovie((int)Request.Form.movieId);
Post["request/tv"] = parameters => RequestTvShow((int)Request.Form.tvId, (string)Request.Form.seasons);
Post["request/album"] = parameters => RequestAlbum((string)Request.Form.albumId);
Post["request/movie", true] = async (x, ct) => await RequestMovie((int)Request.Form.movieId);
Post["request/tv", true] = async (x, ct) => await RequestTvShow((int)Request.Form.tvId, (string)Request.Form.seasons);
Post["request/album", true] = async (x, ct) => await RequestAlbum((string)Request.Form.albumId);
Post["/notifyuser"] = x => NotifyUser((bool)Request.Form.notify);
Get["/notifyuser"] = x => GetUserNotificationSettings();
Post["/notifyuser", true] = async (x, ct) => await NotifyUser((bool)Request.Form.notify);
Get["/notifyuser", true] = async (x, ct) => await GetUserNotificationSettings();
Get["/seasons"] = x => GetSeasons();
}
@ -136,9 +136,9 @@ namespace PlexRequests.UI.Modules
private IRepository<UsersToNotify> UsersToNotifyRepo { get; }
private static Logger Log = LogManager.GetCurrentClassLogger();
private Negotiator RequestLoad()
private async Task<Negotiator> RequestLoad()
{
var settings = PrService.GetSettings();
var settings = await PrService.GetSettingsAsync();
Log.Trace("Loading Index");
return View["Search/Index", settings];
@ -215,7 +215,7 @@ namespace PlexRequests.UI.Modules
var cpCached = CpCacher.QueuedIds();
var plexMovies = Checker.GetPlexMovies();
var settings = PrService.GetSettings();
var settings = await PrService.GetSettingsAsync();
var viewMovies = new List<SearchMovieViewModel>();
foreach (MovieResult movie in apiMovies)
{
@ -350,7 +350,7 @@ namespace PlexRequests.UI.Modules
private async Task<Response> SearchMusic(string searchTerm)
{
var apiAlbums = new List<Release>();
await Task.Factory.StartNew(() => MusicBrainzApi.SearchAlbum(searchTerm)).ContinueWith((t) =>
await Task.Run(() => MusicBrainzApi.SearchAlbum(searchTerm)).ContinueWith((t) =>
{
apiAlbums = t.Result.releases ?? new List<Release>();
});
@ -359,7 +359,7 @@ namespace PlexRequests.UI.Modules
allResults = allResults.Where(x => x.Type == RequestType.Album);
var dbAlbum = allResults.ToDictionary(x => x.MusicBrainzId);
var plexAlbums = Checker.GetPlexAlbums();
var viewAlbum = new List<SearchMusicViewModel>();
@ -398,27 +398,26 @@ namespace PlexRequests.UI.Modules
return Response.AsJson(viewAlbum);
}
private Response RequestMovie(int movieId)
private async Task<Response> RequestMovie(int movieId)
{
var movieApi = new TheMovieDbApi();
var movieInfo = movieApi.GetMovieInformation(movieId).Result;
var fullMovieName = $"{movieInfo.Title}{(movieInfo.ReleaseDate.HasValue ? $" ({movieInfo.ReleaseDate.Value.Year})" : string.Empty)}";
Log.Trace("Getting movie info from TheMovieDb");
Log.Trace(movieInfo.DumpJson);
//#if !DEBUG
var settings = PrService.GetSettings();
var settings = await PrService.GetSettingsAsync();
// check if the movie has already been requested
Log.Info("Requesting movie with id {0}", movieId);
var existingRequest = RequestService.CheckRequest(movieId);
var existingRequest = await RequestService.CheckRequestAsync(movieId);
if (existingRequest != null)
{
// check if the current user is already marked as a requester for this movie, if not, add them
if (!existingRequest.UserHasRequested(Username))
{
existingRequest.RequestedUsers.Add(Username);
RequestService.UpdateRequest(existingRequest);
await RequestService.UpdateRequestAsync(existingRequest);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{fullMovieName} was successfully added!" : $"{fullMovieName} has already been requested!" });
@ -457,13 +456,10 @@ namespace PlexRequests.UI.Modules
};
Log.Trace(settings.DumpJson());
if (ShouldAutoApprove(RequestType.Movie, settings))
{
var cpSettings = CpService.GetSettings();
var cpSettings = await CpService.GetSettingsAsync();
Log.Trace("Settings: ");
Log.Trace(cpSettings.DumpJson);
if (cpSettings.Enabled)
{
Log.Info("Adding movie to CP (No approval required)");
@ -474,8 +470,7 @@ namespace PlexRequests.UI.Modules
{
model.Approved = true;
Log.Info("Adding movie to database (No approval required)");
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
@ -486,7 +481,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notificationModel);
await NotificationService.Publish(notificationModel);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" });
}
@ -502,7 +497,7 @@ namespace PlexRequests.UI.Modules
{
model.Approved = true;
Log.Info("Adding movie to database (No approval required)");
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
@ -513,7 +508,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notificationModel);
await NotificationService.Publish(notificationModel);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" });
@ -523,10 +518,10 @@ namespace PlexRequests.UI.Modules
try
{
Log.Info("Adding movie to database");
var id = RequestService.AddRequest(model);
var id = await RequestService.AddRequestAsync(model);
var notificationModel = new NotificationModel { Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest };
NotificationService.Publish(notificationModel);
await NotificationService.Publish(notificationModel);
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullMovieName} was successfully added!" });
}
@ -543,9 +538,8 @@ namespace PlexRequests.UI.Modules
/// </summary>
/// <param name="showId">The show identifier.</param>
/// <param name="seasons">The seasons.</param>
/// <param name="notify">if set to <c>true</c> [notify].</param>
/// <returns></returns>
private Response RequestTvShow(int showId, string seasons)
private async Task<Response> RequestTvShow(int showId, string seasons)
{
var tvApi = new TvMazeApi();
@ -555,18 +549,18 @@ namespace PlexRequests.UI.Modules
string fullShowName = $"{showInfo.name} ({firstAir.Year})";
//#if !DEBUG
var settings = PrService.GetSettings();
var settings = await PrService.GetSettingsAsync();
// check if the show has already been requested
Log.Info("Requesting tv show with id {0}", showId);
var existingRequest = RequestService.CheckRequest(showId);
var existingRequest = await RequestService.CheckRequestAsync(showId);
if (existingRequest != null)
{
// check if the current user is already marked as a requester for this show, if not, add them
if (!existingRequest.UserHasRequested(Username))
{
existingRequest.RequestedUsers.Add(Username);
RequestService.UpdateRequest(existingRequest);
await RequestService.UpdateRequestAsync(existingRequest);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{fullShowName} was successfully added!" : $"{fullShowName} has already been requested!" });
}
@ -635,16 +629,16 @@ namespace PlexRequests.UI.Modules
if (ShouldAutoApprove(RequestType.TvShow, settings))
{
var sonarrSettings = SonarrService.GetSettings();
var sonarrSettings = await SonarrService.GetSettingsAsync();
var sender = new TvSender(SonarrApi, SickrageApi);
if (sonarrSettings.Enabled)
{
var result = sender.SendToSonarr(sonarrSettings, model);
if (result != null && !string.IsNullOrEmpty(result.title))
if (!string.IsNullOrEmpty(result?.title))
{
model.Approved = true;
Log.Debug("Adding tv to database requests (No approval required & Sonarr)");
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
@ -655,7 +649,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notify1);
await NotificationService.Publish(notify1);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullShowName} was successfully added!" });
}
@ -673,7 +667,7 @@ namespace PlexRequests.UI.Modules
{
model.Approved = true;
Log.Debug("Adding tv to database requests (No approval required & SickRage)");
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
var notify2 = new NotificationModel
@ -683,7 +677,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notify2);
await NotificationService.Publish(notify2);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullShowName} was successfully added!" });
@ -695,7 +689,7 @@ namespace PlexRequests.UI.Modules
{
model.Approved = true;
Log.Debug("Adding tv to database requests (No approval required) and Sonarr/Sickrage not setup");
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
var notify2 = new NotificationModel
@ -705,7 +699,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notify2);
await NotificationService.Publish(notify2);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullShowName} was successfully added!" });
}
@ -714,10 +708,10 @@ namespace PlexRequests.UI.Modules
}
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
var notificationModel = new NotificationModel { Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest };
NotificationService.Publish(notificationModel);
await NotificationService.Publish(notificationModel);
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullShowName} was successfully added!" });
}
@ -728,7 +722,8 @@ namespace PlexRequests.UI.Modules
var claims = Context.CurrentUser?.Claims;
if (claims != null)
{
if (claims.Contains(UserClaims.Admin) || claims.Contains(UserClaims.PowerUser))
var enumerable = claims as string[] ?? claims.ToArray();
if (enumerable.Contains(UserClaims.Admin) || enumerable.Contains(UserClaims.PowerUser))
{
sendNotification = false; // Don't bother sending a notification if the user is an admin
}
@ -737,10 +732,10 @@ namespace PlexRequests.UI.Modules
}
private Response RequestAlbum(string releaseId)
private async Task<Response> RequestAlbum(string releaseId)
{
var settings = PrService.GetSettings();
var existingRequest = RequestService.CheckRequest(releaseId);
var settings = await PrService.GetSettingsAsync();
var existingRequest = await RequestService.CheckRequestAsync(releaseId);
Log.Debug("Checking for an existing request");
if (existingRequest != null)
@ -751,12 +746,11 @@ namespace PlexRequests.UI.Modules
Log.Debug("Not in the requested list so adding them and updating the request. User: {0}", Username);
existingRequest.RequestedUsers.Add(Username);
RequestService.UpdateRequest(existingRequest);
await RequestService.UpdateRequestAsync(existingRequest);
}
return Response.AsJson(new JsonResponseModel { Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{existingRequest.Title} was successfully added!" : $"{existingRequest.Title} has already been requested!" });
}
Log.Debug("This is a new request");
var albumInfo = MusicBrainzApi.GetAlbum(releaseId);
@ -816,7 +810,7 @@ namespace PlexRequests.UI.Modules
if (!hpSettings.Enabled)
{
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
return
Response.AsJson(new JsonResponseModel
{
@ -826,9 +820,9 @@ namespace PlexRequests.UI.Modules
}
var sender = new HeadphonesSender(HeadphonesApi, hpSettings, RequestService);
sender.AddAlbum(model).Wait();
await sender.AddAlbum(model);
model.Approved = true;
RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
if (ShouldSendNotification())
{
@ -839,7 +833,7 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notify2);
await NotificationService.Publish(notify2);
}
return
@ -859,9 +853,9 @@ namespace PlexRequests.UI.Modules
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest
};
NotificationService.Publish(notify2);
await NotificationService.Publish(notify2);
}
var result = RequestService.AddRequest(model);
await RequestService.AddRequestAsync(model);
return Response.AsJson(new JsonResponseModel
{
Result = true,
@ -902,10 +896,12 @@ namespace PlexRequests.UI.Modules
}
}
private Response NotifyUser(bool notify)
private async Task<Response> NotifyUser(bool notify)
{
var auth = Auth.GetSettings().UserAuthentication;
var email = EmailNotificationSettings.GetSettings().EnableUserEmailNotifications;
var authSettings = await Auth.GetSettingsAsync();
var auth = authSettings.UserAuthentication;
var emailSettings = await EmailNotificationSettings.GetSettingsAsync();
var email = emailSettings.EnableUserEmailNotifications;
if (!auth)
{
return Response.AsJson(new JsonResponseModel { Result = false, Message = "Sorry, but this functionality is currently only for users with Plex accounts" });
@ -915,7 +911,7 @@ namespace PlexRequests.UI.Modules
return Response.AsJson(new JsonResponseModel { Result = false, Message = "Sorry, but your administrator has not yet enabled this functionality." });
}
var username = Username;
var originalList = UsersToNotifyRepo.GetAll();
var originalList = await UsersToNotifyRepo.GetAllAsync();
if (!notify)
{
if (originalList == null)
@ -925,7 +921,7 @@ namespace PlexRequests.UI.Modules
var userToRemove = originalList.FirstOrDefault(x => x.Username == username);
if (userToRemove != null)
{
UsersToNotifyRepo.Delete(userToRemove);
await UsersToNotifyRepo.DeleteAsync(userToRemove);
}
return Response.AsJson(new JsonResponseModel { Result = true });
}
@ -934,7 +930,7 @@ namespace PlexRequests.UI.Modules
if (originalList == null)
{
var userModel = new UsersToNotify { Username = username };
var insertResult = UsersToNotifyRepo.Insert(userModel);
var insertResult = await UsersToNotifyRepo.InsertAsync(userModel);
return Response.AsJson(insertResult != -1 ? new JsonResponseModel { Result = true } : new JsonResponseModel { Result = false, Message = "Could not save, please try again" });
}
@ -946,15 +942,16 @@ namespace PlexRequests.UI.Modules
else
{
var userModel = new UsersToNotify { Username = username };
var insertResult = UsersToNotifyRepo.Insert(userModel);
var insertResult = await UsersToNotifyRepo.InsertAsync(userModel);
return Response.AsJson(insertResult != -1 ? new JsonResponseModel { Result = true } : new JsonResponseModel { Result = false, Message = "Could not save, please try again" });
}
}
private Response GetUserNotificationSettings()
private async Task<Response> GetUserNotificationSettings()
{
var retval = UsersToNotifyRepo.GetAll().FirstOrDefault(x => x.Username == Username);
return Response.AsJson(retval != null);
var all = await UsersToNotifyRepo.GetAllAsync();
var retVal = all.FirstOrDefault(x => x.Username == Username);
return Response.AsJson(retVal != null);
}
private Response GetSeasons()