-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathPhotosController.cs
More file actions
250 lines (202 loc) · 9.63 KB
/
PhotosController.cs
File metadata and controls
250 lines (202 loc) · 9.63 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
using Discord;
using LBPUnion.ProjectLighthouse.Configuration;
using LBPUnion.ProjectLighthouse.Database;
using LBPUnion.ProjectLighthouse.Extensions;
using LBPUnion.ProjectLighthouse.Files;
using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.Logging;
using LBPUnion.ProjectLighthouse.Servers.GameServer.Types;
using LBPUnion.ProjectLighthouse.Types.Entities.Level;
using LBPUnion.ProjectLighthouse.Types.Entities.Profile;
using LBPUnion.ProjectLighthouse.Types.Entities.Token;
using LBPUnion.ProjectLighthouse.Types.Filter;
using LBPUnion.ProjectLighthouse.Types.Levels;
using LBPUnion.ProjectLighthouse.Types.Logging;
using LBPUnion.ProjectLighthouse.Types.Serialization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace LBPUnion.ProjectLighthouse.Servers.GameServer.Controllers.Resources;
public class PhotosController : GameController
{
private readonly DatabaseContext database;
public PhotosController(DatabaseContext database)
{
this.database = database;
}
[HttpPost("uploadPhoto")]
public async Task<IActionResult> UploadPhoto()
{
GameTokenEntity token = this.GetToken();
// Deny request if in read-only mode
if (ServerConfiguration.Instance.UserGeneratedContentLimits.ReadOnlyMode) return this.BadRequest();
int photoCount = await this.database.Photos.CountAsync(p => p.CreatorId == token.UserId);
if (photoCount >= ServerConfiguration.Instance.UserGeneratedContentLimits.PhotosQuota) return this.BadRequest();
GamePhoto? photo = await this.DeserializeBody<GamePhoto>();
if (photo == null) return this.BadRequest();
string[] photoHashes =
{
photo.LargeHash, photo.MediumHash, photo.SmallHash, photo.PlanHash,
};
if (photoHashes.Any(hash => !FileHelper.ResourceExists(hash))) return this.BadRequest();
foreach (PhotoEntity p in this.database.Photos.Where(p => p.CreatorId == token.UserId))
{
if (p.LargeHash == photo.LargeHash) return this.Ok(); // photo already uploaded
if (p.MediumHash == photo.MediumHash) return this.Ok();
if (p.SmallHash == photo.SmallHash) return this.Ok();
if (p.PlanHash == photo.PlanHash) return this.Ok();
}
PhotoEntity photoEntity = new()
{
CreatorId = token.UserId,
SmallHash = photo.SmallHash,
MediumHash = photo.MediumHash,
LargeHash = photo.LargeHash,
PlanHash = photo.PlanHash,
Timestamp = photo.Timestamp,
};
if (photo.LevelInfo?.RootLevel != null)
{
bool validLevel = false;
PhotoSlot photoSlot = photo.LevelInfo;
if (photoSlot.SlotType is SlotType.Pod or SlotType.Local) photoSlot.SlotId = 0;
switch (photoSlot.SlotType)
{
case SlotType.User:
{
// We'll grab the slot by the RootLevel and see what happens from here.
SlotEntity? slot = await this.database.Slots.FirstOrDefaultAsync(s => s.Type == SlotType.User && s.ResourceCollection.Contains(photoSlot.RootLevel));
if (slot == null) break;
if (!string.IsNullOrEmpty(slot.RootLevel)) validLevel = true;
if (slot.IsAdventurePlanet) photoSlot.SlotId = slot.SlotId;
break;
}
case SlotType.Pod:
case SlotType.Local:
case SlotType.Developer:
{
SlotEntity? slot = await this.database.Slots.FirstOrDefaultAsync(s => s.Type == photoSlot.SlotType && s.InternalSlotId == photoSlot.SlotId);
if (slot != null)
photoSlot.SlotId = slot.SlotId;
else
photoSlot.SlotId = await SlotHelper.GetPlaceholderSlotId(this.database, photoSlot.SlotId, photoSlot.SlotType);
validLevel = true;
break;
}
case SlotType.Moon:
case SlotType.Unknown:
case SlotType.Unknown2:
case SlotType.DLC:
default: Logger.Warn($"Invalid photo level type: {photoSlot.SlotType}", LogArea.Photos);
break;
}
if (validLevel) photoEntity.SlotId = photoSlot.SlotId;
}
if (photo.Subjects?.Count > 4) return this.BadRequest();
if (photo.Timestamp > TimeHelper.Timestamp) photoEntity.Timestamp = TimeHelper.Timestamp;
this.database.Photos.Add(photoEntity);
// Save to get photo ID for the PhotoSubject foreign keys
await this.database.SaveChangesAsync();
if (photo.Subjects != null)
{
// Check for duplicate photo subjects
List<string> subjectUserIds = new(4);
foreach (GamePhotoSubject subject in photo.Subjects)
{
if (subjectUserIds.Contains(subject.Username) && !string.IsNullOrEmpty(subject.Username))
return this.BadRequest();
subjectUserIds.Add(subject.Username);
}
foreach (GamePhotoSubject subject in photo.Subjects.Where(subject => !string.IsNullOrEmpty(subject.Username)))
{
subject.UserId = await this.database.Users.Where(u => u.Username == subject.Username)
.Select(u => u.UserId)
.FirstOrDefaultAsync();
if (subject.UserId == 0) continue;
PhotoSubjectEntity subjectEntity = new()
{
PhotoId = photoEntity.PhotoId,
UserId = subject.UserId,
Bounds = subject.Bounds,
};
Logger.Debug($"Adding PhotoSubject (userid {subject.UserId}) to db", LogArea.Photos);
this.database.PhotoSubjects.Add(subjectEntity);
}
}
await this.database.SaveChangesAsync();
string username = await this.database.UsernameFromGameToken(token);
await WebhookHelper.SendWebhook
(
new EmbedBuilder
{
Title = "New photo uploaded!",
Description = $"{username} uploaded a new photo.",
ImageUrl = $"{ServerConfiguration.Instance.ExternalUrl}/gameAssets/{photo.LargeHash}",
Color = WebhookHelper.GetEmbedColor(),
}
);
return this.Ok();
}
[HttpGet("photos/{slotType}/{id:int}")]
public async Task<IActionResult> SlotPhotos(string slotType, int id, [FromQuery] string? by)
{
if (SlotHelper.IsTypeInvalid(slotType)) return this.BadRequest();
if (slotType == "developer") id = await SlotHelper.GetPlaceholderSlotId(this.database, id, SlotType.Developer);
PaginationData pageData = this.Request.GetPaginationData();
int creatorId = 0;
if (by != null)
{
creatorId = await this.database.Users.Where(u => u.Username == by)
.Select(u => u.UserId)
.FirstOrDefaultAsync();
}
List<GamePhoto> photos = (await this.database.Photos.Include(p => p.PhotoSubjects)
.Where(p => creatorId == 0 || p.CreatorId == creatorId)
.Where(p => p.SlotId == id)
.OrderByDescending(s => s.Timestamp)
.ApplyPagination(pageData)
.ToListAsync()).ToSerializableList(GamePhoto.CreateFromEntity);
return this.Ok(new PhotoListResponse(photos));
}
[HttpGet("photos/by")]
public async Task<IActionResult> UserPhotosBy(string user)
{
int targetUserId = await this.database.UserIdFromUsername(user);
if (targetUserId == 0) return this.NotFound();
PaginationData pageData = this.Request.GetPaginationData();
List<GamePhoto> photos = (await this.database.Photos.Include(p => p.PhotoSubjects)
.Where(p => p.CreatorId == targetUserId)
.OrderByDescending(s => s.Timestamp)
.ApplyPagination(pageData)
.ToListAsync()).ToSerializableList(GamePhoto.CreateFromEntity);
return this.Ok(new PhotoListResponse(photos));
}
[HttpGet("photos/with")]
public async Task<IActionResult> UserPhotosWith(string user)
{
int targetUserId = await this.database.UserIdFromUsername(user);
if (targetUserId == 0) return this.NotFound();
PaginationData pageData = this.Request.GetPaginationData();
List<GamePhoto> photos = (await this.database.Photos.Include(p => p.PhotoSubjects)
.Where(p => p.PhotoSubjects.Any(ps => ps.UserId == targetUserId))
.OrderByDescending(s => s.Timestamp)
.ApplyPagination(pageData)
.ToListAsync()).ToSerializableList(GamePhoto.CreateFromEntity);
return this.Ok(new PhotoListResponse(photos));
}
[HttpPost("deletePhoto/{id:int}")]
public async Task<IActionResult> DeletePhoto(int id)
{
GameTokenEntity token = this.GetToken();
PhotoEntity? photo = await this.database.Photos.FirstOrDefaultAsync(p => p.PhotoId == id);
if (photo == null) return this.NotFound();
// If user isn't photo creator then check if they own the level
if (photo.CreatorId != token.UserId)
{
SlotEntity? photoSlot = await this.database.Slots.FirstOrDefaultAsync(s => s.SlotId == photo.SlotId && s.Type == SlotType.User);
if (photoSlot == null || photoSlot.CreatorId != token.UserId) return this.Unauthorized();
}
this.database.Photos.Remove(photo);
await this.database.SaveChangesAsync();
return this.Ok();
}
}