feat: paste cleanup service; sveltekit frontend; paste editing; paste metadata modifying

refactor: rename SharpbinV3 -> SharpbinV3.Server; run cleanup
This commit is contained in:
2025-12-28 05:39:18 -05:00
parent 19f439a405
commit adad139081
56 changed files with 4432 additions and 81 deletions
+5 -5
View File
@@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Mvc;
using SharpbinV3.Services;
using SharpbinV3.DTOs;
using Bcrypt = BCrypt.Net.BCrypt;
using SharpbinV3.Data.Entities;
using Microsoft.AspNetCore.RateLimiting;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Controllers
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
+72 -5
View File
@@ -1,9 +1,10 @@
using Microsoft.AspNetCore.Mvc;
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using SharpbinV3.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Controllers
namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
@@ -16,6 +17,15 @@ namespace SharpbinV3.Controllers
[Route("create")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(visibility))
return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(syntax))
return BadRequest(new { message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(title))
return BadRequest(new { message = "Invalid title. Must be less than 500 characters." });
string content = await new StreamReader(Request.Body).ReadToEndAsync();
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
@@ -76,5 +86,62 @@ namespace SharpbinV3.Controllers
return File(paste.Content, "text/plain; charset=utf-8");
}
}
[HttpPut]
[Route("{id}/edit")]
[Authorize]
public async Task<IActionResult> EditPaste(string id)
{
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null) return NotFound();
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
if (userUUID == null || paste.AuthorUUID != Guid.Parse(userUUID))
return Forbid();
bool result = await _pasteService.EditText(paste, content);
if (!result) return NotFound();
return Ok(new { message = "Paste edited successfully." });
}
[HttpPatch]
[Route("{id}/modify")]
[Authorize]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] PasteMetadataUpdateRequest request)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
if (userUUID == null || paste.AuthorUUID != Guid.Parse(userUUID))
return Forbid();
if (request.Title != null)
paste.Title = request.Title;
if (request.Syntax != null)
paste.Syntax = request.Syntax;
if (request.Visibility.HasValue)
paste.Visibility = request.Visibility.Value;
if (request.ExpiresAt.HasValue)
paste.ExpiresAt = request.ExpiresAt.Value;
var newPaste = await _pasteService.Edit(paste);
return Ok(new
{
message = "Paste metadata updated successfully.",
paste = new
{
newPaste.ID,
newPaste.UUID,
newPaste.Title,
newPaste.Size,
newPaste.TrueSize,
newPaste.IsCompressed,
newPaste.Views,
newPaste.Syntax,
newPaste.Visibility,
newPaste.ExpiresAt
}
});
}
}
}
+2 -2
View File
@@ -1,8 +1,8 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SharpbinV3.Services;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Controllers
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
+1 -1
View File
@@ -1,4 +1,4 @@
namespace SharpbinV3.DTOs
namespace SharpbinV3.Server.DTOs
{
public class JWTResult
{
+1 -1
View File
@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs
namespace SharpbinV3.Server.DTOs
{
public class LoginRequest
{
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
{
public class PasteMetadataUpdateRequest
{
[StringLength(500)]
public string? Title { get; set; }
public string? Syntax { get; set; }
public int? Visibility { get; set; }
public long? ExpiresAt { get; set; }
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs
namespace SharpbinV3.Server.DTOs
{
public class RefreshTokenRequest
{
+1 -1
View File
@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs
namespace SharpbinV3.Server.DTOs
{
public class RegisterRequest
{
+2 -2
View File
@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data.Entities;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Data
namespace SharpbinV3.Server.Data
{
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
+5 -5
View File
@@ -1,7 +1,7 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Data.Entities
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(PID), IsUnique = true)]
[Index(nameof(UUID), IsUnique = true)]
@@ -20,9 +20,9 @@ namespace SharpbinV3.Data.Entities
public required Guid AuthorUUID { get; set; } = Guid.Empty; // uuid of the user who created the paste, or Guid.Empty for anonymous pastes
public User? User { get; set; }
public long? EditedAt { get; set; }
public required byte[] Content { get; set; }
public int Size { get; set; } // stored size (may be compressed)
public int TrueSize { get; set; } // uncompressed size
+1 -1
View File
@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Data.Entities
namespace SharpbinV3.Server.Data.Entities
{
public sealed class RefreshToken
{
+1 -1
View File
@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Data.Entities
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(UID), IsUnique = true)]
[Index(nameof(UUID), IsUnique = true)]
+2 -2
View File
@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251125015039_Init")]
+1 -1
View File
@@ -3,7 +3,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251125053617_ImprovePastes")]
@@ -2,7 +2,7 @@
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class ImprovePastes : Migration
@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251125055340_PasteContent")]
@@ -2,7 +2,7 @@
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class PasteContent : Migration
+2 -2
View File
@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251125061310_GrammarFix")]
@@ -2,7 +2,7 @@
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class GrammarFix : Migration
@@ -3,11 +3,11 @@ using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Migrations
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
+12 -6
View File
@@ -1,13 +1,13 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data;
using SharpbinV3.Services;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Services;
using System.Text;
using System.Threading.RateLimiting;
namespace SharpbinV3
namespace SharpbinV3.Server
{
public class Program
{
@@ -65,6 +65,13 @@ namespace SharpbinV3
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(p =>
p.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.AllowAnyMethod());
});
var app = builder.Build();
app.UseRateLimiter();
@@ -80,7 +87,6 @@ namespace SharpbinV3
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
using (var scope = app.Services.CreateScope())
+5 -5
View File
@@ -1,14 +1,14 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Data;
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public sealed class AuthService(AppDbContext db, IConfiguration configuration) : IAuthService
{
@@ -125,7 +125,7 @@ namespace SharpbinV3.Services
ValidateAudience = true,
ValidAudience = _configuration["JwtConfig:Audience"],
ClockSkew = TimeSpan.Zero,
ValidateLifetime = true
ValidateLifetime = false
}, out SecurityToken validatedToken);
var jwtId = validatedToken.Id;
var storedRefreshToken = await _db.RefreshTokens
+1 -1
View File
@@ -1,7 +1,7 @@
using System.IO.Compression;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public class CompressionService : ICompressionService
{
+3 -3
View File
@@ -1,7 +1,7 @@
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public interface IAuthService
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public interface ICompressionService
{
+6 -3
View File
@@ -1,7 +1,6 @@
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public interface IPasteService
{
@@ -13,5 +12,9 @@ namespace SharpbinV3.Services
Task<bool> EditText(Paste paste, string text);
Task<Paste> Get(string id);
Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false);
Task<bool> ValidateSyntax(string syntax);
Task<bool> ValidateTitle(string title);
Task<bool> ValidateVisibility(int visibility);
Task<bool> ValidateExpiresAt(long expiresAt);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
using SharpbinV3.Data.Entities;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public interface IUserService
{
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services
{
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(_period);
await Cleanup(stoppingToken);
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await Cleanup(stoppingToken);
}
catch (Exception ex)
{
logger.LogError(ex, "Error occurred during paste cleanup");
}
}
}
private async Task Cleanup(CancellationToken stoppingToken)
{
using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var expiredPastes = db.Pastes.Where(p => p.ExpiresAt != 0 && p.ExpiresAt <= now);
if (await expiredPastes.AnyAsync(stoppingToken))
{
var deletedCount = await expiredPastes.CountAsync(stoppingToken);
db.Pastes.RemoveRange(expiredPastes);
await db.SaveChangesAsync(stoppingToken);
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
}
}
}
}
+49 -4
View File
@@ -1,15 +1,41 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data;
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using System.Text;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(AppDbContext db, ICompressionService cs) : IPasteService
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
private readonly static string[] ValidSyntaxLanguages =
[
"plaintext",
"autoHotkey",
"autoIt",
"bash",
"c",
"cpp",
"csharp",
"css",
"dart",
"html",
"java",
"javascript",
"json",
"lua",
"markdown",
"php",
"python",
"ruby",
"rust",
"sql",
"swift",
"typescript",
"toml",
"xml"
];
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt)
{
@@ -61,6 +87,7 @@ namespace SharpbinV3.Services
paste.Size = compressedData.Length;
paste.TrueSize = Encoding.UTF8.GetByteCount(text);
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
paste.IsCompressed = compressedData.Length < Encoding.UTF8.GetByteCount(text);
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
return result > 0;
@@ -83,5 +110,23 @@ namespace SharpbinV3.Services
.ToListAsync();
}
public async Task<bool> ValidateSyntax(string syntax)
{
return await Task.FromResult(ValidSyntaxLanguages.Contains(syntax));
}
public async Task<bool> ValidateTitle(string title)
{
return await Task.FromResult(title.Length <= 500);
}
public async Task<bool> ValidateVisibility(int visibility)
{
return await Task.FromResult(visibility >= 0 && visibility <= 2);
}
public async Task<bool> ValidateExpiresAt(long expiresAt)
{
if (expiresAt == 0) return true;
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return await Task.FromResult(expiresAt > currentTime - 1000);
}
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data;
using SharpbinV3.Data.Entities;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Services
namespace SharpbinV3.Server.Services
{
public sealed class UserService(AppDbContext db) : IUserService
{
@@ -6,11 +6,10 @@
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>a95b1aac-5cce-4fa9-8056-51f0d045cf2f</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<None Remove="Controllers\UserController.cs~RF7ce337d.TMP" />
</ItemGroup>
<EnableStaticWebAssets>false</EnableStaticWebAssets>
<EnableDefaultContentItems>false</EnableDefaultContentItems>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
-6
View File
@@ -1,6 +0,0 @@
@SharpbinV3_HostAddress = http://localhost:5050
GET {{SharpbinV3_HostAddress}}/weatherforecast/
Accept: application/json
###
+24
View File
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7F30EE13-B933-4515-AA54-DBDD2605C90C}
EndGlobalSection
EndGlobal
+2 -3
View File
@@ -1,4 +1,4 @@
namespace SharpbinV3
namespace SharpbinV3.Server
{
public class Utilities
{
@@ -6,8 +6,7 @@
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
}
}
}