diff --git a/SharpbinV3.Client/src/lib/types/paste.ts b/SharpbinV3.Client/src/lib/types/paste.ts index 81b4b8d..03d8592 100644 --- a/SharpbinV3.Client/src/lib/types/paste.ts +++ b/SharpbinV3.Client/src/lib/types/paste.ts @@ -11,5 +11,6 @@ export interface Paste { syntax: string; visibility: 0 | 1 | 2; expiresAt: number; + editedAt: number | null; author: Author | null; } diff --git a/SharpbinV3.Client/src/routes/[id]/+page.svelte b/SharpbinV3.Client/src/routes/[id]/+page.svelte index 133f1d7..040e0ed 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.svelte +++ b/SharpbinV3.Client/src/routes/[id]/+page.svelte @@ -2,24 +2,98 @@ import hljs from 'highlight.js'; import { onMount } from 'svelte'; import type { PageData } from './$types'; - import { FileBox, Eye, User, CalendarDays, CalendarOff, Code } from '@lucide/svelte/icons/index'; + import { + FileBox, + Eye, + EyeClosed, + EyeOff, + User, + CalendarDays, + CalendarOff, + Code, + Pencil, + PencilOff, + PencilLine, + Trash2, + Download, + Copy, + Check, + CalendarCog + } from '@lucide/svelte/icons/index'; import { formatBytes, + formatNumber, extractDateFromUUIDv7, dateToRelativeString, tooltip } from '$lib/utils/misc'; import { displayNames } from '$lib/consts'; import { resolve } from '$app/paths'; - import { decryptAES } from '$lib/utils/encryption'; + import { decryptAES, encryptAES } from '$lib/utils/encryption'; + import { fade } from 'svelte/transition'; + import { getToken } from '$lib/utils/auth'; + import { user } from '$lib/stores/user'; + import Dropdown from '$lib/components/Dropdown.svelte'; + import type { Paste } from '$lib/types/paste'; export let data: PageData; - let codeElement: HTMLElement; let showPasswordModal = false; + let passwordModalResolve: ((password: string) => void) | null = null; + let passwordModalMode: 'decrypt' | 'encrypt' = 'decrypt'; + let editing = false; + let editContent: string | null = null; + let editMetadata: Paste | null = data.paste ? { ...data.paste } : null; + let editError = ''; + let editLoading = false; let passwordInput = ''; + let pasteContent = ''; let decryptedContent: string | null = null; let decryptError = ''; let contentRendered = false; + let downloadedPaste = false; + let copiedPaste = false; + + let now = new Date(); + $: isExpired = + data?.paste?.expiresAt && data.paste.expiresAt !== 0 + ? new Date(data.paste.expiresAt).getTime() <= now.getTime() + : false; + + let interval: ReturnType | null = null; + const syntaxOptions = data.options?.syntaxes.map((lang: string) => ({ + value: lang, + label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1) + })); + const expiresOptions = [ + { value: 0, label: 'Never Expire' }, + { value: 600000, label: 'Expire in 10 Minutes' }, + { value: 3600000, label: 'Expire in 1 Hour' }, + { value: 86400000, label: 'Expire in 1 Day' }, + { value: 604800000, label: 'Expire in 1 Week' }, + { value: 1209600000, label: 'Expire in 2 Weeks' }, + { value: 2592000000, label: 'Expire in 1 Month' }, + { value: 7776000000, label: 'Expire in 3 Months' }, + { value: 15552000000, label: 'Expire in 6 Months' }, + { value: 31536000000, label: 'Expire in 1 Year' }, + { value: 63072000000, label: 'Expire in 2 Years' }, + { value: 157680000000, label: 'Expire in 5 Years' }, + { value: 315360000000, label: 'Expire in 10 Years' } + ]; + const visibilityOptions = data.options?.visibilities.map( + (visibility: { value: number; displayName: string }) => ({ + value: visibility.value, + label: visibility.displayName + }) + ); + + onMount(() => { + interval = setInterval(() => { + now = new Date(); + }, 1000); + return () => { + if (interval) clearInterval(interval); + }; + }); function addLineNumbers(html: string): string { const match = html.match(/[\s\S]*?([\s\S]*?)<\/code><\/pre>/); @@ -36,19 +110,15 @@ return html.replace(code, numbered); } - function renderCode() { - if (!codeElement || !data?.paste) return; - let code = decryptedContent ?? data.content ?? ''; - if (data.paste.visibility === 2 && JSON.parse(data.content)?.kdf) { - let json = JSON.parse(data.content); - if (json?.version === 1) { - } - } + function renderCode(content: string | null = null) { + if (!data?.paste) return; + let code = content ?? decryptedContent ?? data.content ?? ''; const lang = (data.paste.syntax ?? '').toLowerCase(); let highlighted = ''; try { if (lang === 'plaintext') { - const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(//g, '>'); + const escapeHtml = (s: string) => + s.replace(/&/g, '&').replace(//g, '>'); highlighted = escapeHtml(code); } else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) { highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value; @@ -57,17 +127,117 @@ } } catch { if (lang === 'plaintext') { - const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(//g, '>'); + const escapeHtml = (s: string) => + s.replace(/&/g, '&').replace(//g, '>'); highlighted = escapeHtml(code); } else { highlighted = hljs.highlightAuto(code).value; } } const wrapped = `
${highlighted}
`; - codeElement.innerHTML = addLineNumbers(wrapped); + pasteContent = addLineNumbers(wrapped); contentRendered = true; } + async function updatePaste(content: string | null, metadata: Paste | null) { + editError = ''; + editLoading = true; + try { + if (!data?.paste) { + editError = 'Paste data is missing.'; + editLoading = false; + return; + } + const token = getToken(); + if (!token) { + editError = 'Not authenticated.'; + editLoading = false; + return; + } + if ( + (content !== (decryptedContent ?? data.content) || + metadata?.visibility === 2 || + data.paste.visibility === 2) && + content !== null + ) { + let rawContent = content; + if (metadata?.visibility === 2 || data.paste.visibility === 2) { + const password = await promptPassword('encrypt'); + if (!password) { + editError = 'Password required for encryption.'; + editLoading = false; + return; + } + const encrypted = await encryptAES(content, password); + content = encrypted; + } + const res = await fetch(`/api/paste/${data.paste.id}/edit`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + }, + body: content + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + editError = err?.message || 'Failed to update paste content.'; + editLoading = false; + return; + } + data.content = rawContent; + decryptedContent = rawContent; + renderCode(rawContent); + } + if ( + (metadata?.syntax !== data.paste.syntax || + metadata?.expiresAt !== data.paste.expiresAt || + metadata?.visibility !== data.paste.visibility || + metadata?.title !== data.paste.title) && + metadata !== null + ) { + const res = await fetch(`/api/paste/${data.paste.id}/modify`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + }, + body: JSON.stringify({ + syntax: metadata.syntax, + expiresAt: metadata.expiresAt === 0 ? 0 : Date.now() + (metadata.expiresAt ?? 0), + visibility: metadata.visibility, + title: metadata.title + }) + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + editError = err?.message || 'Failed to update paste metadata.'; + editLoading = false; + 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; + } + } catch { + editError = 'An error occurred while updating.'; + } finally { + editLoading = false; + editing = false; + editContent = null; + } + } + + async function promptPassword(mode: 'decrypt' | 'encrypt' = 'decrypt'): Promise { + return new Promise((resolve) => { + showPasswordModal = true; + passwordModalResolve = resolve; + passwordModalMode = mode; + }); + } + onMount(async () => { try { if (data?.paste && data.paste.visibility === 2) { @@ -77,13 +247,30 @@ const passwordFromUrl = atob(urlHash); decryptedContent = await decryptAES(data.content, passwordFromUrl); if (decryptedContent === null) { - showPasswordModal = true; + const password = await promptPassword('decrypt'); + if (password) { + decryptedContent = await decryptAES(data.content, password); + if (decryptedContent === null) { + decryptError = 'Incorrect password. Please try again.'; + } else { + renderCode(); + history.replaceState(null, '', window.location.pathname + window.location.search); + } + } } else { renderCode(); } return; } - showPasswordModal = true; + const password = await promptPassword('decrypt'); + if (password) { + decryptedContent = await decryptAES(data.content, password); + if (decryptedContent === null) { + decryptError = 'Incorrect password. Please try again.'; + } else { + renderCode(); + } + } } else { renderCode(); } @@ -102,49 +289,25 @@ class="max-h-[80vh] w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4" > {#if data.paste} -

40 ? data.paste.title : ''} - > - {data.paste.title || 'Untitled Paste'} -

-
- -
-
- - {formatBytes(data.paste.size)} -
-
- -
- - {data.paste.views} view{data.paste.views !== 1 ? 's' : ''} -
- -
- - - {extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'} - -
- - {#if data.paste.expiresAt !== 0} -
- - - Expires in {dateToRelativeString(new Date(data.paste.expiresAt), false)} - -
- {/if} - -
- +
+

40 ? data.paste.title : ''} + > + {#if !editing} + {data.paste.title || 'Untitled Paste'} + {:else if editMetadata} + + {/if} +

+
+ {#if data.paste.author} Anonymous {/if}
-
- - - {displayNames[data.paste.syntax] ?? - data.paste.syntax.charAt(0).toUpperCase() + data.paste.syntax.slice(1)} - +
+
+
+
+
+ + {formatBytes(data.paste.size)} +
+
+ +
+ + {data.paste.views} view{data.paste.views !== 1 ? 's' : ''} +
+ +
+ + + {extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'} + +
+ {#if data.paste.editedAt} +
+ + + {#if new Date(data.paste.editedAt).getTime() > new Date().getTime() - 86400000} + Edited {dateToRelativeString(new Date(data.paste.editedAt), false, false, now)} ago + {:else} + {new Date(data.paste.editedAt).toLocaleDateString()} + {/if} + +
+ {/if} + {#if data.paste.expiresAt !== 0 || editing} +
+ + {#if !editing} + + {isExpired ? 'Expired' : 'Expires in'} + {dateToRelativeString(new Date(data.paste.expiresAt), false, false, now)} + {isExpired ? 'ago' : ''} + + {:else if editMetadata} + { + const option = expiresOptions.find((opt) => opt.value === val); + return option ? option.label : 'Select expiration...'; + }} + /> + {/if} +
+ {/if} + +
+ + {#if !editing} + + {displayNames[data.paste.syntax] ?? + data.paste.syntax.charAt(0).toUpperCase() + data.paste.syntax.slice(1)} + + {:else if editMetadata} + + {/if} +
+
+
+ {#if data.paste.visibility === 0} + + {editing ? '' : 'Public'} + {:else if data.paste.visibility === 1} + + {editing ? '' : 'Unlisted'} + {:else if data.paste.visibility === 2} + + {editing ? '' : 'Private'} + {/if} + {#if editing && editMetadata} + + {/if} +
+
-
- + +
+
+
+ {formatNumber((editContent ?? decryptedContent ?? data.content).length)} + chars + • + {formatNumber( + (editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n') + .length + )} + line{(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n') + .length !== 1 + ? 's' + : ''} +
+
+ + + {#if $user && ($user.uuid === data.paste?.author?.uuid || ['1', '255'].some( (r) => $user.roles + .toString() + .split(',') + .includes(r) ))} + {#if !editing} + + + {:else} + + + {/if} + {/if} +
+
+ {#if editing} + + {#if editError} +
+ {editError} +
+ {/if} + {:else} +
+ + {/if} +
{:else}

Paste not found

The paste you are looking for does not exist.

@@ -180,25 +613,21 @@ {#if showPasswordModal}
{ - decryptError = ''; - try { - const decrypted = await decryptAES(data.content ?? '', passwordInput); - if (decrypted === null) { - decryptError = 'Incorrect password. Please try again.'; - } else { - decryptedContent = decrypted; - showPasswordModal = false; - renderCode(); - history.replaceState(null, '', window.location.pathname + window.location.search); - } - } catch { - decryptError = 'An error occurred during decryption. Please try again.'; + on:submit|preventDefault={() => { + if (passwordModalResolve) { + passwordModalResolve(passwordInput); + passwordModalResolve = null; } + showPasswordModal = false; + decryptError = ''; }} class="w-full max-w-md rounded bg-neutral-900 p-6" > -

Enter password to decrypt

+

+ {passwordModalMode === 'decrypt' + ? 'Enter password to decrypt' + : 'Enter password to encrypt'} +

Decrypt{passwordModalMode === 'decrypt' ? 'Decrypt' : 'OK'}