Made the search page all async goodness #278

pull/284/head
tidusjar 8 years ago
parent 05b219a351
commit 03ce361183

@ -37,7 +37,9 @@ namespace PlexRequests.Core
long AddRequest(RequestedModel model); long AddRequest(RequestedModel model);
Task<int> AddRequestAsync(RequestedModel model); Task<int> AddRequestAsync(RequestedModel model);
RequestedModel CheckRequest(int providerId); RequestedModel CheckRequest(int providerId);
Task<RequestedModel> CheckRequestAsync(int providerId);
RequestedModel CheckRequest(string musicId); RequestedModel CheckRequest(string musicId);
Task<RequestedModel> CheckRequestAsync(string musicId);
void DeleteRequest(RequestedModel request); void DeleteRequest(RequestedModel request);
Task DeleteRequestAsync(RequestedModel request); Task DeleteRequestAsync(RequestedModel request);

@ -24,12 +24,18 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System.Threading.Tasks;
namespace PlexRequests.Core namespace PlexRequests.Core
{ {
public interface ISettingsService<T> public interface ISettingsService<T>
{ {
T GetSettings(); T GetSettings();
Task<T> GetSettingsAsync();
bool SaveSettings(T model); bool SaveSettings(T model);
Task<bool> SaveSettingsAsync(T model);
bool Delete(T model); bool Delete(T model);
Task<bool> DeleteAsync(T model);
} }
} }

@ -78,6 +78,13 @@ namespace PlexRequests.Core
return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null; return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null;
} }
public async Task<RequestedModel> CheckRequestAsync(int providerId)
{
var blobs = await Repo.GetAllAsync();
var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId);
return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null;
}
public RequestedModel CheckRequest(string musicId) public RequestedModel CheckRequest(string musicId)
{ {
var blobs = Repo.GetAll(); var blobs = Repo.GetAll();
@ -85,6 +92,13 @@ namespace PlexRequests.Core
return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null; return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null;
} }
public async Task<RequestedModel> CheckRequestAsync(string musicId)
{
var blobs = await Repo.GetAllAsync();
var blob = blobs.FirstOrDefault(x => x.MusicId == musicId);
return blob != null ? ByteConverterHelper.ReturnObject<RequestedModel>(blob.Content) : null;
}
public void DeleteRequest(RequestedModel request) public void DeleteRequest(RequestedModel request)
{ {
var blob = Repo.Get(request.Id); var blob = Repo.Get(request.Id);

@ -24,6 +24,8 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
@ -62,6 +64,21 @@ namespace PlexRequests.Core
return model; return model;
} }
public async Task<T> GetSettingsAsync()
{
var result = await Repo.GetAsync(EntityName);
if (result == null)
{
return new T();
}
result.Content = DecryptSettings(result);
var obj = string.IsNullOrEmpty(result.Content) ? null : JsonConvert.DeserializeObject<T>(result.Content, SerializerSettings.Settings);
var model = obj;
return model;
}
public bool SaveSettings(T model) public bool SaveSettings(T model)
{ {
var entity = Repo.Get(EntityName); var entity = Repo.Get(EntityName);
@ -88,6 +105,31 @@ namespace PlexRequests.Core
return result; return result;
} }
public async Task<bool> SaveSettingsAsync(T model)
{
var entity = await Repo.GetAsync(EntityName);
if (entity == null)
{
var newEntity = model;
var settings = new GlobalSettings { SettingsName = EntityName, Content = JsonConvert.SerializeObject(newEntity, SerializerSettings.Settings) };
settings.Content = EncryptSettings(settings);
var insertResult = await Repo.InsertAsync(settings);
return insertResult != int.MinValue;
}
var modified = model;
modified.Id = entity.Id;
var globalSettings = new GlobalSettings { SettingsName = EntityName, Content = JsonConvert.SerializeObject(modified, SerializerSettings.Settings), Id = entity.Id };
globalSettings.Content = EncryptSettings(globalSettings);
var result = await Repo.UpdateAsync(globalSettings);
return result;
}
public bool Delete(T model) public bool Delete(T model)
{ {
var entity = Repo.Get(EntityName); var entity = Repo.Get(EntityName);
@ -100,6 +142,17 @@ namespace PlexRequests.Core
return true; return true;
} }
public async Task<bool> DeleteAsync(T model)
{
var entity = Repo.Get(EntityName);
if (entity != null)
{
return await Repo.DeleteAsync(entity);
}
return true;
}
private string EncryptSettings(GlobalSettings settings) private string EncryptSettings(GlobalSettings settings)
{ {
return StringCipher.Encrypt(settings.Content, settings.SettingsName); return StringCipher.Encrypt(settings.Content, settings.SettingsName);

@ -187,7 +187,7 @@ namespace PlexRequests.Core
{ {
try try
{ {
var userMapper = new UserMapper(new UserRepository<UsersModel>(Db)); var userMapper = new UserMapper(new UserRepository<UsersModel>(Db, new MemoryCacheProvider()));
var users = userMapper.GetUsers(); var users = userMapper.GetUsers();
foreach (var u in users) foreach (var u in users)

@ -61,6 +61,7 @@
<Compile Include="Entity.cs" /> <Compile Include="Entity.cs" />
<Compile Include="Models\ScheduledJobs.cs" /> <Compile Include="Models\ScheduledJobs.cs" />
<Compile Include="Models\UsersToNotify.cs" /> <Compile Include="Models\UsersToNotify.cs" />
<Compile Include="Repository\BaseGenericRepository.cs" />
<Compile Include="Repository\IRequestRepository.cs" /> <Compile Include="Repository\IRequestRepository.cs" />
<Compile Include="Repository\ISettingsRepository.cs" /> <Compile Include="Repository\ISettingsRepository.cs" />
<Compile Include="ISqliteConfiguration.cs" /> <Compile Include="ISqliteConfiguration.cs" />

@ -0,0 +1,179 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: BaseGenericRepository.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
using NLog;
using PlexRequests.Helpers;
namespace PlexRequests.Store.Repository
{
public abstract class BaseGenericRepository<T> where T : class
{
protected BaseGenericRepository(ISqliteConfiguration config, ICacheProvider cache)
{
Config = config;
Cache = cache;
}
protected ICacheProvider Cache { get; }
protected ISqliteConfiguration Config { get; }
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public abstract T Get(string id);
public abstract Task<T> GetAsync(int id);
public abstract T Get(int id);
public abstract Task<T> GetAsync(string id);
public long Insert(T entity)
{
ResetCache();
using (var cnn = Config.DbConnection())
{
cnn.Open();
return cnn.Insert(entity);
}
}
public void Delete(T entity)
{
ResetCache();
using (var db = Config.DbConnection())
{
db.Open();
db.Delete(entity);
}
}
public async Task DeleteAsync(T entity)
{
ResetCache();
using (var db = Config.DbConnection())
{
db.Open();
await db.DeleteAsync(entity);
}
}
public bool Update(T entity)
{
ResetCache();
Log.Trace("Updating entity");
Log.Trace(entity.DumpJson());
using (var db = Config.DbConnection())
{
db.Open();
return db.Update(entity);
}
}
public async Task<bool> UpdateAsync(T entity)
{
ResetCache();
Log.Trace("Updating entity");
Log.Trace(entity.DumpJson());
using (var db = Config.DbConnection())
{
db.Open();
return await db.UpdateAsync(entity);
}
}
public bool UpdateAll(IEnumerable<T> entity)
{
ResetCache();
Log.Trace("Updating all entities");
var result = new HashSet<bool>();
using (var db = Config.DbConnection())
{
db.Open();
foreach (var e in entity)
{
result.Add(db.Update(e));
}
}
return result.All(x => true);
}
public async Task<bool> UpdateAllAsync(IEnumerable<T> entity)
{
ResetCache();
Log.Trace("Updating all entities");
var result = new HashSet<bool>();
using (var db = Config.DbConnection())
{
db.Open();
foreach (var e in entity)
{
result.Add(await db.UpdateAsync(e));
}
}
return result.All(x => true);
}
public async Task<int> InsertAsync(T entity)
{
ResetCache();
using (var cnn = Config.DbConnection())
{
cnn.Open();
return await cnn.InsertAsync(entity);
}
}
private void ResetCache()
{
Cache.Remove("Get");
Cache.Remove("GetAll");
}
public IEnumerable<T> GetAll()
{
using (var db = Config.DbConnection())
{
db.Open();
var result = db.GetAll<T>();
return result;
}
}
public async Task<IEnumerable<T>> GetAllAsync()
{
using (var db = Config.DbConnection())
{
db.Open();
var result = await db.GetAllAsync<T>();
return result;
}
}
}
}

@ -1,4 +1,5 @@
#region Copyright #region Copyright
// /************************************************************************ // /************************************************************************
// Copyright (c) 2016 Jamie Rees // Copyright (c) 2016 Jamie Rees
// File: GenericRepository.cs // File: GenericRepository.cs
@ -23,59 +24,38 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions; using Dapper.Contrib.Extensions;
using NLog; using NLog;
using PlexRequests.Helpers; using PlexRequests.Helpers;
namespace PlexRequests.Store.Repository namespace PlexRequests.Store.Repository
{ {
public class GenericRepository<T> : IRepository<T> where T : Entity public class GenericRepository<T> : BaseGenericRepository<T>, IRepository<T> where T : Entity
{ {
private ICacheProvider Cache { get; }
public GenericRepository(ISqliteConfiguration config, ICacheProvider cache) public GenericRepository(ISqliteConfiguration config, ICacheProvider cache) : base(config, cache)
{
Config = config;
Cache = cache;
}
private static Logger Log = LogManager.GetCurrentClassLogger();
private ISqliteConfiguration Config { get; }
public long Insert(T entity)
{ {
ResetCache();
using (var cnn = Config.DbConnection())
{
cnn.Open();
return cnn.Insert(entity);
}
} }
public IEnumerable<T> GetAll() public override T Get(string id)
{ {
throw new NotSupportedException("Get(string) is not supported. Use Get(int)");
using (var db = Config.DbConnection())
{
db.Open();
var result = db.GetAll<T>();
return result;
}
} }
public T Get(string id) public override Task<T> GetAsync(string id)
{ {
throw new NotSupportedException("Get(string) is not supported. Use Get(int)"); throw new NotSupportedException("GetAsync(string) is not supported. Use GetAsync(int)");
} }
public T Get(int id) public override T Get(int id)
{ {
var key = "Get" + id; var key = "Get" + id;
var item = Cache.GetOrSet( var item = Cache.GetOrSet(
@ -91,49 +71,22 @@ namespace PlexRequests.Store.Repository
return item; return item;
} }
public void Delete(T entity) public override async Task<T> GetAsync(int id)
{
ResetCache();
using (var db = Config.DbConnection())
{
db.Open();
db.Delete(entity);
}
}
public bool Update(T entity)
{
ResetCache();
Log.Trace("Updating entity");
Log.Trace(entity.DumpJson());
using (var db = Config.DbConnection())
{
db.Open();
return db.Update(entity);
}
}
public bool UpdateAll(IEnumerable<T> entity)
{ {
ResetCache(); var key = "Get" + id;
Log.Trace("Updating all entities"); var item = await Cache.GetOrSetAsync(
var result = new HashSet<bool>(); key,
async () =>
using (var db = Config.DbConnection())
{
db.Open();
foreach (var e in entity)
{ {
result.Add(db.Update(e)); using (var db = Config.DbConnection())
} {
} db.Open();
return result.All(x => true); return await db.GetAsync<T>(id);
}
});
return item;
} }
private void ResetCache()
{
Cache.Remove("Get");
Cache.Remove("GetAll");
}
} }
} }

@ -25,6 +25,7 @@
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace PlexRequests.Store.Repository namespace PlexRequests.Store.Repository
{ {
@ -35,12 +36,15 @@ namespace PlexRequests.Store.Repository
/// </summary> /// </summary>
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
long Insert(T entity); long Insert(T entity);
Task<int> InsertAsync(T entity);
/// <summary> /// <summary>
/// Gets all. /// Gets all.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
IEnumerable<T> GetAll(); IEnumerable<T> GetAll();
Task<IEnumerable<T>> GetAllAsync();
/// <summary> /// <summary>
/// Gets the specified identifier. /// Gets the specified identifier.
@ -48,12 +52,15 @@ namespace PlexRequests.Store.Repository
/// <param name="id">The identifier.</param> /// <param name="id">The identifier.</param>
/// <returns></returns> /// <returns></returns>
T Get(string id); T Get(string id);
Task<T> GetAsync(string id);
T Get(int id); T Get(int id);
Task<T> GetAsync(int id);
/// <summary> /// <summary>
/// Deletes the specified entity. /// Deletes the specified entity.
/// </summary> /// </summary>
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
void Delete(T entity); void Delete(T entity);
Task DeleteAsync(T entity);
/// <summary> /// <summary>
/// Updates the specified entity. /// Updates the specified entity.
@ -61,6 +68,7 @@ namespace PlexRequests.Store.Repository
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
/// <returns></returns> /// <returns></returns>
bool Update(T entity); bool Update(T entity);
Task<bool> UpdateAsync(T entity);
/// <summary> /// <summary>
/// Updates all. /// Updates all.
@ -68,5 +76,6 @@ namespace PlexRequests.Store.Repository
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
/// <returns></returns> /// <returns></returns>
bool UpdateAll(IEnumerable<T> entity); bool UpdateAll(IEnumerable<T> entity);
Task<bool> UpdateAllAsync(IEnumerable<T> entity);
} }
} }

@ -25,7 +25,7 @@
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using PlexRequests.Store.Models; using PlexRequests.Store.Models;
namespace PlexRequests.Store.Repository namespace PlexRequests.Store.Repository
@ -37,12 +37,14 @@ namespace PlexRequests.Store.Repository
/// </summary> /// </summary>
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
long Insert(GlobalSettings entity); long Insert(GlobalSettings entity);
Task<int> InsertAsync(GlobalSettings entity);
/// <summary> /// <summary>
/// Gets all. /// Gets all.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
IEnumerable<GlobalSettings> GetAll(); IEnumerable<GlobalSettings> GetAll();
Task<IEnumerable<GlobalSettings>> GetAllAsync();
/// <summary> /// <summary>
/// Gets the specified identifier. /// Gets the specified identifier.
@ -50,12 +52,14 @@ namespace PlexRequests.Store.Repository
/// <param name="settingsName">Name of the settings.</param> /// <param name="settingsName">Name of the settings.</param>
/// <returns></returns> /// <returns></returns>
GlobalSettings Get(string settingsName); GlobalSettings Get(string settingsName);
Task<GlobalSettings> GetAsync(string settingsName);
/// <summary> /// <summary>
/// Deletes the specified entity. /// Deletes the specified entity.
/// </summary> /// </summary>
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
/// <returns></returns> /// <returns></returns>
Task<bool> DeleteAsync(GlobalSettings entity);
bool Delete(GlobalSettings entity); bool Delete(GlobalSettings entity);
/// <summary> /// <summary>
@ -63,6 +67,7 @@ namespace PlexRequests.Store.Repository
/// </summary> /// </summary>
/// <param name="entity">The entity.</param> /// <param name="entity">The entity.</param>
/// <returns></returns> /// <returns></returns>
Task<bool> UpdateAsync(GlobalSettings entity);
bool Update(GlobalSettings entity); bool Update(GlobalSettings entity);

@ -26,7 +26,7 @@
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions; using Dapper.Contrib.Extensions;
using PlexRequests.Helpers; using PlexRequests.Helpers;
@ -57,6 +57,15 @@ namespace PlexRequests.Store.Repository
} }
} }
public async Task<int> InsertAsync(GlobalSettings entity)
{
ResetCache();
using (var con = Db.DbConnection())
{
return await con.InsertAsync(entity);
}
}
public IEnumerable<GlobalSettings> GetAll() public IEnumerable<GlobalSettings> GetAll()
{ {
var key = TypeName + "GetAll"; var key = TypeName + "GetAll";
@ -71,6 +80,20 @@ namespace PlexRequests.Store.Repository
return item; return item;
} }
public async Task<IEnumerable<GlobalSettings>> GetAllAsync()
{
var key = TypeName + "GetAll";
var item = await Cache.GetOrSetAsync(key, async() =>
{
using (var con = Db.DbConnection())
{
var page = await con.GetAllAsync<GlobalSettings>();
return page;
}
}, 5);
return item;
}
public GlobalSettings Get(string pageName) public GlobalSettings Get(string pageName)
{ {
var key = pageName + "Get"; var key = pageName + "Get";
@ -85,6 +108,38 @@ namespace PlexRequests.Store.Repository
return item; return item;
} }
public async Task<GlobalSettings> GetAsync(string settingsName)
{
var key = settingsName + "Get";
var item = await Cache.GetOrSetAsync(key, async() =>
{
using (var con = Db.DbConnection())
{
var page = await con.GetAllAsync<GlobalSettings>();
return page.SingleOrDefault(x => x.SettingsName == settingsName);
}
}, 5);
return item;
}
public async Task<bool> DeleteAsync(GlobalSettings entity)
{
ResetCache();
using (var con = Db.DbConnection())
{
return await con.DeleteAsync(entity);
}
}
public async Task<bool> UpdateAsync(GlobalSettings entity)
{
ResetCache();
using (var con = Db.DbConnection())
{
return await con.UpdateAsync(entity);
}
}
public bool Delete(GlobalSettings entity) public bool Delete(GlobalSettings entity)
{ {
ResetCache(); ResetCache();

@ -27,41 +27,31 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions; using Dapper.Contrib.Extensions;
using PlexRequests.Helpers;
using PlexRequests.Store.Repository; using PlexRequests.Store.Repository;
namespace PlexRequests.Store namespace PlexRequests.Store
{ {
public class UserRepository<T> : IRepository<T> where T : UserEntity public class UserRepository<T> : BaseGenericRepository<T>, IRepository<T> where T : UserEntity
{ {
public UserRepository(ISqliteConfiguration config) public UserRepository(ISqliteConfiguration config, ICacheProvider cache) : base(config, cache)
{ {
Config = config;
} }
private ISqliteConfiguration Config { get; } public override T Get(int id)
public long Insert(T entity)
{ {
using (var cnn = Config.DbConnection()) throw new NotSupportedException("Get(int) is not supported. Use Get(string)");
{
cnn.Open();
return cnn.Insert(entity);
}
} }
public IEnumerable<T> GetAll() public override Task<T> GetAsync(int id)
{ {
using (var db = Config.DbConnection()) throw new NotSupportedException("GetAsync(int) is not supported. Use GetAsync(string)");
{
db.Open();
var result = db.GetAll<T>();
return result;
}
} }
public T Get(string id) public override T Get(string id)
{ {
using (var db = Config.DbConnection()) using (var db = Config.DbConnection())
{ {
@ -72,33 +62,18 @@ namespace PlexRequests.Store
} }
} }
public T Get(int id) public override async Task<T> GetAsync(string id)
{
throw new NotSupportedException("Get(int) is not supported. Use Get(string)");
}
public void Delete(T entity)
{ {
using (var db = Config.DbConnection()) using (var db = Config.DbConnection())
{ {
db.Open(); db.Open();
db.Delete(entity); var result = await db.GetAllAsync<T>();
var selected = result.FirstOrDefault(x => x.UserGuid == id);
return selected;
} }
} }
public bool Update(T entity)
{
using (var db = Config.DbConnection())
{
db.Open();
return db.Update(entity);
}
}
public bool UpdateAll(IEnumerable<T> entity)
{
throw new NotSupportedException();
}
} }
} }

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

Loading…
Cancel
Save