1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
|
using System.Security.Claims;
using System.Text.Json;
using Elements.Data;
using Elements.Data.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
namespace Elements.Backend.Controllers;
[ApiController]
public class SuggestionController : ControllerBase
{
private readonly ApplicationDbContext _dbContext;
public SuggestionController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
[Route("/suggestion/search")]
[HttpGet]
public async Task<IActionResult> GetSuggestions(int firstElementId, int secondElementId)
{
bool firstExists = await _dbContext.Elements.AnyAsync(e => e.Id == firstElementId);
bool secondExists = await _dbContext.Elements.AnyAsync(e => e.Id == secondElementId);
if (!firstExists || !secondExists)
return BadRequest();
IEnumerable<Suggestion> suggestions = await _dbContext.Suggestions
.Where(s =>
(s.FirstElementId == firstElementId && s.SecondElementId == secondElementId) ||
(s.FirstElementId == secondElementId && s.SecondElementId == firstElementId))
.Include(suggestion => suggestion.Votes)
.ToListAsync();
if (!suggestions.Any())
return NotFound();
DateTime votingEnd = suggestions.OrderBy(s => s.VotingEnd).First().VotingEnd;
var suggestionJson = suggestions.Select(s => new
{
s.Id,
s.Name,
Icon = Convert.ToBase64String(s.Icon),
s.FirstElementId,
s.SecondElementId,
Votes = s.Votes.Count,
s.UserId,
s.VotingEnd
}).ToList();
var result = new
{
VotingEnd = votingEnd,
Suggestions = suggestionJson
};
var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
return Ok(JsonSerializer.Serialize(result, serializeOptions));
}
public class SuggestionVoteModel
{
public required int Id { get; set; }
}
[Route("/suggestion/vote")]
[Authorize]
[HttpPost]
public async Task<IActionResult> PostVote([FromBody] SuggestionVoteModel vote)
{
Suggestion? suggestion = await _dbContext.Suggestions
.Include(s => s.Votes)
.FirstOrDefaultAsync(s => s.Id == vote.Id);
if (suggestion == null)
return NotFound();
IEnumerable<Claim> claims = User.Claims;
string? currentUserId = claims.FirstOrDefault(claim => claim.Type == "id")?.Value;
if (currentUserId == null)
return StatusCode(StatusCodes.Status500InternalServerError);
//Check if user is voting for own element
if (suggestion.UserId.ToString() == currentUserId)
return BadRequest();
//Check if user already voted for this element
IEnumerable<Vote> suggestionVotes = suggestion.Votes;
if (suggestionVotes.Any(s => s.UserId.ToString() == currentUserId))
return BadRequest();
Vote newVote = new()
{
UserId = int.Parse(currentUserId),
SuggestionId = suggestion.Id
};
await _dbContext.Votes.AddAsync(newVote);
await _dbContext.SaveChangesAsync();
return Ok();
}
public class SuggestionCreateModel
{
public required string Name { get; set; }
public required string IconBitmap { get; set; }
public required int FirstElementId { get; set; }
public required int SecondElementId { get; set; }
}
[Route("/suggestion/create")]
[Authorize]
[HttpPost]
public async Task<IActionResult> PostSuggestion([FromBody] SuggestionCreateModel suggestion)
{
IEnumerable<Claim> claims = User.Claims;
string? currentUserId = claims.FirstOrDefault(claim => claim.Type == "id")?.Value;
if (currentUserId == null)
return StatusCode(StatusCodes.Status500InternalServerError);
//User already suggested something
if (await _dbContext.Suggestions.AnyAsync(s => s.UserId.ToString() == currentUserId))
return BadRequest();
var exists = await _dbContext.Recipes.AnyAsync(r =>
(r.FirstElementId == suggestion.FirstElementId && r.SecondElementId == suggestion.SecondElementId) ||
(r.FirstElementId == suggestion.SecondElementId && r.SecondElementId == suggestion.FirstElementId));
if (exists)
return BadRequest();
Suggestion newSuggestion = new()
{
CreationDate = DateTime.UtcNow,
Name = suggestion.Name,
Icon = ConvertBitmapToPng(Convert.FromBase64String(suggestion.IconBitmap)),
FirstElementId = suggestion.FirstElementId,
SecondElementId = suggestion.SecondElementId,
VotingEnd = DateTime.UtcNow + TimeSpan.FromMinutes(1),
UserId = int.Parse(currentUserId)
};
await _dbContext.Suggestions.AddAsync(newSuggestion);
await _dbContext.SaveChangesAsync();
Vote newVote = new()
{
UserId = int.Parse(currentUserId),
SuggestionId = newSuggestion.Id
};
await _dbContext.Votes.AddAsync(newVote);
await _dbContext.SaveChangesAsync();
return Ok();
}
private static byte[] ConvertBitmapToPng(byte[] bitmapData)
{
Image<Argb32> image = Image.LoadPixelData<Argb32>(bitmapData, 16, 16);
using MemoryStream resultStream = new();
image.Save(resultStream, new PngEncoder());
return resultStream.ToArray();
}
}
|