Refactor statistics page and enhance logging

- Updated the layout and styling of the statistics page for better responsiveness and visual appeal.
- Introduced a new error page for 404 errors with user-friendly messaging and navigation options.
- Enhanced logging functionality to capture detailed events related to asset uploads, deletions, and HTTP requests.
- Implemented an AssetTracker to manage assets in memory, allowing for efficient tracking and retrieval.
- Improved the API for uploading and retrieving assets, ensuring better error handling and response formatting.
- Added auto-refresh functionality to the statistics page to keep data up-to-date.
This commit is contained in:
2026-01-11 07:51:47 +01:00
parent 81656ec0da
commit cde83139b1
13 changed files with 974 additions and 847 deletions

View File

@@ -2,83 +2,11 @@ name: Build & Publish
on: on:
push: push:
branches: ["main"] tags: ["v*"]
paths:
- "CHANGELOG.md"
workflow_dispatch: {} workflow_dispatch: {}
jobs: jobs:
check:
runs-on: ubuntu-latest
outputs:
should_build: ${{ steps.version_check.outputs.should_build }}
version: ${{ steps.version_check.outputs.version }}
pkg_version: ${{ steps.version_check.outputs.pkg_version }}
short_sha: ${{ steps.version_check.outputs.short_sha }}
owner: ${{ steps.meta.outputs.owner }}
repo: ${{ steps.meta.outputs.repo }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Repo meta (owner/repo)
id: meta
shell: bash
run: |
set -e
# Gitea Actions is GitHub-compatible; this usually exists.
FULL="${GITHUB_REPOSITORY:-}"
if [ -z "$FULL" ]; then
echo "GITHUB_REPOSITORY is empty. Set it in runner env or switch to explicit OWNER/REPO vars."
exit 1
fi
OWNER="${FULL%%/*}"
REPO="${FULL##*/}"
echo "owner=$OWNER" >> "$GITHUB_OUTPUT"
echo "repo=$REPO" >> "$GITHUB_OUTPUT"
- name: Check version change in CHANGELOG
id: version_check
shell: bash
run: |
set -e
OLD=$(git show HEAD~1:CHANGELOG.md | grep '^## \[' | head -1 || true)
NEW=$(grep '^## \[' CHANGELOG.md | head -1 || true)
echo "Old: $OLD"
echo "New: $NEW"
# Extract x.y.z from: ## [x.y.z] - YYYY-MM-DD
VERSION=$(echo "$NEW" | sed -n 's/^## \[\([0-9]\+\.[0-9]\+\.[0-9]\+\)\].*$/\1/p')
if [ -z "$VERSION" ]; then
echo "Could not parse version from CHANGELOG.md (expected: ## [x.y.z] - YYYY-MM-DD)"
exit 1
fi
SHORT_SHA="$(git rev-parse --short=7 HEAD)"
PKG_VERSION="${VERSION}+g${SHORT_SHA}"
echo "Parsed VERSION=$VERSION"
echo "SHORT_SHA=$SHORT_SHA"
echo "PKG_VERSION=$PKG_VERSION"
if [ "$OLD" = "$NEW" ]; then
echo "should_build=false" >> "$GITHUB_OUTPUT"
else
echo "should_build=true" >> "$GITHUB_OUTPUT"
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "short_sha=$SHORT_SHA" >> "$GITHUB_OUTPUT"
echo "pkg_version=$PKG_VERSION" >> "$GITHUB_OUTPUT"
build_publish: build_publish:
needs: check
if: needs.check.outputs.should_build == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: archlinux:latest image: archlinux:latest
@@ -93,13 +21,31 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Read package name
id: pkg_meta
shell: bash
run: |
set -e
PKG_NAME="$(sed -n 's/^name = \"\\(.*\\)\"/\\1/p' Cargo.toml | head -n 1)"
if [ -z "$PKG_NAME" ]; then
echo "Could not read package name from Cargo.toml"
exit 1
fi
echo "pkg_name=$PKG_NAME" >> "$GITHUB_OUTPUT"
- name: Create source tarball (code) - name: Create source tarball (code)
shell: bash shell: bash
run: | run: |
set -e set -e
OWNER="${{ needs.check.outputs.owner }}" FULL="${GITHUB_REPOSITORY:-}"
REPO="${{ needs.check.outputs.repo }}" if [ -z "$FULL" ]; then
PKG_VERSION="${{ needs.check.outputs.pkg_version }}" echo "GITHUB_REPOSITORY is empty. Set it in runner env or switch to explicit OWNER/REPO vars."
exit 1
fi
OWNER="${FULL%%/*}"
REPO="${FULL##*/}"
VERSION="${GITHUB_REF_NAME#v}"
PKG_VERSION="${VERSION}"
mkdir -p dist mkdir -p dist
# Clean source snapshot of the repository at current commit # Clean source snapshot of the repository at current commit
@@ -121,11 +67,18 @@ jobs:
shell: bash shell: bash
run: | run: |
set -e set -e
REPO="${{ needs.check.outputs.repo }}" FULL="${GITHUB_REPOSITORY:-}"
PKG_VERSION="${{ needs.check.outputs.pkg_version }}" if [ -z "$FULL" ]; then
echo "GITHUB_REPOSITORY is empty. Set it in runner env or switch to explicit OWNER/REPO vars."
exit 1
fi
REPO="${FULL##*/}"
VERSION="${GITHUB_REF_NAME#v}"
PKG_VERSION="${VERSION}"
BIN_NAME="${{ steps.pkg_meta.outputs.pkg_name }}"
mkdir -p dist mkdir -p dist
cp "target/release/${REPO}" "dist/${REPO}-${PKG_VERSION}-linux-x86_64" cp "target/release/${BIN_NAME}" "dist/${REPO}-${PKG_VERSION}-linux-x86_64"
chmod +x "dist/${REPO}-${PKG_VERSION}-linux-x86_64" chmod +x "dist/${REPO}-${PKG_VERSION}-linux-x86_64"
ls -lh dist ls -lh dist
@@ -137,9 +90,15 @@ jobs:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: | run: |
set -e set -e
OWNER="${{ needs.check.outputs.owner }}" FULL="${GITHUB_REPOSITORY:-}"
REPO="${{ needs.check.outputs.repo }}" if [ -z "$FULL" ]; then
PKG_VERSION="${{ needs.check.outputs.pkg_version }}" echo "GITHUB_REPOSITORY is empty. Set it in runner env or switch to explicit OWNER/REPO vars."
exit 1
fi
OWNER="${FULL%%/*}"
REPO="${FULL##*/}"
VERSION="${GITHUB_REF_NAME#v}"
PKG_VERSION="${VERSION}"
if [ -z "${GITEA_BASE_URL:-}" ]; then if [ -z "${GITEA_BASE_URL:-}" ]; then
echo "Missing vars.GITEA_BASE_URL (example: https://gitea.example.com)" echo "Missing vars.GITEA_BASE_URL (example: https://gitea.example.com)"

View File

@@ -1,16 +0,0 @@
# Black Hole Share AI Guide
- Purpose: lightweight Actix-Web service for ephemeral image/text sharing; uploads saved as JSON files on disk and purged after their TTL.
- **Base directory is `data/`**: the server uses relative paths `data/html/`, `data/logs/`, `data/storage/`. Run from repo root locally; Docker mounts `./data:/data`.
- HTTP entrypoint and routing live in [src/main.rs](../src/main.rs): `/` serves `index.html`, `/bhs/{id}` serves `view.html`, `/api/upload` and `/api/content/{id}` registered from the API module, catch-all serves other static files under `html/` (list cached at startup via `STATIC_PAGES`).
- Request JSON bodies capped at ~3 MiB via `web::JsonConfig`. Background cleanup task runs every 60s to delete expired assets in `storage/`.
- Upload API in [src/api.rs](../src/api.rs): accepts JSON `{ duration: minutes, content_type, content }`; `text/plain` content is stored raw bytes, other types are base64-decoded. On success returns `{ "link": "/bhs/<uuid>" }`.
- Fetch API in [src/api.rs](../src/api.rs): loads `{id}` from `storage/`, rejects missing or expired assets, responds with original MIME and bytes.
- Asset model and persistence in [src/data_mgt.rs](../src/data_mgt.rs): assets serialized as JSON files named by UUID, with `expires_at` computed from `share_duration` (minutes). Cleanup logs removals to stdout.
- Logging helper in [src/logs.rs](../src/logs.rs): appends access lines with timing, IPs, scheme, UA to `logs/access.log`; runs for every handled request.
- Frontend upload page [data/html/index.html](../data/html/index.html): JS handles drag/drop, paste, or file picker; converts images to base64 or keeps text, POSTs to `/api/upload`, shows returned link and copies to clipboard. Styling/theme in [data/html/style.css](../data/html/style.css).
- Viewer page [data/html/view.html](../data/html/view.html): fetches `/api/content/{id}`, renders images with zoom overlay or text with zoomable modal; shows error when content missing/expired.
- Environment: `BIND_ADDR` and `BIND_PORT` (defaults 0.0.0.0:8080) are read via `LazyLock` on startup; `tokio` multi-thread runtime used.
- Build/dev: `cargo run --release` from repo root (ensure `data/` exists with `html/`, `logs/`, `storage/`), or use Dockerfile (Arch base + rustup build) and docker-compose (Traefik labels, port 8080→80, volume `./data:/data`).
- No test suite present; verify changes by running the server and exercising `/api/upload` and `/api/content/{id}` via the provided UI or curl.
- When adding features, keep payload sizes small or adjust the JSON limit in [src/main.rs](../src/main.rs); ensure new routes log via `log_to_file` for observability; clean up expired artifacts consistently with `clear_assets()` patterns.

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.cargo/ .cargo/
.codex/
/target /target
/data/storage/* /data/storage/*
/data/logs/* /data/logs/*

View File

@@ -88,7 +88,6 @@ GET /api/stats
"storage_bytes": 1048576, "storage_bytes": 1048576,
"image_count": 3, "image_count": 3,
"text_count": 2, "text_count": 2,
"avg_response_ms": 0.85,
"total_requests": 150, "total_requests": 150,
"recent_activity": [...] "recent_activity": [...]
} }

40
data/html/error.html Normal file
View File

@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Black Hole Share - Error</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body class="view-page error-page">
<h1><a href="/" class="home-link">Black Hole Share</a> - Error</h1>
<div class="view-container">
<div class="content-area">
<div class="error-content">
<div class="error-code">404</div>
<p class="error-message">The page you're looking for vanished into the black hole.</p>
<div class="error-actions">
<a class="upload-btn action-btn" href="/">Go Home</a>
<a class="reset-btn action-btn" href="/stats">View Stats</a>
</div>
</div>
</div>
</div>
<footer class="powered-by" style="display: flex; align-items: center">
<span style="flex: 1"></span>
<span>Powered by: <img src="/logo.png" alt="ICSBox" class="footer-logo" /></span>
<span style="flex: 1; text-align: right">
<a href="/stats" style="
color: var(--text-secondary);
font-size: 0.8em;
text-decoration: none;
">📊 Stats</a>
</span>
</footer>
</body>
</html>

View File

@@ -1,388 +1,373 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Upload</title>
<link rel="stylesheet" href="style.css" />
</head>
<body> <head>
<h1>Black Hole Share</h1> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Upload</title>
<link rel="stylesheet" href="style.css" />
</head>
<div class="upload-container"> <body>
<div class="upload-area"> <h1>Black Hole Share</h1>
<input
type="file" <div class="upload-container">
id="fileInput" <div class="upload-area">
accept="image/*" <input type="file" id="fileInput" accept="image/*" style="display: none" />
style="display: none" <div id="uploadZone" class="upload-zone">
/> <p>Click to select file, paste image, text data, or drag & drop</p>
<div id="uploadZone" class="upload-zone">
<p>Click to select file, paste image, text data, or drag & drop</p>
</div>
</div> </div>
</div> </div>
</div>
<div class="duration-container"> <div class="duration-container">
<label for="durationSlider" <label for="durationSlider">Duration: <span id="durationValue">5</span> min</label>
>Duration: <span id="durationValue">5</span> min</label <input type="range" id="durationSlider" min="1" max="60" value="5" step="1" />
> <div class="button-row">
<input <button id="resetBtn" class="reset-btn" style="display: none">
type="range" Reset
id="durationSlider" </button>
min="1" <button id="uploadBtn" class="upload-btn" style="display: none">
max="60" Upload
value="5" </button>
step="1"
/>
<div class="button-row">
<button id="resetBtn" class="reset-btn" style="display: none">
Reset
</button>
<button id="uploadBtn" class="upload-btn" style="display: none">
Upload
</button>
</div>
<div id="linkContainer" class="link-container" style="display: none">
<p>Link:</p>
<a id="uploadedLink" href="#" target="_blank"></a>
<p
id="clipboardMessage"
class="clipboard-message"
style="display: none"
></p>
</div>
</div> </div>
<div id="linkContainer" class="link-container" style="display: none">
<p>Link:</p>
<a id="uploadedLink" href="#" target="_blank"></a>
<p id="clipboardMessage" class="clipboard-message" style="display: none"></p>
</div>
</div>
<footer class="powered-by" style="display: flex; align-items: center"> <footer class="powered-by" style="display: flex; align-items: center">
<span style="flex: 1"></span> <span style="flex: 1"></span>
<span <span>Powered by: <img src="logo.png" alt="ICSBox" class="footer-logo" /></span>
>Powered by: <img src="logo.png" alt="ICSBox" class="footer-logo" <span style="flex: 1; text-align: right">
/></span> <a href="/stats" style="
<span style="flex: 1; text-align: right">
<a
href="/stats.html"
style="
color: var(--text-secondary); color: var(--text-secondary);
font-size: 0.8em; font-size: 0.8em;
text-decoration: none; text-decoration: none;
" ">📊 Stats</a>
>📊 Stats</a </span>
> </footer>
</span>
</footer>
<!-- Zoom overlay --> <!-- Zoom overlay -->
<div id="zoomOverlay" class="zoom-overlay" style="display: none"></div> <div id="zoomOverlay" class="zoom-overlay" style="display: none"></div>
<script> <script>
let currentContentData = null; let currentContentData = null;
const fileInput = document.getElementById("fileInput"); const fileInput = document.getElementById("fileInput");
const uploadZone = document.getElementById("uploadZone"); const uploadZone = document.getElementById("uploadZone");
const uploadContainer = document.querySelector(".upload-container"); const uploadContainer = document.querySelector(".upload-container");
const durationSlider = document.getElementById("durationSlider"); const durationSlider = document.getElementById("durationSlider");
const durationValue = document.getElementById("durationValue"); const durationValue = document.getElementById("durationValue");
const uploadBtn = document.getElementById("uploadBtn"); const uploadBtn = document.getElementById("uploadBtn");
const resetBtn = document.getElementById("resetBtn"); const resetBtn = document.getElementById("resetBtn");
const zoomOverlay = document.getElementById("zoomOverlay"); const zoomOverlay = document.getElementById("zoomOverlay");
const linkContainer = document.getElementById("linkContainer"); const linkContainer = document.getElementById("linkContainer");
const uploadedLink = document.getElementById("uploadedLink"); const uploadedLink = document.getElementById("uploadedLink");
const clipboardMessage = document.getElementById("clipboardMessage"); const clipboardMessage = document.getElementById("clipboardMessage");
// Update duration display // Update duration display
durationSlider.addEventListener("input", function () { durationSlider.addEventListener("input", function () {
durationValue.textContent = this.value; durationValue.textContent = this.value;
}); });
uploadBtn.addEventListener("click", async () => { // fischi20 thanks!!!
const duration = durationSlider.value; durationSlider.addEventListener("wheel", (e) => {
const isText = uploadZone.querySelector(".text-content") !== null; e.preventDefault();
const mimeType = isText ? "text/plain" : "image/png"; durationSlider.valueAsNumber += e.deltaY < 0 ? -1 : 1;
const contentData = currentContentData; durationValue.textContent = durationSlider.value;
});
if (!contentData) { uploadBtn.addEventListener("click", async () => {
console.log("❌ No content to upload!"); const duration = durationSlider.value;
return; const isText = uploadZone.querySelector(".text-content") !== null;
} const mimeType = isText ? "text/plain" : "image/png";
const contentData = currentContentData;
sendUpload(duration, mimeType, contentData); if (!contentData) {
}); console.log("❌ No content to upload!");
return;
async function sendUpload(duration, mimeType, contentData) {
const isText = mimeType === "text/plain";
let content = contentData;
// For images, remove data URL prefix to send only base64 string
if (!isText && contentData.includes("base64,")) {
content = contentData.split("base64,")[1];
}
const payload = {
duration: parseInt(duration),
content_type: mimeType,
content: content,
};
try {
const response = await fetch("/api/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const result = await response.json();
console.log(
`✅ Upload received!\n${JSON.stringify(result, null, 2)}`
);
// Hide duration controls and buttons
document.querySelector('label[for="durationSlider"]').style.display =
"none";
durationSlider.style.display = "none";
uploadBtn.style.display = "none";
resetBtn.style.display = "none";
// Show link
const fullLink = window.location.origin + result.link;
uploadedLink.href = fullLink;
uploadedLink.textContent = fullLink;
linkContainer.style.display = "block";
// Copy to clipboard
try {
await navigator.clipboard.writeText(fullLink);
clipboardMessage.textContent = "✓ Copied to clipboard!";
clipboardMessage.style.color = "var(--accent-green)";
clipboardMessage.style.cursor = "default";
clipboardMessage.style.display = "block";
clipboardMessage.onclick = null;
} catch (error) {
clipboardMessage.textContent = "⚠ Click here to copy link";
clipboardMessage.style.color = "var(--accent-cyan)";
clipboardMessage.style.cursor = "pointer";
clipboardMessage.style.display = "block";
clipboardMessage.onclick = function () {
const textArea = document.createElement("textarea");
textArea.value = fullLink;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand("copy");
clipboardMessage.textContent = "✓ Copied to clipboard!";
clipboardMessage.style.color = "var(--accent-green)";
clipboardMessage.style.cursor = "default";
clipboardMessage.onclick = null;
} catch (e) {
clipboardMessage.textContent = "✗ Copy failed";
clipboardMessage.style.color = "#ff6666";
}
document.body.removeChild(textArea);
};
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
}
} }
// Reset to initial state sendUpload(duration, mimeType, contentData);
resetBtn.addEventListener("click", function () { });
currentContentData = null;
uploadZone.innerHTML = async function sendUpload(duration, mimeType, contentData) {
"<p>Click to select file, paste image data, or drag & drop</p>"; const isText = mimeType === "text/plain";
uploadContainer.style.height = "180px"; let content = contentData;
uploadContainer.style.pointerEvents = "";
uploadContainer.style.overflow = ""; // For images, remove data URL prefix to send only base64 string
uploadZone.style.pointerEvents = ""; if (!isText && contentData.includes("base64,")) {
uploadZone.style.alignItems = ""; content = contentData.split("base64,")[1];
uploadZone.style.justifyContent = ""; }
uploadZone.style.padding = "";
fileInput.value = ""; const payload = {
durationSlider.value = "5"; duration: parseInt(duration),
durationValue.textContent = "5"; content_type: mimeType,
content: content,
};
try {
const response = await fetch("/api/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const result = await response.json();
console.log(
`✅ Upload received!\n${JSON.stringify(result, null, 2)}`
);
// Hide duration controls and buttons
document.querySelector('label[for="durationSlider"]').style.display = document.querySelector('label[for="durationSlider"]').style.display =
""; "none";
durationSlider.style.display = ""; durationSlider.style.display = "none";
uploadBtn.style.display = "none"; uploadBtn.style.display = "none";
resetBtn.style.display = "none"; resetBtn.style.display = "none";
linkContainer.style.display = "none";
clipboardMessage.style.display = "none";
uploadZone.focus();
});
// Display and scale image or text content maintaining aspect ratio // Show link
function displayContent(content, isText = false) { const fullLink = window.location.origin + result.link;
currentContentData = content; uploadedLink.href = fullLink;
uploadedLink.textContent = fullLink;
linkContainer.style.display = "block";
if (isText) { // Copy to clipboard
// Display text content - ZOOM ENABLED try {
uploadZone.innerHTML = `<div class="text-content" style="cursor: zoom-in;">${content await navigator.clipboard.writeText(fullLink);
.replace(/</g, "&lt;") clipboardMessage.textContent = "✓ Copied to clipboard!";
.replace(/>/g, "&gt;")}</div>`; clipboardMessage.style.color = "var(--accent-green)";
uploadContainer.style.height = "500px"; clipboardMessage.style.cursor = "default";
uploadContainer.style.overflow = "hidden"; clipboardMessage.style.display = "block";
clipboardMessage.onclick = null;
} catch (error) {
clipboardMessage.textContent = "⚠ Click here to copy link";
clipboardMessage.style.color = "var(--accent-cyan)";
clipboardMessage.style.cursor = "pointer";
clipboardMessage.style.display = "block";
clipboardMessage.onclick = function () {
const textArea = document.createElement("textarea");
textArea.value = fullLink;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand("copy");
clipboardMessage.textContent = "✓ Copied to clipboard!";
clipboardMessage.style.color = "var(--accent-green)";
clipboardMessage.style.cursor = "default";
clipboardMessage.onclick = null;
} catch (e) {
clipboardMessage.textContent = "✗ Copy failed";
clipboardMessage.style.color = "#ff6666";
}
document.body.removeChild(textArea);
};
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
}
}
// Reset to initial state
resetBtn.addEventListener("click", function () {
currentContentData = null;
uploadZone.innerHTML =
"<p>Click to select file, paste image data, or drag & drop</p>";
uploadContainer.style.height = "180px";
uploadContainer.style.pointerEvents = "";
uploadContainer.style.overflow = "";
uploadZone.style.pointerEvents = "";
uploadZone.style.alignItems = "";
uploadZone.style.justifyContent = "";
uploadZone.style.padding = "";
fileInput.value = "";
durationSlider.value = "5";
durationValue.textContent = "5";
document.querySelector('label[for="durationSlider"]').style.display =
"";
durationSlider.style.display = "";
uploadBtn.style.display = "none";
resetBtn.style.display = "none";
linkContainer.style.display = "none";
clipboardMessage.style.display = "none";
uploadZone.focus();
});
// Display and scale image or text content maintaining aspect ratio
function displayContent(content, isText = false) {
currentContentData = content;
if (isText) {
// Display text content - ZOOM ENABLED
uploadZone.innerHTML = `<div class="text-content" style="cursor: zoom-in;">${content
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</div>`;
uploadContainer.style.height = "500px";
uploadContainer.style.overflow = "hidden";
uploadZone.style.pointerEvents = "auto";
uploadZone.style.alignItems = "stretch";
uploadZone.style.justifyContent = "stretch";
uploadZone.style.padding = "0";
uploadBtn.style.display = "block";
resetBtn.style.display = "block";
// ZOOM FOR TEXT
const textContent = uploadZone.querySelector(".text-content");
textContent.addEventListener("click", function (e) {
e.stopPropagation();
showZoom(content, true);
});
} else {
// Display image
const img = new Image();
img.onload = function () {
const maxWidth = 620;
const maxHeight = 800;
const scale = Math.min(
maxWidth / img.width,
maxHeight / img.height,
1
);
const displayHeight = Math.floor(img.height * scale);
const displayWidth = Math.floor(img.width * scale);
uploadZone.innerHTML = `<img src="${content}" alt="Uploaded Image" style="width: ${displayWidth}px; height: ${displayHeight}px; object-fit: contain; cursor: zoom-in;">`;
uploadContainer.style.height = `${displayHeight + 20}px`;
uploadContainer.style.pointerEvents = "none";
uploadZone.style.pointerEvents = "auto"; uploadZone.style.pointerEvents = "auto";
uploadZone.style.alignItems = "stretch";
uploadZone.style.justifyContent = "stretch";
uploadZone.style.padding = "0";
uploadBtn.style.display = "block"; uploadBtn.style.display = "block";
resetBtn.style.display = "block"; resetBtn.style.display = "block";
// ZOOM FOR TEXT const uploadedImg = uploadZone.querySelector("img");
const textContent = uploadZone.querySelector(".text-content"); uploadedImg.addEventListener("click", function (e) {
textContent.addEventListener("click", function (e) {
e.stopPropagation(); e.stopPropagation();
showZoom(content, true); showZoom(content, false);
}); });
} else { };
// Display image img.src = content;
const img = new Image();
img.onload = function () {
const maxWidth = 620;
const maxHeight = 800;
const scale = Math.min(
maxWidth / img.width,
maxHeight / img.height,
1
);
const displayHeight = Math.floor(img.height * scale);
const displayWidth = Math.floor(img.width * scale);
uploadZone.innerHTML = `<img src="${content}" alt="Uploaded Image" style="width: ${displayWidth}px; height: ${displayHeight}px; object-fit: contain; cursor: zoom-in;">`;
uploadContainer.style.height = `${displayHeight + 20}px`;
uploadContainer.style.pointerEvents = "none";
uploadZone.style.pointerEvents = "auto";
uploadBtn.style.display = "block";
resetBtn.style.display = "block";
const uploadedImg = uploadZone.querySelector("img");
uploadedImg.addEventListener("click", function (e) {
e.stopPropagation();
showZoom(content, false);
});
};
img.src = content;
}
} }
}
// Open file picker on container click (ONLY IF EMPTY) // Open file picker on container click (ONLY IF EMPTY)
uploadContainer.addEventListener("click", function (e) { uploadContainer.addEventListener("click", function (e) {
if ( if (
uploadContainer.style.pointerEvents !== "none" && uploadContainer.style.pointerEvents !== "none" &&
!uploadZone.querySelector(".text-content") && !uploadZone.querySelector(".text-content") &&
!uploadZone.querySelector("img") !uploadZone.querySelector("img")
) { ) {
fileInput.click(); fileInput.click();
} }
}); });
fileInput.addEventListener("change", function (e) { fileInput.addEventListener("change", function (e) {
const file = e.target.files[0]; const file = e.target.files[0];
if (file) { if (file) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function (event) { reader.onload = function (event) {
displayContent(event.target.result); displayContent(event.target.result);
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
} }
}); });
// Handle paste from clipboard // Handle paste from clipboard
uploadZone.addEventListener("paste", function (e) { uploadZone.addEventListener("paste", function (e) {
e.preventDefault(); e.preventDefault();
const items = e.clipboardData.items; const items = e.clipboardData.items;
for (let item of items) { for (let item of items) {
if (item.type.startsWith("image/")) { if (item.type.startsWith("image/")) {
const file = item.getAsFile(); const file = item.getAsFile();
const reader = new FileReader();
reader.onload = function (event) {
displayContent(event.target.result);
};
reader.readAsDataURL(file);
return;
}
}
const text = e.clipboardData.getData("text");
if (text) {
displayContent(text, true);
}
});
// Handle drag and drop
uploadZone.addEventListener("drop", handleDrop);
uploadContainer.addEventListener("drop", handleDrop);
function handleDrop(e) {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file && file.type.startsWith("image/")) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function (event) { reader.onload = function (event) {
displayContent(event.target.result); displayContent(event.target.result);
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
return;
} }
} }
uploadZone.addEventListener("dragover", function (e) { const text = e.clipboardData.getData("text");
e.preventDefault(); if (text) {
uploadZone.style.borderColor = "var(--border-hover)"; displayContent(text, true);
}); }
});
uploadZone.addEventListener("dragleave", function (e) { // Handle drag and drop
uploadZone.style.borderColor = ""; uploadZone.addEventListener("drop", handleDrop);
}); uploadContainer.addEventListener("drop", handleDrop);
uploadContainer.addEventListener("dragover", function (e) { function handleDrop(e) {
e.preventDefault(); e.preventDefault();
}); const file = e.dataTransfer.files[0];
if (file && file.type.startsWith("image/")) {
const reader = new FileReader();
reader.onload = function (event) {
displayContent(event.target.result);
};
reader.readAsDataURL(file);
}
}
uploadZone.setAttribute("tabindex", "0"); uploadZone.addEventListener("dragover", function (e) {
e.preventDefault();
uploadZone.style.borderColor = "var(--border-hover)";
});
window.addEventListener("focus", function () { uploadZone.addEventListener("dragleave", function (e) {
uploadZone.focus(); uploadZone.style.borderColor = "";
}); });
uploadContainer.addEventListener("dragover", function (e) {
e.preventDefault();
});
uploadZone.setAttribute("tabindex", "0");
window.addEventListener("focus", function () {
uploadZone.focus(); uploadZone.focus();
});
// Improved zoom overlay functions uploadZone.focus();
function showZoom(content, isText = false) {
if (isText) { // Improved zoom overlay functions
zoomOverlay.innerHTML = ` function showZoom(content, isText = false) {
if (isText) {
zoomOverlay.innerHTML = `
<div class="zoom-text-content">${content <div class="zoom-text-content">${content
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</div> .replace(/>/g, "&gt;")}</div>
`; `;
} else { } else {
zoomOverlay.innerHTML = `<img id="zoomImage" src="${content}" alt="Zoomed Image" style="max-width: 95vw; max-height: 95vh; object-fit: contain; box-shadow: 0 0 50px rgba(51, 204, 255, 0.5);">`; zoomOverlay.innerHTML = `<img id="zoomImage" src="${content}" alt="Zoomed Image" style="max-width: 95vw; max-height: 95vh; object-fit: contain; box-shadow: 0 0 50px rgba(51, 204, 255, 0.5);">`;
}
zoomOverlay.style.display = "flex";
} }
zoomOverlay.style.display = "flex";
}
function hideZoom() { function hideZoom() {
zoomOverlay.style.display = "none"; zoomOverlay.style.display = "none";
}
zoomOverlay.addEventListener("click", hideZoom);
// ESC TO EXIT ZOOM
document.addEventListener("keydown", function (e) {
if (e.key === "Escape" || e.key === "Esc") {
hideZoom();
} }
});
zoomOverlay.addEventListener("click", hideZoom); window.addEventListener("resize", function () {
if (currentContentData) {
displayContent(currentContentData);
}
});
</script>
</body>
// ESC TO EXIT ZOOM </html>
document.addEventListener("keydown", function (e) {
if (e.key === "Escape" || e.key === "Esc") {
hideZoom();
}
});
window.addEventListener("resize", function () {
if (currentContentData) {
displayContent(currentContentData);
}
});
</script>
</body>
</html>

View File

@@ -1,207 +1,258 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Black Hole Share - Statistics</title>
<link rel="stylesheet" href="/style.css" />
<style>
.stats-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin-top: 20px;
}
.stat-card { <head>
background-color: var(--bg-secondary); <meta charset="UTF-8" />
border: 2px solid var(--border-color); <meta name="viewport" content="width=device-width, initial-scale=1.0" />
border-radius: 12px; <title>Black Hole Share - Statistics</title>
padding: 20px; <link rel="stylesheet" href="/style.css" />
text-align: center; <style>
transition: all 0.3s ease; .stats-layout {
} display: grid;
grid-template-columns: minmax(0, 1fr) minmax(140px, 170px);
gap: 20px;
margin-top: 20px;
align-items: stretch;
}
.stat-card:hover { .stats-grid {
border-color: var(--border-hover); display: grid;
box-shadow: 0 4px 15px rgba(0, 255, 153, 0.2); grid-template-columns: repeat(3, minmax(160px, 1fr));
} gap: 20px;
}
.stat-value { .stats-request-card {
font-size: 2.5em; height: 100%;
font-weight: bold; display: flex;
color: var(--accent-cyan); flex-direction: column;
margin: 10px 0; justify-content: center;
} align-items: center;
}
.stat-label { .stat-card {
color: var(--text-secondary); background-color: var(--bg-secondary);
font-size: 0.9em; border: 2px solid var(--border-color);
text-transform: uppercase; border-radius: 12px;
letter-spacing: 1px; padding: 20px;
} text-align: center;
transition: all 0.3s ease;
}
.stat-card.highlight .stat-value { .stat-card:hover {
color: var(--accent-green); border-color: var(--border-hover);
} box-shadow: 0 4px 15px rgba(0, 255, 153, 0.2);
}
.recent-activity { .stat-value {
margin-top: 30px; font-size: 1.5em;
background-color: var(--bg-secondary); font-weight: bold;
border: 2px solid var(--border-color); color: var(--accent-cyan);
border-radius: 12px; margin: 10px 0;
padding: 20px; }
}
.recent-activity h2 { .stat-label {
color: var(--accent-cyan); color: var(--text-secondary);
margin: 0 0 15px 0; font-size: 0.9em;
font-size: 1.2em; text-transform: uppercase;
} letter-spacing: 1px;
}
.activity-list { .stat-card.highlight .stat-value {
max-height: 300px; color: var(--accent-green);
overflow-y: auto; }
font-family: "JetBrains Mono", monospace;
font-size: 0.85em;
}
.activity-item { .recent-activity {
padding: 8px 0; margin-top: 30px;
border-bottom: 1px solid var(--inactive-gray); background-color: var(--bg-secondary);
display: flex; border: 2px solid var(--border-color);
justify-content: space-between; border-radius: 12px;
align-items: center; padding: 20px;
} transition: all 0.3s ease;
}
.activity-item:last-child { .recent-activity h2 {
border-bottom: none; color: var(--accent-cyan);
} margin: 0 0 15px 0;
font-size: 1.2em;
}
.activity-action { .recent-activity:hover {
padding: 2px 8px; border-color: var(--border-hover);
border-radius: 4px; box-shadow: 0 4px 15px rgba(0, 255, 153, 0.2);
font-size: 0.8em; }
font-weight: bold;
}
.activity-action.upload { .activity-list {
background-color: rgba(0, 255, 153, 0.2); max-height: 300px;
color: var(--accent-green); overflow-y: auto;
} font-family: "JetBrains Mono", monospace;
font-size: 0.85em;
}
.activity-action.delete { .activity-item {
background-color: rgba(255, 102, 102, 0.2); padding: 8px 0;
color: #ff6666; border-bottom: 1px solid var(--inactive-gray);
} display: grid;
grid-template-columns: 90px minmax(120px, 1fr) minmax(90px, 1fr) minmax(180px, 1fr);
align-items: center;
gap: 10px;
white-space: nowrap;
}
.activity-time { .activity-item:last-child {
color: var(--text-secondary); border-bottom: none;
} }
.activity-details { .activity-action {
color: var(--text-primary); padding: 2px 8px;
} border-radius: 4px;
font-size: 0.8em;
font-weight: bold;
}
.refresh-btn { .activity-action.upload {
background-color: var(--border-color); background-color: rgba(0, 255, 153, 0.2);
color: var(--bg-tertiary); color: var(--accent-green);
border: none; }
padding: 10px 20px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
margin-top: 20px;
transition: all 0.2s ease;
}
.refresh-btn:hover { .activity-action.delete {
background-color: var(--border-hover); background-color: rgba(255, 102, 102, 0.2);
} color: #ff6666;
}
.loading { .activity-time {
text-align: center; color: var(--text-secondary);
color: var(--text-secondary); white-space: nowrap;
padding: 40px; }
}
</style>
</head>
<body class="view-page"> .activity-details {
<h1><a href="/" class="home-link">Black Hole Share</a> - Statistics</h1> color: var(--text-primary);
display: contents;
}
<div id="statsContent" class="loading"> .activity-mime {
<p>Loading statistics...</p> text-align: left;
</div> }
<footer class="powered-by"> .activity-duration {
<span text-align: left;
>Powered by: <img src="/logo.png" alt="ICSBox" class="footer-logo" }
/></span>
</footer>
<script> .activity-time {
async function loadStats() { text-align: left;
try { }
const response = await fetch("/api/stats");
if (!response.ok) { .refresh-btn {
throw new Error("Failed to load stats"); background-color: var(--border-color);
} color: var(--bg-tertiary);
const stats = await response.json(); border: none;
renderStats(stats); padding: 10px 20px;
} catch (error) { border-radius: 8px;
document.getElementById("statsContent").innerHTML = ` cursor: pointer;
font-weight: bold;
margin-top: 20px;
transition: all 0.2s ease;
}
.refresh-btn:hover {
background-color: var(--border-hover);
}
.loading {
text-align: center;
color: var(--text-secondary);
padding: 40px;
}
</style>
</head>
<body class="view-page">
<h1><a href="/" class="home-link">Black Hole Share</a> - Statistics</h1>
<div id="statsContent" class="loading">
<p>Loading statistics...</p>
</div>
<footer class="powered-by" style="display: flex; align-items: center">
<span style="flex: 1"></span>
<span>Powered by: <img src="/logo.png" alt="ICSBox" class="footer-logo" /></span>
<span style="flex: 1; text-align: right">
<a href="/stats" style="
color: var(--text-secondary);
font-size: 0.8em;
text-decoration: none;
">📊 Stats</a>
</span>
</footer>
<script>
async function loadStats() {
try {
const response = await fetch("/api/stats");
if (!response.ok) {
throw new Error("Failed to load stats");
}
const stats = await response.json();
renderStats(stats);
} catch (error) {
document.getElementById("statsContent").innerHTML = `
<p class="error">Failed to load statistics: ${error.message}</p> <p class="error">Failed to load statistics: ${error.message}</p>
`; `;
}
} }
}
function formatBytes(bytes) { function formatBytes(bytes) {
if (bytes === 0) return "0 B"; if (bytes === 0) return "0 B";
const k = 1024; const k = 1024;
const sizes = ["B", "KB", "MB", "GB"]; const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k)); const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]; return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
} }
function formatTime(timestamp) { function formatTime(timestamp) {
const date = new Date(timestamp); const date = new Date(timestamp);
return date.toLocaleString(); return date.toLocaleString("en-GB", {
} year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
});
}
function renderStats(stats) { function renderStats(stats) {
const html = ` const html = `
<div class="stats-container"> <div class="stats-layout">
<div class="stat-card highlight"> <div class="stats-grid">
<div class="stat-label">Active Assets</div> <div class="stat-card highlight">
<div class="stat-value">${stats.active_assets}</div> <div class="stat-label">Active Assets</div>
<div class="stat-value">${stats.active_assets}</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Uploads</div>
<div class="stat-value">${stats.total_uploads}</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Deleted</div>
<div class="stat-value">${stats.total_deleted}</div>
</div>
<div class="stat-card">
<div class="stat-label">Storage Used</div>
<div class="stat-value">${formatBytes(stats.storage_bytes)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Images</div>
<div class="stat-value">${stats.image_count}</div>
</div>
<div class="stat-card">
<div class="stat-label">Text</div>
<div class="stat-value">${stats.text_count}</div>
</div>
</div> </div>
<div class="stat-card">
<div class="stat-label">Total Uploads</div> <div class="stat-card stats-request-card">
<div class="stat-value">${stats.total_uploads}</div> <div class="stat-label">Total Server Requests</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Deleted</div>
<div class="stat-value">${stats.total_deleted}</div>
</div>
<div class="stat-card">
<div class="stat-label">Storage Used</div>
<div class="stat-value">${formatBytes(stats.storage_bytes)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Images</div>
<div class="stat-value">${stats.image_count}</div>
</div>
<div class="stat-card">
<div class="stat-label">Text</div>
<div class="stat-value">${stats.text_count}</div>
</div>
<div class="stat-card">
<div class="stat-label">Avg Response</div>
<div class="stat-value">${stats.avg_response_ms.toFixed(2)} ms</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Requests</div>
<div class="stat-value">${stats.total_requests}</div> <div class="stat-value">${stats.total_requests}</div>
</div> </div>
</div> </div>
@@ -209,36 +260,36 @@
<div class="recent-activity"> <div class="recent-activity">
<h2>Recent Activity</h2> <h2>Recent Activity</h2>
<div class="activity-list"> <div class="activity-list">
${ ${stats.recent_activity.length === 0
stats.recent_activity.length === 0 ? '<p style="color: var(--text-secondary);">No recent activity</p>'
? '<p style="color: var(--text-secondary);">No recent activity</p>' : stats.recent_activity
: stats.recent_activity .map(
.map( (item) => `
(item) => `
<div class="activity-item"> <div class="activity-item">
<span class="activity-action ${item.action}">${ <span class="activity-action ${item.action}">${item.action
item.action }</span>
}</span> <span class="activity-details">
<span class="activity-details">${item.mime} (${formatBytes( <span class="activity-mime">${item.mime}</span>
item.size_bytes <span class="activity-duration">${item.share_duration} min</span>
)})</span> </span>
<span class="activity-time">${item.timestamp}</span> <span class="activity-time">${formatTime(item.timestamp)}</span>
</div> </div>
` `
) )
.join("") .join("")
} }
</div> </div>
</div> </div>
<button class="refresh-btn" onclick="loadStats()">Refresh</button> <button class="refresh-btn" onclick="loadStats()">Refresh</button>
`; `;
document.getElementById("statsContent").innerHTML = html; document.getElementById("statsContent").innerHTML = html;
} }
loadStats();
// Auto-refresh every 30 seconds
setInterval(loadStats, 30000);
</script>
</body>
loadStats();
// Auto-refresh every 30 seconds
setInterval(loadStats, 30000);
</script>
</body>
</html> </html>

View File

@@ -3,6 +3,8 @@
--bg-primary: #1e1e2e; --bg-primary: #1e1e2e;
--bg-secondary: #1a1a1a; --bg-secondary: #1a1a1a;
--bg-tertiary: #1a1a1a; --bg-tertiary: #1a1a1a;
--bg-glow: rgba(51, 204, 255, 0.08);
--bg-glow-strong: rgba(0, 255, 153, 0.07);
--active-cyan: #33ccff; --active-cyan: #33ccff;
--active-green: #00ff99; --active-green: #00ff99;
--inactive-gray: #595959; --inactive-gray: #595959;
@@ -29,6 +31,11 @@ body {
padding: 20px; padding: 20px;
padding-bottom: 140px; padding-bottom: 140px;
background-color: var(--bg-tertiary); background-color: var(--bg-tertiary);
background-image:
radial-gradient(1200px 800px at 10% -20%, var(--bg-glow), transparent 60%),
radial-gradient(900px 700px at 110% 0%, var(--bg-glow-strong), transparent 55%),
linear-gradient(180deg, rgba(30, 30, 46, 0.35), rgba(26, 26, 26, 0.85));
background-attachment: fixed;
color: var(--text-primary); color: var(--text-primary);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -512,6 +519,55 @@ body.view-page {
text-align: center; text-align: center;
} }
/* Error page styles */
.error-page .content-area {
min-height: 320px;
}
.error-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
text-align: center;
padding: 10px;
}
.error-code {
font-size: 3.2em;
font-weight: bold;
color: var(--accent-cyan);
text-shadow: 0 0 12px rgba(51, 204, 255, 0.4);
}
.error-message {
color: var(--text-secondary);
font-size: 1.05em;
margin: 0;
}
.error-actions {
display: flex;
gap: 12px;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.action-btn {
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
text-align: center;
min-width: 140px;
}
.error-actions .upload-btn,
.error-actions .reset-btn {
flex: 0 0 auto;
}
@keyframes pulse { @keyframes pulse {
0%, 0%,
@@ -560,4 +616,4 @@ body.view-page {
.text-content-view::-webkit-scrollbar-thumb:hover { .text-content-view::-webkit-scrollbar-thumb:hover {
background: var(--border-hover); background: var(--border-hover);
} }

View File

@@ -17,8 +17,16 @@
</div> </div>
</div> </div>
<footer class="powered-by"> <footer class="powered-by" style="display: flex; align-items: center">
<span>Powered by: <img src="/logo.png" alt="ICSBox" class="footer-logo"></span> <span style="flex: 1"></span>
<span>Powered by: <img src="/logo.png" alt="ICSBox" class="footer-logo" /></span>
<span style="flex: 1; text-align: right">
<a href="/stats" style="
color: var(--text-secondary);
font-size: 0.8em;
text-decoration: none;
">📊 Stats</a>
</span>
</footer> </footer>
<!-- Zoom overlay --> <!-- Zoom overlay -->
@@ -120,4 +128,4 @@
</script> </script>
</body> </body>
</html> </html>

View File

@@ -1,11 +1,12 @@
use actix_web::{HttpRequest, HttpResponse, get, post, web}; use actix_web::{HttpRequest, HttpResponse, get, post, web};
use base64::{Engine, engine::general_purpose}; use base64::{Engine, engine::general_purpose};
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
use crate::{ use crate::{
DATA_STORAGE, data_mgt::AssetTracker,
logs::{log_asset_event, log_to_file}, logs::{LogEventType, log_event},
}; };
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
@@ -16,7 +17,11 @@ pub struct UploadRequest {
} }
#[post("/api/upload")] #[post("/api/upload")]
async fn api_upload(req: HttpRequest, body: web::Json<UploadRequest>) -> Result<HttpResponse, actix_web::Error> { async fn api_upload(
req: HttpRequest,
body: web::Json<UploadRequest>,
assets: web::Data<AssetTracker>,
) -> Result<HttpResponse, actix_web::Error> {
// Convert to bytes // Convert to bytes
let content_bytes = if body.content_type == "text/plain" { let content_bytes = if body.content_type == "text/plain" {
body.content.as_bytes().to_vec() // UTF-8 bytes body.content.as_bytes().to_vec() // UTF-8 bytes
@@ -38,41 +43,27 @@ async fn api_upload(req: HttpRequest, body: web::Json<UploadRequest>) -> Result<
Some(uploader_ip.clone()), Some(uploader_ip.clone()),
); );
let id = asset log_event(LogEventType::AssetUploaded(&asset));
.save() let id = asset.id();
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to save asset: {}", e)))?; assets.add_asset(asset).await;
log_asset_event(
"upload",
asset.id(),
asset.mime(),
asset.size_bytes(),
asset.share_duration(),
asset.created_at(),
asset.expires_at(),
asset.uploader_ip().unwrap_or("-"),
);
let response_body = json!({ "link": format!("/bhs/{}", id) }); let response_body = json!({ "link": format!("/bhs/{}", id) });
Ok(HttpResponse::Ok().json(response_body)) Ok(HttpResponse::Ok().json(response_body))
} }
#[get("/api/content/{id}")] #[get("/api/content/{id}")]
async fn api_get_asset(req: HttpRequest, path: web::Path<String>) -> Result<HttpResponse, actix_web::Error> { async fn api_get_asset(
let now = std::time::Instant::now(); req: HttpRequest,
path: web::Path<String>,
assets: web::Data<AssetTracker>,
) -> Result<HttpResponse, actix_web::Error> {
log_event(LogEventType::HttpRequest(&req.into()));
let id = path.into_inner(); match assets.get_asset(&path.into_inner()).await {
let asset_path = format!("{}{}", DATA_STORAGE, id); None => Ok(HttpResponse::NotFound().body("Asset not found")),
let data = std::fs::read(&asset_path).map_err(|_| actix_web::error::ErrorNotFound("Asset not found"))?; Some(asset) => Ok(HttpResponse::Ok()
let asset = serde_json::from_slice::<crate::data_mgt::Asset>(&data) .content_type(asset.mime())
.map_err(|_| actix_web::error::ErrorInternalServerError("Failed to parse asset data"))?; .body(asset.content().clone())),
if asset.is_expired() {
return Err(actix_web::error::ErrorNotFound("Asset has expired"));
} }
log_to_file(&req, now);
Ok(HttpResponse::Ok().content_type(asset.mime()).body(asset.content()))
} }
#[derive(serde::Serialize)] #[derive(serde::Serialize)]
@@ -83,7 +74,6 @@ struct StatsResponse {
storage_bytes: u64, storage_bytes: u64,
image_count: usize, image_count: usize,
text_count: usize, text_count: usize,
avg_response_ms: f64,
total_requests: usize, total_requests: usize,
recent_activity: Vec<ActivityItem>, recent_activity: Vec<ActivityItem>,
} }
@@ -92,78 +82,88 @@ struct StatsResponse {
struct ActivityItem { struct ActivityItem {
action: String, action: String,
mime: String, mime: String,
size_bytes: usize, share_duration: u32,
timestamp: String, timestamp: String,
} }
#[derive(Deserialize)]
struct LogEventLine {
time: String,
event: LogEventBody,
}
#[derive(Deserialize)]
enum LogEventBody {
AssetUploaded(LogAsset),
AssetDeleted(LogAsset),
HttpRequest(LogHttpRequest),
}
#[derive(Deserialize)]
struct LogAsset {
id: String,
share_duration: u32,
created_at: i64,
expires_at: i64,
mime: String,
uploader_ip: Option<String>,
}
#[derive(Deserialize)]
struct LogHttpRequest {
method: String,
path: String,
query_string: String,
scheme: String,
ip: String,
real_ip: String,
user_agent: String,
}
#[get("/api/stats")] #[get("/api/stats")]
async fn api_stats() -> Result<HttpResponse, actix_web::Error> { async fn api_stats(assets: web::Data<AssetTracker>) -> Result<HttpResponse, actix_web::Error> {
use crate::LOG_DIR; use crate::LOG_DIR;
use std::fs; use std::fs;
let mut active_assets = 0; let (active_assets, storage_bytes, image_count, text_count) =
let mut storage_bytes: u64 = 0; assets.stats_summary().await;
let mut image_count = 0;
let mut text_count = 0;
// Count active assets and calculate storage
if let Ok(entries) = fs::read_dir(DATA_STORAGE) {
for entry in entries.flatten() {
if let Ok(data) = fs::read(entry.path()) {
if let Ok(asset) = serde_json::from_slice::<crate::data_mgt::Asset>(&data) {
if !asset.is_expired() {
active_assets += 1;
storage_bytes += asset.size_bytes() as u64;
if asset.mime().starts_with("image/") {
image_count += 1;
} else if asset.mime().starts_with("text/") {
text_count += 1;
}
}
}
}
}
}
// Parse log for upload/delete counts, response times, and recent activity
let mut total_uploads = 0; let mut total_uploads = 0;
let mut total_deleted = 0; let mut total_deleted = 0;
let mut recent_activity: Vec<ActivityItem> = Vec::new(); let mut recent_activity: Vec<ActivityItem> = Vec::new();
let mut total_response_ms: f64 = 0.0;
let mut request_count: usize = 0; let mut request_count: usize = 0;
let log_path = format!("{}access.log", LOG_DIR); let log_path = format!("{}access.log", LOG_DIR);
if let Ok(content) = fs::read_to_string(&log_path) { if let Ok(content) = fs::read_to_string(&log_path) {
for line in content.lines() { for line in content.lines() {
// Parse response time from request logs if let Ok(entry) = serde_json::from_str::<LogEventLine>(line) {
if line.contains("dur_ms=") { match entry.event {
if let Some(dur_str) = line.split("dur_ms=").nth(1) { LogEventBody::HttpRequest(_req) => {
if let Some(dur_val) = dur_str.split_whitespace().next() { request_count += 1;
if let Ok(ms) = dur_val.parse::<f64>() { }
total_response_ms += ms; LogEventBody::AssetUploaded(asset) => {
request_count += 1; total_uploads += 1;
} recent_activity.push(ActivityItem {
action: "upload".to_string(),
mime: asset.mime,
share_duration: asset.share_duration,
timestamp: entry.time,
});
}
LogEventBody::AssetDeleted(asset) => {
total_deleted += 1;
recent_activity.push(ActivityItem {
action: "delete".to_string(),
mime: asset.mime,
share_duration: asset.share_duration,
timestamp: entry.time,
});
} }
}
}
if line.contains("event=asset") {
if line.contains("action=upload") {
total_uploads += 1;
} else if line.contains("action=delete_expired") {
total_deleted += 1;
}
// Parse for recent activity (last 20)
if let Some(activity) = parse_activity_line(line) {
recent_activity.push(activity);
} }
} }
} }
} }
let avg_response_ms = if request_count > 0 { total_response_ms / request_count as f64 } else { 0.0 };
// Keep only last 20, most recent first // Keep only last 20, most recent first
recent_activity.reverse(); recent_activity.reverse();
recent_activity.truncate(20); recent_activity.truncate(20);
@@ -175,39 +175,9 @@ async fn api_stats() -> Result<HttpResponse, actix_web::Error> {
storage_bytes, storage_bytes,
image_count, image_count,
text_count, text_count,
avg_response_ms,
total_requests: request_count, total_requests: request_count,
recent_activity, recent_activity,
}; };
Ok(HttpResponse::Ok().json(response)) Ok(HttpResponse::Ok().json(response))
} }
fn parse_activity_line(line: &str) -> Option<ActivityItem> {
let timestamp = line.split_whitespace().next()?.to_string();
let action = if line.contains("action=upload") {
"upload".to_string()
} else if line.contains("action=delete_expired") {
"delete".to_string()
} else {
return None;
};
let mime = line.split("mime=").nth(1)?.split_whitespace().next()?.to_string();
let size_bytes: usize = line
.split("size_bytes=")
.nth(1)?
.split_whitespace()
.next()?
.parse()
.ok()?;
Some(ActivityItem {
action,
mime,
size_bytes,
timestamp,
})
}

View File

@@ -1,22 +1,27 @@
use std::fmt::Debug;
use std::sync::Arc;
use anyhow::Result; use anyhow::Result;
use chrono::{Duration, Utc}; use chrono::{Duration, Utc};
use futures::lock::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::DATA_STORAGE; use crate::DATA_STORAGE;
use crate::logs::log_asset_event; use crate::logs::{LogEventType, log_event};
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct Asset { pub struct Asset {
id: String, id: String,
share_duration: u32, share_duration: u32,
created_at: i64, created_at: i64,
expires_at: i64, expires_at: i64,
mime: String, mime: String,
#[serde(skip)]
content: Vec<u8>, content: Vec<u8>,
#[serde(default)]
uploader_ip: Option<String>, uploader_ip: Option<String>,
} }
#[allow(dead_code)]
impl Asset { impl Asset {
pub fn new(share_duration: u32, mime: String, content: Vec<u8>, uploader_ip: Option<String>) -> Self { pub fn new(share_duration: u32, mime: String, content: Vec<u8>, uploader_ip: Option<String>) -> Self {
let id = uuid::Uuid::new_v4().to_string(); let id = uuid::Uuid::new_v4().to_string();
@@ -36,8 +41,8 @@ impl Asset {
Utc::now().timestamp_millis() > self.expires_at Utc::now().timestamp_millis() > self.expires_at
} }
pub fn id(&self) -> &str { pub fn id(&self) -> String {
&self.id self.id.clone()
} }
pub fn mime(&self) -> &str { pub fn mime(&self) -> &str {
@@ -82,29 +87,85 @@ impl Asset {
} }
} }
pub async fn clear_assets() -> Result<()> { #[derive(Clone)]
let entries = std::fs::read_dir(DATA_STORAGE)?; pub struct AssetTracker {
for entry in entries { assets: Arc<Mutex<Vec<Asset>>>,
let entry = entry?; }
let path = entry.path();
if path.is_file() { #[allow(dead_code)]
let data = std::fs::read(&path)?; impl AssetTracker {
let asset = serde_json::from_slice::<Asset>(&data)?; pub fn new() -> Self {
if asset.is_expired() { AssetTracker {
println!("Removing expired asset: {}", asset.id()); assets: Arc::new(Mutex::new(Vec::new())),
log_asset_event(
"delete_expired",
asset.id(),
asset.mime(),
asset.size_bytes(),
asset.share_duration(),
asset.created_at(),
asset.expires_at(),
asset.uploader_ip().unwrap_or("-"),
);
std::fs::remove_file(&path)?;
}
} }
} }
pub async fn add_asset(&self, asset: Asset) {
print!("[{}] Adding asset: {}", chrono::Local::now().to_rfc3339(), asset.id());
self.assets.lock().await.push(asset);
self.show_assets().await;
}
pub async fn remove_expired(&self) {
let mut assets = self.assets.lock().await;
let removed_assets = assets.extract_if(.., |asset| asset.is_expired());
for asset in removed_assets {
log_event(LogEventType::AssetDeleted(&asset));
println!("[{}] Removing asset: {}", chrono::Local::now().to_rfc3339(), asset.id());
}
}
pub async fn active_assets(&self) -> usize {
self.assets.lock().await.len()
}
pub async fn stats_summary(&self) -> (usize, u64, usize, usize) {
let assets = self.assets.lock().await;
let mut active_assets = 0;
let mut storage_bytes: u64 = 0;
let mut image_count = 0;
let mut text_count = 0;
for asset in assets.iter() {
if asset.is_expired() {
continue;
}
active_assets += 1;
storage_bytes += asset.size_bytes() as u64;
if asset.mime().starts_with("image/") {
image_count += 1;
} else if asset.mime().starts_with("text/") {
text_count += 1;
}
}
(active_assets, storage_bytes, image_count, text_count)
}
pub async fn show_assets(&self) {
for asset in self.assets.lock().await.iter() {
println!(
"Asset ID: {}, Expires At: {}, MIME: {}, Size: {} bytes",
asset.id(),
asset.expires_at(),
asset.mime(),
asset.size_bytes()
);
}
}
pub async fn get_asset(&self, id: &str) -> Option<Asset> {
let assets = self.assets.lock().await;
for asset in assets.iter().cloned() {
if asset.id() == id {
return Some(asset.clone());
}
}
None
}
}
pub async fn clear_assets(assets: AssetTracker) -> Result<()> {
assets.remove_expired().await;
Ok(()) Ok(())
} }

View File

@@ -1,68 +1,72 @@
use std::{fs::OpenOptions, io::Write, time::Instant}; use std::{fs::OpenOptions, io::Write};
use actix_web::HttpRequest; use actix_web::HttpRequest;
use serde::Serialize;
use crate::LOG_DIR; use crate::{LOG_DIR, data_mgt::Asset};
pub fn log_to_file(req: &HttpRequest, start: Instant) { #[derive(Debug, Serialize)]
let delta = start.elapsed().as_nanos(); pub struct LogHttpRequest {
println!("Request processed in {} ns", delta); pub method: String,
let duration_ms = delta as f64 / 1000_000.0; pub path: String,
pub query_string: String,
pub scheme: String,
pub ip: String,
pub real_ip: String,
pub user_agent: String,
}
impl From<HttpRequest> for LogHttpRequest {
fn from(req: HttpRequest) -> Self {
let method = req.method().as_str().to_string();
let uri = req.uri();
let path = uri.path().to_string();
let query_string = uri.query().unwrap_or("-").to_string();
let log_path = LOG_DIR.to_string() + "access.log"; let connection_info = req.connection_info();
let scheme = connection_info.scheme().to_string();
let ip = connection_info.peer_addr().unwrap_or("-").to_string();
let real_ip = connection_info.realip_remote_addr().unwrap_or("-").to_string();
// Ensure log directory exists let user_agent = req
if let Err(e) = std::fs::create_dir_all(LOG_DIR) { .headers()
eprintln!("failed to create log dir: {}", e); .get("user-agent")
return; .and_then(|v| v.to_str().ok())
.unwrap_or("-")
.to_string();
LogHttpRequest {
method,
path,
query_string,
scheme,
ip,
real_ip,
user_agent,
}
} }
let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else {
eprintln!("failed to open log file");
return;
};
let ts = chrono::Local::now().to_rfc3339();
let method = req.method();
let uri = req.uri();
let path = uri.path();
let query = uri.query().unwrap_or("-");
let connection_info = req.connection_info();
let scheme = connection_info.scheme();
let ip = connection_info.peer_addr().unwrap_or("-");
let real_ip = connection_info.realip_remote_addr().unwrap_or("-");
let ua = req
.headers()
.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("-");
let line = format!(
"{ts} scheme={scheme} ip={ip} real_ip={real_ip} method={method} path={path} qs={query} dur_ms={duration_ms} ua=\"{ua}\"\n"
);
let _ = file.write_all(line.as_bytes());
} }
pub fn log_asset_event( #[derive(Debug, Serialize)]
action: &str, pub enum LogEventType<'a> {
id: &str, AssetUploaded(&'a Asset),
mime: &str, AssetDeleted(&'a Asset),
size_bytes: usize, HttpRequest(&'a LogHttpRequest),
duration_min: u32, }
created_at_ms: i64,
expires_at_ms: i64,
uploader_ip: &str,
) {
// Ensure logging directory exists before writing
if let Err(e) = std::fs::create_dir_all(LOG_DIR) {
eprintln!("failed to create log dir for asset event: {}", e);
return;
}
#[derive(Debug, Serialize)]
pub struct LogEvent<'a> {
pub time: String,
pub event: LogEventType<'a>,
}
impl<'a> From<LogEventType<'a>> for LogEvent<'a> {
fn from(event: LogEventType<'a>) -> Self {
let time = chrono::Utc::now().to_rfc3339();
LogEvent { time, event }
}
}
pub fn log_event(event: LogEventType) {
let log_path = LOG_DIR.to_string() + "access.log"; let log_path = LOG_DIR.to_string() + "access.log";
let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else { let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else {
@@ -70,11 +74,8 @@ pub fn log_asset_event(
return; return;
}; };
let ts = chrono::Local::now().to_rfc3339(); let log_event: LogEvent = event.into();
let line = serde_json::to_string(&log_event).unwrap_or_else(|e| e.to_string());
let line = format!( let _ = writeln!(file, "{}", line);
"{ts} event=asset action={action} id={id} mime={mime} size_bytes={size_bytes} duration_min={duration_min} created_at_ms={created_at_ms} expires_at_ms={expires_at_ms} uploader_ip={uploader_ip}\n"
);
let _ = file.write_all(line.as_bytes());
} }

View File

@@ -4,9 +4,10 @@ mod logs;
use actix_files::NamedFile; use actix_files::NamedFile;
use actix_web::{ use actix_web::{
App, HttpRequest, HttpResponse, HttpServer, get, route, App, HttpRequest, HttpServer, get, route,
web::{self}, web::{self},
}; };
use serde_json::Value; use serde_json::Value;
use std::{env, fs, path::PathBuf, sync::LazyLock}; use std::{env, fs, path::PathBuf, sync::LazyLock};
@@ -44,38 +45,44 @@ pub static STATIC_PAGES: LazyLock<Vec<String>> = LazyLock::new(|| {
use crate::{ use crate::{
api::{api_get_asset, api_stats, api_upload}, api::{api_get_asset, api_stats, api_upload},
logs::log_to_file, logs::{LogEventType, log_event},
}; };
#[get("/")] #[get("/")]
async fn index(reg: HttpRequest) -> actix_web::Result<NamedFile> { async fn index(req: HttpRequest) -> actix_web::Result<NamedFile> {
let now = std::time::Instant::now();
let path: PathBuf = PathBuf::from(HTML_DIR.to_string() + "index.html"); let path: PathBuf = PathBuf::from(HTML_DIR.to_string() + "index.html");
log_to_file(&reg, now); log_event(LogEventType::HttpRequest(&req.into()));
Ok(NamedFile::open(path)?)
}
#[get("/stats")]
async fn stats(req: HttpRequest) -> actix_web::Result<NamedFile> {
let path: PathBuf = PathBuf::from(HTML_DIR.to_string() + "stats.html");
log_event(LogEventType::HttpRequest(&req.into()));
Ok(NamedFile::open(path)?) Ok(NamedFile::open(path)?)
} }
#[get("/bhs/{id}")] #[get("/bhs/{id}")]
async fn view_asset(req: HttpRequest) -> actix_web::Result<NamedFile> { async fn view_asset(req: HttpRequest) -> actix_web::Result<NamedFile> {
let now = std::time::Instant::now();
let path: PathBuf = PathBuf::from(HTML_DIR.to_string() + "view.html"); let path: PathBuf = PathBuf::from(HTML_DIR.to_string() + "view.html");
log_to_file(&req, now); log_event(LogEventType::HttpRequest(&req.into()));
Ok(NamedFile::open(path)?) Ok(NamedFile::open(path)?)
} }
#[route("/{tail:.*}", method = "GET", method = "POST")] #[route("/{tail:.*}", method = "GET", method = "POST")]
async fn catch_all(req: HttpRequest, _payload: Option<web::Json<Value>>) -> actix_web::Result<HttpResponse> { async fn catch_all(req: HttpRequest, _payload: Option<web::Json<Value>>) -> actix_web::Result<NamedFile> {
let now = std::time::Instant::now();
let response = match req.uri().path() { let response = match req.uri().path() {
path if STATIC_PAGES.contains(&path[1..].into()) => { path if STATIC_PAGES.contains(&path[1..].into()) => {
let file_path = HTML_DIR.to_string() + path; let file_path = HTML_DIR.to_string() + path;
Ok(NamedFile::open(file_path)?.into_response(&req)) Ok(NamedFile::open(file_path)?)
}
_ => {
let file_path = PathBuf::from(HTML_DIR.to_string() + "error.html");
Ok(NamedFile::open(file_path)?)
} }
_ => Ok(HttpResponse::NotFound().body("Not Found")),
}; };
log_to_file(&req, now); log_event(LogEventType::HttpRequest(&req.into()));
response response
} }
@@ -84,21 +91,26 @@ async fn main() -> std::io::Result<()> {
let _ = fs::create_dir_all(DATA_STORAGE); let _ = fs::create_dir_all(DATA_STORAGE);
let _ = fs::create_dir_all(LOG_DIR); let _ = fs::create_dir_all(LOG_DIR);
println!("Starting server at http://{}:{}/", *BIND_ADDR, *BIND_PORT); let assets = data_mgt::AssetTracker::new();
tokio::spawn(async { println!("Starting server at http://{}:{}/", *BIND_ADDR, *BIND_PORT);
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(60)); let assets_clone = assets.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
loop { loop {
interval.tick().await; interval.tick().await;
if let Err(e) = data_mgt::clear_assets().await { if let Err(e) = data_mgt::clear_assets(assets_clone.clone()).await {
eprintln!("Error clearing assets: {}", e); eprintln!("Error clearing assets: {}", e);
} }
} }
}); });
HttpServer::new(|| { HttpServer::new(move || {
App::new() App::new()
.app_data(web::JsonConfig::default().limit(1024 * 1024 * 3)) .app_data(web::JsonConfig::default().limit(1024 * 1024 * 3))
.app_data(web::Data::new(assets.clone()))
.service(index) .service(index)
.service(stats)
.service(view_asset) .service(view_asset)
.service(api_get_asset) .service(api_get_asset)
.service(api_upload) .service(api_upload)