feat: comments & paste/comment reactions; renames/refactors

this is a LOT, i should've commited in stages but oh well, from what i can remember:
- paste interactions (reactions)
- comments
- comment interactions (reactions)
- rich text editor
- move all report apis into report controller
- rename size to sizeStored
- rename trueSize to originalSize
- fixed compression on paste compression
    - implemented compression threshold
- use longs instead of ints where possible in the entities
- improve record view + remove redundant check for existing view
This commit is contained in:
2026-04-24 08:52:33 -04:00
parent f82d314d80
commit 63b77bece9
43 changed files with 4560 additions and 403 deletions
@@ -0,0 +1,222 @@
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public class CommentService(AppDbContext dbContext, ICompressionService cs, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = dbContext;
private readonly ICompressionService _cs = cs;
private readonly PasteSettings _pasteSettings = options.Value;
public async Task<Comment> CreateComment(User author, Paste paste, string content, long? parentCommentId)
{
long originalSize = Encoding.UTF8.GetByteCount(content);
var data = Encoding.UTF8.GetBytes(content);
if (_pasteSettings.EnablePasteCompression)
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var comment = new Comment
{
PastePID = paste.PID,
ParentCommentID = parentCommentId,
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
UserUUID = author.UUID,
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
};
_db.Comments.Add(comment);
author.Comments.Add(comment);
paste.Comments.Add(comment);
await _db.SaveChangesAsync();
return comment;
}
public async Task<bool> EditComment(Comment comment, string newContent)
{
long originalSize = Encoding.UTF8.GetByteCount(newContent);
var data = Encoding.UTF8.GetBytes(newContent);
if (_pasteSettings.EnablePasteCompression)
data = _cs.Compress(newContent);
double compressionRatio = (double)data.Length / originalSize;
comment.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(newContent);
comment.StoredSize = data.Length;
comment.OriginalSize = originalSize;
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
comment.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
_db.Comments.Update(comment);
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<bool> DeleteComment(Comment comment)
{
comment.Content = null;
comment.StoredSize = 0;
comment.OriginalSize = 0;
comment.IsCompressed = false;
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
_db.Comments.Update(comment);
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<bool> HardDeleteComment(Comment comment)
{
_db.Comments.Remove(comment);
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<Comment?> GetCommentByID(long commentID)
{
var comment = await _db.Comments.Include(c => c.User).Include(c => c.Paste).FirstOrDefaultAsync(c => c.Id == commentID);
if (comment == null)
return null;
comment.PositiveInteractionCount = await _db.CommentInteractions.CountAsync(ci =>
ci.CommentID == commentID && ci.Type == Interaction.Positive
);
comment.NegativeInteractionCount = await _db.CommentInteractions.CountAsync(ci =>
ci.CommentID == commentID && ci.Type == Interaction.Negative
);
return comment;
}
public async Task<Comment?> GetCommentByID(long commentID, long pastePID)
{
var comment = await _db
.Comments.Include(c => c.User)
.Include(c => c.Paste)
.FirstOrDefaultAsync(c => c.Id == commentID && c.PastePID == pastePID);
if (comment == null)
return null;
comment.PositiveInteractionCount = await _db.CommentInteractions.CountAsync(ci =>
ci.CommentID == commentID && ci.Type == Interaction.Positive
);
comment.NegativeInteractionCount = await _db.CommentInteractions.CountAsync(ci =>
ci.CommentID == commentID && ci.Type == Interaction.Negative
);
return comment;
}
public async Task<List<Comment>> GetCommentsByPaste(Paste paste)
{
var comments = await _db.Comments.Where(c => c.PastePID == paste.PID).Include(c => c.User).ToListAsync();
await PopulateInteractionCounts(comments);
return comments;
}
public async Task<List<Comment>> GetCommentsByUser(User user)
{
var comments = await _db.Comments.Where(c => c.UserUUID == user.UUID).Include(c => c.Paste).ToListAsync();
await PopulateInteractionCounts(comments);
return comments;
}
public async Task<List<Comment>> GetReplies(Comment parentComment)
{
var comments = await _db.Comments.Where(c => c.ParentCommentID == parentComment.Id).Include(c => c.User).ToListAsync();
await PopulateInteractionCounts(comments);
return comments;
}
public async Task<Dictionary<long, Interaction>> GetUserInteractions(List<long> commentIds, Guid userUUID)
{
if (commentIds.Count == 0)
return [];
return await _db
.CommentInteractions.Where(ci => commentIds.Contains(ci.CommentID) && ci.UserUUID == userUUID)
.ToDictionaryAsync(ci => ci.CommentID, ci => ci.Type);
}
public async Task<CommentInteraction?> UpsertInteraction(Comment comment, User user, Interaction type)
{
var interaction = await _db.CommentInteractions.FirstOrDefaultAsync(ci => ci.CommentID == comment.Id && ci.UserUUID == user.UUID);
if (interaction == null)
{
interaction = new CommentInteraction
{
CommentID = comment.Id,
UserUUID = user.UUID,
Type = type,
};
_db.CommentInteractions.Add(interaction);
}
else
{
interaction.Type = type;
_db.CommentInteractions.Update(interaction);
}
try
{
await _db.SaveChangesAsync();
return interaction;
}
catch (DbUpdateException)
{
return null;
}
}
public async Task<bool> RemoveInteraction(Comment comment, User user)
{
var interaction = await _db.CommentInteractions.FirstOrDefaultAsync(ci => ci.CommentID == comment.Id && ci.UserUUID == user.UUID);
if (interaction == null)
return false;
_db.CommentInteractions.Remove(interaction);
await _db.SaveChangesAsync();
return true;
}
private async Task PopulateInteractionCounts(List<Comment> comments)
{
if (comments.Count == 0)
return;
var commentIds = comments.Select(c => c.Id).ToList();
var groupedCounts = await _db
.CommentInteractions.Where(ci => commentIds.Contains(ci.CommentID))
.GroupBy(ci => new { ci.CommentID, ci.Type })
.Select(g => new
{
g.Key.CommentID,
g.Key.Type,
Count = g.Count(),
})
.ToListAsync();
var positiveCounts = groupedCounts.Where(c => c.Type == Interaction.Positive).ToDictionary(c => c.CommentID, c => c.Count);
var negativeCounts = groupedCounts.Where(c => c.Type == Interaction.Negative).ToDictionary(c => c.CommentID, c => c.Count);
foreach (var comment in comments)
{
comment.PositiveInteractionCount = positiveCounts.GetValueOrDefault(comment.Id, 0);
comment.NegativeInteractionCount = negativeCounts.GetValueOrDefault(comment.Id, 0);
}
}
}
}
@@ -33,13 +33,11 @@ namespace SharpbinV3.Server.Services
if (!IsCompressed(compressedData))
throw new ArgumentException("Data is not in a valid compressed format.", nameof(compressedData));
using (MemoryStream ms = new())
{
using MemoryStream compressedStream = new(compressedData);
using GZipStream gzip = new(compressedStream, CompressionMode.Decompress);
gzip.CopyTo(ms);
}
return compressedData;
using MemoryStream ms = new();
using MemoryStream compressedStream = new(compressedData);
using GZipStream gzip = new(compressedStream, CompressionMode.Decompress);
gzip.CopyTo(ms);
return ms.ToArray();
}
private static bool IsCompressed(byte[] data)
+98 -35
View File
@@ -29,10 +29,13 @@ namespace SharpbinV3.Server.Services
bool shouldCompress
)
{
long originalSize = Encoding.UTF8.GetByteCount(content);
var data = Encoding.UTF8.GetBytes(content);
if (shouldCompress)
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var paste = new Paste
{
UUID = Guid.CreateVersion7(),
@@ -40,10 +43,10 @@ namespace SharpbinV3.Server.Services
Title = title,
AuthorUUID = author?.UUID,
User = author,
Content = data,
Size = data.Length,
TrueSize = Encoding.UTF8.GetByteCount(content),
IsCompressed = data.Length < Encoding.UTF8.GetByteCount(content),
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
Syntax = syntax,
Visibility = visibility,
ExpiresAt = expiresAt,
@@ -93,15 +96,18 @@ namespace SharpbinV3.Server.Services
public async Task<bool> EditText(Paste paste, string text)
{
long originalSize = Encoding.UTF8.GetByteCount(text);
var data = Encoding.UTF8.GetBytes(text);
if (_pasteSettings.EnablePasteCompression)
data = _cs.Compress(text);
paste.Content = data;
paste.Size = data.Length;
paste.TrueSize = Encoding.UTF8.GetByteCount(text);
double compressionRatio = (double)data.Length / originalSize;
paste.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(text);
paste.StoredSize = data.Length;
paste.OriginalSize = originalSize;
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
paste.IsCompressed = data.Length < Encoding.UTF8.GetByteCount(text);
paste.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
@@ -112,43 +118,82 @@ namespace SharpbinV3.Server.Services
public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context)
{
if (paste == null)
return (null, false);
if (context == null)
return (null, false);
if (_pasteSettings.View_HMAC_Secret == null)
if (paste == null || context == null || _pasteSettings.View_HMAC_Secret == null)
return (null, false);
var viewerIp = context.GetRequestIP();
var viewerUserAgent = context.Request.Headers.UserAgent.ToString();
JwtUser? viewerUser = context.GetJwtUser();
var viewerUser = context.GetJwtUser();
string viewerHash;
if (viewerUser != null)
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString());
else
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent);
var viewerHash =
viewerUser != null
? Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, $"user:{viewerUser.UUID}")
: Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, $"anon:{viewerIp}:{viewerUserAgent}");
if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash))
var view = new PasteView
{
PastePID = paste.PID,
ViewerHash = viewerHash,
ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
};
_db.PasteViews.Add(view);
try
{
paste.Views += 1;
_db.Pastes.Update(paste);
await _db.SaveChangesAsync();
}
catch (DbUpdateException)
{
return (null, true);
}
_db.PasteViews.Add(
new PasteView
{
PastePID = paste.PID,
ViewerHash = viewerHash,
ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
}
);
InvalidatePasteCache(paste.ID);
return (paste, false);
}
paste.Views += 1;
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
public async Task<PasteInteraction?> RecordInteraction(Paste paste, User user, Interaction type)
{
if (paste == null || user == null)
return null;
if (result > 0)
var interaction = new PasteInteraction
{
PasteID = paste.PID,
UserUUID = user.UUID,
Type = type,
};
_db.PasteInteractions.Add(interaction);
try
{
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return interaction;
}
catch (DbUpdateException)
{
return null;
}
}
return (result > 0 ? paste : null, result > 0);
public async Task<bool> RemoveInteraction(Paste paste, User user)
{
if (paste == null || user == null)
return false;
var interaction = await _db.PasteInteractions.FirstOrDefaultAsync(pi => pi.PasteID == paste.PID && pi.UserUUID == user.UUID);
if (interaction == null)
return false;
_db.PasteInteractions.Remove(interaction);
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return true;
}
public async Task<Paste?> Get(string id)
@@ -159,7 +204,17 @@ namespace SharpbinV3.Server.Services
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
return await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
var _paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
if (_paste != null)
{
_paste.PositiveInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Positive)
.CountAsync();
_paste.NegativeInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Negative)
.CountAsync();
}
return _paste;
}
);
return paste ?? null;
@@ -189,6 +244,14 @@ namespace SharpbinV3.Server.Services
return pastes ?? [];
}
public async Task<PasteInteraction?> GetUserInteraction(Paste paste, Guid userUUID)
{
if (paste == null)
return null;
return await _db.PasteInteractions.FirstOrDefaultAsync(pi => pi.PasteID == paste.PID && pi.UserUUID == userUUID);
}
public bool ValidateSyntax(string syntax)
{
return _pasteSettings.ValidSyntaxLanguages.Contains(syntax);
@@ -201,7 +264,7 @@ namespace SharpbinV3.Server.Services
public bool ValidateVisibility(Visibility visibility)
{
return Enum.IsDefined(typeof(Visibility), visibility);
return Enum.IsDefined(visibility);
}
public bool ValidateExpiresAt(long expiresAt)
+2 -4
View File
@@ -26,7 +26,7 @@ namespace SharpbinV3.Server.Services
return report;
}
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, int? pastePID, ReportType type, string description)
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, long? pastePID, ReportType type, string description)
{
var report = new Report
{
@@ -55,9 +55,7 @@ namespace SharpbinV3.Server.Services
q = q.Where(r => r.PastePID == query.PastePID);
if (query.PasteId != null)
{
q = q.Where(r => _db.Pastes.Where(p => p.ID == query.PasteId).Select(p => (int?)p.PID).Contains(r.PastePID));
}
q = q.Where(r => r.Paste != null && r.Paste.ID == query.PasteId);
if (query.TargetType != null)
q = q.Where(r => r.TargetType == query.TargetType);