more htmx

This commit is contained in:
Gregor Lohaus
2026-02-25 12:44:20 +01:00
parent 2b77988086
commit 860dfd062e
10 changed files with 191 additions and 138 deletions

View File

@@ -50,6 +50,11 @@ public class ConfigRuntimeHints implements RuntimeHintsRegistrar {
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(UploadConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(TypeAdapter.class,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);

View File

@@ -10,6 +10,7 @@ import com.gregor_lohaus.gtransfer.config.types.ServletConfig;
import com.gregor_lohaus.gtransfer.config.types.SpringConfig;
import com.gregor_lohaus.gtransfer.config.types.StorageService;
import com.gregor_lohaus.gtransfer.config.types.StorageServiceType;
import com.gregor_lohaus.gtransfer.config.types.UploadConfig;
public class DefaultConfig {
public static final Config config;
@@ -42,6 +43,12 @@ public class DefaultConfig {
sc.servletConfig = svc;
c.springConfig = sc;
UploadConfig uc = new UploadConfig();
uc.maxDownloadLimit = 100;
uc.maxExpiryDays = 30;
c.uploadConfig = uc;
config = c;
}
}

View File

@@ -11,4 +11,6 @@ public class Config implements TomlSerializable {
public SpringConfig springConfig;
@Nested(name = "storageService")
public StorageService storageService;
@Nested(name = "upload")
public UploadConfig uploadConfig;
}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class UploadConfig implements TomlSerializable {
@Property(name = "maxDownloadLimit")
public Integer maxDownloadLimit;
@Property(name = "maxExpiryDays")
public Integer maxExpiryDays;
}

View File

@@ -1,37 +1,63 @@
package com.gregor_lohaus.gtransfer.controller;
import java.io.IOException;
import java.util.Map;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.gregor_lohaus.gtransfer.model.File;
import com.gregor_lohaus.gtransfer.model.FileRepository;
import com.gregor_lohaus.gtransfer.services.filewriter.AbstractStorageService;
@RestController
@Controller
public class UploadController {
@Value("${gtransfer-config.upload.maxDownloadLimit:100}")
private Integer maxDownloadLimit;
@Value("${gtransfer-config.upload.maxExpiryDays:30}")
private Integer maxExpiryDays;
@Autowired
private AbstractStorageService storageService;
@Autowired
private FileRepository fileRepository;
@GetMapping("/upload/options")
public String options(@RequestParam String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("maxExpiryDays", maxExpiryDays);
model.addAttribute("maxDownloadLimit", maxDownloadLimit);
return "upload/options :: form";
}
@PostMapping("/upload")
public ResponseEntity<Map<String, String>> upload(
public String upload(
@RequestParam("file") MultipartFile file,
@RequestParam("hash") String hash,
@RequestParam("name") String name) throws IOException {
@RequestParam("name") String name,
@RequestParam(required = false) Integer expiryDays,
@RequestParam(required = false) Integer downloadLimit,
Model model) throws IOException {
storageService.put(hash, file.getBytes());
fileRepository.save(new File(hash, hash, name, null));
return ResponseEntity.ok(Map.of("id", hash));
int days = expiryDays != null ? Math.min(expiryDays, maxExpiryDays) : maxExpiryDays;
Integer limit = downloadLimit != null ? Math.min(downloadLimit, maxDownloadLimit) : null;
File f = new File(hash, hash, name, LocalDateTime.now().plusDays(days));
f.setDownloadLimit(limit);
fileRepository.save(f);
model.addAttribute("id", hash);
return "upload/result :: view";
}
}

View File

@@ -0,0 +1,28 @@
async function encryptFile(arrayBuffer) {
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, arrayBuffer);
// Payload: 12-byte IV prepended to ciphertext
const payload = new Uint8Array(12 + ciphertext.byteLength);
payload.set(iv, 0);
payload.set(new Uint8Array(ciphertext), 12);
// SHA-256(rawKey) → file identifier sent to server; server never sees the key itself
const rawKey = await crypto.subtle.exportKey('raw', key);
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', rawKey)))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
// Base64url-encode key for URL fragment
const base64urlKey = btoa(String.fromCharCode(...new Uint8Array(rawKey)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
return { payload, hash, base64urlKey };
}

View File

@@ -1,28 +1,17 @@
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const views = {
prompt: document.getElementById('view-prompt'),
selected: document.getElementById('view-selected'),
uploading: document.getElementById('view-uploading'),
result: document.getElementById('view-result'),
};
const promptHtml = dropZone.innerHTML;
let selectedFile = null;
function showView(name) {
Object.entries(views).forEach(([key, el]) => el.classList.toggle('d-none', key !== name));
}
// ── File selection ────────────────────────────────────────────────────────────
dropZone.addEventListener('click', () => {
if (views.prompt.classList.contains('d-none')) return;
fileInput.click();
if (selectedFile === null) fileInput.click();
});
fileInput.addEventListener('change', e => {
if (e.target.files[0]) selectFile(e.target.files[0]);
if (e.target.files[0]) onFileSelected(e.target.files[0]);
});
dropZone.addEventListener('dragover', e => {
@@ -35,101 +24,78 @@ dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
if (e.dataTransfer.files[0]) selectFile(e.dataTransfer.files[0]);
if (e.dataTransfer.files[0] && selectedFile === null) onFileSelected(e.dataTransfer.files[0]);
});
function selectFile(file) {
function onFileSelected(file) {
selectedFile = file;
document.getElementById('selected-name').textContent = file.name;
showView('selected');
// Use htmx to fetch the options form — server renders max values from config
htmx.ajax('GET', '/upload/options?name=' + encodeURIComponent(file.name), {
target: '#drop-zone',
swap: 'innerHTML'
});
}
document.getElementById('reset-btn').addEventListener('click', e => {
e.stopPropagation();
selectedFile = null;
fileInput.value = '';
showView('prompt');
});
// ── Upload (called from onclick in server-rendered options form) ──────────────
document.getElementById('new-upload-btn').addEventListener('click', e => {
e.stopPropagation();
selectedFile = null;
fileInput.value = '';
showView('prompt');
});
async function startUpload() {
const expiryDays = document.getElementById('expiry-days')?.value;
const downloadLimit = document.getElementById('download-limit')?.value;
// ── Upload ────────────────────────────────────────────────────────────────────
document.getElementById('upload-btn').addEventListener('click', async e => {
e.stopPropagation();
await upload();
});
function setStatus(msg) {
document.getElementById('upload-status').textContent = msg;
}
async function upload() {
const file = selectedFile;
showView('uploading');
dropZone.innerHTML = `
<div class="mb-3">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading\u2026</span>
</div>
</div>
<div class="drop-zone-text" id="upload-status">Encrypting\u2026</div>`;
try {
setStatus('Generating encryption key\u2026');
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
setStatus('Encrypting\u2026');
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
await file.arrayBuffer()
);
// Payload: 12-byte IV prepended to ciphertext
const payload = new Uint8Array(12 + ciphertext.byteLength);
payload.set(iv, 0);
payload.set(new Uint8Array(ciphertext), 12);
// SHA-256(rawKey) → file identifier sent to server (server never sees the key)
const rawKey = await crypto.subtle.exportKey('raw', key);
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', rawKey)))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
// Base64url-encode key for URL fragment
const base64urlKey = btoa(String.fromCharCode(...new Uint8Array(rawKey)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
const { payload, hash, base64urlKey } = await encryptFile(await selectedFile.arrayBuffer());
setStatus('Uploading\u2026');
const formData = new FormData();
formData.append('file', new Blob([payload]), file.name);
formData.append('file', new Blob([payload]), selectedFile.name);
formData.append('hash', hash);
formData.append('name', file.name);
formData.append('name', selectedFile.name);
if (expiryDays) formData.append('expiryDays', expiryDays);
if (downloadLimit) formData.append('downloadLimit', downloadLimit);
const response = await fetch('/upload', { method: 'POST', body: formData });
if (!response.ok) throw new Error(`Server responded with ${response.status}`);
if (!response.ok) throw new Error(`Server error ${response.status}`);
const { id } = await response.json();
document.getElementById('share-link').value =
`${window.location.origin}/download/${id}#${base64urlKey}`;
showView('result');
// Server returns HTML fragment; append key fragment client-side
dropZone.innerHTML = await response.text();
htmx.process(dropZone);
document.getElementById('share-link').value += '#' + base64urlKey;
} catch (err) {
setStatus(`Error: ${err.message}`);
dropZone.innerHTML = `
<div class="drop-zone-icon mb-3">&#x26A0;</div>
<div class="drop-zone-text mb-3">${err.message}</div>
<button class="btn btn-link drop-zone-text text-decoration-none" onclick="resetUpload()">Try again</button>`;
}
}
// ── Copy link ─────────────────────────────────────────────────────────────────
function setStatus(msg) {
const el = document.getElementById('upload-status');
if (el) el.textContent = msg;
}
document.getElementById('copy-btn').addEventListener('click', async e => {
e.stopPropagation();
// ── Reset (called from onclick in server-rendered fragments) ──────────────────
function resetUpload() {
selectedFile = null;
fileInput.value = '';
dropZone.innerHTML = promptHtml;
}
// ── Copy link (called from onclick in result fragment) ────────────────────────
async function copyLink() {
await navigator.clipboard.writeText(document.getElementById('share-link').value);
const btn = document.getElementById('copy-btn');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
});
}

View File

@@ -8,6 +8,7 @@
<link rel="stylesheet" th:href="@{/style.css}">
<script th:src="@{/webjars/bootstrap/dist/js/bootstrap.bundle.min.js}" defer></script>
<script th:src="@{/webjars/htmx.org/dist/htmx.min.js}" defer></script>
<script th:src="@{/crypto.js}" defer></script>
<script th:src="@{/upload.js}" defer></script>
</head>
<body class="d-flex flex-column min-vh-100">
@@ -27,10 +28,8 @@
</p>
</div>
<div class="col-lg-7 d-flex justify-content-center justify-content-lg-end">
<input type="file" id="file-input" hidden>
<div id="drop-zone" class="drop-zone text-center py-5 px-4 w-100">
<!-- State: prompt (default) -->
<div id="view-prompt">
<div class="drop-zone-icon mb-3">&#x1F4C2;</div>
<div class="mb-2">
<strong>Choose a file</strong>
@@ -38,42 +37,6 @@
</div>
<div class="drop-zone-text small">Any file type &middot; Up to <span th:text="${maxFileSize}">10GB</span></div>
</div>
<!-- State: file selected -->
<div id="view-selected" class="d-none">
<div class="drop-zone-icon mb-3">&#x1F4C4;</div>
<div class="fw-medium mb-3" id="selected-name"></div>
<div class="d-flex gap-2 justify-content-center">
<button id="upload-btn" class="btn btn-success px-4">Send</button>
<button id="reset-btn" class="btn btn-link drop-zone-text text-decoration-none">Change file</button>
</div>
</div>
<!-- State: uploading -->
<div id="view-uploading" class="d-none">
<div class="mb-3">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div class="drop-zone-text" id="upload-status">Preparing&hellip;</div>
</div>
<!-- State: result -->
<div id="view-result" class="d-none">
<div class="drop-zone-icon mb-3">&#x2705;</div>
<div class="drop-zone-text mb-3">Your file is ready to share</div>
<div class="input-group mb-2">
<input type="text" id="share-link" class="form-control form-control-sm" readonly>
<button id="copy-btn" class="btn btn-outline-success btn-sm">Copy</button>
</div>
<button id="new-upload-btn" class="btn btn-link drop-zone-text text-decoration-none small">
Send another file
</button>
</div>
<input type="file" id="file-input" hidden>
</div>
</div>
</div>
</main>

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="form">
<div class="drop-zone-icon mb-3">&#x1F4C4;</div>
<div class="fw-medium mb-3 text-truncate" th:text="${name}">filename</div>
<div class="row g-2 mb-3 text-start">
<div class="col-6">
<label for="expiry-days" class="form-label drop-zone-text small">Expires after (days)</label>
<input type="number" id="expiry-days" class="form-control form-control-sm"
min="1" th:max="${maxExpiryDays}" th:value="${maxExpiryDays}">
</div>
<div class="col-6">
<label for="download-limit" class="form-label drop-zone-text small">Download limit</label>
<input type="number" id="download-limit" class="form-control form-control-sm"
min="1" th:max="${maxDownloadLimit}" placeholder="Unlimited">
</div>
</div>
<div class="d-flex gap-2 justify-content-center">
<button class="btn btn-success px-4" onclick="startUpload()">Send</button>
<button class="btn btn-link drop-zone-text text-decoration-none" onclick="resetUpload()">Change file</button>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="view">
<div class="drop-zone-icon mb-3">&#x2705;</div>
<div class="drop-zone-text mb-3">Your file is ready to share</div>
<div class="input-group mb-2">
<input type="text" id="share-link" class="form-control form-control-sm"
th:value="@{/download/{id}(id=${id})}" readonly>
<button id="copy-btn" class="btn btn-outline-success btn-sm" onclick="copyLink()">Copy</button>
</div>
<button class="btn btn-link drop-zone-text text-decoration-none small" onclick="resetUpload()">
Send another file
</button>
</div>
</body>
</html>