From 63b77bece9b71d547d15403257da44e8597db97b Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 24 Apr 2026 08:48:13 -0400 Subject: [PATCH] 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 --- .../src/lib/components/Modal.svelte | 3 +- .../src/lib/components/Paste.svelte | 12 +- .../lib/components/PasteCommentItem.svelte | 236 +++++++ .../src/lib/components/PasteComments.svelte | 246 +++++++ .../src/lib/components/RichTextEditor.svelte | 217 ++++++ SharpbinV3.Client/src/lib/types/comment.ts | 35 + SharpbinV3.Client/src/lib/types/paste.ts | 9 +- SharpbinV3.Client/src/lib/types/report.ts | 2 +- SharpbinV3.Client/src/lib/utils/markdown.ts | 193 ++++++ .../src/routes/[id].jpg/+server.ts | 2 +- .../src/routes/[id]/+page.server.ts | 11 + .../src/routes/[id]/+page.svelte | 189 +++++- SharpbinV3.Client/src/routes/layout.css | 4 + .../routes/user/[username]/+page.server.ts | 4 +- .../Controllers/PasteController.cs | 313 ++++++--- .../Controllers/ReportController.cs | 308 ++++++++- .../Controllers/UserController.cs | 173 +---- SharpbinV3.Server/DTOs/Paste/CommentDtos.cs | 53 ++ .../DTOs/Paste/PasteResponseDto.cs | 11 +- .../DTOs/Report/ReportQueryDto.cs | 2 +- .../DTOs/User/UserResponseDto.cs | 2 +- SharpbinV3.Server/Data/AppDbContext.cs | 27 + SharpbinV3.Server/Data/Entities/Comment.cs | 37 ++ .../Data/Entities/CommentInteraction.cs | 20 + SharpbinV3.Server/Data/Entities/Paste.cs | 20 +- .../Data/Entities/PasteInteraction.cs | 20 + SharpbinV3.Server/Data/Entities/PasteView.cs | 3 +- SharpbinV3.Server/Data/Entities/Report.cs | 7 +- SharpbinV3.Server/Data/Entities/User.cs | 3 +- SharpbinV3.Server/Data/Enums/Interaction.cs | 8 + ...085542_InteractionsAndComments.Designer.cs | 615 +++++++++++++++++ .../20260424085542_InteractionsAndComments.cs | 243 +++++++ ...260424090002_IndexInteractions.Designer.cs | 621 +++++++++++++++++ .../20260424090002_IndexInteractions.cs | 74 +++ ...60424091805_RenameCommentSizes.Designer.cs | 623 ++++++++++++++++++ .../20260424091805_RenameCommentSizes.cs | 38 ++ .../Migrations/AppDbContextModelSnapshot.cs | 200 +++++- SharpbinV3.Server/Program.cs | 5 +- SharpbinV3.Server/Services/CommentService.cs | 222 +++++++ .../Services/CompressionService.cs | 12 +- SharpbinV3.Server/Services/PasteService.cs | 133 +++- SharpbinV3.Server/Services/ReportService.cs | 6 +- SharpbinV3.Server/Settings/PasteSettings.cs | 1 + 43 files changed, 4560 insertions(+), 403 deletions(-) create mode 100644 SharpbinV3.Client/src/lib/components/PasteCommentItem.svelte create mode 100644 SharpbinV3.Client/src/lib/components/PasteComments.svelte create mode 100644 SharpbinV3.Client/src/lib/components/RichTextEditor.svelte create mode 100644 SharpbinV3.Client/src/lib/types/comment.ts create mode 100644 SharpbinV3.Server/DTOs/Paste/CommentDtos.cs create mode 100644 SharpbinV3.Server/Data/Entities/Comment.cs create mode 100644 SharpbinV3.Server/Data/Entities/CommentInteraction.cs create mode 100644 SharpbinV3.Server/Data/Entities/PasteInteraction.cs create mode 100644 SharpbinV3.Server/Data/Enums/Interaction.cs create mode 100644 SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.cs create mode 100644 SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.cs create mode 100644 SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.cs create mode 100644 SharpbinV3.Server/Services/CommentService.cs diff --git a/SharpbinV3.Client/src/lib/components/Modal.svelte b/SharpbinV3.Client/src/lib/components/Modal.svelte index 468893c..475bc0a 100644 --- a/SharpbinV3.Client/src/lib/components/Modal.svelte +++ b/SharpbinV3.Client/src/lib/components/Modal.svelte @@ -302,7 +302,8 @@ body.VerificationToken = verification; } const targetId = encodeURIComponent(String(reportTargetId)); - const res = await fetch(`/api/${reportTarget}/${targetId}/report`, { + const reportPath = reportTarget === 'paste' ? 'pastes' : 'users'; + const res = await fetch(`/api/report/${reportPath}/${targetId}/report`, { method: 'POST', headers: { 'Content-Type': 'application/json', diff --git a/SharpbinV3.Client/src/lib/components/Paste.svelte b/SharpbinV3.Client/src/lib/components/Paste.svelte index c76a473..d9140af 100644 --- a/SharpbinV3.Client/src/lib/components/Paste.svelte +++ b/SharpbinV3.Client/src/lib/components/Paste.svelte @@ -92,10 +92,12 @@
- {formatBytes(paste.trueSize)} + {formatBytes(paste.originalSize)}
@@ -174,10 +176,12 @@
- {formatBytes(paste.trueSize)} + {formatBytes(paste.originalSize)}
diff --git a/SharpbinV3.Client/src/lib/components/PasteCommentItem.svelte b/SharpbinV3.Client/src/lib/components/PasteCommentItem.svelte new file mode 100644 index 0000000..1115bba --- /dev/null +++ b/SharpbinV3.Client/src/lib/components/PasteCommentItem.svelte @@ -0,0 +1,236 @@ + + +
+
+
+ {#if node.author} + {#if node.author.isBanned} + BANNED + {/if} + + {authorDisplay} + + {/if} + {#if node.updatedAt} + edited + {/if} +
+ {dateToRelativeString(new Date(node.createdAt * 1000), true, false, now, 2)} +
+ +
+
+ {#if expanded || !isLongComment} + + {@html parsedHtml} + {:else} +
+ + {@html parsedHtml} +
+ {/if} +
+ {#if isLongComment} + + {/if} +
+ +
+ + + {#if $user} + {#if !replyOpen} + + {/if} + + {/if} +
+ + {#if replyOpen} + + {#if replyError} +

{replyError}

+ {/if} + {/if} + + {#if node.children.length > 0} +
+ {#if depth >= 3 && !showDeepReplies} + + {:else} +
+ {#each node.children as child (child.id)} + + {/each} +
+ {/if} +
+ {/if} +
diff --git a/SharpbinV3.Client/src/lib/components/PasteComments.svelte b/SharpbinV3.Client/src/lib/components/PasteComments.svelte new file mode 100644 index 0000000..a2a2676 --- /dev/null +++ b/SharpbinV3.Client/src/lib/components/PasteComments.svelte @@ -0,0 +1,246 @@ + + +
+
+

Comments ({comments.length})

+ +
+ + {#if $user} + + {:else} +
+ Sign in to post comments and reactions. +
+ {/if} + + {#if errorMessage} +
+ {errorMessage} +
+ {/if} + + {#if loading && comments.length === 0} +
+ Loading comments... +
+ {:else if threadedComments.length === 0} +
+ No comments yet. +
+ {:else} +
+ {#each threadedComments as node (node.id)} + postComment(content, parentCommentID)} + /> + {/each} +
+ {/if} +
diff --git a/SharpbinV3.Client/src/lib/components/RichTextEditor.svelte b/SharpbinV3.Client/src/lib/components/RichTextEditor.svelte new file mode 100644 index 0000000..c451cc3 --- /dev/null +++ b/SharpbinV3.Client/src/lib/components/RichTextEditor.svelte @@ -0,0 +1,217 @@ + + +
+ {#if mode === 'raw'} + + {:else} +
+ {#if value.trim().length === 0} +
{placeholder}
+ {:else} +
+ + {@html parsedHtml} +
+ {/if} +
+ {/if} +
+
+ + + + +
+
+ + +
+
+
diff --git a/SharpbinV3.Client/src/lib/types/comment.ts b/SharpbinV3.Client/src/lib/types/comment.ts new file mode 100644 index 0000000..cce5fba --- /dev/null +++ b/SharpbinV3.Client/src/lib/types/comment.ts @@ -0,0 +1,35 @@ +import type { Author } from './author'; + +export type CommentReaction = 1 | 2 | null; + +export interface CommentAuthor extends Author { + displayName?: string | null; + roles?: number; + isBanned?: boolean; +} + +export interface PasteComment { + id: number; + parentCommentID: number | null; + content: string | null; + storedSize: number; + originalSize: number; + isCompressed: boolean; + createdAt: number; + updatedAt: number | null; + likes: number; + dislikes: number; + userReaction: CommentReaction; + author: CommentAuthor | null; +} + +export interface CommentReactionResult { + commentID: number; + likes: number; + dislikes: number; + userReaction: CommentReaction; +} + +export interface CommentTreeNode extends PasteComment { + children: CommentTreeNode[]; +} diff --git a/SharpbinV3.Client/src/lib/types/paste.ts b/SharpbinV3.Client/src/lib/types/paste.ts index 67a57eb..bc5b41c 100644 --- a/SharpbinV3.Client/src/lib/types/paste.ts +++ b/SharpbinV3.Client/src/lib/types/paste.ts @@ -1,18 +1,23 @@ import type { Author } from './author'; +export type PasteReaction = 1 | 2 | null; + export interface Paste { id: string; uuid: string; createdAt: number; title: string | null; - size: number; - trueSize: number; + sizeStored: number; + originalSize: number; isCompressed: boolean; views: number; syntax: string; visibility: 0 | 1 | 2; expiresAt: number; editedAt: number | null; + likes: number; + dislikes: number; + userReaction: PasteReaction; reportCount: number | null; author: Author | null; } diff --git a/SharpbinV3.Client/src/lib/types/report.ts b/SharpbinV3.Client/src/lib/types/report.ts index f027efa..243fb0b 100644 --- a/SharpbinV3.Client/src/lib/types/report.ts +++ b/SharpbinV3.Client/src/lib/types/report.ts @@ -28,4 +28,4 @@ export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud' export const reportStatusLabels = ['Open', 'Closed'] as const; -export const reportTargetLabels = ['Paste', 'User'] as const; +export const reportTargetLabels = ['Paste', 'User', 'Comment'] as const; diff --git a/SharpbinV3.Client/src/lib/utils/markdown.ts b/SharpbinV3.Client/src/lib/utils/markdown.ts index 8324403..c11385e 100644 --- a/SharpbinV3.Client/src/lib/utils/markdown.ts +++ b/SharpbinV3.Client/src/lib/utils/markdown.ts @@ -2,6 +2,7 @@ import { marked } from 'marked'; import createDOMPurify from 'dompurify'; import type { WindowLike } from 'dompurify'; import { trustedDomains } from '$lib/consts'; +import { escapeHtml } from './html'; export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning'; @@ -138,3 +139,195 @@ export async function parseMarkdown( return DOMPurify.sanitize(html); } + +export function parseCommentMarkdown(text: string): string { + const lines = text.replace(/\r\n?/g, '\n').split('\n'); + const output: string[] = []; + let index = 0; + + while (index < lines.length) { + const codeBlock = tryParseCodeBlock(lines, index); + if (codeBlock) { + output.push(codeBlock.html); + index = codeBlock.nextIndex; + continue; + } + + const spoilerBlock = tryParseSpoilerBlock(lines, index); + if (spoilerBlock) { + output.push(spoilerBlock.html); + index = spoilerBlock.nextIndex; + continue; + } + + const quoteBlock = tryParseQuoteBlock(lines, index); + if (quoteBlock) { + output.push(quoteBlock.html); + index = quoteBlock.nextIndex; + continue; + } + + if (/^\s*---\s*$/.test(lines[index])) { + output.push('
'); + index += 1; + continue; + } + + output.push(parseInlineElements(lines[index])); + index += 1; + } + + return output.join(''); +} + +interface ParsedCommentBlock { + html: string; + nextIndex: number; +} + +function tryParseCodeBlock(lines: string[], startIndex: number): ParsedCommentBlock | null { + const firstLine = lines[startIndex]; + if (!firstLine.startsWith('```')) return null; + + const inlineCloseIndex = firstLine.indexOf('```', 3); + if (inlineCloseIndex > -1) { + const code = firstLine.slice(3, inlineCloseIndex); + const trailing = firstLine.slice(inlineCloseIndex + 3).trim(); + const html = renderCodeBlock(code); + if (trailing.length === 0) { + return { html, nextIndex: startIndex + 1 }; + } + return { + html: `${html}\n${parseInlineElements(trailing)}`, + nextIndex: startIndex + 1 + }; + } + + const codeLines: string[] = []; + let index = startIndex + 1; + + while (index < lines.length && !lines[index].startsWith('```')) { + codeLines.push(lines[index]); + index += 1; + } + + if (index < lines.length) index += 1; + + return { + html: renderCodeBlock(codeLines.join('\n')), + nextIndex: index + }; +} + +function tryParseSpoilerBlock(lines: string[], startIndex: number): ParsedCommentBlock | null { + const spoilerOpenMatch = lines[startIndex].match(/^\[Spoiler(?:="([^"]*)")?\](.*)$/i); + if (!spoilerOpenMatch) return null; + + const title = spoilerOpenMatch[1]?.trim() || 'Spoiler'; + const contentParts: string[] = []; + let remainder = spoilerOpenMatch[2] ?? ''; + let index = startIndex; + + while (true) { + const closeMatch = /\[\/spoiler\]/i.exec(remainder); + if (closeMatch && closeMatch.index !== undefined) { + const beforeClose = remainder.slice(0, closeMatch.index); + if (beforeClose.length > 0) contentParts.push(beforeClose); + + const contentHtml = contentParts.map((line) => parseInlineElements(line)).join('
'); + let html = `
${escapeHtml(title)}
${contentHtml}
`; + + const afterClose = remainder.slice(closeMatch.index + closeMatch[0].length).trim(); + if (afterClose.length > 0) { + html += `\n${parseInlineElements(afterClose)}`; + } + + return { + html, + nextIndex: index + 1 + }; + } + + if (remainder.length > 0) contentParts.push(remainder); + index += 1; + if (index >= lines.length) return null; + remainder = lines[index]; + } +} + +function tryParseQuoteBlock(lines: string[], startIndex: number): ParsedCommentBlock | null { + if (!lines[startIndex].startsWith('>')) return null; + + const quoteLines: string[] = []; + let index = startIndex; + + while (index < lines.length && lines[index].startsWith('>')) { + quoteLines.push(parseInlineElements(lines[index].replace(/^>\s?/, ''))); + index += 1; + } + + return { + html: `
${quoteLines.join('
')}
`, + nextIndex: index + }; +} + +function renderCodeBlock(code: string): string { + return `
${escapeHtml(code)}
`; +} + +function normalizeCommentLink(rawUrl: string): string | null { + const url = rawUrl.trim(); + if (url.length === 0) return null; + if (url.startsWith('/')) return url; + + try { + const parsed = new URL(url); + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { + return parsed.toString(); + } + return null; + } catch { + return null; + } +} + +function parseInlineElements(text: string): string { + const inlinePattern = + /```([\s\S]*?)```|\*\*\*([^*\n]+)\*\*\*|\*\*([^*\n]+)\*\*|\*([^*\n]+)\*|`([^`\n]+)`|\[([^\]\n]+)\]\(([^)\n]+)\)|@([a-zA-Z0-9_-]+)/g; + + let output = ''; + let lastIndex = 0; + + for (const match of text.matchAll(inlinePattern)) { + const index = match.index ?? 0; + output += escapeHtml(text.slice(lastIndex, index)); + + if (match[1] !== undefined) { + output += renderCodeBlock(match[1]); + } else if (match[2] !== undefined) { + output += `${escapeHtml(match[2])}`; + } else if (match[3] !== undefined) { + output += `${escapeHtml(match[3])}`; + } else if (match[4] !== undefined) { + output += `${escapeHtml(match[4])}`; + } else if (match[5] !== undefined) { + output += `${escapeHtml(match[5])}`; + } else if (match[6] !== undefined && match[7] !== undefined) { + const safeUrl = normalizeCommentLink(match[7]); + if (safeUrl) { + output += `${escapeHtml(match[6])}`; + } else { + output += escapeHtml(match[0]); + } + } else if (match[8] !== undefined) { + const username = match[8]; + output += `@${escapeHtml(username)}`; + } + + lastIndex = index + match[0].length; + } + + output += escapeHtml(text.slice(lastIndex)); + return output; +} diff --git a/SharpbinV3.Client/src/routes/[id].jpg/+server.ts b/SharpbinV3.Client/src/routes/[id].jpg/+server.ts index 7076212..b35fee7 100644 --- a/SharpbinV3.Client/src/routes/[id].jpg/+server.ts +++ b/SharpbinV3.Client/src/routes/[id].jpg/+server.ts @@ -161,7 +161,7 @@ export const GET: RequestHandler = async ({ params, fetch }) => { const content = rawContent || 'No content available.'; const created = paste.createdAt ? new Date(paste.createdAt) : extractDateFromUUIDv7(paste.uuid); const metadata: PasteEmbedProps['metadata'] = [ - { icon: 'size', value: formatBytes(paste.trueSize) }, + { icon: 'size', value: formatBytes(paste.originalSize) }, { icon: 'views', value: `${formatNumber(paste.views)} view${paste.views === 1 ? '' : 's'}` diff --git a/SharpbinV3.Client/src/routes/[id]/+page.server.ts b/SharpbinV3.Client/src/routes/[id]/+page.server.ts index 2617d34..119b60d 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.server.ts +++ b/SharpbinV3.Client/src/routes/[id]/+page.server.ts @@ -1,5 +1,6 @@ import type { PageServerLoad } from './$types'; import type { Paste } from '$lib/types/paste'; +import type { PasteComment } from '$lib/types/comment'; import { getServerToken } from '$lib/utils/auth'; import { apiUrl, viewInternalApiKey } from '$lib/server/api'; import { error } from '@sveltejs/kit'; @@ -46,12 +47,22 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders }); const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders }); + const commentsRes = await fetch(`${apiUrl}/api/paste/${id}/comments`, { headers: clientHeaders }); const options = await pasteOptions.json(); const content = await pasteContent.text(); + let comments: PasteComment[] = []; + + if (commentsRes.ok) { + const commentsJson = await commentsRes.json().catch(() => ({})); + comments = Array.isArray(commentsJson?.comments) + ? (commentsJson.comments as PasteComment[]) + : []; + } return { paste, content, + comments, options, authOptions: parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData diff --git a/SharpbinV3.Client/src/routes/[id]/+page.svelte b/SharpbinV3.Client/src/routes/[id]/+page.svelte index dec4a12..8363436 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.svelte +++ b/SharpbinV3.Client/src/routes/[id]/+page.svelte @@ -24,7 +24,10 @@ CalendarCog, Flag, ArrowUp, - HatGlasses + HatGlasses, + MessageCircle, + ThumbsUp, + ThumbsDown } from '@lucide/svelte/icons/index'; import { formatBytes, @@ -47,8 +50,9 @@ import { getToken, hasRole } from '$lib/utils/auth'; import { user } from '$lib/stores/user'; import Dropdown from '$lib/components/Dropdown.svelte'; + import PasteComments from '$lib/components/PasteComments.svelte'; import { openModal } from '$lib/stores/modal'; - import type { Paste } from '$lib/types/paste'; + import type { Paste, PasteReaction } from '$lib/types/paste'; import HighlightWorker from '$lib/workers/highlight.worker?worker'; interface Props { data: PageData; @@ -56,6 +60,24 @@ let { data = $bindable() }: Props = $props(); + function updatePasteState(patch: Partial) { + if (!data?.paste) return; + data = { + ...data, + paste: { + ...data.paste, + ...patch + } + }; + } + + function updatePageContent(content: string) { + data = { + ...data, + content + }; + } + let reportSiteKey = $derived( (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions ?.cf_turnstile_site_key ?? null @@ -73,9 +95,11 @@ let contentRendered = $state(false); let downloadedPaste = $state(false); let copiedPaste = $state(false); + let reactingToPaste = $state(false); let highlightWorker: Worker | null = null; let highlightRequestId = 0; let ignoreExternalMediaWarning = false; + let iconsOnly = $state(false); let scrollY = $state(0); @@ -293,7 +317,7 @@ editLoading = false; return; } - data.content = rawContent; + updatePageContent(rawContent); decryptedContent = rawContent; await renderPaste(rawContent); } @@ -324,10 +348,13 @@ return; } const resJson = await res.json(); - data.paste.syntax = resJson.paste.syntax ?? data.paste.syntax; - data.paste.expiresAt = resJson.paste.expiresAt ?? data.paste.expiresAt; - data.paste.visibility = resJson.paste.visibility ?? data.paste.visibility; - data.paste.title = resJson.paste.title ?? data.paste.title; + updatePasteState({ + syntax: resJson.paste.syntax ?? data.paste.syntax, + expiresAt: resJson.paste.expiresAt ?? data.paste.expiresAt, + visibility: resJson.paste.visibility ?? data.paste.visibility, + title: resJson.paste.title ?? data.paste.title + }); + editMetadata = data.paste ? { ...data.paste } : null; } } catch { editError = 'An error occurred while updating.'; @@ -338,6 +365,48 @@ } } + async function reactToPaste(target: 1 | 2) { + if (!data?.paste || reactingToPaste) return; + + const token = getToken(); + if (!token) { + return; + } + + reactingToPaste = true; + const currentReaction = (data.paste.userReaction ?? null) as PasteReaction; + const nextReaction: PasteReaction = currentReaction === target ? null : target; + + try { + const res = await fetch(`/api/paste/${data.paste.id}/reaction`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + }, + body: JSON.stringify({ reaction: nextReaction }) + }); + + if (!res.ok) { + return; + } + + const json = await res.json(); + const reaction = json?.reaction; + if (!reaction) { + return; + } + + updatePasteState({ + likes: reaction.likes ?? data.paste.likes, + dislikes: reaction.dislikes ?? data.paste.dislikes, + userReaction: reaction.userReaction ?? null + }); + } finally { + reactingToPaste = false; + } + } + async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') { const title = modalTitleMap[mode]; if (mode === 'confirm') { @@ -599,7 +668,9 @@
- {formatBytes(data.paste.trueSize)} + {formatBytes(data.paste.originalSize)}
@@ -745,6 +816,32 @@ ? 's' : ''} + {#if $user && $user.uuid !== data.paste?.author?.uuid} + + + {/if}
{:else}
@@ -760,7 +857,7 @@ setTimeout(() => (copiedPaste = false), 1000); }} > -
+
{#if copiedPaste} {/if}
- - Copy + {#if !iconsOnly} + Copy + {/if} {/if} - - View Raw + + {#if !iconsOnly} + View Raw + {/if} + + {#if $user !== null && $user.uuid !== data.paste?.author?.uuid} {/if} {#if $user && ($user.uuid === data.paste?.author?.uuid || hasRole($user.roles, 2) || hasRole($user.roles, 4))} @@ -863,8 +982,10 @@ editing = true; }} > - - Edit + + {#if !iconsOnly} + Edit + {/if} {/if} {:else} {/if} {/if} @@ -929,8 +1056,10 @@ onclick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} aria-label="Scroll to top" > - - Scroll to top + + {#if !iconsOnly} + Scroll to top + {/if} {/if}
@@ -974,6 +1103,8 @@ {@html pasteContent} {/if} + + {:else}

Paste not found

The paste you are looking for does not exist.

diff --git a/SharpbinV3.Client/src/routes/layout.css b/SharpbinV3.Client/src/routes/layout.css index cc95c03..2b1fa41 100644 --- a/SharpbinV3.Client/src/routes/layout.css +++ b/SharpbinV3.Client/src/routes/layout.css @@ -121,3 +121,7 @@ select { .markdown th { background-color: #2a2a2a; } + +button { + cursor: pointer; +} diff --git a/SharpbinV3.Client/src/routes/user/[username]/+page.server.ts b/SharpbinV3.Client/src/routes/user/[username]/+page.server.ts index a381e65..d9203d1 100644 --- a/SharpbinV3.Client/src/routes/user/[username]/+page.server.ts +++ b/SharpbinV3.Client/src/routes/user/[username]/+page.server.ts @@ -77,7 +77,7 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) { headers.set('Authorization', `Bearer ${token}`); - const submittedRes = await fetch(`${apiUrl}/api/user/${user.uuid}/reports/submitted`, { + const submittedRes = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports/submitted`, { headers: headers }); if (submittedRes.ok) reportsSubmitted = await submittedRes.json(); @@ -85,7 +85,7 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent if (token && !asGuest && !isOwner && canModerate) { headers.set('Authorization', `Bearer ${token}`); - const r = await fetch(`${apiUrl}/api/user/${user.uuid}/reports`, { + const r = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports`, { headers: headers }); if (r.ok) reportsTarget = await r.json(); diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 688b615..4452526 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Authorization; +using System.Text; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Options; @@ -18,17 +19,21 @@ namespace SharpbinV3.Server.Controllers [ApiController] public class PasteController( PasteService pasteService, + CommentService commentService, VerificationService verificationService, AuthService authService, ReportService reportService, + ICompressionService compressionService, IOptions options, IOptions authSettings ) : ControllerBase { private readonly PasteService _pasteService = pasteService; + private readonly CommentService _commentService = commentService; private readonly VerificationService _verificationService = verificationService; private readonly AuthService _authService = authService; private readonly ReportService _reportService = reportService; + private readonly ICompressionService _compressionService = compressionService; private readonly PasteSettings _pasteSettings = options.Value; private readonly AuthSettings _authSettings = authSettings.Value; @@ -83,8 +88,8 @@ namespace SharpbinV3.Server.Controllers UUID = paste.UUID, CreatedAt = paste.CreatedAt, IsCompressed = paste.IsCompressed, - Size = paste.Size, - TrueSize = paste.TrueSize, + StoredSize = paste.StoredSize, + OriginalSize = paste.OriginalSize, ExpiresAt = paste.ExpiresAt, Visibility = paste.Visibility, } @@ -101,6 +106,9 @@ namespace SharpbinV3.Server.Controllers return NotFound(new { success = false, message = "Paste not found" }); var jwtUser = HttpContext.GetJwtUser(); + PasteInteraction? userInteraction = null; + if (jwtUser != null) + userInteraction = await _pasteService.GetUserInteraction(paste, jwtUser.UUID); int? reportCount = null; if (jwtUser != null && (jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator))) @@ -119,8 +127,8 @@ namespace SharpbinV3.Server.Controllers UUID = paste.UUID, CreatedAt = paste.CreatedAt, Title = paste.Title, - Size = paste.Size, - TrueSize = paste.TrueSize, + StoredSize = paste.StoredSize, + OriginalSize = paste.OriginalSize, IsCompressed = paste.IsCompressed, Views = paste.Views, Syntax = paste.Syntax, @@ -128,6 +136,9 @@ namespace SharpbinV3.Server.Controllers ExpiresAt = paste.ExpiresAt, EditedAt = paste.EditedAt, ReportCount = reportCount, + UserReaction = userInteraction != null ? userInteraction.Type : null, + Likes = paste.PositiveInteractionCount, + Dislikes = paste.NegativeInteractionCount, Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto @@ -231,8 +242,8 @@ namespace SharpbinV3.Server.Controllers UUID = newPaste.UUID, CreatedAt = newPaste.CreatedAt, Title = newPaste.Title, - Size = newPaste.Size, - TrueSize = newPaste.TrueSize, + OriginalSize = newPaste.OriginalSize, + StoredSize = newPaste.StoredSize, IsCompressed = newPaste.IsCompressed, Views = newPaste.Views, Syntax = newPaste.Syntax, @@ -297,113 +308,69 @@ namespace SharpbinV3.Server.Controllers } [HttpPost] - [Route("{id}/report")] [Authorize(Policy = "JwtOnlyAndNotBanned")] - [EnableRateLimiting("Sensitive")] - public async Task ReportPaste(string id, [FromBody] ReportDto request) + [Route("{id}/reaction")] + public async Task ReactToPaste(string id, [FromBody] ReactToPasteDto request) { var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(new { success = false, message = "Paste not found." }); - var user = HttpContext.GetJwtUser()!; + if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + return NotFound(new { success = false, message = "Paste not found" }); - Enum.TryParse(request.ReportType, true, out var reportType); - if (!Enum.IsDefined(reportType)) - return BadRequest(new { success = false, message = "Invalid report type." }); + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return Unauthorized(new { success = false, message = "User not authenticated." }); + if (paste.AuthorUUID == user.UUID) + return BadRequest(new { success = false, message = "You cannot react to your own paste." }); - if ( - !await _verificationService.VerifyAsync( - new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() } - ) - ) - return BadRequest(new { success = false, message = "Verification failed." }); + var existingInteraction = await _pasteService.GetUserInteraction(paste, user.UUID); - Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description); - if (report == null) - return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." }); + if (request.Reaction.HasValue) + { + if (existingInteraction == null) + { + var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value); + if (created == null) + return StatusCode(500, new { success = false, message = "Could not save reaction." }); + } + else if (existingInteraction.Type != request.Reaction.Value) + { + var removed = await _pasteService.RemoveInteraction(paste, user); + if (!removed) + return StatusCode(500, new { success = false, message = "Could not update reaction." }); + + var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value); + if (created == null) + return StatusCode(500, new { success = false, message = "Could not update reaction." }); + } + } + else if (existingInteraction != null) + { + var removed = await _pasteService.RemoveInteraction(paste, user); + if (!removed) + return StatusCode(500, new { success = false, message = "Could not remove reaction." }); + } + + var updatedPaste = await _pasteService.Get(id); + if (updatedPaste == null) + return StatusCode(500, new { success = false, message = "Could not load updated paste." }); + + var updatedInteraction = await _pasteService.GetUserInteraction(updatedPaste, user.UUID); return Ok( new { success = true, - message = "Paste reported successfully.", - report = new ReportResponseDto + reaction = new PasteReactionResponseDto { - ReportID = report.ReportID, - Type = report.Type, - Status = report.Status, - Description = report.Description, - CreatedAt = report.CreatedAt, - UpdatedAt = report.UpdatedAt, - ReporterUUID = report.ReporterUUID, - TargetType = report.TargetType, - UserUUID = report.UserUUID, + PasteID = updatedPaste.ID, + Likes = updatedPaste.PositiveInteractionCount, + Dislikes = updatedPaste.NegativeInteractionCount, + UserReaction = updatedInteraction?.Type, }, } ); } - [HttpPatch] - [Route("{id}/report/{reportId}")] - [Authorize(Policy = "JwtOnlyAndNotBanned")] - [EnableRateLimiting("Sensitive")] - public async Task ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request) - { - var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(new { success = false, message = "Paste not found." }); - - var report = await _reportService.GetReportByID(reportId); - if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) - return NotFound(new { success = false, message = "Report not found." }); - - var user = HttpContext.GetJwtUser()!; - - var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator); - if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) - return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." }); - - Enum.TryParse(request.ReportType, true, out var reportType); - if (!Enum.IsDefined(reportType)) - return BadRequest(new { success = false, message = "Invalid report type." }); - - report.Type = reportType; - report.Description = request.Description; - - var updatedReport = await _reportService.UpdateReport(report); - if (updatedReport == null) - return StatusCode(500, new { success = false, message = "An error occurred while updating the report." }); - - return Ok(new { success = true, message = "Report updated successfully." }); - } - - [HttpDelete] - [Route("{id}/report/{reportId}")] - [Authorize(Policy = "JwtOnlyAndNotBanned")] - [EnableRateLimiting("Sensitive")] - public async Task DeletePasteReport(string id, int reportId) - { - var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(new { success = false, message = "Paste not found." }); - - var report = await _reportService.GetReportByID(reportId); - if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) - return NotFound(new { success = false, message = "Report not found." }); - - var user = HttpContext.GetJwtUser()!; - - var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator); - if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) - return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." }); - - bool result = await _reportService.DeleteReport(report); - if (!result) - return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); - - return Ok(new { success = true, message = "Report deleted successfully." }); - } - [HttpGet] [Route("recent")] public async Task GetRecentPastes() @@ -416,8 +383,8 @@ namespace SharpbinV3.Server.Controllers UUID = p.UUID, CreatedAt = p.CreatedAt, Title = p.Title, - Size = p.Size, - TrueSize = p.TrueSize, + StoredSize = p.StoredSize, + OriginalSize = p.OriginalSize, IsCompressed = p.IsCompressed, Views = p.Views, Syntax = p.Syntax, @@ -441,6 +408,112 @@ namespace SharpbinV3.Server.Controllers ); } + [HttpGet] + [EnableRateLimiting("NoLimit")] + [Route("{id}/comments")] + public async Task GetComments(string id) + { + var paste = await _pasteService.Get(id); + if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + return NotFound(new { success = false, message = "Paste not found" }); + + var comments = await _commentService.GetCommentsByPaste(paste); + + Dictionary? userInteractionMap = null; + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user != null) + userInteractionMap = await _commentService.GetUserInteractions(comments.Select(c => c.Id).ToList(), user.UUID); + + return Ok(new { success = true, comments = comments.Select(c => ToCommentResponse(c, userInteractionMap)) }); + } + + [HttpPost] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [Route("{id}/comments")] + public async Task CreateComment(string id, [FromBody] CreateCommentDto request) + { + if (string.IsNullOrWhiteSpace(request.Content)) + return BadRequest(new { success = false, message = "Comment content cannot be empty." }); + + var paste = await _pasteService.Get(id); + if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + return NotFound(new { success = false, message = "Paste not found" }); + + if (Encoding.UTF8.GetByteCount(request.Content) > 5000) + return BadRequest(new { success = false, message = "Comment content exceeds maximum size of 5000 bytes." }); + + if (request.ParentCommentID.HasValue) + { + var parent = await _commentService.GetCommentByID(request.ParentCommentID.Value, paste.PID); + if (parent == null) + return BadRequest(new { success = false, message = "Parent comment not found for this paste." }); + } + + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return Unauthorized(new { success = false, message = "User not authenticated." }); + + var comment = await _commentService.CreateComment(user, paste, request.Content, request.ParentCommentID); + var created = await _commentService.GetCommentByID(comment.Id); + if (created == null) + return StatusCode(500, new { success = false, message = "Failed to load created comment." }); + + var userInteractionMap = new Dictionary(); + return Ok(new { success = true, comment = ToCommentResponse(created, userInteractionMap) }); + } + + [HttpPost] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [Route("{id}/comments/{commentId}/reaction")] + public async Task ReactToComment(string id, long commentId, [FromBody] ReactToCommentDto request) + { + var paste = await _pasteService.Get(id); + if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + return NotFound(new { success = false, message = "Paste not found" }); + + var comment = await _commentService.GetCommentByID(commentId, paste.PID); + if (comment == null) + return NotFound(new { success = false, message = "Comment not found for this paste." }); + + var user = await _authService.GetUserFromHttpContext(HttpContext); + if (user == null) + return Unauthorized(new { success = false, message = "User not authenticated." }); + + if (request.Reaction.HasValue) + { + var result = await _commentService.UpsertInteraction(comment, user, request.Reaction.Value); + if (result == null) + return StatusCode(500, new { success = false, message = "Could not save reaction." }); + } + else + { + await _commentService.RemoveInteraction(comment, user); + } + + var updated = await _commentService.GetCommentByID(commentId); + if (updated == null) + return StatusCode(500, new { success = false, message = "Could not load updated comment." }); + + var interactionMap = await _commentService.GetUserInteractions([commentId], user.UUID); + Interaction? userReaction = null; + if (interactionMap.TryGetValue(commentId, out var mappedReaction)) + userReaction = mappedReaction; + + return Ok( + new + { + success = true, + reaction = new CommentReactionResponseDto + { + CommentID = updated.Id, + Likes = updated.PositiveInteractionCount, + Dislikes = updated.NegativeInteractionCount, + UserReaction = userReaction, + }, + } + ); + } + [HttpGet] [EnableRateLimiting("NoLimit")] [Route("info")] @@ -462,5 +535,47 @@ namespace SharpbinV3.Server.Controllers } ); } + + private CommentResponseDto ToCommentResponse(Comment comment, Dictionary? userInteractionMap) + { + string? content = null; + if (comment.Content != null) + { + var bytes = comment.IsCompressed ? _compressionService.Decompress(comment.Content) : comment.Content; + content = Encoding.UTF8.GetString(bytes); + } + + Interaction? userReaction = null; + if (userInteractionMap != null && userInteractionMap.TryGetValue(comment.Id, out var mappedReaction)) + userReaction = mappedReaction; + + return new CommentResponseDto + { + Id = comment.Id, + ParentCommentID = comment.ParentCommentID, + Content = content, + StoredSize = comment.StoredSize, + OriginalSize = comment.OriginalSize, + IsCompressed = comment.IsCompressed, + CreatedAt = comment.CreatedAt, + UpdatedAt = comment.UpdatedAt, + Likes = comment.PositiveInteractionCount, + Dislikes = comment.NegativeInteractionCount, + UserReaction = userReaction, + Author = + comment.User != null && comment.User.Visibility == 0 + ? new UserSimpleDto + { + UID = comment.User.UID, + UUID = comment.User.UUID, + Username = comment.User.Username, + DisplayName = comment.User.DisplayName, + Visibility = comment.User.Visibility, + Roles = comment.User.Roles, + IsBanned = comment.User.IsBanned, + } + : null, + }; + } } } diff --git a/SharpbinV3.Server/Controllers/ReportController.cs b/SharpbinV3.Server/Controllers/ReportController.cs index 70172e9..acd9c04 100644 --- a/SharpbinV3.Server/Controllers/ReportController.cs +++ b/SharpbinV3.Server/Controllers/ReportController.cs @@ -2,16 +2,28 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using SharpbinV3.Server.Data.Entities; +using SharpbinV3.Server.Data.Enums; using SharpbinV3.Server.DTOs.Report; using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Services; +using SharpbinV3.Server.Services.Verification; namespace SharpbinV3.Server.Controllers { [Route("api/[controller]")] [ApiController] - public class ReportController(ReportService reportService) : Controller + public class ReportController( + ReportService reportService, + PasteService pasteService, + UserService userService, + VerificationService verificationService + ) : Controller { + private readonly ReportService _reportService = reportService; + private readonly PasteService _pasteService = pasteService; + private readonly UserService _userService = userService; + private readonly VerificationService _verificationService = verificationService; + [Route("{reportId:int}")] [HttpGet] [EnableRateLimiting("Sliding")] @@ -20,7 +32,7 @@ namespace SharpbinV3.Server.Controllers { var user = HttpContext.GetJwtUser()!; - var report = await reportService.GetReportByID(reportId); + var report = await _reportService.GetReportByID(reportId); if (report is null) return NotFound(new { success = false, message = "Report not found." }); @@ -28,7 +40,7 @@ namespace SharpbinV3.Server.Controllers if (!hasPrivilegedRole && report.ReporterUUID != user.UUID) return StatusCode(403, new { success = false, message = "You do not have permission to view this report." }); - var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID); + var (Username, DisplayName) = await _reportService.GetReporterInfo(report.ReporterUUID); return Ok( new ReportResponseDto @@ -62,7 +74,7 @@ namespace SharpbinV3.Server.Controllers if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator)) return StatusCode(403, new { success = false, message = "You do not have permission to update reports." }); - var report = await reportService.GetReportByID(reportId); + var report = await _reportService.GetReportByID(reportId); if (report is null) return NotFound(new { success = false, message = "Report not found." }); @@ -86,8 +98,8 @@ namespace SharpbinV3.Server.Controllers report.Description = request.Description; report.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - var updated = await reportService.UpdateReport(report); - var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID); + var updated = await _reportService.UpdateReport(report); + var (Username, DisplayName) = await _reportService.GetReporterInfo(updated.ReporterUUID); return Ok( new ReportResponseDto @@ -132,8 +144,8 @@ namespace SharpbinV3.Server.Controllers var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null }; - var reports = await reportService.GetPasteReports(query); - var totalCount = await reportService.GetReportCount(query); + var reports = await _reportService.GetPasteReports(query); + var totalCount = await _reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); return Ok( new @@ -168,8 +180,8 @@ namespace SharpbinV3.Server.Controllers PasteId = null, }; - var reports = await reportService.GetUserReports(query); - var totalCount = await reportService.GetReportCount(query); + var reports = await _reportService.GetUserReports(query); + var totalCount = await _reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); return Ok( new @@ -213,8 +225,8 @@ namespace SharpbinV3.Server.Controllers PageSize = Math.Clamp(pageSize, 1, 100), }; - var reports = await reportService.GetReports(query); - var totalCount = await reportService.GetReportCount(query); + var reports = await _reportService.GetReports(query); + var totalCount = await _reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); return Ok( new @@ -230,5 +242,277 @@ namespace SharpbinV3.Server.Controllers } ); } + + [HttpPost("pastes/{id}/report")] + [HttpPost("/api/paste/{id}/report")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task ReportPaste(string id, [FromBody] ReportDto request) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + var user = HttpContext.GetJwtUser()!; + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + if (!await _verificationService.VerifyAsync(new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() })) + return BadRequest(new { success = false, message = "Verification failed." }); + + Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description); + if (report == null) + return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." }); + + return Ok( + new + { + success = true, + message = "Paste reported successfully.", + report = new ReportResponseDto + { + ReportID = report.ReportID, + Type = report.Type, + Status = report.Status, + Description = report.Description, + CreatedAt = report.CreatedAt, + UpdatedAt = report.UpdatedAt, + ReporterUUID = report.ReporterUUID, + TargetType = report.TargetType, + UserUUID = report.UserUUID, + }, + } + ); + } + + [HttpPatch("pastes/{id}/report/{reportId}")] + [HttpPatch("/api/paste/{id}/report/{reportId}")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) + return NotFound(new { success = false, message = "Report not found." }); + + var user = HttpContext.GetJwtUser()!; + + var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator); + if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) + return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." }); + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + report.Type = reportType; + report.Description = request.Description; + + var updatedReport = await _reportService.UpdateReport(report); + if (updatedReport == null) + return StatusCode(500, new { success = false, message = "An error occurred while updating the report." }); + + return Ok(new { success = true, message = "Report updated successfully." }); + } + + [HttpDelete("pastes/{id}/report/{reportId}")] + [HttpDelete("/api/paste/{id}/report/{reportId}")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task DeletePasteReport(string id, int reportId) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) + return NotFound(new { success = false, message = "Report not found." }); + + var user = HttpContext.GetJwtUser()!; + + var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator); + if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) + return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." }); + + bool result = await _reportService.DeleteReport(report); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); + + return Ok(new { success = true, message = "Report deleted successfully." }); + } + + [HttpPost("users/{uuid}/report")] + [HttpPost("/api/user/{uuid}/report")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task ReportUser(Guid uuid, [FromBody] ReportDto request) + { + var reporter = HttpContext.GetJwtUser()!; + + var reportedUser = await _userService.GetByUUID(uuid); + if (reportedUser == null) + return NotFound(new { success = false, message = "User not found." }); + if (reportedUser.UUID == reporter.UUID) + return BadRequest(new { success = false, message = "You cannot report yourself." }); + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + if (!await _verificationService.VerifyAsync(new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() })) + return Unauthorized(new { success = false, message = "Invalid verification token." }); + + Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description); + if (report == null) + return StatusCode(500, new { success = false, message = "An error occurred while creating the report." }); + + return Ok( + new + { + success = true, + message = "User reported successfully.", + report = new ReportResponseDto + { + ReportID = report.ReportID, + Type = report.Type, + Status = report.Status, + Description = report.Description, + CreatedAt = report.CreatedAt, + UpdatedAt = report.UpdatedAt, + ReporterUUID = report.ReporterUUID, + TargetType = report.TargetType, + UserUUID = report.UserUUID, + }, + } + ); + } + + [HttpPatch("users/{uuid}/report/{reportId}")] + [HttpPatch("/api/user/{uuid}/report/{reportId}")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request) + { + var jwtUser = HttpContext.GetJwtUser()!; + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) + return NotFound(new { success = false, message = "Report not found." }); + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + report.Type = reportType; + report.Description = request.Description ?? report.Description; + + var updatedReport = await _reportService.UpdateReport(report); + if (updatedReport == null) + return StatusCode(500, new { success = false, message = "An error occurred while updating the report." }); + + return Ok(new { success = true, message = "Report updated successfully." }); + } + + [HttpDelete("users/{uuid}/report/{reportId}")] + [HttpDelete("/api/user/{uuid}/report/{reportId}")] + [Authorize(Policy = "JwtOnlyAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task DeleteUserReport(Guid uuid, int reportId) + { + var jwtUser = HttpContext.GetJwtUser()!; + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) + return NotFound(new { success = false, message = "Report not found." }); + + var result = await _reportService.DeleteReport(report); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); + + return Ok(new { success = true, message = "Report deleted successfully." }); + } + + [HttpGet("users/{uuid}/reports")] + [HttpGet("/api/user/{uuid}/reports")] + [Authorize(Policy = "JwtOnly")] + public async Task GetUserReports(Guid uuid, [FromQuery] ReportQuery request) + { + var jwtUser = HttpContext.GetJwtUser()!; + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + if (!jwtUser.Roles.HasFlag(Role.Admin)) + return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." }); + + var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; + var reports = await _reportService.GetUserReports(query); + var totalCount = await _reportService.GetReportCount(query); + var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); + return Ok( + new + { + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, + } + ); + } + + [HttpGet("users/{uuid}/reports/submitted")] + [HttpGet("/api/user/{uuid}/reports/submitted")] + [Authorize(Policy = "JwtOnly")] + public async Task GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request) + { + var jwtUser = HttpContext.GetJwtUser()!; + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + var isOwner = user.UUID == jwtUser.UUID; + var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator); + if (!isOwner && !hasPrivilegedRole) + return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." }); + + var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; + + var reports = await _reportService.GetReports(query); + var totalCount = await _reportService.GetReportCount(query); + var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); + + return Ok( + new + { + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, + } + ); + } } } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index 372de1b..1da4356 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -200,175 +200,6 @@ namespace SharpbinV3.Server.Controllers return Ok(new { message = "User deleted successfully." }); } - [HttpPost] - [Route("{uuid}/report")] - [EnableRateLimiting("Sensitive")] - [Authorize(Policy = "JwtOnlyAndNotBanned")] - public async Task ReportUser(Guid uuid, [FromBody] ReportDto request) - { - var reporter = HttpContext.GetJwtUser()!; - - var reportedUser = await _userService.GetByUUID(uuid); - if (reportedUser == null) - return NotFound(new { success = false, message = "User not found." }); - if (reportedUser.UUID == reporter.UUID) - return BadRequest(new { success = false, message = "You cannot report yourself." }); - Enum.TryParse(request.ReportType, true, out var reportType); - if (!Enum.IsDefined(reportType)) - return BadRequest(new { success = false, message = "Invalid report type." }); - - if ( - !await _verificationService.VerifyAsync( - new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() } - ) - ) - return Unauthorized(new { success = false, message = "Invalid verification token." }); - - Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description); - if (report == null) - return StatusCode(500, new { success = false, message = "An error occurred while creating the report." }); - - return Ok( - new - { - success = true, - message = "User reported successfully.", - report = new ReportResponseDto - { - ReportID = report.ReportID, - Type = report.Type, - Status = report.Status, - Description = report.Description, - CreatedAt = report.CreatedAt, - UpdatedAt = report.UpdatedAt, - ReporterUUID = report.ReporterUUID, - TargetType = report.TargetType, - UserUUID = report.UserUUID, - }, - } - ); - } - - [HttpPatch] - [Route("{uuid}/report/{reportId}")] - [EnableRateLimiting("Sensitive")] - [Authorize(Policy = "JwtOnlyAndNotBanned")] - public async Task UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request) - { - var jwtUser = HttpContext.GetJwtUser()!; - - var user = await _userService.GetByUUID(uuid); - if (user == null) - return NotFound(new { success = false, message = "User not found." }); - - var report = await _reportService.GetReportByID(reportId); - if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) - return NotFound(new { success = false, message = "Report not found." }); - - Enum.TryParse(request.ReportType, true, out var reportType); - if (!Enum.IsDefined(reportType)) - return BadRequest(new { success = false, message = "Invalid report type." }); - - report.Type = reportType; - report.Description = request.Description ?? report.Description; - - await _db.SaveChangesAsync(); - return Ok(new { success = true, message = "Report updated successfully." }); - } - - [HttpDelete] - [Route("{uuid}/report/{reportId}")] - [EnableRateLimiting("Sensitive")] - [Authorize(Policy = "JwtOnlyAndNotBanned")] - public async Task DeleteUserReport(Guid uuid, int reportId) - { - var jwtUser = HttpContext.GetJwtUser()!; - - var user = await _userService.GetByUUID(uuid); - if (user == null) - return NotFound(new { success = false, message = "User not found." }); - - var report = await _reportService.GetReportByID(reportId); - if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) - return NotFound(new { success = false, message = "Report not found." }); - - var result = await _reportService.DeleteReport(report); - if (!result) - return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); - - return Ok(new { success = true, message = "Report deleted successfully." }); - } - - [HttpGet] - [Authorize(Policy = "JwtOnly")] - [Route("{uuid}/reports")] - public async Task GetUserReports(Guid uuid, [FromQuery] ReportQuery request) - { - var jwtUser = HttpContext.GetJwtUser()!; - - var user = await _userService.GetByUUID(uuid); - if (user == null) - return NotFound(new { success = false, message = "User not found." }); - - if (!jwtUser.Roles.HasFlag(Role.Admin)) - return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." }); - - var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; - var reports = await _reportService.GetUserReports(query); - var totalCount = await _reportService.GetReportCount(query); - var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok( - new - { - Reports = reports, - Pagination = new - { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages, - }, - } - ); - } - - [HttpGet] - [Authorize(Policy = "JwtOnly")] - [Route("{uuid}/reports/submitted")] - public async Task GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request) - { - var jwtUser = HttpContext.GetJwtUser()!; - - var user = await _userService.GetByUUID(uuid); - if (user == null) - return NotFound(new { success = false, message = "User not found." }); - - var isOwner = user.UUID == jwtUser.UUID; - var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator); - if (!isOwner && !hasPrivilegedRole) - return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." }); - - var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; - - var reports = await _reportService.GetReports(query); - var totalCount = await _reportService.GetReportCount(query); - var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - - return Ok( - new - { - Reports = reports, - Pagination = new - { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages, - }, - } - ); - } - private async Task BuildUserResponse(User user, int page = 1) { var isAuthenticatedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString(); @@ -400,8 +231,8 @@ namespace SharpbinV3.Server.Controllers CreatedAt = p.CreatedAt, Title = p.Title, Syntax = p.Syntax, - Size = p.Size, - TrueSize = p.TrueSize, + OriginalSize = p.OriginalSize, + StoredSize = p.StoredSize, Views = p.Views, Visibility = p.Visibility, EditedAt = p.EditedAt, diff --git a/SharpbinV3.Server/DTOs/Paste/CommentDtos.cs b/SharpbinV3.Server/DTOs/Paste/CommentDtos.cs new file mode 100644 index 0000000..11d9d96 --- /dev/null +++ b/SharpbinV3.Server/DTOs/Paste/CommentDtos.cs @@ -0,0 +1,53 @@ +using SharpbinV3.Server.Data.Enums; +using SharpbinV3.Server.DTOs.User; + +namespace SharpbinV3.Server.DTOs.Paste +{ + public class CreateCommentDto + { + public string Content { get; set; } = string.Empty; + public long? ParentCommentID { get; set; } + } + + public class ReactToCommentDto + { + public Interaction? Reaction { get; set; } + } + + public class ReactToPasteDto + { + public Interaction? Reaction { get; set; } + } + + public class CommentResponseDto + { + public long Id { get; set; } + public long? ParentCommentID { get; set; } + public string? Content { get; set; } + public long StoredSize { get; set; } + public long OriginalSize { get; set; } + public bool IsCompressed { get; set; } + public long CreatedAt { get; set; } + public long? UpdatedAt { get; set; } + public int Likes { get; set; } + public int Dislikes { get; set; } + public Interaction? UserReaction { get; set; } + public UserSimpleDto? Author { get; set; } + } + + public class CommentReactionResponseDto + { + public long CommentID { get; set; } + public int Likes { get; set; } + public int Dislikes { get; set; } + public Interaction? UserReaction { get; set; } + } + + public class PasteReactionResponseDto + { + public string PasteID { get; set; } = string.Empty; + public int Likes { get; set; } + public int Dislikes { get; set; } + public Interaction? UserReaction { get; set; } + } +} diff --git a/SharpbinV3.Server/DTOs/Paste/PasteResponseDto.cs b/SharpbinV3.Server/DTOs/Paste/PasteResponseDto.cs index 1706606..5397c35 100644 --- a/SharpbinV3.Server/DTOs/Paste/PasteResponseDto.cs +++ b/SharpbinV3.Server/DTOs/Paste/PasteResponseDto.cs @@ -10,14 +10,17 @@ namespace SharpbinV3.Server.DTOs.Paste public long CreatedAt { get; set; } public string? Title { get; set; } public string? Syntax { get; set; } - public long Size { get; set; } - public long TrueSize { get; set; } + public long StoredSize { get; set; } + public long OriginalSize { get; set; } public bool IsCompressed { get; set; } public int Views { get; set; } public Visibility Visibility { get; set; } public long? EditedAt { get; set; } public long ExpiresAt { get; set; } public int? ReportCount { get; set; } + public int Likes { get; set; } + public int Dislikes { get; set; } + public Interaction? UserReaction { get; set; } public UserSimpleDto? Author { get; set; } } @@ -27,8 +30,8 @@ namespace SharpbinV3.Server.DTOs.Paste public Guid UUID { get; set; } public long CreatedAt { get; set; } public bool IsCompressed { get; set; } - public long Size { get; set; } - public long TrueSize { get; set; } + public long StoredSize { get; set; } + public long OriginalSize { get; set; } public long ExpiresAt { get; set; } public Visibility Visibility { get; set; } } diff --git a/SharpbinV3.Server/DTOs/Report/ReportQueryDto.cs b/SharpbinV3.Server/DTOs/Report/ReportQueryDto.cs index 6910a5e..0b32811 100644 --- a/SharpbinV3.Server/DTOs/Report/ReportQueryDto.cs +++ b/SharpbinV3.Server/DTOs/Report/ReportQueryDto.cs @@ -6,7 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report { public Guid? ReporterUUID { get; init; } public Guid? UserUUID { get; init; } - public int? PastePID { get; init; } + public long? PastePID { get; init; } public string? PasteId { get; init; } public ReportTargetType? TargetType { get; init; } public ReportType? Type { get; init; } diff --git a/SharpbinV3.Server/DTOs/User/UserResponseDto.cs b/SharpbinV3.Server/DTOs/User/UserResponseDto.cs index 910980e..1be9c70 100644 --- a/SharpbinV3.Server/DTOs/User/UserResponseDto.cs +++ b/SharpbinV3.Server/DTOs/User/UserResponseDto.cs @@ -5,7 +5,7 @@ namespace SharpbinV3.Server.DTOs.User { public class UserSimpleDto { - public int? UID { get; set; } + public long? UID { get; set; } public Guid UUID { get; set; } public long CreatedAt { get; set; } public string Username { get; set; } = string.Empty; diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index fa4837a..d713dae 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -7,12 +7,15 @@ namespace SharpbinV3.Server.Data { public DbSet Users => Set(); public DbSet Pastes => Set(); + public DbSet PasteInteractions => Set(); public DbSet PasteViews => Set(); public DbSet RefreshTokens => Set(); public DbSet UserTotps => Set(); public DbSet Reports => Set(); public DbSet ApiKeys => Set(); public DbSet EmailVerificationTokens => Set(); + public DbSet Comments => Set(); + public DbSet CommentInteractions => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -59,6 +62,12 @@ namespace SharpbinV3.Server.Data .HasForeignKey(r => r.UserUUID) .OnDelete(DeleteBehavior.SetNull); + modelBuilder.Entity() + .HasOne() + .WithMany(c => c.Reports) + .HasForeignKey(r => r.CommentID) + .OnDelete(DeleteBehavior.SetNull); + modelBuilder.Entity() .HasOne(a => a.User) .WithMany(u => u.ApiKeys) @@ -70,6 +79,24 @@ namespace SharpbinV3.Server.Data .WithMany(u => u.EmailVerificationTokens) .HasForeignKey(a => a.UserUUID) .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasOne(c => c.ParentComment) + .WithMany(c => c.Replies) + .HasForeignKey(c => c.ParentCommentID) + .OnDelete(DeleteBehavior.Restrict); + + modelBuilder.Entity() + .HasOne(ci => ci.Comment) + .WithMany(c => c.Interactions) + .HasForeignKey(ci => ci.CommentID) + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasOne(pi => pi.Paste) + .WithMany(p => p.Interactions) + .HasForeignKey(pi => pi.PasteID) + .OnDelete(DeleteBehavior.Cascade); } } } diff --git a/SharpbinV3.Server/Data/Entities/Comment.cs b/SharpbinV3.Server/Data/Entities/Comment.cs new file mode 100644 index 0000000..f68cd74 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/Comment.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace SharpbinV3.Server.Data.Entities +{ + public class Comment + { + [Key] + public long Id { get; set; } + public long PastePID { get; set; } + public long? ParentCommentID { get; set; } + + [MaxLength(5000)] + public byte[]? Content { get; set; } = null!; // compressed & decompressed server side, if deleted then null + public long StoredSize { get; set; } + public long OriginalSize { get; set; } + public bool IsCompressed { get; set; } = false; + + public Guid UserUUID { get; set; } + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + public long? UpdatedAt { get; set; } + + public Paste Paste { get; set; } = null!; + public User User { get; set; } = null!; + public Comment? ParentComment { get; set; } + public List Interactions { get; set; } = []; + public List Replies { get; set; } = []; + public List Reports { get; set; } = []; + + [NotMapped] + public int PositiveInteractionCount { get; set; } + + [NotMapped] + public int NegativeInteractionCount { get; set; } + } +} diff --git a/SharpbinV3.Server/Data/Entities/CommentInteraction.cs b/SharpbinV3.Server/Data/Entities/CommentInteraction.cs new file mode 100644 index 0000000..99184e7 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/CommentInteraction.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using SharpbinV3.Server.Data.Enums; + +namespace SharpbinV3.Server.Data.Entities +{ + [Index(nameof(CommentID), nameof(UserUUID), IsUnique = true)] + [Index(nameof(CommentID), nameof(Type))] + public class CommentInteraction + { + [Key] + public long Id { get; set; } + public long CommentID { get; set; } + public Guid UserUUID { get; set; } + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + public Interaction Type { get; set; } + + public Comment Comment { get; set; } = null!; + } +} diff --git a/SharpbinV3.Server/Data/Entities/Paste.cs b/SharpbinV3.Server/Data/Entities/Paste.cs index bd11925..9e17c08 100644 --- a/SharpbinV3.Server/Data/Entities/Paste.cs +++ b/SharpbinV3.Server/Data/Entities/Paste.cs @@ -1,22 +1,21 @@ using Microsoft.EntityFrameworkCore; using SharpbinV3.Server.Data.Enums; using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace SharpbinV3.Server.Data.Entities { - [Index(nameof(PID), IsUnique = true)] - [Index(nameof(UUID), IsUnique = true)] + [Index(nameof(UUID))] [Index(nameof(ID), IsUnique = true)] [Index(nameof(AuthorUUID))] [Index(nameof(ExpiresAt))] - [Index(nameof(Visibility))] [Index(nameof(Syntax))] [Index(nameof(Views))] - [Index(nameof(Size))] + [Index(nameof(StoredSize))] public sealed class Paste { [Key] - public int PID { get; set; } + public long PID { get; set; } public required Guid UUID { get; set; } public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); public required string ID { get; set; } @@ -28,8 +27,8 @@ namespace SharpbinV3.Server.Data.Entities public long? EditedAt { get; set; } public required byte[] Content { get; set; } - public long Size { get; set; } // stored size (may be compressed) - public long TrueSize { get; set; } // uncompressed size + public long StoredSize { get; set; } + public long OriginalSize { get; set; } public bool IsCompressed { get; set; } = false; public int Views { get; set; } @@ -40,5 +39,12 @@ namespace SharpbinV3.Server.Data.Entities public List PasteViews { get; set; } = []; public List Reports { get; set; } = []; + public List Comments { get; set; } = []; + public List Interactions { get; set; } = []; + + [NotMapped] + public int PositiveInteractionCount { get; set; } + [NotMapped] + public int NegativeInteractionCount { get; set; } } } diff --git a/SharpbinV3.Server/Data/Entities/PasteInteraction.cs b/SharpbinV3.Server/Data/Entities/PasteInteraction.cs new file mode 100644 index 0000000..c0ef400 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/PasteInteraction.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using SharpbinV3.Server.Data.Enums; + +namespace SharpbinV3.Server.Data.Entities +{ + [Index(nameof(PasteID), nameof(UserUUID), IsUnique = true)] + [Index(nameof(PasteID), nameof(Type))] + public class PasteInteraction + { + [Key] + public long Id { get; set; } + public long PasteID { get; set; } + public Guid UserUUID { get; set; } + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + public Interaction Type { get; set; } + + public Paste Paste { get; set; } = null!; + } +} diff --git a/SharpbinV3.Server/Data/Entities/PasteView.cs b/SharpbinV3.Server/Data/Entities/PasteView.cs index 577f4d8..3074bde 100644 --- a/SharpbinV3.Server/Data/Entities/PasteView.cs +++ b/SharpbinV3.Server/Data/Entities/PasteView.cs @@ -8,7 +8,8 @@ namespace SharpbinV3.Server.Data.Entities { [Key] public int Id { get; set; } - public int PastePID { get; set; } + public long PastePID { get; set; } + [MaxLength(64)] public string ViewerHash { get; set; } = null!; public long ViewedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); diff --git a/SharpbinV3.Server/Data/Entities/Report.cs b/SharpbinV3.Server/Data/Entities/Report.cs index 3a39f78..e5c956c 100644 --- a/SharpbinV3.Server/Data/Entities/Report.cs +++ b/SharpbinV3.Server/Data/Entities/Report.cs @@ -25,8 +25,9 @@ namespace SharpbinV3.Server.Data.Entities public Guid ReporterUUID { get; set; } public ReportTargetType TargetType { get; set; } - public int? PastePID { get; set; } + public long? PastePID { get; set; } public Guid? UserUUID { get; set; } + public long? CommentID { get; set; } public Paste? Paste { get; set; } public User? User { get; set; } @@ -48,6 +49,8 @@ namespace SharpbinV3.Server.Data.Entities public enum ReportTargetType { Paste, - User + User, + Comment + } } diff --git a/SharpbinV3.Server/Data/Entities/User.cs b/SharpbinV3.Server/Data/Entities/User.cs index b1d9c3b..9d3ed41 100644 --- a/SharpbinV3.Server/Data/Entities/User.cs +++ b/SharpbinV3.Server/Data/Entities/User.cs @@ -17,7 +17,7 @@ namespace SharpbinV3.Server.Data.Entities [Index(nameof(UUID), IsUnique = true)] public sealed class User { - public int? UID { get; set; } + public long? UID { get; set; } [Key] public required Guid UUID { get; set; } = Guid.CreateVersion7(); public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); @@ -39,6 +39,7 @@ namespace SharpbinV3.Server.Data.Entities public List Reports { get; set; } = []; public List ApiKeys { get; set; } = []; public List EmailVerificationTokens { get; set; } = []; + public List Comments { get; set; } = []; public UserTotp? Totp { get; set; } } } diff --git a/SharpbinV3.Server/Data/Enums/Interaction.cs b/SharpbinV3.Server/Data/Enums/Interaction.cs new file mode 100644 index 0000000..31aa003 --- /dev/null +++ b/SharpbinV3.Server/Data/Enums/Interaction.cs @@ -0,0 +1,8 @@ +namespace SharpbinV3.Server.Data.Enums +{ + public enum Interaction + { + Positive = 1, + Negative = 2 + } +} \ No newline at end of file diff --git a/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.Designer.cs b/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.Designer.cs new file mode 100644 index 0000000..04543bc --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.Designer.cs @@ -0,0 +1,615 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260424085542_InteractionsAndComments")] + partial class InteractionsAndComments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.3"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("TrueSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ParentCommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("UserUUID"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CommentID"); + + b.ToTable("CommentInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("StoredSize"); + + b.HasIndex("Syntax"); + + b.HasIndex("UUID"); + + b.HasIndex("Views"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PasteID"); + + b.ToTable("PasteInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("CommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsBanned") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Roles") + .HasColumnType("INTEGER"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment") + .WithMany("Replies") + .HasForeignKey("ParentCommentID") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Comments") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany() + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ParentComment"); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment") + .WithMany("Interactions") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Comment"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("EmailVerificationTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Interactions") + .HasForeignKey("PasteID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null) + .WithMany("Reports") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Navigation("Interactions"); + + b.Navigation("Replies"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("Comments"); + + b.Navigation("Interactions"); + + b.Navigation("PasteViews"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("ApiKeys"); + + b.Navigation("EmailVerificationTokens"); + + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.cs b/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.cs new file mode 100644 index 0000000..33617d5 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424085542_InteractionsAndComments.cs @@ -0,0 +1,243 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class InteractionsAndComments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Pastes_PID", + table: "Pastes"); + + migrationBuilder.DropIndex( + name: "IX_Pastes_Size", + table: "Pastes"); + + migrationBuilder.DropIndex( + name: "IX_Pastes_UUID", + table: "Pastes"); + + migrationBuilder.DropIndex( + name: "IX_Pastes_Visibility", + table: "Pastes"); + + migrationBuilder.RenameColumn( + name: "TrueSize", + table: "Pastes", + newName: "StoredSize"); + + migrationBuilder.RenameColumn( + name: "Size", + table: "Pastes", + newName: "OriginalSize"); + + migrationBuilder.AddColumn( + name: "CommentID", + table: "Reports", + type: "INTEGER", + nullable: true); + + migrationBuilder.CreateTable( + name: "Comments", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PastePID = table.Column(type: "INTEGER", nullable: false), + ParentCommentID = table.Column(type: "INTEGER", nullable: true), + Content = table.Column(type: "BLOB", maxLength: 5000, nullable: true), + Size = table.Column(type: "INTEGER", nullable: false), + TrueSize = table.Column(type: "INTEGER", nullable: false), + IsCompressed = table.Column(type: "INTEGER", nullable: false), + UserUUID = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + UpdatedAt = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Comments", x => x.Id); + table.ForeignKey( + name: "FK_Comments_Comments_ParentCommentID", + column: x => x.ParentCommentID, + principalTable: "Comments", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_Comments_Pastes_PastePID", + column: x => x.PastePID, + principalTable: "Pastes", + principalColumn: "PID", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Comments_Users_UserUUID", + column: x => x.UserUUID, + principalTable: "Users", + principalColumn: "UUID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PasteInteractions", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PasteID = table.Column(type: "INTEGER", nullable: false), + UserUUID = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + Type = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PasteInteractions", x => x.Id); + table.ForeignKey( + name: "FK_PasteInteractions_Pastes_PasteID", + column: x => x.PasteID, + principalTable: "Pastes", + principalColumn: "PID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "CommentInteractions", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + CommentID = table.Column(type: "INTEGER", nullable: false), + UserUUID = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + Type = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CommentInteractions", x => x.Id); + table.ForeignKey( + name: "FK_CommentInteractions_Comments_CommentID", + column: x => x.CommentID, + principalTable: "Comments", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Reports_CommentID", + table: "Reports", + column: "CommentID"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_StoredSize", + table: "Pastes", + column: "StoredSize"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_UUID", + table: "Pastes", + column: "UUID"); + + migrationBuilder.CreateIndex( + name: "IX_CommentInteractions_CommentID", + table: "CommentInteractions", + column: "CommentID"); + + migrationBuilder.CreateIndex( + name: "IX_Comments_ParentCommentID", + table: "Comments", + column: "ParentCommentID"); + + migrationBuilder.CreateIndex( + name: "IX_Comments_PastePID", + table: "Comments", + column: "PastePID"); + + migrationBuilder.CreateIndex( + name: "IX_Comments_UserUUID", + table: "Comments", + column: "UserUUID"); + + migrationBuilder.CreateIndex( + name: "IX_PasteInteractions_PasteID", + table: "PasteInteractions", + column: "PasteID"); + + migrationBuilder.AddForeignKey( + name: "FK_Reports_Comments_CommentID", + table: "Reports", + column: "CommentID", + principalTable: "Comments", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Reports_Comments_CommentID", + table: "Reports"); + + migrationBuilder.DropTable( + name: "CommentInteractions"); + + migrationBuilder.DropTable( + name: "PasteInteractions"); + + migrationBuilder.DropTable( + name: "Comments"); + + migrationBuilder.DropIndex( + name: "IX_Reports_CommentID", + table: "Reports"); + + migrationBuilder.DropIndex( + name: "IX_Pastes_StoredSize", + table: "Pastes"); + + migrationBuilder.DropIndex( + name: "IX_Pastes_UUID", + table: "Pastes"); + + migrationBuilder.DropColumn( + name: "CommentID", + table: "Reports"); + + migrationBuilder.RenameColumn( + name: "StoredSize", + table: "Pastes", + newName: "TrueSize"); + + migrationBuilder.RenameColumn( + name: "OriginalSize", + table: "Pastes", + newName: "Size"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_PID", + table: "Pastes", + column: "PID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_Size", + table: "Pastes", + column: "Size"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_UUID", + table: "Pastes", + column: "UUID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_Visibility", + table: "Pastes", + column: "Visibility"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.Designer.cs b/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.Designer.cs new file mode 100644 index 0000000..e97c589 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.Designer.cs @@ -0,0 +1,621 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260424090002_IndexInteractions")] + partial class IndexInteractions + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.3"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("TrueSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ParentCommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("UserUUID"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CommentID", "Type"); + + b.HasIndex("CommentID", "UserUUID") + .IsUnique(); + + b.ToTable("CommentInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("StoredSize"); + + b.HasIndex("Syntax"); + + b.HasIndex("UUID"); + + b.HasIndex("Views"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PasteID", "Type"); + + b.HasIndex("PasteID", "UserUUID") + .IsUnique(); + + b.ToTable("PasteInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("CommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsBanned") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Roles") + .HasColumnType("INTEGER"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment") + .WithMany("Replies") + .HasForeignKey("ParentCommentID") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Comments") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany() + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ParentComment"); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment") + .WithMany("Interactions") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Comment"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("EmailVerificationTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Interactions") + .HasForeignKey("PasteID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null) + .WithMany("Reports") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Navigation("Interactions"); + + b.Navigation("Replies"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("Comments"); + + b.Navigation("Interactions"); + + b.Navigation("PasteViews"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("ApiKeys"); + + b.Navigation("EmailVerificationTokens"); + + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.cs b/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.cs new file mode 100644 index 0000000..30b4607 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424090002_IndexInteractions.cs @@ -0,0 +1,74 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class IndexInteractions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PasteInteractions_PasteID", + table: "PasteInteractions"); + + migrationBuilder.DropIndex( + name: "IX_CommentInteractions_CommentID", + table: "CommentInteractions"); + + migrationBuilder.CreateIndex( + name: "IX_PasteInteractions_PasteID_Type", + table: "PasteInteractions", + columns: new[] { "PasteID", "Type" }); + + migrationBuilder.CreateIndex( + name: "IX_PasteInteractions_PasteID_UserUUID", + table: "PasteInteractions", + columns: new[] { "PasteID", "UserUUID" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_CommentInteractions_CommentID_Type", + table: "CommentInteractions", + columns: new[] { "CommentID", "Type" }); + + migrationBuilder.CreateIndex( + name: "IX_CommentInteractions_CommentID_UserUUID", + table: "CommentInteractions", + columns: new[] { "CommentID", "UserUUID" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PasteInteractions_PasteID_Type", + table: "PasteInteractions"); + + migrationBuilder.DropIndex( + name: "IX_PasteInteractions_PasteID_UserUUID", + table: "PasteInteractions"); + + migrationBuilder.DropIndex( + name: "IX_CommentInteractions_CommentID_Type", + table: "CommentInteractions"); + + migrationBuilder.DropIndex( + name: "IX_CommentInteractions_CommentID_UserUUID", + table: "CommentInteractions"); + + migrationBuilder.CreateIndex( + name: "IX_PasteInteractions_PasteID", + table: "PasteInteractions", + column: "PasteID"); + + migrationBuilder.CreateIndex( + name: "IX_CommentInteractions_CommentID", + table: "CommentInteractions", + column: "CommentID"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.Designer.cs b/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.Designer.cs new file mode 100644 index 0000000..88daca7 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.Designer.cs @@ -0,0 +1,623 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260424091805_RenameCommentSizes")] + partial class RenameCommentSizes + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.3"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ParentCommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("UserUUID"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CommentID", "Type"); + + b.HasIndex("CommentID", "UserUUID") + .IsUnique(); + + b.ToTable("CommentInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("StoredSize"); + + b.HasIndex("Syntax"); + + b.HasIndex("UUID"); + + b.HasIndex("Views"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PasteID", "Type"); + + b.HasIndex("PasteID", "UserUUID") + .IsUnique(); + + b.ToTable("PasteInteractions"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("CommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsBanned") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Roles") + .HasColumnType("INTEGER"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment") + .WithMany("Replies") + .HasForeignKey("ParentCommentID") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Comments") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Comments") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ParentComment"); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment") + .WithMany("Interactions") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Comment"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("EmailVerificationTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Interactions") + .HasForeignKey("PasteID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null) + .WithMany("Reports") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Navigation("Interactions"); + + b.Navigation("Replies"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("Comments"); + + b.Navigation("Interactions"); + + b.Navigation("PasteViews"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("ApiKeys"); + + b.Navigation("Comments"); + + b.Navigation("EmailVerificationTokens"); + + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.cs b/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.cs new file mode 100644 index 0000000..e1d7b06 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260424091805_RenameCommentSizes.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class RenameCommentSizes : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "TrueSize", + table: "Comments", + newName: "StoredSize"); + + migrationBuilder.RenameColumn( + name: "Size", + table: "Comments", + newName: "OriginalSize"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "StoredSize", + table: "Comments", + newName: "TrueSize"); + + migrationBuilder.RenameColumn( + name: "OriginalSize", + table: "Comments", + newName: "Size"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index 8660c80..3f87888 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -47,6 +47,79 @@ namespace SharpbinV3.Server.Migrations b.ToTable("ApiKeys"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ParentCommentID"); + + b.HasIndex("PastePID"); + + b.HasIndex("UserUUID"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CommentID", "Type"); + + b.HasIndex("CommentID", "UserUUID") + .IsUnique(); + + b.ToTable("CommentInteractions"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => { b.Property("UUID") @@ -81,7 +154,7 @@ namespace SharpbinV3.Server.Migrations modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { - b.Property("PID") + b.Property("PID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); @@ -107,7 +180,10 @@ namespace SharpbinV3.Server.Migrations b.Property("IsCompressed") .HasColumnType("INTEGER"); - b.Property("Size") + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") .HasColumnType("INTEGER"); b.Property("Syntax") @@ -116,9 +192,6 @@ namespace SharpbinV3.Server.Migrations b.Property("Title") .HasColumnType("TEXT"); - b.Property("TrueSize") - .HasColumnType("INTEGER"); - b.Property("UUID") .HasColumnType("TEXT"); @@ -137,30 +210,52 @@ namespace SharpbinV3.Server.Migrations b.HasIndex("ID") .IsUnique(); - b.HasIndex("PID") - .IsUnique(); - - b.HasIndex("Size"); + b.HasIndex("StoredSize"); b.HasIndex("Syntax"); - b.HasIndex("UUID") - .IsUnique(); + b.HasIndex("UUID"); b.HasIndex("Views"); - b.HasIndex("Visibility"); - b.ToTable("Pastes"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PasteID", "Type"); + + b.HasIndex("PasteID", "UserUUID") + .IsUnique(); + + b.ToTable("PasteInteractions"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); - b.Property("PastePID") + b.Property("PastePID") .HasColumnType("INTEGER"); b.Property("ViewedAt") @@ -231,6 +326,9 @@ namespace SharpbinV3.Server.Migrations .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); + b.Property("CommentID") + .HasColumnType("INTEGER"); + b.Property("CreatedAt") .HasColumnType("INTEGER"); @@ -238,7 +336,7 @@ namespace SharpbinV3.Server.Migrations .HasMaxLength(1000) .HasColumnType("TEXT"); - b.Property("PastePID") + b.Property("PastePID") .HasColumnType("INTEGER"); b.Property("ReporterUUID") @@ -261,6 +359,8 @@ namespace SharpbinV3.Server.Migrations b.HasKey("ReportID"); + b.HasIndex("CommentID"); + b.HasIndex("PastePID"); b.HasIndex("ReportID") @@ -306,7 +406,7 @@ namespace SharpbinV3.Server.Migrations b.Property("Roles") .HasColumnType("INTEGER"); - b.Property("UID") + b.Property("UID") .HasColumnType("INTEGER"); b.Property("Username") @@ -354,6 +454,43 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment") + .WithMany("Replies") + .HasForeignKey("ParentCommentID") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Comments") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Comments") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ParentComment"); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment") + .WithMany("Interactions") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Comment"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => { b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") @@ -375,6 +512,17 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Interactions") + .HasForeignKey("PasteID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => { b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") @@ -399,6 +547,11 @@ namespace SharpbinV3.Server.Migrations modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => { + b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null) + .WithMany("Reports") + .HasForeignKey("CommentID") + .OnDelete(DeleteBehavior.SetNull); + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") .WithMany("Reports") .HasForeignKey("PastePID") @@ -425,8 +578,21 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Navigation("Interactions"); + + b.Navigation("Replies"); + + b.Navigation("Reports"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { + b.Navigation("Comments"); + + b.Navigation("Interactions"); + b.Navigation("PasteViews"); b.Navigation("Reports"); @@ -436,6 +602,8 @@ namespace SharpbinV3.Server.Migrations { b.Navigation("ApiKeys"); + b.Navigation("Comments"); + b.Navigation("EmailVerificationTokens"); b.Navigation("Pastes"); diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 8f09990..68800bc 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -74,6 +74,7 @@ namespace SharpbinV3.Server builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -331,8 +332,8 @@ namespace SharpbinV3.Server var pasteCount = await db.Pastes.CountAsync(); var userCount = await db.Users.CountAsync(); - var totalPasteSize = await db.Pastes.SumAsync(p => p.Size); - var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.TrueSize); + var totalPasteSize = await db.Pastes.SumAsync(p => p.StoredSize); + var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.OriginalSize); var dailyCounts = await db .Pastes.Where(p => p.CreatedAt >= sevenDaysAgo) diff --git a/SharpbinV3.Server/Services/CommentService.cs b/SharpbinV3.Server/Services/CommentService.cs new file mode 100644 index 0000000..884eaa0 --- /dev/null +++ b/SharpbinV3.Server/Services/CommentService.cs @@ -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 options) + { + private readonly AppDbContext _db = dbContext; + private readonly ICompressionService _cs = cs; + private readonly PasteSettings _pasteSettings = options.Value; + + public async Task 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 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 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 HardDeleteComment(Comment comment) + { + _db.Comments.Remove(comment); + var result = await _db.SaveChangesAsync(); + return result > 0; + } + + public async Task 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 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> 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> 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> 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> GetUserInteractions(List 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 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 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 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); + } + } + } +} diff --git a/SharpbinV3.Server/Services/CompressionService.cs b/SharpbinV3.Server/Services/CompressionService.cs index afd418a..8f92b9e 100644 --- a/SharpbinV3.Server/Services/CompressionService.cs +++ b/SharpbinV3.Server/Services/CompressionService.cs @@ -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) diff --git a/SharpbinV3.Server/Services/PasteService.cs b/SharpbinV3.Server/Services/PasteService.cs index 0311944..8d88273 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -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 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 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 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 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 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) diff --git a/SharpbinV3.Server/Services/ReportService.cs b/SharpbinV3.Server/Services/ReportService.cs index cb0e3f9..3b955ee 100644 --- a/SharpbinV3.Server/Services/ReportService.cs +++ b/SharpbinV3.Server/Services/ReportService.cs @@ -26,7 +26,7 @@ namespace SharpbinV3.Server.Services return report; } - public async Task CreateReport(Guid reporterUUID, ReportTargetType targetType, int? pastePID, ReportType type, string description) + public async Task 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); diff --git a/SharpbinV3.Server/Settings/PasteSettings.cs b/SharpbinV3.Server/Settings/PasteSettings.cs index 9854ad6..4f8a55e 100644 --- a/SharpbinV3.Server/Settings/PasteSettings.cs +++ b/SharpbinV3.Server/Settings/PasteSettings.cs @@ -8,6 +8,7 @@ namespace SharpbinV3.Server.Settings public int MaxTitleLength { get; set; } = 500; public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB public bool EnablePasteCompression { get; set; } = true; + public double CompressionThreshold { get; set; } = 0.9; // only store compressed if reduced by at least 10% public bool RequiresVerification { get; set; } = true; [Required, MinLength(32), MaxLength(128)]