diff --git a/PlexRequests.Core/IRequestService.cs b/PlexRequests.Core/IRequestService.cs index dabade7ae..20fe5e071 100644 --- a/PlexRequests.Core/IRequestService.cs +++ b/PlexRequests.Core/IRequestService.cs @@ -37,7 +37,9 @@ namespace PlexRequests.Core long AddRequest(RequestedModel model); Task AddRequestAsync(RequestedModel model); RequestedModel CheckRequest(int providerId); + Task CheckRequestAsync(int providerId); RequestedModel CheckRequest(string musicId); + Task CheckRequestAsync(string musicId); void DeleteRequest(RequestedModel request); Task DeleteRequestAsync(RequestedModel request); diff --git a/PlexRequests.Core/ISettingsService.cs b/PlexRequests.Core/ISettingsService.cs index 9687d920e..a1ef1341e 100644 --- a/PlexRequests.Core/ISettingsService.cs +++ b/PlexRequests.Core/ISettingsService.cs @@ -24,12 +24,18 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ************************************************************************/ #endregion + +using System.Threading.Tasks; + namespace PlexRequests.Core { public interface ISettingsService { T GetSettings(); + Task GetSettingsAsync(); bool SaveSettings(T model); + Task SaveSettingsAsync(T model); bool Delete(T model); + Task DeleteAsync(T model); } } \ No newline at end of file diff --git a/PlexRequests.Core/JsonRequestService.cs b/PlexRequests.Core/JsonRequestService.cs index 5a5ec2e4f..d44069271 100644 --- a/PlexRequests.Core/JsonRequestService.cs +++ b/PlexRequests.Core/JsonRequestService.cs @@ -78,6 +78,13 @@ namespace PlexRequests.Core return blob != null ? ByteConverterHelper.ReturnObject(blob.Content) : null; } + public async Task CheckRequestAsync(int providerId) + { + var blobs = await Repo.GetAllAsync(); + var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId); + return blob != null ? ByteConverterHelper.ReturnObject(blob.Content) : null; + } + public RequestedModel CheckRequest(string musicId) { var blobs = Repo.GetAll(); @@ -85,6 +92,13 @@ namespace PlexRequests.Core return blob != null ? ByteConverterHelper.ReturnObject(blob.Content) : null; } + public async Task CheckRequestAsync(string musicId) + { + var blobs = await Repo.GetAllAsync(); + var blob = blobs.FirstOrDefault(x => x.MusicId == musicId); + return blob != null ? ByteConverterHelper.ReturnObject(blob.Content) : null; + } + public void DeleteRequest(RequestedModel request) { var blob = Repo.Get(request.Id); diff --git a/PlexRequests.Core/SettingsServiceV2.cs b/PlexRequests.Core/SettingsServiceV2.cs index 3fb53cd35..5705544d0 100644 --- a/PlexRequests.Core/SettingsServiceV2.cs +++ b/PlexRequests.Core/SettingsServiceV2.cs @@ -24,6 +24,8 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ************************************************************************/ #endregion + +using System.Threading.Tasks; using Newtonsoft.Json; using PlexRequests.Core.SettingModels; @@ -62,6 +64,21 @@ namespace PlexRequests.Core return model; } + public async Task 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(result.Content, SerializerSettings.Settings); + + var model = obj; + + return model; + } + public bool SaveSettings(T model) { var entity = Repo.Get(EntityName); @@ -88,6 +105,31 @@ namespace PlexRequests.Core return result; } + public async Task 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) { var entity = Repo.Get(EntityName); @@ -100,6 +142,17 @@ namespace PlexRequests.Core return true; } + public async Task DeleteAsync(T model) + { + var entity = Repo.Get(EntityName); + if (entity != null) + { + return await Repo.DeleteAsync(entity); + } + + return true; + } + private string EncryptSettings(GlobalSettings settings) { return StringCipher.Encrypt(settings.Content, settings.SettingsName); diff --git a/PlexRequests.Core/Setup.cs b/PlexRequests.Core/Setup.cs index 4c6128259..87e16118e 100644 --- a/PlexRequests.Core/Setup.cs +++ b/PlexRequests.Core/Setup.cs @@ -187,7 +187,7 @@ namespace PlexRequests.Core { try { - var userMapper = new UserMapper(new UserRepository(Db)); + var userMapper = new UserMapper(new UserRepository(Db, new MemoryCacheProvider())); var users = userMapper.GetUsers(); foreach (var u in users) diff --git a/PlexRequests.Store/PlexRequests.Store.csproj b/PlexRequests.Store/PlexRequests.Store.csproj index 19578aee5..f9feb0c3b 100644 --- a/PlexRequests.Store/PlexRequests.Store.csproj +++ b/PlexRequests.Store/PlexRequests.Store.csproj @@ -61,6 +61,7 @@ + diff --git a/PlexRequests.Store/Repository/BaseGenericRepository.cs b/PlexRequests.Store/Repository/BaseGenericRepository.cs new file mode 100644 index 000000000..ac8c45203 --- /dev/null +++ b/PlexRequests.Store/Repository/BaseGenericRepository.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 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 GetAsync(int id); + public abstract T Get(int id); + public abstract Task 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 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 entity) + { + ResetCache(); + Log.Trace("Updating all entities"); + var result = new HashSet(); + + 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 UpdateAllAsync(IEnumerable entity) + { + ResetCache(); + Log.Trace("Updating all entities"); + var result = new HashSet(); + + 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 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 GetAll() + { + + using (var db = Config.DbConnection()) + { + db.Open(); + var result = db.GetAll(); + return result; + } + + } + public async Task> GetAllAsync() + { + + using (var db = Config.DbConnection()) + { + db.Open(); + var result = await db.GetAllAsync(); + return result; + } + + } + } +} \ No newline at end of file diff --git a/PlexRequests.Store/Repository/GenericRepository.cs b/PlexRequests.Store/Repository/GenericRepository.cs index 17e7b9c0f..6fb1e8216 100644 --- a/PlexRequests.Store/Repository/GenericRepository.cs +++ b/PlexRequests.Store/Repository/GenericRepository.cs @@ -1,4 +1,5 @@ #region Copyright + // /************************************************************************ // Copyright (c) 2016 Jamie Rees // File: GenericRepository.cs @@ -23,59 +24,38 @@ // 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 class GenericRepository : IRepository where T : Entity + public class GenericRepository : BaseGenericRepository, IRepository where T : Entity { - private ICacheProvider Cache { get; } - public GenericRepository(ISqliteConfiguration config, ICacheProvider cache) - { - Config = config; - Cache = cache; - } - - private static Logger Log = LogManager.GetCurrentClassLogger(); - - private ISqliteConfiguration Config { get; } - public long Insert(T entity) + + public GenericRepository(ISqliteConfiguration config, ICacheProvider cache) : base(config, cache) { - ResetCache(); - using (var cnn = Config.DbConnection()) - { - cnn.Open(); - return cnn.Insert(entity); - } + } - - public IEnumerable GetAll() + + public override T Get(string id) { - - using (var db = Config.DbConnection()) - { - db.Open(); - var result = db.GetAll(); - return result; - } - + throw new NotSupportedException("Get(string) is not supported. Use Get(int)"); } - public T Get(string id) + public override Task 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 item = Cache.GetOrSet( @@ -91,49 +71,22 @@ namespace PlexRequests.Store.Repository return item; } - public void Delete(T entity) - { - 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 entity) + public override async Task GetAsync(int id) { - ResetCache(); - Log.Trace("Updating all entities"); - var result = new HashSet(); - - using (var db = Config.DbConnection()) - { - db.Open(); - foreach (var e in entity) + var key = "Get" + id; + var item = await Cache.GetOrSetAsync( + key, + async () => { - result.Add(db.Update(e)); - } - } - return result.All(x => true); + using (var db = Config.DbConnection()) + { + db.Open(); + return await db.GetAsync(id); + } + }); + return item; } - private void ResetCache() - { - Cache.Remove("Get"); - Cache.Remove("GetAll"); - } + } -} +} \ No newline at end of file diff --git a/PlexRequests.Store/Repository/IRepository.cs b/PlexRequests.Store/Repository/IRepository.cs index 4d301047c..15cf2a2c5 100644 --- a/PlexRequests.Store/Repository/IRepository.cs +++ b/PlexRequests.Store/Repository/IRepository.cs @@ -25,6 +25,7 @@ // ************************************************************************/ #endregion using System.Collections.Generic; +using System.Threading.Tasks; namespace PlexRequests.Store.Repository { @@ -35,12 +36,15 @@ namespace PlexRequests.Store.Repository /// /// The entity. long Insert(T entity); + Task InsertAsync(T entity); /// /// Gets all. /// /// IEnumerable GetAll(); + Task> GetAllAsync(); + /// /// Gets the specified identifier. @@ -48,12 +52,15 @@ namespace PlexRequests.Store.Repository /// The identifier. /// T Get(string id); + Task GetAsync(string id); T Get(int id); + Task GetAsync(int id); /// /// Deletes the specified entity. /// /// The entity. void Delete(T entity); + Task DeleteAsync(T entity); /// /// Updates the specified entity. @@ -61,6 +68,7 @@ namespace PlexRequests.Store.Repository /// The entity. /// bool Update(T entity); + Task UpdateAsync(T entity); /// /// Updates all. @@ -68,5 +76,6 @@ namespace PlexRequests.Store.Repository /// The entity. /// bool UpdateAll(IEnumerable entity); + Task UpdateAllAsync(IEnumerable entity); } } diff --git a/PlexRequests.Store/Repository/ISettingsRepository.cs b/PlexRequests.Store/Repository/ISettingsRepository.cs index 393da6ef7..3f6761c66 100644 --- a/PlexRequests.Store/Repository/ISettingsRepository.cs +++ b/PlexRequests.Store/Repository/ISettingsRepository.cs @@ -25,7 +25,7 @@ // ************************************************************************/ #endregion using System.Collections.Generic; - +using System.Threading.Tasks; using PlexRequests.Store.Models; namespace PlexRequests.Store.Repository @@ -37,12 +37,14 @@ namespace PlexRequests.Store.Repository /// /// The entity. long Insert(GlobalSettings entity); + Task InsertAsync(GlobalSettings entity); /// /// Gets all. /// /// IEnumerable GetAll(); + Task> GetAllAsync(); /// /// Gets the specified identifier. @@ -50,12 +52,14 @@ namespace PlexRequests.Store.Repository /// Name of the settings. /// GlobalSettings Get(string settingsName); + Task GetAsync(string settingsName); /// /// Deletes the specified entity. /// /// The entity. /// + Task DeleteAsync(GlobalSettings entity); bool Delete(GlobalSettings entity); /// @@ -63,6 +67,7 @@ namespace PlexRequests.Store.Repository /// /// The entity. /// + Task UpdateAsync(GlobalSettings entity); bool Update(GlobalSettings entity); diff --git a/PlexRequests.Store/Repository/SettingsJsonRepository.cs b/PlexRequests.Store/Repository/SettingsJsonRepository.cs index 64d98f78a..50a59a6af 100644 --- a/PlexRequests.Store/Repository/SettingsJsonRepository.cs +++ b/PlexRequests.Store/Repository/SettingsJsonRepository.cs @@ -26,7 +26,7 @@ #endregion using System.Collections.Generic; using System.Linq; - +using System.Threading.Tasks; using Dapper.Contrib.Extensions; using PlexRequests.Helpers; @@ -57,6 +57,15 @@ namespace PlexRequests.Store.Repository } } + public async Task InsertAsync(GlobalSettings entity) + { + ResetCache(); + using (var con = Db.DbConnection()) + { + return await con.InsertAsync(entity); + } + } + public IEnumerable GetAll() { var key = TypeName + "GetAll"; @@ -71,6 +80,20 @@ namespace PlexRequests.Store.Repository return item; } + public async Task> GetAllAsync() + { + var key = TypeName + "GetAll"; + var item = await Cache.GetOrSetAsync(key, async() => + { + using (var con = Db.DbConnection()) + { + var page = await con.GetAllAsync(); + return page; + } + }, 5); + return item; + } + public GlobalSettings Get(string pageName) { var key = pageName + "Get"; @@ -85,6 +108,38 @@ namespace PlexRequests.Store.Repository return item; } + public async Task GetAsync(string settingsName) + { + var key = settingsName + "Get"; + var item = await Cache.GetOrSetAsync(key, async() => + { + using (var con = Db.DbConnection()) + { + var page = await con.GetAllAsync(); + return page.SingleOrDefault(x => x.SettingsName == settingsName); + } + }, 5); + return item; + } + + public async Task DeleteAsync(GlobalSettings entity) + { + ResetCache(); + using (var con = Db.DbConnection()) + { + return await con.DeleteAsync(entity); + } + } + + public async Task UpdateAsync(GlobalSettings entity) + { + ResetCache(); + using (var con = Db.DbConnection()) + { + return await con.UpdateAsync(entity); + } + } + public bool Delete(GlobalSettings entity) { ResetCache(); diff --git a/PlexRequests.Store/UserRepository.cs b/PlexRequests.Store/UserRepository.cs index 467e0487c..0a938e49f 100644 --- a/PlexRequests.Store/UserRepository.cs +++ b/PlexRequests.Store/UserRepository.cs @@ -27,41 +27,31 @@ using System; using System.Collections.Generic; using System.Linq; - +using System.Threading.Tasks; using Dapper.Contrib.Extensions; - +using PlexRequests.Helpers; using PlexRequests.Store.Repository; namespace PlexRequests.Store { - public class UserRepository : IRepository where T : UserEntity + public class UserRepository : BaseGenericRepository, IRepository where T : UserEntity { - public UserRepository(ISqliteConfiguration config) + public UserRepository(ISqliteConfiguration config, ICacheProvider cache) : base(config, cache) { - Config = config; + } - private ISqliteConfiguration Config { get; } - public long Insert(T entity) + public override T Get(int id) { - using (var cnn = Config.DbConnection()) - { - cnn.Open(); - return cnn.Insert(entity); - } + throw new NotSupportedException("Get(int) is not supported. Use Get(string)"); } - public IEnumerable GetAll() + public override Task GetAsync(int id) { - using (var db = Config.DbConnection()) - { - db.Open(); - var result = db.GetAll(); - return result; - } + throw new NotSupportedException("GetAsync(int) is not supported. Use GetAsync(string)"); } - public T Get(string id) + public override T Get(string id) { using (var db = Config.DbConnection()) { @@ -72,33 +62,18 @@ namespace PlexRequests.Store } } - public T Get(int id) - { - throw new NotSupportedException("Get(int) is not supported. Use Get(string)"); - } - - public void Delete(T entity) + public override async Task GetAsync(string id) { using (var db = Config.DbConnection()) { db.Open(); - db.Delete(entity); + var result = await db.GetAllAsync(); + 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 entity) - { - throw new NotSupportedException(); - } } } diff --git a/PlexRequests.UI/Modules/SearchModule.cs b/PlexRequests.UI/Modules/SearchModule.cs index 0979c1c6a..05c835350 100644 --- a/PlexRequests.UI/Modules/SearchModule.cs +++ b/PlexRequests.UI/Modules/SearchModule.cs @@ -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 UsersToNotifyRepo { get; } private static Logger Log = LogManager.GetCurrentClassLogger(); - private Negotiator RequestLoad() + private async Task 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(); foreach (MovieResult movie in apiMovies) { @@ -350,7 +350,7 @@ namespace PlexRequests.UI.Modules private async Task SearchMusic(string searchTerm) { var apiAlbums = new List(); - await Task.Factory.StartNew(() => MusicBrainzApi.SearchAlbum(searchTerm)).ContinueWith((t) => + await Task.Run(() => MusicBrainzApi.SearchAlbum(searchTerm)).ContinueWith((t) => { apiAlbums = t.Result.releases ?? new List(); }); @@ -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(); @@ -398,27 +398,26 @@ namespace PlexRequests.UI.Modules return Response.AsJson(viewAlbum); } - private Response RequestMovie(int movieId) + private async Task 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 /// /// The show identifier. /// The seasons. - /// if set to true [notify]. /// - private Response RequestTvShow(int showId, string seasons) + private async Task 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 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 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 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()