diff --git a/GanjooRazor/Areas/Admin/Pages/Banners.cshtml.cs b/GanjooRazor/Areas/Admin/Pages/Banners.cshtml.cs index ed199da4..2bf8ae83 100644 --- a/GanjooRazor/Areas/Admin/Pages/Banners.cshtml.cs +++ b/GanjooRazor/Areas/Admin/Pages/Banners.cshtml.cs @@ -40,7 +40,7 @@ namespace GanjooRazor.Areas.Admin.Pages { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { - var response = await secureClient.GetAsync($"{APIRoot.Url}/api/ganjoor/site/banners"); + var response = await secureClient.GetAsync($"{APIRoot.Url}/api/banners"); if (!response.IsSuccessStatusCode) { LastMessage = await response.Content.ReadAsStringAsync(); @@ -78,7 +78,7 @@ namespace GanjooRazor.Areas.Admin.Pages TargetUrl = url, Active = active }; - HttpResponseMessage response = await secureClient.PutAsync($"{APIRoot.Url}/api/ganjoor/site/banner/{id}", new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json")); + HttpResponseMessage response = await secureClient.PutAsync($"{APIRoot.Url}/api/banners/{id}", new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { LastMessage = await response.Content.ReadAsStringAsync(); @@ -102,7 +102,7 @@ namespace GanjooRazor.Areas.Admin.Pages { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { - var response = await secureClient.DeleteAsync($"{APIRoot.Url}/api/ganjoor/site/banner?id={id}"); + var response = await secureClient.DeleteAsync($"{APIRoot.Url}/api/banners?id={id}"); if (response.StatusCode != HttpStatusCode.OK) { @@ -133,7 +133,7 @@ namespace GanjooRazor.Areas.Admin.Pages var fileContent = stream.ToArray(); form.Add(new ByteArrayContent(fileContent, 0, fileContent.Length), Upload.Image.FileName, Upload.Image.FileName); - HttpResponseMessage response = await secureClient.PostAsync($"{APIRoot.Url}/api/ganjoor/site/banner", form); + HttpResponseMessage response = await secureClient.PostAsync($"{APIRoot.Url}/api/banners", form); if (!response.IsSuccessStatusCode) { LastMessage = await response.Content.ReadAsStringAsync(); diff --git a/GanjooRazor/Pages/Index.cshtml.cs b/GanjooRazor/Pages/Index.cshtml.cs index f9fe5c83..1b874cf5 100644 --- a/GanjooRazor/Pages/Index.cshtml.cs +++ b/GanjooRazor/Pages/Index.cshtml.cs @@ -530,7 +530,7 @@ namespace GanjooRazor.Pages if (IsPoemPage) { - var bannerQuery = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/site/banner"); + var bannerQuery = await _httpClient.GetAsync($"{APIRoot.Url}/api/banners/random"); bannerQuery.EnsureSuccessStatusCode(); string bannerResponse = await bannerQuery.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(bannerResponse)) diff --git a/GanjooRazor/appsettings.json b/GanjooRazor/appsettings.json index 3b721e74..c9528db1 100644 --- a/GanjooRazor/appsettings.json +++ b/GanjooRazor/appsettings.json @@ -8,7 +8,7 @@ }, "AllowedHosts": "*", "GoogleAnalyticsCode": "", - "APIRoot": "https://ganjgah.ir", + "APIRoot": "http://localhost:3439", "GlobalAPIRoot": "https://ganjgah.ir", "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=museum;Trusted_Connection=True;MultipleActiveResultSets=true" diff --git a/RMuseum/Controllers/GanjoorController.cs b/RMuseum/Controllers/GanjoorController.cs index 56fb8083..e634877a 100644 --- a/RMuseum/Controllers/GanjoorController.cs +++ b/RMuseum/Controllers/GanjoorController.cs @@ -1000,179 +1000,7 @@ namespace RMuseum.Controllers return Ok(res.Result); } - /// - /// add site banner (send form) with these fields: alt, url and an image attachment - /// - /// - [HttpPost] - [Route("site/banner")] - [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] - [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel))] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - [ProducesResponseType((int)HttpStatusCode.Unauthorized)] - public async Task AddSiteBanner() - { - try - { - if (!Request.Form.TryGetValue("alt", out Microsoft.Extensions.Primitives.StringValues alt)) - { - return BadRequest("alt is null"); - } - if (!Request.Form.TryGetValue("url", out Microsoft.Extensions.Primitives.StringValues url)) - { - return BadRequest("url is null"); - } - if(Request.Form.Files.Count != 1) - { - return BadRequest("a single image is not provided"); - } - using Stream stream = Request.Form.Files[0].OpenReadStream(); - RServiceResult res = await _ganjoorService.AddSiteBanner(stream, Request.Form.Files[0].FileName, alt.ToString(), url.ToString(), false); - if (!string.IsNullOrEmpty(res.ExceptionString)) - { - return BadRequest(res.ExceptionString); - } - return Ok(res.Result); - } - catch (Exception exp) - { - return BadRequest(exp.ToString()); - } - } - - /// - /// modify site banner - /// - /// - /// - /// - [HttpPut] - [Route("site/banner/{id}")] - [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] - [ProducesResponseType((int)HttpStatusCode.OK)] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - [ProducesResponseType((int)HttpStatusCode.Unauthorized)] - [ProducesResponseType((int)HttpStatusCode.NotFound)] - public async Task ModifySiteBanner(int id, [FromBody] GanjoorSiteBannerModifyViewModel model) - { - try - { - - RServiceResult res = await _ganjoorService.ModifySiteBanner(id, model.AlternateText, model.TargetUrl, model.Active); - - if (!string.IsNullOrEmpty(res.ExceptionString)) - { - return BadRequest(res.ExceptionString); - } - - if(!res.Result) - { - return NotFound(); - } - - return Ok(); - } - catch (Exception exp) - { - return BadRequest(exp.ToString()); - } - } - - /// - /// delete site banner - /// - /// - /// - [HttpDelete] - [Route("site/banner")] - [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] - [ProducesResponseType((int)HttpStatusCode.OK)] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - [ProducesResponseType((int)HttpStatusCode.Unauthorized)] - [ProducesResponseType((int)HttpStatusCode.NotFound)] - public async Task DeleteSiteBanner(int id) - { - try - { - - RServiceResult res = await _ganjoorService.DeleteSiteBanner(id); - - if (!string.IsNullOrEmpty(res.ExceptionString)) - { - return BadRequest(res.ExceptionString); - } - - if (!res.Result) - { - return NotFound(); - } - - return Ok(); - } - catch (Exception exp) - { - return BadRequest(exp.ToString()); - } - } - - /// - /// get all defined site banners - /// - /// - - [HttpGet] - [Route("site/banners")] - [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] - [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel[]))] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - [ProducesResponseType((int)HttpStatusCode.Unauthorized)] - public async Task GetSiteBanners() - { - try - { - RServiceResult res = await _ganjoorService.GetSiteBanners(); - - if (!string.IsNullOrEmpty(res.ExceptionString)) - { - return BadRequest(res.ExceptionString); - } - return Ok(res.Result); - } - catch (Exception exp) - { - return BadRequest(exp.ToString()); - } - } - - /// - /// get a random active site banner - /// - /// - [HttpGet] - [Route("site/banner")] - [AllowAnonymous] - [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel))] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - [ProducesResponseType((int)HttpStatusCode.Unauthorized)] - [ProducesResponseType((int)HttpStatusCode.NotFound)] - public async Task GetARandomActiveSiteBanner() - { - try - { - RServiceResult res = await _ganjoorService.GetARandomActiveSiteBanner(); - - if (!string.IsNullOrEmpty(res.ExceptionString)) - { - return BadRequest(res.ExceptionString); - } - - return Ok(res.Result); //this might be null - } - catch (Exception exp) - { - return BadRequest(exp.ToString()); - } - } + /// /// examine site pages for broken links diff --git a/RMuseum/Controllers/SiteBannersController.cs b/RMuseum/Controllers/SiteBannersController.cs new file mode 100644 index 00000000..fc780f7b --- /dev/null +++ b/RMuseum/Controllers/SiteBannersController.cs @@ -0,0 +1,203 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using RMuseum.Models.Auth.Memory; +using RMuseum.Models.Ganjoor.ViewModels; +using RMuseum.Services; +using RSecurityBackend.Models.Generic; +using System; +using System.IO; +using System.Net; +using System.Threading.Tasks; + +namespace RMuseum.Controllers +{ + [Produces("application/json")] + [Route("api/banners")] + public class SiteBannersController : Controller + { + /// + /// add site banner (send form) with these fields: alt, url and an image attachment + /// + /// + [HttpPost] + [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] + [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel))] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.Unauthorized)] + public async Task AddSiteBanner() + { + try + { + if (!Request.Form.TryGetValue("alt", out Microsoft.Extensions.Primitives.StringValues alt)) + { + return BadRequest("alt is null"); + } + if (!Request.Form.TryGetValue("url", out Microsoft.Extensions.Primitives.StringValues url)) + { + return BadRequest("url is null"); + } + if (Request.Form.Files.Count != 1) + { + return BadRequest("a single image is not provided"); + } + using Stream stream = Request.Form.Files[0].OpenReadStream(); + RServiceResult res = await _bannersService.AddSiteBanner(stream, Request.Form.Files[0].FileName, alt.ToString(), url.ToString(), false); + if (!string.IsNullOrEmpty(res.ExceptionString)) + { + return BadRequest(res.ExceptionString); + } + return Ok(res.Result); + } + catch (Exception exp) + { + return BadRequest(exp.ToString()); + } + } + + /// + /// modify site banner + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] + [ProducesResponseType((int)HttpStatusCode.OK)] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.Unauthorized)] + [ProducesResponseType((int)HttpStatusCode.NotFound)] + public async Task ModifySiteBanner(int id, [FromBody] GanjoorSiteBannerModifyViewModel model) + { + try + { + + RServiceResult res = await _bannersService.ModifySiteBanner(id, model.AlternateText, model.TargetUrl, model.Active); + + if (!string.IsNullOrEmpty(res.ExceptionString)) + { + return BadRequest(res.ExceptionString); + } + + if (!res.Result) + { + return NotFound(); + } + + return Ok(); + } + catch (Exception exp) + { + return BadRequest(exp.ToString()); + } + } + + /// + /// delete site banner + /// + /// + /// + [HttpDelete] + [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] + [ProducesResponseType((int)HttpStatusCode.OK)] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.Unauthorized)] + [ProducesResponseType((int)HttpStatusCode.NotFound)] + public async Task DeleteSiteBanner(int id) + { + try + { + + RServiceResult res = await _bannersService.DeleteSiteBanner(id); + + if (!string.IsNullOrEmpty(res.ExceptionString)) + { + return BadRequest(res.ExceptionString); + } + + if (!res.Result) + { + return NotFound(); + } + + return Ok(); + } + catch (Exception exp) + { + return BadRequest(exp.ToString()); + } + } + + /// + /// get all defined site banners + /// + /// + + [HttpGet] + [Authorize(Policy = RMuseumSecurableItem.GanjoorEntityShortName + ":" + RMuseumSecurableItem.Banners)] + [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel[]))] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.Unauthorized)] + public async Task GetSiteBanners() + { + try + { + RServiceResult res = await _bannersService.GetSiteBanners(); + + if (!string.IsNullOrEmpty(res.ExceptionString)) + { + return BadRequest(res.ExceptionString); + } + return Ok(res.Result); + } + catch (Exception exp) + { + return BadRequest(exp.ToString()); + } + } + + /// + /// get a random active site banner + /// + /// + [HttpGet] + [Route("random")] + [AllowAnonymous] + [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(GanjoorSiteBannerViewModel))] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.Unauthorized)] + [ProducesResponseType((int)HttpStatusCode.NotFound)] + public async Task GetARandomActiveSiteBanner() + { + try + { + RServiceResult res = await _bannersService.GetARandomActiveSiteBanner(); + + if (!string.IsNullOrEmpty(res.ExceptionString)) + { + return BadRequest(res.ExceptionString); + } + + return Ok(res.Result); //this might be null + } + catch (Exception exp) + { + return BadRequest(exp.ToString()); + } + } + + /// + /// Ganjoor Service + /// + + protected readonly ISiteBannersService _bannersService; + + /// + /// constructor + /// + /// + public SiteBannersController(ISiteBannersService bannersService) + { + _bannersService = bannersService; + } + } +} diff --git a/RMuseum/RMuseum.xml b/RMuseum/RMuseum.xml index c6ef6fa6..f10030f9 100644 --- a/RMuseum/RMuseum.xml +++ b/RMuseum/RMuseum.xml @@ -885,39 +885,6 @@ - - - add site banner (send form) with these fields: alt, url and an image attachment - - - - - - modify site banner - - - - - - - - delete site banner - - - - - - - get all defined site banners - - - - - - get a random active site banner - - - examine site pages for broken links @@ -1288,6 +1255,50 @@ + + + add site banner (send form) with these fields: alt, url and an image attachment + + + + + + modify site banner + + + + + + + + delete site banner + + + + + + + get all defined site banners + + + + + + get a random active site banner + + + + + + Ganjoor Service + + + + + constructor + + + Museum Database Context @@ -6785,46 +6796,6 @@ - - - Add site banner - - - - - - - - - - - modify site banner - - - - - - - - - - delete site banner - - - - - - - get site banners - - - - - - get a random site banner - - - get a random poem (2 = from hafez) @@ -7937,46 +7908,6 @@ - - - Add site banner - - - - - - - - - - - modify site banner - - - - - - - - - - delete site banner - - - - - - - get site banners - - - - - - get a random site banner - - - examine site pages for broken links @@ -8280,6 +8211,74 @@ + + + ganjoor.net banners service + + + + + Add site banner + + + + + + + + + + + modify site banner + + + + + + + + + + delete site banner + + + + + + + get site banners + + + + + + get a random site banner + + + + + + Database Context + + + + + Image File Service + + + + + IMemoryCache + + + + + constructor + + + + + Audio Narration Service Implementation @@ -8829,6 +8828,46 @@ Upload Enabled (temporary switch off/on for upload) + + + Add site banner + + + + + + + + + + + modify site banner + + + + + + + + + + delete site banner + + + + + + + get site banners + + + + + + get a random site banner + + + //https://mattfrear.com/2018/07/21/add-an-authorization-header-to-your-swagger-ui-with-swashbuckle-revisited/ diff --git a/RMuseum/Services/IGanjoorService.cs b/RMuseum/Services/IGanjoorService.cs index 0d598d72..6a1ed231 100644 --- a/RMuseum/Services/IGanjoorService.cs +++ b/RMuseum/Services/IGanjoorService.cs @@ -3,7 +3,6 @@ using RMuseum.Models.Ganjoor.ViewModels; using RMuseum.Models.GanjoorAudio.ViewModels; using RSecurityBackend.Models.Generic; using System; -using System.IO; using System.Threading.Tasks; namespace RMuseum.Services @@ -258,45 +257,6 @@ namespace RMuseum.Services /// Task> GetGanjoorMetres(); - /// - /// Add site banner - /// - /// - /// - /// - /// - /// - /// - Task> AddSiteBanner(Stream imageStream, string fileName, string alternateText, string targetUrl, bool active); - - /// - /// modify site banner - /// - /// - /// - /// - /// - /// - Task> ModifySiteBanner(int id, string alternateText, string targetUrl, bool active); - - /// - /// delete site banner - /// - /// - /// - Task> DeleteSiteBanner(int id); - - /// - /// get site banners - /// - /// - Task> GetSiteBanners(); - - /// - /// get a random site banner - /// - /// - Task> GetARandomActiveSiteBanner(); /// /// get a random poem (2 = from hafez) diff --git a/RMuseum/Services/ISiteBannersService.cs b/RMuseum/Services/ISiteBannersService.cs new file mode 100644 index 00000000..72e72128 --- /dev/null +++ b/RMuseum/Services/ISiteBannersService.cs @@ -0,0 +1,50 @@ +using RMuseum.Models.Ganjoor.ViewModels; +using RSecurityBackend.Models.Generic; +using System.IO; +using System.Threading.Tasks; + +namespace RMuseum.Services +{ + public interface ISiteBannersService + { + /// + /// Add site banner + /// + /// + /// + /// + /// + /// + /// + Task> AddSiteBanner(Stream imageStream, string fileName, string alternateText, string targetUrl, bool active); + + /// + /// modify site banner + /// + /// + /// + /// + /// + /// + Task> ModifySiteBanner(int id, string alternateText, string targetUrl, bool active); + + /// + /// delete site banner + /// + /// + /// + Task> DeleteSiteBanner(int id); + + /// + /// get site banners + /// + /// + Task> GetSiteBanners(); + + /// + /// get a random site banner + /// + /// + Task> GetARandomActiveSiteBanner(); + } +} diff --git a/RMuseum/Services/Implementation/GanjoorService.cs b/RMuseum/Services/Implementation/GanjoorService.cs index ff51cf28..63e72d40 100644 --- a/RMuseum/Services/Implementation/GanjoorService.cs +++ b/RMuseum/Services/Implementation/GanjoorService.cs @@ -17,8 +17,6 @@ using System.Threading.Tasks; using RMuseum.Models.Artifact; using RSecurityBackend.Services.Implementation; using DNTPersianUtils.Core; -using System.IO; -using RSecurityBackend.Models.Image; using Microsoft.Extensions.Caching.Memory; namespace RMuseum.Services.Implementation @@ -2212,182 +2210,6 @@ namespace RMuseum.Services.Implementation } } - /// - /// Add site banner - /// - /// - /// - /// - /// - /// - /// - public async Task> AddSiteBanner(Stream imageStream, string fileName, string alternateText, string targetUrl, bool active) - { - try - { - RServiceResult image = await _imageFileService.Add(null, imageStream, fileName, "SiteBanners"); - - if (!string.IsNullOrEmpty(image.ExceptionString)) - { - return new RServiceResult(null, image.ExceptionString); - } - - - GanjoorSiteBanner banner = new GanjoorSiteBanner() - { - RImage = image.Result, - AlternateText = alternateText, - TargetUrl = targetUrl, - Active = active - }; - - _context.GanjoorSiteBanners.Add(banner); - await _context.SaveChangesAsync(); - - return new RServiceResult - ( - new GanjoorSiteBannerViewModel() - { - Id = banner.Id, - ImageUrl = $"api/rimages/{banner.RImageId}.jpg", - AlternateText = banner.AlternateText, - TargetUrl = banner.TargetUrl, - Active = banner.Active - } - ); - - } - catch(Exception exp) - { - return new RServiceResult(null, exp.ToString()); - } - } - - /// - /// modify site banner - /// - /// - /// - /// - /// - /// - public async Task> ModifySiteBanner(int id, string alternateText, string targetUrl, bool active) - { - try - { - GanjoorSiteBanner target = await _context.GanjoorSiteBanners.Where(b => b.Id == id).SingleOrDefaultAsync(); - if(target == null) - return new RServiceResult(false);//not found - - target.AlternateText = alternateText; - target.TargetUrl = targetUrl; - target.Active = active; - - _context.GanjoorSiteBanners.Update(target); - - await _context.SaveChangesAsync(); - - return new RServiceResult(true); - - } - catch (Exception exp) - { - return new RServiceResult(false, exp.ToString()); - } - } - - /// - /// delete site banner - /// - /// - /// - public async Task> DeleteSiteBanner(int id) - { - try - { - GanjoorSiteBanner target = await _context.GanjoorSiteBanners.Where(b => b.Id == id).SingleOrDefaultAsync(); - if (target == null) - return new RServiceResult(false);//not found - - _context.GanjoorSiteBanners.Remove(target); - - await _context.SaveChangesAsync(); - - return new RServiceResult(true); - - } - catch (Exception exp) - { - return new RServiceResult(false, exp.ToString()); - } - } - - /// - /// get site banners - /// - /// - public async Task> GetSiteBanners() - { - try - { - return new RServiceResult( - await _context.GanjoorSiteBanners - .Select(b => new GanjoorSiteBannerViewModel() - { - Id = b.Id, - ImageUrl = $"api/rimages/{b.RImageId}.jpg", - AlternateText = b.AlternateText, - TargetUrl = b.TargetUrl, - Active = b.Active - }).ToArrayAsync() - ); - } - catch(Exception exp) - { - return new RServiceResult(null, exp.ToString()); - } - } - - /// - /// get a random site banner - /// - /// - public async Task> GetARandomActiveSiteBanner() - { - try - { - var cacheKeyForIdSet = $"GetARandomActiveSiteBanner::idSet"; - if(!_memoryCache.TryGetValue(cacheKeyForIdSet, out int[] idSet)) - { - idSet = await _context.GanjoorSiteBanners.Where(b => b.Active == true).Select(b => b.Id).ToArrayAsync(); - _memoryCache.Set(cacheKeyForIdSet, idSet); - } - if (idSet.Length == 0) - return new RServiceResult(null);//not found - - Random rnd = new Random(DateTime.Now.Millisecond); - int id = idSet[rnd.Next(0, idSet.Length)]; - - return new RServiceResult( - await _context.GanjoorSiteBanners - .Where(b => b.Id == id) - .Select(b => new GanjoorSiteBannerViewModel() - { - Id = b.Id, - ImageUrl = $"api/rimages/{b.RImageId}.jpg", - AlternateText = b.AlternateText, - TargetUrl = b.TargetUrl, - Active = b.Active - }).AsNoTracking().SingleAsync() - ); - - } - catch (Exception exp) - { - return new RServiceResult(null, exp.ToString()); - } - } - /// /// examine site pages for broken links /// diff --git a/RMuseum/Services/Implementation/SiteBannersService.cs b/RMuseum/Services/Implementation/SiteBannersService.cs new file mode 100644 index 00000000..5c2957f2 --- /dev/null +++ b/RMuseum/Services/Implementation/SiteBannersService.cs @@ -0,0 +1,227 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; +using RMuseum.DbContext; +using RMuseum.Models.Ganjoor; +using RMuseum.Models.Ganjoor.ViewModels; +using RSecurityBackend.Models.Generic; +using RSecurityBackend.Models.Image; +using RSecurityBackend.Services; +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace RMuseum.Services.Implementation +{ + /// + /// ganjoor.net banners service + /// + public class SiteBannersService : ISiteBannersService + { + /// + /// Add site banner + /// + /// + /// + /// + /// + /// + /// + public async Task> AddSiteBanner(Stream imageStream, string fileName, string alternateText, string targetUrl, bool active) + { + try + { + RServiceResult image = await _imageFileService.Add(null, imageStream, fileName, "SiteBanners"); + + if (!string.IsNullOrEmpty(image.ExceptionString)) + { + return new RServiceResult(null, image.ExceptionString); + } + + + GanjoorSiteBanner banner = new GanjoorSiteBanner() + { + RImage = image.Result, + AlternateText = alternateText, + TargetUrl = targetUrl, + Active = active + }; + + _context.GanjoorSiteBanners.Add(banner); + await _context.SaveChangesAsync(); + + return new RServiceResult + ( + new GanjoorSiteBannerViewModel() + { + Id = banner.Id, + ImageUrl = $"api/rimages/{banner.RImageId}.jpg", + AlternateText = banner.AlternateText, + TargetUrl = banner.TargetUrl, + Active = banner.Active + } + ); + + } + catch (Exception exp) + { + return new RServiceResult(null, exp.ToString()); + } + } + + /// + /// modify site banner + /// + /// + /// + /// + /// + /// + public async Task> ModifySiteBanner(int id, string alternateText, string targetUrl, bool active) + { + try + { + GanjoorSiteBanner target = await _context.GanjoorSiteBanners.Where(b => b.Id == id).SingleOrDefaultAsync(); + if (target == null) + return new RServiceResult(false);//not found + + target.AlternateText = alternateText; + target.TargetUrl = targetUrl; + target.Active = active; + + _context.GanjoorSiteBanners.Update(target); + + await _context.SaveChangesAsync(); + + return new RServiceResult(true); + + } + catch (Exception exp) + { + return new RServiceResult(false, exp.ToString()); + } + } + + /// + /// delete site banner + /// + /// + /// + public async Task> DeleteSiteBanner(int id) + { + try + { + GanjoorSiteBanner target = await _context.GanjoorSiteBanners.Where(b => b.Id == id).SingleOrDefaultAsync(); + if (target == null) + return new RServiceResult(false);//not found + + _context.GanjoorSiteBanners.Remove(target); + + await _context.SaveChangesAsync(); + + return new RServiceResult(true); + + } + catch (Exception exp) + { + return new RServiceResult(false, exp.ToString()); + } + } + + /// + /// get site banners + /// + /// + public async Task> GetSiteBanners() + { + try + { + return new RServiceResult( + await _context.GanjoorSiteBanners + .Select(b => new GanjoorSiteBannerViewModel() + { + Id = b.Id, + ImageUrl = $"api/rimages/{b.RImageId}.jpg", + AlternateText = b.AlternateText, + TargetUrl = b.TargetUrl, + Active = b.Active + }).ToArrayAsync() + ); + } + catch (Exception exp) + { + return new RServiceResult(null, exp.ToString()); + } + } + + /// + /// get a random site banner + /// + /// + public async Task> GetARandomActiveSiteBanner() + { + try + { + var cacheKeyForIdSet = $"GetARandomActiveSiteBanner::idSet"; + if (!_memoryCache.TryGetValue(cacheKeyForIdSet, out int[] idSet)) + { + idSet = await _context.GanjoorSiteBanners.Where(b => b.Active == true).Select(b => b.Id).ToArrayAsync(); + _memoryCache.Set(cacheKeyForIdSet, idSet); + } + if (idSet.Length == 0) + return new RServiceResult(null);//not found + + Random rnd = new Random(DateTime.Now.Millisecond); + int id = idSet[rnd.Next(0, idSet.Length)]; + + return new RServiceResult( + await _context.GanjoorSiteBanners + .Where(b => b.Id == id) + .Select(b => new GanjoorSiteBannerViewModel() + { + Id = b.Id, + ImageUrl = $"api/rimages/{b.RImageId}.jpg", + AlternateText = b.AlternateText, + TargetUrl = b.TargetUrl, + Active = b.Active + }).AsNoTracking().SingleAsync() + ); + + } + catch (Exception exp) + { + return new RServiceResult(null, exp.ToString()); + } + } + + /// + /// Database Context + /// + protected readonly RMuseumDbContext _context; + + /// + /// Image File Service + /// + protected readonly IImageFileService _imageFileService; + + /// + /// IMemoryCache + /// + protected readonly IMemoryCache _memoryCache; + + + + /// + /// constructor + /// + /// + /// + /// + public SiteBannersService(RMuseumDbContext context,IImageFileService imageFileService, IMemoryCache memoryCache) + { + _context = context; + _imageFileService = imageFileService; + _memoryCache = memoryCache; + } + } +} diff --git a/RMuseum/Startup.cs b/RMuseum/Startup.cs index 04760b97..f087ce40 100644 --- a/RMuseum/Startup.cs +++ b/RMuseum/Startup.cs @@ -274,6 +274,9 @@ namespace RMuseum //long running job service services.AddTransient(); + //site banner service + services.AddTransient(); + //upload limit for IIS services.Configure(options => {