Skip to content

Commit

Permalink
KESKENERÄINEN infotv bg admin
Browse files Browse the repository at this point in the history
  • Loading branch information
ArttuKuikka committed Dec 11, 2024
1 parent da4f5e1 commit 4a02595
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 145 deletions.
2 changes: 1 addition & 1 deletion src/Controllers/InfotvController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public async Task<IActionResult> GetBgForWeek(int week)
return Ok(bg);
}

public string GetLocalImage()
public static string GetLocalImage()
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BackgroundsPath")))
{
Expand Down
145 changes: 4 additions & 141 deletions src/Controllers/RuokalistaAdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using RuokalistaServer.Data;
using RuokalistaServer.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace RuokalistaServer.Controllers
{
Expand All @@ -23,144 +23,6 @@ public RuokalistaAdminController(ApplicationDbContext context)
_context = context;
}


public async Task<IActionResult> NewRandomBG(int? id)
{
if (id == null || id == 0)
{
throw new ArgumentException("Invalid id number (0 or NULL)");
}

var ruokalista = await _context.Ruokalista.FindAsync(id);
if( ruokalista == null)
{
throw new Exception("Ruokalista is null");
}

var week = ruokalista.WeekId;

var bg = _context.BackgroundForWeek.FirstOrDefault(x => x.WeekId == week && x.Year == DateTime.Today.Year);
if (bg == null)
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BackgroundsPath")))
{
throw new Exception("The 'BackgroundsPath' Environment variable is Null or empty");

}

string[] files = Directory.GetFiles(Environment.GetEnvironmentVariable("BackgroundsPath"));



var imageFiles = files?.Where(x => x.EndsWith(".jpg") || x.EndsWith(".png"));
var imageFileCount = imageFiles?.Count() ?? 0;

if (imageFileCount.Equals(0))
{
throw new Exception($"0 Image(.png or .jpg) files found in the 'BackgroundsPath', {files.Count()} files overall");
}


string currentMonthString = DateTime.Today.Month.ToString();
if (currentMonthString.Length == 1)
{
currentMonthString = "0" + currentMonthString;
}


var thisMonthsImageFiles = imageFiles?.Where(x => (Path.GetFileName(x)[4].ToString() + Path.GetFileName(x)[5].ToString()) == currentMonthString);

if (!(thisMonthsImageFiles?.Any() ?? false))
{
//jos tässä kuussa ei oo kuvia ota vaan jotai randomilla
thisMonthsImageFiles = imageFiles;
}

var thisMonthsImageFileCount = thisMonthsImageFiles?.Count() ?? 0;


Random random = new Random();
int randomNumber = random.Next(0, thisMonthsImageFileCount);
var newImage = thisMonthsImageFiles?.ElementAtOrDefault(randomNumber);
newImage = Path.GetFileName(newImage);

if (newImage == null)
{
throw new Exception("Error while picking new random backround picture, element is null at index");
}

bg = new BackgroundForWeek
{
FileName = System.Web.HttpUtility.HtmlEncode(newImage),
WeekId = week,
Year = DateTime.Today.Year
};

await _context.BackgroundForWeek.AddAsync(bg);
await _context.SaveChangesAsync();


}
else
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BackgroundsPath")))
{
throw new Exception("The 'BackgroundsPath' Environment variable is Null or empty");

}

string[] files = Directory.GetFiles(Environment.GetEnvironmentVariable("BackgroundsPath"));



var imageFiles = files?.Where(x => x.EndsWith(".jpg") || x.EndsWith(".png"));
var imageFileCount = imageFiles?.Count() ?? 0;

if (imageFileCount.Equals(0))
{
throw new Exception($"0 Image(.png or .jpg) files found in the 'BackgroundsPath', {files.Count()} files overall");
}



string currentMonthString = DateTime.Today.Month.ToString();
if (currentMonthString.Length == 1)
{
currentMonthString = "0" + currentMonthString;
}


var thisMonthsImageFiles = imageFiles?.Where(x => (Path.GetFileName(x)[4].ToString() + Path.GetFileName(x)[5].ToString()) == currentMonthString);

if (!(thisMonthsImageFiles?.Any() ?? false))
{
//jos tässä kuussa ei oo kuvia ota vaan jotai randomilla
thisMonthsImageFiles = imageFiles;
}

var thisMonthsImageFileCount = thisMonthsImageFiles?.Count() ?? 0;


Random random = new Random();
int randomNumber = random.Next(0, thisMonthsImageFileCount);
var newImage = thisMonthsImageFiles?.ElementAtOrDefault(randomNumber);
newImage = Path.GetFileName(newImage);


if (newImage == null)
{
throw new Exception("Error while picking new random backround picture, element is null at index");
}

bg.FileName = System.Web.HttpUtility.HtmlEncode(newImage);

_context.BackgroundForWeek.Update(bg);
await _context.SaveChangesAsync();
}
bg.FileName = "/infotv/GetBgByFilename?filename=" + System.Web.HttpUtility.HtmlEncode(bg.FileName);
return Ok(bg);
}

public async Task<IActionResult> SetBG(int? ruokalistaId)
{
if (ruokalistaId == null || ruokalistaId == 0)
Expand Down Expand Up @@ -198,9 +60,10 @@ public async Task<IActionResult> SetBG(BackgroundForWeek model)
bg.FileName = model.FileName;
await _context.SaveChangesAsync();

var ruokalista = _context.Ruokalista.First(x => x.WeekId == bg.WeekId && x.Year == bg.Year);

return Redirect("i/RuokalistaAdmin/SetBG?ruokalistaId=" + model.Id.ToString());
}
return Redirect("/RuokalistaAdmin/SetBG?ruokalistaId=" + ruokalista.Id.ToString());
}
// GET: RuokalistaAdmin
public async Task<IActionResult> Index()
{
Expand Down
12 changes: 9 additions & 3 deletions src/Views/RuokalistaAdmin/SetBG.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
@{
ViewData["Title"] = "Vaihda taustakuva";
}
<script src="/js/bg.js"></script>
<link rel="stylesheet" href="/css/bg.css" />

<h1>Vaihda taustakuva</h1>

Expand All @@ -12,15 +14,16 @@
<div class="row">
<div class="col-md-4" style="width:60%">
<p>Jos taustakuvaa ei ole valittu, valitaan se automaattisesti valitun viikon alkaessa</p>
<p>Voit lisätä kuvan linkin manuaalisesti, tai valita alla olevista vaihtoehdoista</p>
<p>Vinkki: Kuva näkyy kun pidät hiirtä sen päällä</p>
<form asp-action="SetBG">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<input type="hidden" asp-for="WeekId" />
<a class="btn btn-primary" asp-action="NewRandomBG" asp-route-id="@Model.Id">🏞️ Arvo uusi taustakuva</a>
<br />
<div class="form-group">
<label class="control-label">Tiedostonimi</label>
<input asp-for="FileName" class="form-control" />
<label class="control-label">Linkki kuvaan</label>
<input asp-for="FileName" id="FileName" class="form-control" />
<span asp-validation-for="FileName" class="text-danger"></span>
</div>
<br />
Expand All @@ -30,6 +33,9 @@
<input type="submit" value="Tallenna" class="btn btn-primary" />
</div>
</form>
<div id="ImageBrowser">

</div>
</div>
</div>

Expand Down
13 changes: 13 additions & 0 deletions src/wwwroot/css/bg.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.image-link {
cursor: pointer;
margin: 5px 0;
}

.image-preview {
position: absolute;
width: 200px;
height: 200px;
background-size: cover;
border: 1px solid #ccc;
z-index: 1000;
}
36 changes: 36 additions & 0 deletions src/wwwroot/js/bg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
document.addEventListener('DOMContentLoaded', () => {
var linkField = document.getElementById('FileName');
var imageBrowser = document.getElementById('ImageBrowser');

fetch('/RuokalistaAdmin/Testingimages')
.then(response => response.json())
.then(data => {
data.forEach(image => {
var imageLink = document.createElement('div');
imageLink.textContent = image.name;
imageLink.classList.add('image-link');
imageLink.dataset.url = image.url;

imageLink.addEventListener('mouseover', (event) => {
var preview = document.createElement('div');
preview.classList.add('image-preview');
preview.style.backgroundImage = `url(${event.target.dataset.url})`;
document.body.appendChild(preview);

imageLink.addEventListener('mousemove', (e) => {
preview.style.top = `${e.clientY + 10}px`;
preview.style.left = `${e.clientX + 10}px`;
});
});

imageLink.addEventListener('mouseout', () => {
var preview = document.querySelector('.image-preview');
if (preview) {
preview.remove();
}
});

imageBrowser.appendChild(imageLink);
});
});
});

0 comments on commit 4a02595

Please sign in to comment.