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
+23
View File
@@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
+1
View File
@@ -0,0 +1 @@
engine-strict=true
+9
View File
@@ -0,0 +1,9 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
bun.lock
bun.lockb
# Miscellaneous
/static/
+16
View File
@@ -0,0 +1,16 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
],
"tailwindStylesheet": "./src/routes/layout.css"
}
+6
View File
@@ -0,0 +1,6 @@
{
"files.associations": {
"*.css": "tailwindcss"
},
"tailwindCSS.experimental.configFile": "src/routes/layout.css",
}
+38
View File
@@ -0,0 +1,38 @@
# sv
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```sh
# create a new project in the current directory
npx sv create
# create a new project in my-app
npx sv create my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```sh
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```sh
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
+41
View File
@@ -0,0 +1,41 @@
import prettier from 'eslint-config-prettier';
import { fileURLToPath } from 'node:url';
import { includeIgnoreFile } from '@eslint/compat';
import js from '@eslint/js';
import svelte from 'eslint-plugin-svelte';
import { defineConfig } from 'eslint/config';
import globals from 'globals';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
export default defineConfig(
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs.recommended,
prettier,
...svelte.configs.prettier,
{
languageOptions: { globals: { ...globals.browser, ...globals.node } },
rules: {
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
'no-undef': 'off'
}
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parserOptions: {
projectService: true,
extraFileExtensions: ['.svelte'],
parser: ts.parser,
svelteConfig
}
}
}
);
+3896
View File
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "sharpbinv3.client",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/kit": "^2.49.1",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@types/node": "^22",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.1",
"globals": "^16.5.0",
"prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.45.6",
"svelte-check": "^4.3.4",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
"typescript-eslint": "^8.48.1",
"vite": "^7.2.6"
}
}
+13
View File
@@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+1
View File
@@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.
@@ -0,0 +1,9 @@
<script lang="ts">
import './layout.css';
import favicon from '$lib/assets/favicon.svg';
let { children } = $props();
</script>
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
{@render children()}
@@ -0,0 +1,2 @@
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
+1
View File
@@ -0,0 +1 @@
@import 'tailwindcss';
+3
View File
@@ -0,0 +1,3 @@
# allow crawling everything by default
User-agent: *
Disallow:
+18
View File
@@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://svelte.dev/docs/kit/integrations
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://svelte.dev/docs/kit/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;
+20
View File
@@ -0,0 +1,20 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"rewriteRelativeImportExtensions": true,
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}
+12
View File
@@ -0,0 +1,12 @@
import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
server: {
proxy: {
'/api': 'http://localhost:5050'
}
}
});
+1 -1
View File
@@ -1,3 +1,3 @@
<Solution>
<Project Path="SharpbinV3/SharpbinV3.csproj" />
<Project Path="SharpbinV3/SharpbinV3.Server.csproj" />
</Solution>
+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)])]);
}
}
}