Compare commits
68 Commits
6a0f1771f6
...
v0.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 7a01525ca5 | |||
| 6ac669f8c7 | |||
| 48acf723de | |||
| 650352b103 | |||
| 9e567ae760 | |||
| 0685de8ffa | |||
| 1b295aa843 | |||
| 28b7860c6c | |||
| 62f3c49e8a | |||
| 7d02443e67 | |||
| 2ef2b827b7 | |||
| 8441dbd74e | |||
| 1fa4c50191 | |||
| d831bbe85f | |||
| e24630c4a9 | |||
| b8e209bd03 | |||
| 8145f1c7e4 | |||
| 840cf0ba99 | |||
| d47e73f47b | |||
| cde83139b1 | |||
| 81656ec0da | |||
| 70d7b08b7d | |||
| d6c465466a | |||
| 954a5be8cb | |||
| f3b5ae677d | |||
| 099e628418 | |||
| 92d3ba1929 | |||
| 747fec0749 | |||
| 86c96bf9b2 | |||
| d375b233ef | |||
| 1d0ba36d85 | |||
| 909518cec6 | |||
| a630415818 | |||
| d2ca118eb8 | |||
| b90df5bfed | |||
| d95b4a8fb5 | |||
| dd63e94140 | |||
| 715ae5c971 | |||
| ccb38db7f5 | |||
| c13960750c | |||
| c6285f18e8 | |||
| 2380417f24 | |||
| d2b6f80aee | |||
| 2aa2bd2c23 | |||
| 28f2dc7787 | |||
| 37d17dc8b8 | |||
| f5ed10b822 | |||
| a84f6209f2 | |||
| d7d8e4ebbf | |||
| 7e21dc213a | |||
| c150d8005f | |||
| 62eea535e4 | |||
| 8f29b335a5 | |||
| fc46d0952a | |||
| a288859edb | |||
| 0aff6caee7 | |||
| 63b780ac11 | |||
| 292a081e9d | |||
| 323e28760b | |||
| abac91df4e | |||
| 7faae610f9 | |||
| c6eba691a8 | |||
| 10384d15e5 | |||
| 1147d9b3f0 | |||
| 46cb35e14e | |||
| b0e7d6a40a | |||
| 4ddf4656a1 | |||
| 301f6d6202 |
198
.gitea/workflows/build.yaml
Normal file
198
.gitea/workflows/build.yaml
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
name: Build & Publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ["v*"]
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Install deps (Ubuntu)
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y \
|
||||||
|
build-essential git ca-certificates curl tar gzip python3
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Cache Rust toolchain
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/bin
|
||||||
|
~/.rustup
|
||||||
|
~/.cargo/registry
|
||||||
|
~/.cargo/git
|
||||||
|
key: ${{ runner.os }}-rustup-${{ hashFiles('rust-toolchain.toml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-rustup-
|
||||||
|
|
||||||
|
- name: Cache Cargo build
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
target
|
||||||
|
key: ${{ runner.os }}-cargo-target-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-cargo-target-
|
||||||
|
|
||||||
|
- name: Install Rust (stable)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
if [ ! -x "$HOME/.cargo/bin/cargo" ]; then
|
||||||
|
curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||||
|
fi
|
||||||
|
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
|
- name: Debug workspace
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
pwd
|
||||||
|
ls -la
|
||||||
|
|
||||||
|
- name: Read package name
|
||||||
|
id: pkg_meta
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
if [ -f Cargo.toml ]; then
|
||||||
|
PKG_NAME="$(cargo metadata --no-deps --format-version=1 2>/dev/null | python3 -c 'import json,sys; data=json.load(sys.stdin); names=[t.get("name","") for p in data.get("packages", []) for t in p.get("targets", []) if "bin" in t.get("kind", [])]; print(names[0] if names else "")')"
|
||||||
|
if [ -z "${PKG_NAME:-}" ]; then
|
||||||
|
PKG_NAME="$(sed -n 's/^name = \"\\(.*\\)\"/\\1/p' Cargo.toml | head -n 1)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ -z "${PKG_NAME:-}" ]; then
|
||||||
|
FULL="${GITHUB_REPOSITORY:-}"
|
||||||
|
if [ -z "$FULL" ]; then
|
||||||
|
echo "Could not read Cargo.toml and GITHUB_REPOSITORY is empty"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
PKG_NAME="${FULL##*/}"
|
||||||
|
echo "Cargo.toml missing or unreadable. Falling back to repo name: $PKG_NAME"
|
||||||
|
fi
|
||||||
|
echo "pkg_name=$PKG_NAME" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Compute versions
|
||||||
|
id: version_meta
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
CARGO_VER="$(python3 - << 'PY'
|
||||||
|
import re
|
||||||
|
txt = open("Cargo.toml", "r", encoding="utf-8").read()
|
||||||
|
m = re.search(r'(?m)^\s*version\s*=\s*"([^"]+)"\s*$', txt)
|
||||||
|
print(m.group(1) if m else "")
|
||||||
|
PY
|
||||||
|
)"
|
||||||
|
if [ -z "$CARGO_VER" ]; then
|
||||||
|
echo "Could not read version from Cargo.toml"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
REF="${GITHUB_REF_NAME:-}"
|
||||||
|
SHA="${GITHUB_SHA:-}"
|
||||||
|
SHORT_SHA="${SHA:0:8}"
|
||||||
|
|
||||||
|
if [[ "$REF" == v* ]]; then
|
||||||
|
PKG_VERSION="${REF#v}"
|
||||||
|
else
|
||||||
|
PKG_VERSION="${CARGO_VER}+g${SHORT_SHA}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "cargo_version=$CARGO_VER" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "pkg_version=$PKG_VERSION" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Create source tarball (code)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
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##*/}"
|
||||||
|
PKG_VERSION="${{ steps.version_meta.outputs.pkg_version }}"
|
||||||
|
BIN_NAME="${{ steps.pkg_meta.outputs.pkg_name }}"
|
||||||
|
|
||||||
|
mkdir -p dist
|
||||||
|
# Clean source snapshot of the repository at current commit
|
||||||
|
git archive --format=tar.gz \
|
||||||
|
--prefix="${BIN_NAME}-${PKG_VERSION}/" \
|
||||||
|
-o "dist/${BIN_NAME}-${PKG_VERSION}-source.tar.gz" \
|
||||||
|
HEAD
|
||||||
|
|
||||||
|
ls -lh dist
|
||||||
|
|
||||||
|
# OPTIONAL: build binary and package it too
|
||||||
|
- name: Build (release)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
cargo build --release
|
||||||
|
|
||||||
|
- name: Collect binary
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
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
|
||||||
|
REPO="${FULL##*/}"
|
||||||
|
PKG_VERSION="${{ steps.version_meta.outputs.pkg_version }}"
|
||||||
|
BIN_NAME="${{ steps.pkg_meta.outputs.pkg_name }}"
|
||||||
|
|
||||||
|
mkdir -p dist
|
||||||
|
cp "target/release/${BIN_NAME}" "dist/${BIN_NAME}-${PKG_VERSION}-linux-x86_64"
|
||||||
|
|
||||||
|
chmod +x "dist/${BIN_NAME}-${PKG_VERSION}-linux-x86_64"
|
||||||
|
ls -lh dist
|
||||||
|
|
||||||
|
- name: Upload to Gitea Generic Packages
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ vars.BASE_URL }}
|
||||||
|
GITEA: ${{ secrets.GITEA }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
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##*/}"
|
||||||
|
PKG_VERSION="${{ steps.version_meta.outputs.pkg_version }}"
|
||||||
|
BIN_NAME="${{ steps.pkg_meta.outputs.pkg_name }}"
|
||||||
|
|
||||||
|
if [ -z "${BASE_URL:-}" ]; then
|
||||||
|
echo "Missing vars.BASE_URL (example: https://gitea.example.com)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ -z "${GITEA:-}" ]; then
|
||||||
|
echo "Missing secrets.GITEA"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Choose a package name (keep stable). Here: cargo package name.
|
||||||
|
PACKAGE_NAME="$BIN_NAME"
|
||||||
|
|
||||||
|
for FILE in dist/*; do
|
||||||
|
FILENAME="$(basename "$FILE")"
|
||||||
|
URL="${BASE_URL}/api/packages/${OWNER}/generic/${PACKAGE_NAME}/${PKG_VERSION}/${FILENAME}"
|
||||||
|
echo "Uploading $FILENAME -> $URL"
|
||||||
|
curl -fsS -X PUT \
|
||||||
|
-H "Authorization: token ${GITEA}" \
|
||||||
|
--upload-file "$FILE" \
|
||||||
|
"$URL"
|
||||||
|
done
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,4 +1,5 @@
|
|||||||
.cargo/
|
.cargo/
|
||||||
|
.codex/
|
||||||
/target
|
/target
|
||||||
/data/storage/*
|
/data/storage/*
|
||||||
/data/logs/*
|
/data/logs/*
|
||||||
68
CHANGELOG.md
Normal file
68
CHANGELOG.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [0.3.0] - 2026-01-13
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Favicon set and web manifest for site branding.
|
||||||
|
- Syntax-highlighted rendering for code-like text content in the viewer.
|
||||||
|
- Startup log rotation that archives the previous log with a timestamp.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Access logs now write to `data/logs/log.txt` instead of `access.log`.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-01-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Default implementation for the asset model to simplify log parsing fallbacks.
|
||||||
|
- Basic UI polish for the stats page (background glow and hover highlight on recent activity).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Asset logging now records serialized values without cloning asset content.
|
||||||
|
- Release workflow uses tag-based versioning and caches Rust/toolchain artifacts.
|
||||||
|
|
||||||
|
## [0.1.1] - 2026-01-09
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.0] - 2026-01-09
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Statistics Dashboard** (`/stats.html`) with real-time metrics:
|
||||||
|
- Active assets count
|
||||||
|
- Total uploads and deletions
|
||||||
|
- Storage usage
|
||||||
|
- Image vs text breakdown
|
||||||
|
- Average server response time
|
||||||
|
- Total request count
|
||||||
|
- Recent activity feed (last 20 events)
|
||||||
|
- Auto-refresh every 30 seconds
|
||||||
|
- **Statistics API** (`GET /api/stats`) returning JSON metrics
|
||||||
|
- **Enhanced logging** for asset events:
|
||||||
|
- Upload events with uploader IP, MIME type, size, duration, timestamps
|
||||||
|
- Delete events with full asset metadata
|
||||||
|
- Request timing (`dur_ms`) in access logs
|
||||||
|
- **Uploader IP tracking** stored with each asset for audit purposes
|
||||||
|
- Stats link in index page footer
|
||||||
|
- Ephemeral image and text sharing with configurable TTL (1-60 minutes)
|
||||||
|
- Drag/drop, paste, and file picker upload support
|
||||||
|
- Base64 encoding for images, raw text for plain text
|
||||||
|
- UUID-based asset storage as JSON files
|
||||||
|
- Background cleanup task (every 60 seconds)
|
||||||
|
- Dark theme UI with zoom overlay
|
||||||
|
- View page for shared content
|
||||||
|
- Access logging with timing, IPs, and user agent
|
||||||
|
- Docker and docker-compose support with Traefik labels
|
||||||
|
- Environment variables for bind address and port
|
||||||
|
- Access logging with timing, IPs, and user agent
|
||||||
|
- Docker and docker-compose support with Traefik labels
|
||||||
|
- Environment variables for bind address and port
|
||||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -273,7 +273,7 @@ checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "black_hole_share"
|
name = "black_hole_share"
|
||||||
version = "0.1.0"
|
version = "0.3.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"actix-files",
|
"actix-files",
|
||||||
"actix-web",
|
"actix-web",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "black_hole_share"
|
name = "black_hole_share"
|
||||||
version = "0.1.0"
|
version = "0.3.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
13
Dockerfile
13
Dockerfile
@@ -20,5 +20,14 @@ RUN pacman -Syu --noconfirm --needed \
|
|||||||
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y
|
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y
|
||||||
ENV PATH="/root/.cargo/bin:${PATH}"
|
ENV PATH="/root/.cargo/bin:${PATH}"
|
||||||
|
|
||||||
WORKDIR /data
|
COPY src /opt/bhs/src
|
||||||
CMD ["black_hole_share"]
|
COPY Cargo.toml /opt/bhs/Cargo.toml
|
||||||
|
COPY Cargo.lock /opt/bhs/Cargo.lock
|
||||||
|
|
||||||
|
WORKDIR /opt/bhs
|
||||||
|
RUN ls -al ./
|
||||||
|
RUN cargo build --release
|
||||||
|
RUN cp ./target/release/black_hole_share /usr/local/bin/black_hole_share
|
||||||
|
|
||||||
|
WORKDIR /
|
||||||
|
CMD [ "black_hole_share" ]
|
||||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Black Hole Share Contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
132
README.md
132
README.md
@@ -0,0 +1,132 @@
|
|||||||
|
# Black Hole Share
|
||||||
|
|
||||||
|
A lightweight, ephemeral file sharing service built with Rust and Actix-Web. Upload images or text with a configurable TTL (1-60 minutes) and share via a unique link. Content is automatically purged after expiration.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Ephemeral sharing** – uploads auto-delete after the specified duration
|
||||||
|
- **Image & text support** – drag/drop, paste, or file picker for images; paste text directly
|
||||||
|
- **Zero database** – assets stored as JSON files on disk
|
||||||
|
- **Dark theme UI** – clean, responsive interface with zoom overlay
|
||||||
|
- **Statistics dashboard** – real-time stats at `/stats.html` (active assets, uploads, response times)
|
||||||
|
- **Access logging** – request and asset events logged to `data/logs/log.txt` with IP, timing, and metadata
|
||||||
|
- **Code-friendly text view** – code-like text content auto-formats with syntax highlighting
|
||||||
|
- **Site assets** – favicon set and web manifest for installable branding
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Local Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run from repo root (paths resolve to data/html/, data/logs/, data/storage/)
|
||||||
|
cargo run --release
|
||||||
|
```
|
||||||
|
|
||||||
|
Server starts at `http://0.0.0.0:8080` by default.
|
||||||
|
|
||||||
|
> **Note:** All paths are relative to the repo root: `data/html/`, `data/logs/`, `data/storage/`.
|
||||||
|
|
||||||
|
### Toolchain
|
||||||
|
|
||||||
|
Rust toolchain is pinned in `rust-toolchain.toml` (current: 1.90.0).
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Exposes port `8080` mapped to container port `80`. Volume mounts `./data:/data`.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Environment Variable | Default | Description |
|
||||||
|
| -------------------- | --------- | --------------- |
|
||||||
|
| `BIND_ADDR` | `0.0.0.0` | Address to bind |
|
||||||
|
| `BIND_PORT` | `8080` | Port to bind |
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
### Upload
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/upload
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"duration": 5,
|
||||||
|
"content_type": "text/plain",
|
||||||
|
"content": "Hello, world!"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `duration` – TTL in minutes (1-60)
|
||||||
|
- `content_type` – MIME type (`text/plain` or `image/*`)
|
||||||
|
- `content` – raw text or base64-encoded image data
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "link": "/bhs/550e8400-e29b-41d4-a716-446655440000" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fetch
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/content/{id}
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns the original content with appropriate MIME type, or `404` if expired/missing.
|
||||||
|
|
||||||
|
### Statistics
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/stats
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"active_assets": 5,
|
||||||
|
"total_uploads": 42,
|
||||||
|
"total_deleted": 37,
|
||||||
|
"storage_bytes": 1048576,
|
||||||
|
"image_count": 3,
|
||||||
|
"text_count": 2,
|
||||||
|
"total_requests": 150,
|
||||||
|
"recent_activity": [...]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
├── src/
|
||||||
|
│ ├── main.rs # HTTP server, routing, background cleanup
|
||||||
|
│ ├── api.rs # Upload/fetch endpoints
|
||||||
|
│ ├── data_mgt.rs # Asset model, persistence, expiration
|
||||||
|
│ └── logs.rs # Request and asset event logging
|
||||||
|
├── data/
|
||||||
|
│ ├── html/ # Frontend (index.html, view.html, stats.html, style.css)
|
||||||
|
│ ├── logs/ # Access logs
|
||||||
|
│ └── storage/ # Stored assets (auto-created)
|
||||||
|
├── Dockerfile
|
||||||
|
├── docker-compose.yaml
|
||||||
|
└── Cargo.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Runtime Layout
|
||||||
|
|
||||||
|
The server uses paths relative to the repo root under `data/`:
|
||||||
|
|
||||||
|
- `data/html/` – frontend assets (index.html, view.html, style.css)
|
||||||
|
- `data/logs/` – access logs (`log.txt`, rotated on startup with timestamps)
|
||||||
|
- `data/storage/` – uploaded assets (auto-created)
|
||||||
|
|
||||||
|
- **Local dev:** Run from repo root with `cargo run --release`
|
||||||
|
- **Docker:** Volume mounts `./data:/data`, container WORKDIR is `/`
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
|
|||||||
BIN
data/html/android-chrome-192x192.png
Normal file
BIN
data/html/android-chrome-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
BIN
data/html/android-chrome-512x512.png
Normal file
BIN
data/html/android-chrome-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 347 KiB |
BIN
data/html/apple-touch-icon.png
Normal file
BIN
data/html/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
40
data/html/error.html
Normal file
40
data/html/error.html
Normal 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>
|
||||||
BIN
data/html/favicon-16x16.png
Normal file
BIN
data/html/favicon-16x16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 844 B |
BIN
data/html/favicon-32x32.png
Normal file
BIN
data/html/favicon-32x32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.6 KiB |
BIN
data/html/favicon.ico
Normal file
BIN
data/html/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 866 B |
@@ -2,10 +2,16 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Image Upload</title>
|
<title>Image Upload</title>
|
||||||
<link rel="stylesheet" href="style.css">
|
<link rel="stylesheet" href="style.css" />
|
||||||
|
<link rel="icon" href="/favicon.ico" sizes="any">
|
||||||
|
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||||
|
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||||
|
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||||
|
<link rel="manifest" href="/site.webmanifest">
|
||||||
|
<meta name="theme-color" content="#000000">
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
@@ -13,62 +19,80 @@
|
|||||||
|
|
||||||
<div class="upload-container">
|
<div class="upload-container">
|
||||||
<div class="upload-area">
|
<div class="upload-area">
|
||||||
<input type="file" id="fileInput" accept="image/*" style="display: none;">
|
<input type="file" id="fileInput" accept="image/*" style="display: none" />
|
||||||
<div id="uploadZone" class="upload-zone">
|
<div id="uploadZone" class="upload-zone">
|
||||||
<p>Click to select file, paste image data, or drag & drop</p>
|
<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">Duration: <span id="durationValue">5</span> min</label>
|
<label for="durationSlider">Duration: <span id="durationValue">5</span> min</label>
|
||||||
<input type="range" id="durationSlider" min="1" max="60" value="5" step="1">
|
<input type="range" id="durationSlider" min="1" max="60" value="5" step="1" />
|
||||||
<div class="button-row">
|
<div class="button-row">
|
||||||
<button id="resetBtn" class="reset-btn" style="display: none;">Reset</button>
|
<button id="resetBtn" class="reset-btn" style="display: none">
|
||||||
<button id="uploadBtn" class="upload-btn" style="display: none;">Upload</button>
|
Reset
|
||||||
|
</button>
|
||||||
|
<button id="uploadBtn" class="upload-btn" style="display: none">
|
||||||
|
Upload
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="linkContainer" class="link-container" style="display: none;">
|
<div id="linkContainer" class="link-container" style="display: none">
|
||||||
<p>Link:</p>
|
<p>Link:</p>
|
||||||
<a id="uploadedLink" href="#" target="_blank"></a>
|
<a id="uploadedLink" href="#" target="_blank"></a>
|
||||||
<p id="clipboardMessage" class="clipboard-message" style="display: none;"></p>
|
<p id="clipboardMessage" class="clipboard-message" style="display: none"></p>
|
||||||
</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 -->
|
||||||
<div id="zoomOverlay" class="zoom-overlay" style="display: none;">
|
<div id="zoomOverlay" class="zoom-overlay" style="display: none"></div>
|
||||||
</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!!!
|
||||||
|
durationSlider.addEventListener("wheel", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
durationSlider.valueAsNumber += e.deltaY < 0 ? -1 : 1;
|
||||||
|
durationValue.textContent = durationSlider.value;
|
||||||
|
});
|
||||||
|
|
||||||
|
uploadBtn.addEventListener("click", async () => {
|
||||||
const duration = durationSlider.value;
|
const duration = durationSlider.value;
|
||||||
const isText = uploadZone.querySelector('.text-content') !== null;
|
const isText = uploadZone.querySelector(".text-content") !== null;
|
||||||
const mimeType = isText ? 'text/plain' : 'image/png';
|
const mimeType = isText ? "text/plain" : "image/png";
|
||||||
const contentData = currentContentData;
|
const contentData = currentContentData;
|
||||||
|
|
||||||
if (!contentData) {
|
if (!contentData) {
|
||||||
console.log('❌ No content to upload!');
|
console.log("❌ No content to upload!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,104 +100,107 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function sendUpload(duration, mimeType, contentData) {
|
async function sendUpload(duration, mimeType, contentData) {
|
||||||
const isText = mimeType === 'text/plain';
|
const isText = mimeType === "text/plain";
|
||||||
let content = contentData;
|
let content = contentData;
|
||||||
|
|
||||||
// For images, remove data URL prefix to send only base64 string
|
// For images, remove data URL prefix to send only base64 string
|
||||||
if (!isText && contentData.includes('base64,')) {
|
if (!isText && contentData.includes("base64,")) {
|
||||||
content = contentData.split('base64,')[1];
|
content = contentData.split("base64,")[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
duration: parseInt(duration),
|
duration: parseInt(duration),
|
||||||
content_type: mimeType,
|
content_type: mimeType,
|
||||||
content: content
|
content: content,
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/upload', {
|
const response = await fetch("/api/upload", {
|
||||||
method: 'POST',
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(payload)
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
console.log(`✅ Upload received!\n${JSON.stringify(result, null, 2)}`);
|
console.log(
|
||||||
|
`✅ Upload received!\n${JSON.stringify(result, null, 2)}`
|
||||||
|
);
|
||||||
|
|
||||||
// Hide duration controls and buttons
|
// Hide duration controls and buttons
|
||||||
document.querySelector('label[for="durationSlider"]').style.display = 'none';
|
document.querySelector('label[for="durationSlider"]').style.display =
|
||||||
durationSlider.style.display = 'none';
|
"none";
|
||||||
uploadBtn.style.display = 'none';
|
durationSlider.style.display = "none";
|
||||||
resetBtn.style.display = 'none';
|
uploadBtn.style.display = "none";
|
||||||
|
resetBtn.style.display = "none";
|
||||||
|
|
||||||
// Show link
|
// Show link
|
||||||
const fullLink = window.location.origin + result.link;
|
const fullLink = window.location.origin + result.link;
|
||||||
uploadedLink.href = fullLink;
|
uploadedLink.href = fullLink;
|
||||||
uploadedLink.textContent = fullLink;
|
uploadedLink.textContent = fullLink;
|
||||||
linkContainer.style.display = 'block';
|
linkContainer.style.display = "block";
|
||||||
|
|
||||||
// Copy to clipboard
|
// Copy to clipboard
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(fullLink);
|
await navigator.clipboard.writeText(fullLink);
|
||||||
clipboardMessage.textContent = '✓ Copied to clipboard!';
|
clipboardMessage.textContent = "✓ Copied to clipboard!";
|
||||||
clipboardMessage.style.color = 'var(--accent-green)';
|
clipboardMessage.style.color = "var(--accent-green)";
|
||||||
clipboardMessage.style.cursor = 'default';
|
clipboardMessage.style.cursor = "default";
|
||||||
clipboardMessage.style.display = 'block';
|
clipboardMessage.style.display = "block";
|
||||||
clipboardMessage.onclick = null;
|
clipboardMessage.onclick = null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
clipboardMessage.textContent = '⚠ Click here to copy link';
|
clipboardMessage.textContent = "⚠ Click here to copy link";
|
||||||
clipboardMessage.style.color = 'var(--accent-cyan)';
|
clipboardMessage.style.color = "var(--accent-cyan)";
|
||||||
clipboardMessage.style.cursor = 'pointer';
|
clipboardMessage.style.cursor = "pointer";
|
||||||
clipboardMessage.style.display = 'block';
|
clipboardMessage.style.display = "block";
|
||||||
clipboardMessage.onclick = function () {
|
clipboardMessage.onclick = function () {
|
||||||
const textArea = document.createElement('textarea');
|
const textArea = document.createElement("textarea");
|
||||||
textArea.value = fullLink;
|
textArea.value = fullLink;
|
||||||
textArea.style.position = 'fixed';
|
textArea.style.position = "fixed";
|
||||||
textArea.style.left = '-999999px';
|
textArea.style.left = "-999999px";
|
||||||
document.body.appendChild(textArea);
|
document.body.appendChild(textArea);
|
||||||
textArea.select();
|
textArea.select();
|
||||||
try {
|
try {
|
||||||
document.execCommand('copy');
|
document.execCommand("copy");
|
||||||
clipboardMessage.textContent = '✓ Copied to clipboard!';
|
clipboardMessage.textContent = "✓ Copied to clipboard!";
|
||||||
clipboardMessage.style.color = 'var(--accent-green)';
|
clipboardMessage.style.color = "var(--accent-green)";
|
||||||
clipboardMessage.style.cursor = 'default';
|
clipboardMessage.style.cursor = "default";
|
||||||
clipboardMessage.onclick = null;
|
clipboardMessage.onclick = null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
clipboardMessage.textContent = '✗ Copy failed';
|
clipboardMessage.textContent = "✗ Copy failed";
|
||||||
clipboardMessage.style.color = '#ff6666';
|
clipboardMessage.style.color = "#ff6666";
|
||||||
}
|
}
|
||||||
document.body.removeChild(textArea);
|
document.body.removeChild(textArea);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`❌ Error: ${error.message}`);
|
console.log(`❌ Error: ${error.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Reset to initial state
|
// Reset to initial state
|
||||||
resetBtn.addEventListener('click', function () {
|
resetBtn.addEventListener("click", function () {
|
||||||
currentContentData = null;
|
currentContentData = null;
|
||||||
uploadZone.innerHTML = '<p>Click to select file, paste image data, or drag & drop</p>';
|
uploadZone.innerHTML =
|
||||||
uploadContainer.style.height = '180px';
|
"<p>Click to select file, paste image data, or drag & drop</p>";
|
||||||
uploadContainer.style.pointerEvents = '';
|
uploadContainer.style.height = "180px";
|
||||||
uploadContainer.style.overflow = '';
|
uploadContainer.style.pointerEvents = "";
|
||||||
uploadZone.style.pointerEvents = '';
|
uploadContainer.style.overflow = "";
|
||||||
uploadZone.style.alignItems = '';
|
uploadZone.style.pointerEvents = "";
|
||||||
uploadZone.style.justifyContent = '';
|
uploadZone.style.alignItems = "";
|
||||||
uploadZone.style.padding = '';
|
uploadZone.style.justifyContent = "";
|
||||||
fileInput.value = '';
|
uploadZone.style.padding = "";
|
||||||
durationSlider.value = '5';
|
fileInput.value = "";
|
||||||
durationValue.textContent = '5';
|
durationSlider.value = "5";
|
||||||
document.querySelector('label[for="durationSlider"]').style.display = '';
|
durationValue.textContent = "5";
|
||||||
durationSlider.style.display = '';
|
document.querySelector('label[for="durationSlider"]').style.display =
|
||||||
uploadBtn.style.display = 'none';
|
"";
|
||||||
resetBtn.style.display = 'none';
|
durationSlider.style.display = "";
|
||||||
linkContainer.style.display = 'none';
|
uploadBtn.style.display = "none";
|
||||||
clipboardMessage.style.display = 'none';
|
resetBtn.style.display = "none";
|
||||||
|
linkContainer.style.display = "none";
|
||||||
|
clipboardMessage.style.display = "none";
|
||||||
uploadZone.focus();
|
uploadZone.focus();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -183,42 +210,47 @@
|
|||||||
|
|
||||||
if (isText) {
|
if (isText) {
|
||||||
// Display text content - ZOOM ENABLED
|
// Display text content - ZOOM ENABLED
|
||||||
uploadZone.innerHTML = `<div class="text-content" style="cursor: zoom-in;">${content.replace(/</g, '<').replace(/>/g, '>')}</div>`;
|
uploadZone.innerHTML = `<div class="text-content" style="cursor: zoom-in;">${content
|
||||||
uploadContainer.style.height = '500px';
|
.replace(/</g, "<")
|
||||||
uploadContainer.style.overflow = 'hidden';
|
.replace(/>/g, ">")}</div>`;
|
||||||
uploadZone.style.pointerEvents = 'auto';
|
uploadContainer.style.height = "500px";
|
||||||
uploadZone.style.alignItems = 'stretch';
|
uploadContainer.style.overflow = "hidden";
|
||||||
uploadZone.style.justifyContent = 'stretch';
|
uploadZone.style.pointerEvents = "auto";
|
||||||
uploadZone.style.padding = '0';
|
uploadZone.style.alignItems = "stretch";
|
||||||
uploadBtn.style.display = 'block';
|
uploadZone.style.justifyContent = "stretch";
|
||||||
resetBtn.style.display = 'block';
|
uploadZone.style.padding = "0";
|
||||||
|
uploadBtn.style.display = "block";
|
||||||
|
resetBtn.style.display = "block";
|
||||||
|
|
||||||
// ZOOM FOR TEXT
|
// ZOOM FOR TEXT
|
||||||
const textContent = uploadZone.querySelector('.text-content');
|
const textContent = uploadZone.querySelector(".text-content");
|
||||||
textContent.addEventListener('click', function (e) {
|
textContent.addEventListener("click", function (e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
showZoom(content, true);
|
showZoom(content, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// Display image
|
// Display image
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
img.onload = function () {
|
img.onload = function () {
|
||||||
const maxWidth = 620;
|
const maxWidth = 620;
|
||||||
const maxHeight = 800;
|
const maxHeight = 800;
|
||||||
const scale = Math.min(maxWidth / img.width, maxHeight / img.height, 1);
|
const scale = Math.min(
|
||||||
|
maxWidth / img.width,
|
||||||
|
maxHeight / img.height,
|
||||||
|
1
|
||||||
|
);
|
||||||
const displayHeight = Math.floor(img.height * scale);
|
const displayHeight = Math.floor(img.height * scale);
|
||||||
const displayWidth = Math.floor(img.width * 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;">`;
|
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.height = `${displayHeight + 20}px`;
|
||||||
uploadContainer.style.pointerEvents = 'none';
|
uploadContainer.style.pointerEvents = "none";
|
||||||
uploadZone.style.pointerEvents = 'auto';
|
uploadZone.style.pointerEvents = "auto";
|
||||||
uploadBtn.style.display = 'block';
|
uploadBtn.style.display = "block";
|
||||||
resetBtn.style.display = 'block';
|
resetBtn.style.display = "block";
|
||||||
|
|
||||||
const uploadedImg = uploadZone.querySelector('img');
|
const uploadedImg = uploadZone.querySelector("img");
|
||||||
uploadedImg.addEventListener('click', function (e) {
|
uploadedImg.addEventListener("click", function (e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
showZoom(content, false);
|
showZoom(content, false);
|
||||||
});
|
});
|
||||||
@@ -228,13 +260,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 (uploadContainer.style.pointerEvents !== 'none' && !uploadZone.querySelector('.text-content') && !uploadZone.querySelector('img')) {
|
if (
|
||||||
|
uploadContainer.style.pointerEvents !== "none" &&
|
||||||
|
!uploadZone.querySelector(".text-content") &&
|
||||||
|
!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();
|
||||||
@@ -246,12 +282,12 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 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();
|
const reader = new FileReader();
|
||||||
reader.onload = function (event) {
|
reader.onload = function (event) {
|
||||||
@@ -262,20 +298,20 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const text = e.clipboardData.getData('text');
|
const text = e.clipboardData.getData("text");
|
||||||
if (text) {
|
if (text) {
|
||||||
displayContent(text, true);
|
displayContent(text, true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle drag and drop
|
// Handle drag and drop
|
||||||
uploadZone.addEventListener('drop', handleDrop);
|
uploadZone.addEventListener("drop", handleDrop);
|
||||||
uploadContainer.addEventListener('drop', handleDrop);
|
uploadContainer.addEventListener("drop", handleDrop);
|
||||||
|
|
||||||
function handleDrop(e) {
|
function handleDrop(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const file = e.dataTransfer.files[0];
|
const file = e.dataTransfer.files[0];
|
||||||
if (file && file.type.startsWith('image/')) {
|
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);
|
||||||
@@ -284,22 +320,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadZone.addEventListener('dragover', function (e) {
|
uploadZone.addEventListener("dragover", function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
uploadZone.style.borderColor = 'var(--border-hover)';
|
uploadZone.style.borderColor = "var(--border-hover)";
|
||||||
});
|
});
|
||||||
|
|
||||||
uploadZone.addEventListener('dragleave', function (e) {
|
uploadZone.addEventListener("dragleave", function (e) {
|
||||||
uploadZone.style.borderColor = '';
|
uploadZone.style.borderColor = "";
|
||||||
});
|
});
|
||||||
|
|
||||||
uploadContainer.addEventListener('dragover', function (e) {
|
uploadContainer.addEventListener("dragover", function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
});
|
});
|
||||||
|
|
||||||
uploadZone.setAttribute('tabindex', '0');
|
uploadZone.setAttribute("tabindex", "0");
|
||||||
|
|
||||||
window.addEventListener('focus', function () {
|
window.addEventListener("focus", function () {
|
||||||
uploadZone.focus();
|
uploadZone.focus();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -309,28 +345,30 @@
|
|||||||
function showZoom(content, isText = false) {
|
function showZoom(content, isText = false) {
|
||||||
if (isText) {
|
if (isText) {
|
||||||
zoomOverlay.innerHTML = `
|
zoomOverlay.innerHTML = `
|
||||||
<div class="zoom-text-content">${content.replace(/</g, '<').replace(/>/g, '>')}</div>
|
<div class="zoom-text-content">${content
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")}</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);
|
zoomOverlay.addEventListener("click", hideZoom);
|
||||||
|
|
||||||
// ESC TO EXIT ZOOM
|
// ESC TO EXIT ZOOM
|
||||||
document.addEventListener('keydown', function (e) {
|
document.addEventListener("keydown", function (e) {
|
||||||
if (e.key === 'Escape' || e.key === 'Esc') {
|
if (e.key === "Escape" || e.key === "Esc") {
|
||||||
hideZoom();
|
hideZoom();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
window.addEventListener('resize', function () {
|
window.addEventListener("resize", function () {
|
||||||
if (currentContentData) {
|
if (currentContentData) {
|
||||||
displayContent(currentContentData);
|
displayContent(currentContentData);
|
||||||
}
|
}
|
||||||
|
|||||||
19
data/html/site.webmanifest
Normal file
19
data/html/site.webmanifest
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "Black Hole Share",
|
||||||
|
"short_name": "BHS",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "/android-chrome-192x192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/android-chrome-512x512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"theme_color": "#000000",
|
||||||
|
"background_color": "#000000",
|
||||||
|
"display": "standalone"
|
||||||
|
}
|
||||||
295
data/html/stats.html
Normal file
295
data/html/stats.html
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
<!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 - Statistics</title>
|
||||||
|
<link rel="stylesheet" href="/style.css" />
|
||||||
|
<style>
|
||||||
|
.stats-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(140px, 170px);
|
||||||
|
gap: 20px;
|
||||||
|
margin-top: 20px;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stats-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(160px, 1fr));
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stats-request-card {
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-card {
|
||||||
|
background-color: var(--bg-secondary);
|
||||||
|
border: 2px solid var(--border-color);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
text-align: center;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-card:hover {
|
||||||
|
border-color: var(--border-hover);
|
||||||
|
box-shadow: 0 4px 15px rgba(0, 255, 153, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
font-size: 1.5em;
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--accent-cyan);
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-label {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 0.9em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-card.highlight .stat-value {
|
||||||
|
color: var(--accent-green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity {
|
||||||
|
margin-top: 30px;
|
||||||
|
background-color: var(--bg-secondary);
|
||||||
|
border: 2px solid var(--border-color);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity h2 {
|
||||||
|
color: var(--accent-cyan);
|
||||||
|
margin: 0 0 15px 0;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity:hover {
|
||||||
|
border-color: var(--border-hover);
|
||||||
|
box-shadow: 0 4px 15px rgba(0, 255, 153, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-list {
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
font-family: "JetBrains Mono", monospace;
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-item {
|
||||||
|
padding: 8px 0;
|
||||||
|
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-item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-action {
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.8em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-action.upload {
|
||||||
|
background-color: rgba(0, 255, 153, 0.2);
|
||||||
|
color: var(--accent-green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-action.delete {
|
||||||
|
background-color: rgba(255, 102, 102, 0.2);
|
||||||
|
color: #ff6666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-time {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-details {
|
||||||
|
color: var(--text-primary);
|
||||||
|
display: contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-mime {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-duration {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-time {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.refresh-btn {
|
||||||
|
background-color: var(--border-color);
|
||||||
|
color: var(--bg-tertiary);
|
||||||
|
border: none;
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
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>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
if (bytes === 0) return "0 B";
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ["B", "KB", "MB", "GB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(timestamp) {
|
||||||
|
const date = new Date(timestamp);
|
||||||
|
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) {
|
||||||
|
const html = `
|
||||||
|
<div class="stats-layout">
|
||||||
|
<div class="stats-grid">
|
||||||
|
<div class="stat-card highlight">
|
||||||
|
<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 class="stat-card stats-request-card">
|
||||||
|
<div class="stat-label">Total Server Requests</div>
|
||||||
|
<div class="stat-value">${stats.total_requests}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="recent-activity">
|
||||||
|
<h2>Recent Activity</h2>
|
||||||
|
<div class="activity-list">
|
||||||
|
${stats.recent_activity.length === 0
|
||||||
|
? '<p style="color: var(--text-secondary);">No recent activity</p>'
|
||||||
|
: stats.recent_activity
|
||||||
|
.map(
|
||||||
|
(item) => `
|
||||||
|
<div class="activity-item">
|
||||||
|
<span class="activity-action ${item.action}">${item.action
|
||||||
|
}</span>
|
||||||
|
<span class="activity-details">
|
||||||
|
<span class="activity-mime">${item.mime}</span>
|
||||||
|
<span class="activity-duration">${item.share_duration} min</span>
|
||||||
|
</span>
|
||||||
|
<span class="activity-time">${formatTime(item.timestamp)}</span>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
)
|
||||||
|
.join("")
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button class="refresh-btn" onclick="loadStats()">Refresh</button>
|
||||||
|
`;
|
||||||
|
document.getElementById("statsContent").innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
loadStats();
|
||||||
|
// Auto-refresh every 30 seconds
|
||||||
|
setInterval(loadStats, 30000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -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;
|
||||||
@@ -356,6 +363,18 @@ h1 .home-link:hover {
|
|||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.zoom-text-content.code-content {
|
||||||
|
background-color: var(--bg-primary);
|
||||||
|
border-color: var(--border-color);
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
.zoom-text-content.code-content code {
|
||||||
|
display: block;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
|
||||||
.zoom-text-content::-webkit-scrollbar {
|
.zoom-text-content::-webkit-scrollbar {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
}
|
}
|
||||||
@@ -386,7 +405,7 @@ h1 .home-link:hover {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
z-index: 9999;
|
z-index: 9999;
|
||||||
cursor: zoom-out;
|
cursor: default;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
@@ -512,6 +531,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%,
|
||||||
@@ -544,6 +612,18 @@ body.view-page {
|
|||||||
border: none;
|
border: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.text-content-view.code-content {
|
||||||
|
background-color: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-content-view.code-content code {
|
||||||
|
display: block;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
|
||||||
.text-content-view::-webkit-scrollbar {
|
.text-content-view::-webkit-scrollbar {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Black Hole Share - View</title>
|
<title>Black Hole Share - View</title>
|
||||||
<link rel="stylesheet" href="/style.css">
|
<link rel="stylesheet" href="/style.css">
|
||||||
|
<link rel="stylesheet"
|
||||||
|
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body class="view-page">
|
<body class="view-page">
|
||||||
@@ -17,13 +19,22 @@
|
|||||||
</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 -->
|
||||||
<div id="zoomOverlay" class="zoom-overlay" style="display: none;"></div>
|
<div id="zoomOverlay" class="zoom-overlay" style="display: none;"></div>
|
||||||
|
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
const contentArea = document.getElementById('contentArea');
|
const contentArea = document.getElementById('contentArea');
|
||||||
const zoomOverlay = document.getElementById('zoomOverlay');
|
const zoomOverlay = document.getElementById('zoomOverlay');
|
||||||
@@ -32,6 +43,28 @@
|
|||||||
const pathParts = window.location.pathname.split('/');
|
const pathParts = window.location.pathname.split('/');
|
||||||
const assetId = pathParts[pathParts.length - 1];
|
const assetId = pathParts[pathParts.length - 1];
|
||||||
|
|
||||||
|
function escapeHtml(text) {
|
||||||
|
return text.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCodeLike(text) {
|
||||||
|
const lines = text.split('\n');
|
||||||
|
if (lines.length < 2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const indicators = [
|
||||||
|
/;\s*$/,
|
||||||
|
/^\s*(fn|function|class|def|public|private|struct|enum|pub\s+struct)\b/,
|
||||||
|
/^\s*#\[/,
|
||||||
|
/=>|::|#include|import\s+\w+/,
|
||||||
|
/\{|\}|\(|\)|\[|\]/,
|
||||||
|
];
|
||||||
|
const indicatorHits = indicators.reduce((count, re) => count + (re.test(text) ? 1 : 0), 0);
|
||||||
|
return indicatorHits >= 2;
|
||||||
|
}
|
||||||
|
|
||||||
async function loadContent() {
|
async function loadContent() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/content/${assetId}`);
|
const response = await fetch(`/api/content/${assetId}`);
|
||||||
@@ -74,12 +107,23 @@
|
|||||||
} else if (contentType.startsWith('text/')) {
|
} else if (contentType.startsWith('text/')) {
|
||||||
// Display text
|
// Display text
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
contentArea.innerHTML = `<div class="text-content-view" style="cursor: zoom-in;">${text.replace(/</g, '<').replace(/>/g, '>')}</div>`;
|
const safeText = escapeHtml(text);
|
||||||
|
const isCode = isCodeLike(text);
|
||||||
|
const textHtml = isCode
|
||||||
|
? `<pre class="text-content-view code-content"><code>${safeText}</code></pre>`
|
||||||
|
: `<div class="text-content-view">${safeText}</div>`;
|
||||||
|
|
||||||
|
contentArea.innerHTML = textHtml;
|
||||||
|
if (isCode && window.hljs) {
|
||||||
|
contentArea.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
window.hljs.highlightElement(block);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const textContent = contentArea.querySelector('.text-content-view');
|
const textContent = contentArea.querySelector('.text-content-view');
|
||||||
textContent.addEventListener('click', function (e) {
|
textContent.addEventListener('click', function (e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
showZoom(text, true);
|
showZoom(text, true, isCode);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
contentArea.innerHTML = '<p class="error">Unsupported content type</p>';
|
contentArea.innerHTML = '<p class="error">Unsupported content type</p>';
|
||||||
@@ -91,11 +135,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showZoom(content, isText = false) {
|
function showZoom(content, isText = false, isCode = false) {
|
||||||
if (isText) {
|
if (isText) {
|
||||||
zoomOverlay.innerHTML = `
|
const safeText = escapeHtml(content);
|
||||||
<div class="zoom-text-content">${content.replace(/</g, '<').replace(/>/g, '>')}</div>
|
const zoomClass = isCode ? 'zoom-text-content code-content' : 'zoom-text-content';
|
||||||
`;
|
const zoomHtml = isCode
|
||||||
|
? `<pre class="${zoomClass}"><code>${safeText}</code></pre>`
|
||||||
|
: `<div class="${zoomClass}">${safeText}</div>`;
|
||||||
|
zoomOverlay.innerHTML = zoomHtml;
|
||||||
|
if (isCode && window.hljs) {
|
||||||
|
zoomOverlay.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
window.hljs.highlightElement(block);
|
||||||
|
});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
zoomOverlay.innerHTML = `<img id="zoomImage" src="${content}" alt="Zoomed Content"
|
zoomOverlay.innerHTML = `<img id="zoomImage" src="${content}" alt="Zoomed Content"
|
||||||
style="max-width: 95vw; max-height: 95vh; object-fit: contain; box-shadow: 0 0 50px rgba(51, 204, 255, 0.5);">`;
|
style="max-width: 95vw; max-height: 95vh; object-fit: contain; box-shadow: 0 0 50px rgba(51, 204, 255, 0.5);">`;
|
||||||
@@ -107,8 +159,6 @@
|
|||||||
zoomOverlay.style.display = 'none';
|
zoomOverlay.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
zoomOverlay.addEventListener('click', hideZoom);
|
|
||||||
|
|
||||||
document.addEventListener('keydown', function (e) {
|
document.addEventListener('keydown', function (e) {
|
||||||
if (e.key === 'Escape' || e.key === 'Esc') {
|
if (e.key === 'Escape' || e.key === 'Esc') {
|
||||||
hideZoom();
|
hideZoom();
|
||||||
|
|||||||
@@ -7,9 +7,27 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
- /etc/localtime:/etc/localtime:ro
|
- /etc/localtime:/etc/localtime:ro
|
||||||
|
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
- "traefik.docker.network=vlan250"
|
||||||
|
- "traefik.http.routers.bhs.rule=Host(`bhs.qosnet.it`)"
|
||||||
|
- "traefik.http.routers.bhs.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.bhs.tls=true"
|
||||||
|
- "traefik.http.routers.bhs.tls.certresolver=le"
|
||||||
|
- "traefik.http.services.bhs.loadbalancer.server.port=80"
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
- TZ="Europe/Rome"
|
- TZ=Europe/Rome
|
||||||
|
- BIND_ADDR=0.0.0.0
|
||||||
|
- BIND_PORT=80
|
||||||
tty: true
|
tty: true
|
||||||
stdin_open: true
|
stdin_open: true
|
||||||
ports:
|
ports:
|
||||||
- "8080:80"
|
- "8080:80"
|
||||||
|
networks:
|
||||||
|
- vlan250
|
||||||
|
|
||||||
|
networks:
|
||||||
|
vlan250:
|
||||||
|
external: true
|
||||||
|
|||||||
2
rust-toolchain.toml
Normal file
2
rust-toolchain.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "1.90.0"
|
||||||
145
src/api.rs
145
src/api.rs
@@ -1,9 +1,14 @@
|
|||||||
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::{DATA_STORAGE, logs::log_to_file};
|
use crate::{
|
||||||
|
LOG_FILE_NAME,
|
||||||
|
data_mgt::{Asset, AssetTracker},
|
||||||
|
logs::{LogEvent, LogEventType, log_event},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct UploadRequest {
|
pub struct UploadRequest {
|
||||||
@@ -13,38 +18,136 @@ pub struct UploadRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/api/upload")]
|
#[post("/api/upload")]
|
||||||
async fn api_upload(req: 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 req.content_type == "text/plain" {
|
let content_bytes = if body.content_type == "text/plain" {
|
||||||
req.content.as_bytes().to_vec() // UTF-8 bytes
|
body.content.as_bytes().to_vec()
|
||||||
} else {
|
} else {
|
||||||
// Decode base64 → bytes
|
match general_purpose::STANDARD.decode(&body.content) {
|
||||||
general_purpose::STANDARD.decode(&req.content).unwrap()
|
Ok(bytes) => bytes,
|
||||||
|
Err(_) => return Ok(HttpResponse::BadRequest().body("Invalid base64 payload")),
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let asset = crate::data_mgt::Asset::new(req.duration, req.content_type.clone(), content_bytes);
|
let connection_info = req.connection_info();
|
||||||
|
let uploader_ip = connection_info
|
||||||
|
.realip_remote_addr()
|
||||||
|
.or_else(|| connection_info.peer_addr())
|
||||||
|
.unwrap_or("-")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
let id = asset
|
let asset = crate::data_mgt::Asset::new(
|
||||||
.save()
|
body.duration,
|
||||||
.map_err(|e| actix_web::error::ErrorInternalServerError(format!("Failed to save asset: {}", e)))?;
|
body.content_type.clone(),
|
||||||
|
content_bytes,
|
||||||
|
Some(uploader_ip.clone()),
|
||||||
|
);
|
||||||
|
|
||||||
|
let id = asset.id();
|
||||||
|
log_event(LogEventType::AssetUploaded(asset.to_value()));
|
||||||
|
assets.add_asset(asset).await;
|
||||||
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() {
|
#[derive(serde::Serialize)]
|
||||||
return Err(actix_web::error::ErrorNotFound("Asset has expired"));
|
struct StatsResponse {
|
||||||
|
active_assets: usize,
|
||||||
|
total_uploads: usize,
|
||||||
|
total_deleted: usize,
|
||||||
|
storage_bytes: u64,
|
||||||
|
image_count: usize,
|
||||||
|
text_count: usize,
|
||||||
|
total_requests: usize,
|
||||||
|
recent_activity: Vec<ActivityItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct ActivityItem {
|
||||||
|
action: String,
|
||||||
|
mime: String,
|
||||||
|
share_duration: u32,
|
||||||
|
timestamp: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/api/stats")]
|
||||||
|
async fn api_stats(assets: web::Data<AssetTracker>) -> Result<HttpResponse, actix_web::Error> {
|
||||||
|
use crate::LOG_DIR;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
let (active_assets, storage_bytes, image_count, text_count) = assets.stats_summary().await;
|
||||||
|
|
||||||
|
let mut total_uploads = 0;
|
||||||
|
let mut total_deleted = 0;
|
||||||
|
let mut recent_activity: Vec<ActivityItem> = Vec::new();
|
||||||
|
let mut request_count: usize = 0;
|
||||||
|
|
||||||
|
let log_path = format!("{}{}", LOG_DIR, LOG_FILE_NAME);
|
||||||
|
if let Ok(content) = fs::read_to_string(&log_path) {
|
||||||
|
for line in content.lines() {
|
||||||
|
if let Ok(entry) = serde_json::from_str::<LogEvent>(line) {
|
||||||
|
match entry.event {
|
||||||
|
LogEventType::HttpRequest(_req) => {
|
||||||
|
request_count += 1;
|
||||||
|
}
|
||||||
|
LogEventType::AssetUploaded(asset) => {
|
||||||
|
let asset = serde_json::from_value::<Asset>(asset).unwrap_or_default();
|
||||||
|
total_uploads += 1;
|
||||||
|
recent_activity.push(ActivityItem {
|
||||||
|
action: "upload".to_string(),
|
||||||
|
mime: asset.mime(),
|
||||||
|
share_duration: asset.share_duration(),
|
||||||
|
timestamp: entry.time,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
LogEventType::AssetDeleted(asset) => {
|
||||||
|
let asset = serde_json::from_value::<Asset>(asset).unwrap_or_default();
|
||||||
|
total_deleted += 1;
|
||||||
|
recent_activity.push(ActivityItem {
|
||||||
|
action: "delete".to_string(),
|
||||||
|
mime: asset.mime(),
|
||||||
|
share_duration: asset.share_duration(),
|
||||||
|
timestamp: entry.time,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log_to_file(&req, now);
|
// Keep only last 20, most recent first
|
||||||
Ok(HttpResponse::Ok().content_type(asset.mime()).body(asset.content()))
|
recent_activity.reverse();
|
||||||
|
recent_activity.truncate(20);
|
||||||
|
|
||||||
|
let response = StatsResponse {
|
||||||
|
active_assets,
|
||||||
|
total_uploads,
|
||||||
|
total_deleted,
|
||||||
|
storage_bytes,
|
||||||
|
image_count,
|
||||||
|
text_count,
|
||||||
|
total_requests: request_count,
|
||||||
|
recent_activity,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(response))
|
||||||
}
|
}
|
||||||
|
|||||||
157
src/data_mgt.rs
157
src/data_mgt.rs
@@ -1,21 +1,29 @@
|
|||||||
|
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 serde_json::Value;
|
||||||
|
|
||||||
use crate::DATA_STORAGE;
|
use crate::logs::{LogEventType, log_event};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
|
||||||
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>,
|
||||||
|
uploader_ip: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
impl Asset {
|
impl Asset {
|
||||||
pub fn new(share_duration: u32, mime: String, content: Vec<u8>) -> 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();
|
||||||
let created_at = Utc::now().timestamp_millis();
|
let created_at = Utc::now().timestamp_millis();
|
||||||
let expires_at = created_at + Duration::minutes(share_duration as i64).num_milliseconds();
|
let expires_at = created_at + Duration::minutes(share_duration as i64).num_milliseconds();
|
||||||
@@ -26,51 +34,146 @@ impl Asset {
|
|||||||
expires_at,
|
expires_at,
|
||||||
mime,
|
mime,
|
||||||
content,
|
content,
|
||||||
|
uploader_ip,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn is_expired(&self) -> bool {
|
pub fn is_expired(&self) -> bool {
|
||||||
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) -> String {
|
||||||
&self.mime
|
self.mime.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn content(&self) -> Vec<u8> {
|
pub fn content(&self) -> Vec<u8> {
|
||||||
self.content.clone()
|
self.content.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn share_duration(&self) -> u32 {
|
||||||
|
self.share_duration
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn created_at(&self) -> i64 {
|
||||||
|
self.created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn expires_at(&self) -> i64 {
|
||||||
|
self.expires_at
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mime_type(&self) -> &str {
|
||||||
|
&self.mime
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size_bytes(&self) -> usize {
|
||||||
|
self.content.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uploader_ip(&self) -> Option<&str> {
|
||||||
|
self.uploader_ip.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn to_bytes(&self) -> Result<Vec<u8>> {
|
pub fn to_bytes(&self) -> Result<Vec<u8>> {
|
||||||
let bytes = serde_json::to_vec(self)?;
|
let bytes = serde_json::to_vec(self)?;
|
||||||
Ok(bytes)
|
Ok(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save(&self) -> Result<String> {
|
pub fn to_value(&self) -> Value {
|
||||||
let id = self.id.clone();
|
serde_json::to_value(self).unwrap_or(Value::Null)
|
||||||
let path = format!("{}{}", DATA_STORAGE, self.id);
|
}
|
||||||
std::fs::create_dir_all(DATA_STORAGE)?;
|
|
||||||
std::fs::write(&path, self.to_bytes()?)?;
|
// pub fn save(&self) -> Result<String> {
|
||||||
Ok(id)
|
// let id = self.id.clone();
|
||||||
|
// let path = format!("{}{}", DATA_STORAGE, self.id);
|
||||||
|
// std::fs::create_dir_all(DATA_STORAGE)?;
|
||||||
|
// std::fs::write(&path, self.to_bytes()?)?;
|
||||||
|
// Ok(id)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AssetTracker {
|
||||||
|
assets: Arc<Mutex<Vec<Asset>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl AssetTracker {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
AssetTracker {
|
||||||
|
assets: Arc::new(Mutex::new(Vec::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
println!("[{}] Removing asset: {}", chrono::Local::now().to_rfc3339(), asset.id());
|
||||||
|
log_event(LogEventType::AssetDeleted(asset.to_value()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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() -> Result<()> {
|
pub async fn clear_assets(assets: AssetTracker) -> Result<()> {
|
||||||
let entries = std::fs::read_dir(DATA_STORAGE)?;
|
assets.remove_expired().await;
|
||||||
for entry in entries {
|
|
||||||
let entry = entry?;
|
|
||||||
let path = entry.path();
|
|
||||||
if path.is_file() {
|
|
||||||
let data = std::fs::read(&path)?;
|
|
||||||
let asset = serde_json::from_slice::<Asset>(&data)?;
|
|
||||||
if asset.is_expired() {
|
|
||||||
println!("Removing expired asset: {}", asset.id());
|
|
||||||
std::fs::remove_file(&path)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
103
src/logs.rs
103
src/logs.rs
@@ -1,47 +1,82 @@
|
|||||||
use std::{
|
use std::{fs::OpenOptions, io::Write};
|
||||||
fs::{self, OpenOptions},
|
|
||||||
io::Write,
|
|
||||||
time::Instant,
|
|
||||||
};
|
|
||||||
|
|
||||||
use actix_web::HttpRequest;
|
use actix_web::HttpRequest;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::LOG_DIR;
|
use crate::{LOG_DIR, LOG_FILE_NAME};
|
||||||
|
|
||||||
pub fn log_to_file(req: &HttpRequest, start: Instant) {
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
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,
|
||||||
let _ = fs::create_dir_all(LOG_DIR);
|
pub query_string: String,
|
||||||
|
pub scheme: String,
|
||||||
let log_path = LOG_DIR.to_string() + "access.log";
|
pub ip: String,
|
||||||
|
pub real_ip: String,
|
||||||
let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else {
|
pub user_agent: String,
|
||||||
eprintln!("failed to open log file");
|
}
|
||||||
return;
|
impl From<HttpRequest> for LogHttpRequest {
|
||||||
};
|
fn from(req: HttpRequest) -> Self {
|
||||||
|
let method = req.method().as_str().to_string();
|
||||||
let ts = chrono::Local::now().to_rfc3339();
|
|
||||||
|
|
||||||
let method = req.method();
|
|
||||||
let uri = req.uri();
|
let uri = req.uri();
|
||||||
let path = uri.path();
|
let path = uri.path().to_string();
|
||||||
let query = uri.query().unwrap_or("-");
|
let query_string = uri.query().unwrap_or("-").to_string();
|
||||||
|
|
||||||
let connection_info = req.connection_info();
|
let connection_info = req.connection_info();
|
||||||
let scheme = connection_info.scheme();
|
let scheme = connection_info.scheme().to_string();
|
||||||
let ip = connection_info.peer_addr().unwrap_or("-");
|
let ip = connection_info.peer_addr().unwrap_or("-").to_string();
|
||||||
let real_ip = connection_info.realip_remote_addr().unwrap_or("-");
|
let real_ip = connection_info.realip_remote_addr().unwrap_or("-").to_string();
|
||||||
|
|
||||||
let ua = req
|
let user_agent = req
|
||||||
.headers()
|
.headers()
|
||||||
.get("user-agent")
|
.get("user-agent")
|
||||||
.and_then(|v| v.to_str().ok())
|
.and_then(|v| v.to_str().ok())
|
||||||
.unwrap_or("-");
|
.unwrap_or("-")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
let line = format!(
|
LogHttpRequest {
|
||||||
"{ts} scheme={scheme} ip={ip} real_ip={real_ip} method={method} path={path} qs={query} dur_ms={duration_ms} ua=\"{ua}\"\n"
|
method,
|
||||||
);
|
path,
|
||||||
|
query_string,
|
||||||
let _ = file.write_all(line.as_bytes());
|
scheme,
|
||||||
|
ip,
|
||||||
|
real_ip,
|
||||||
|
user_agent,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub enum LogEventType {
|
||||||
|
AssetUploaded(Value),
|
||||||
|
AssetDeleted(Value),
|
||||||
|
HttpRequest(LogHttpRequest),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct LogEvent {
|
||||||
|
pub time: String,
|
||||||
|
pub event: LogEventType,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<LogEventType> for LogEvent {
|
||||||
|
fn from(event: LogEventType) -> Self {
|
||||||
|
let time = chrono::Utc::now().to_rfc3339();
|
||||||
|
LogEvent { time, event }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_event(event: LogEventType) {
|
||||||
|
let log_path = LOG_DIR.to_string() + LOG_FILE_NAME;
|
||||||
|
|
||||||
|
let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else {
|
||||||
|
eprintln!("failed to open log file for asset event");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let log_event: LogEvent = event.into();
|
||||||
|
let line = serde_json::to_string(&log_event).unwrap_or_else(|e| e.to_string());
|
||||||
|
|
||||||
|
let _ = writeln!(file, "{}", line);
|
||||||
}
|
}
|
||||||
|
|||||||
117
src/main.rs
117
src/main.rs
@@ -4,78 +4,137 @@ 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 std::path::PathBuf;
|
|
||||||
|
|
||||||
pub static BIND_ADDR: &str = "0.0.0.0";
|
use serde_json::Value;
|
||||||
pub static BIND_PORT: u16 = 80;
|
use std::{env, fs, path::PathBuf, sync::LazyLock};
|
||||||
pub static STATIC_PAGES: &[&str] = &["index.html", "style.css", "view.html", "logo.png"];
|
|
||||||
pub static HTML_DIR: &str = "html/";
|
pub static HTML_DIR: &str = "data/html/";
|
||||||
pub static LOG_DIR: &str = "logs/";
|
pub static LOG_DIR: &str = "data/logs/";
|
||||||
pub static DATA_STORAGE: &str = "storage/";
|
pub static LOG_FILE_NAME: &str = "log.txt";
|
||||||
|
|
||||||
|
pub static BIND_ADDR: LazyLock<String> = LazyLock::new(|| match env::var("BIND_ADDR") {
|
||||||
|
Ok(addr) => {
|
||||||
|
println!("Binding to address: {}", addr);
|
||||||
|
addr.parse().unwrap_or("127.0.0.1".to_string())
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
println!("Binding to default address: 0.0.0.0");
|
||||||
|
"0.0.0.0".to_string()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
pub static BIND_PORT: LazyLock<u16> = LazyLock::new(|| match env::var("BIND_PORT") {
|
||||||
|
Ok(port_str) => {
|
||||||
|
println!("Binding to port: {}", port_str);
|
||||||
|
port_str.parse().unwrap_or(8080)
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
println!("Binding to default port: 8080");
|
||||||
|
8080
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
pub static STATIC_PAGES: LazyLock<Vec<String>> = LazyLock::new(|| {
|
||||||
|
fs::read_dir(HTML_DIR)
|
||||||
|
.unwrap()
|
||||||
|
.filter_map(|entry| entry.ok().and_then(|e| e.file_name().to_str().map(|s| s.to_string())))
|
||||||
|
.collect()
|
||||||
|
});
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
api::{api_get_asset, 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(®, 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..]) => {
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
println!("Starting server at http://{}:{}/", BIND_ADDR, BIND_PORT);
|
let _ = fs::create_dir_all(LOG_DIR);
|
||||||
tokio::spawn(async {
|
let log_filename = format!("{}{}", LOG_DIR, LOG_FILE_NAME);
|
||||||
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(60));
|
let log_filename_path = std::path::Path::new(&log_filename);
|
||||||
|
|
||||||
|
let time_tag = chrono::Local::now().format("%Y_%m_%d_%H_%M_%S");
|
||||||
|
if log_filename_path.exists() {
|
||||||
|
println!("File: {}, exists, rotating.", &log_filename_path.display());
|
||||||
|
fs::rename(
|
||||||
|
&log_filename_path,
|
||||||
|
format!("{}{}_{}", LOG_DIR, time_tag, &LOG_FILE_NAME),
|
||||||
|
)
|
||||||
|
.unwrap_or_else(|e| {
|
||||||
|
println!(
|
||||||
|
"No existing log file {} to rotate. Error: {}",
|
||||||
|
log_filename_path.to_string_lossy(),
|
||||||
|
e
|
||||||
|
)
|
||||||
|
});
|
||||||
|
println!("Rotated log file to: {}_{}", time_tag, &LOG_FILE_NAME);
|
||||||
|
}
|
||||||
|
let assets = data_mgt::AssetTracker::new();
|
||||||
|
|
||||||
|
println!("Starting server at http://{}:{}/", *BIND_ADDR, *BIND_PORT);
|
||||||
|
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)
|
||||||
|
.service(api_stats)
|
||||||
.service(catch_all)
|
.service(catch_all)
|
||||||
})
|
})
|
||||||
.bind((BIND_ADDR, BIND_PORT))?
|
.bind((BIND_ADDR.clone(), *BIND_PORT))?
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user