This commit is contained in:
zastian@mrthoddata.com
2025-05-08 18:18:39 +01:00
commit 7ba4004c22
24 changed files with 5042 additions and 0 deletions

19
.direnv/bin/nix-direnv-reload Executable file
View File

@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -e
if [[ ! -d "/home/work/Documents/rust/bitBeam" ]]; then
echo "Cannot find source directory; Did you move it?"
echo "(Looking for "/home/work/Documents/rust/bitBeam")"
echo 'Cannot force reload with this script - use "direnv reload" manually and then try again'
exit 1
fi
# rebuild the cache forcefully
_nix_direnv_force_reload=1 direnv exec "/home/work/Documents/rust/bitBeam" true
# Update the mtime for .envrc.
# This will cause direnv to reload again - but without re-building.
touch "/home/work/Documents/rust/bitBeam/.envrc"
# Also update the timestamp of whatever profile_rc we have.
# This makes sure that we know we are up to date.
touch -r "/home/work/Documents/rust/bitBeam/.envrc" "/home/work/Documents/rust/bitBeam/.direnv"/*.rc

View File

@@ -0,0 +1 @@
/nix/store/52hxk3ygip5xv1jrjymnn4yh9rqikj91-source

View File

@@ -0,0 +1 @@
/nix/store/yhc8a0a2mvbp8fp53l57i3d5cnz735fc-source

View File

@@ -0,0 +1 @@
/nix/store/z8zpl9cslb32bn0fcc2r8hlssxqlrdpq-source

1
.direnv/flake-profile Symbolic link
View File

@@ -0,0 +1 @@
flake-profile-1-link

View File

@@ -0,0 +1 @@
/nix/store/vdijc3indsq6j6xbridfqjib4pkg6vhs-nix-shell-env

View File

@@ -0,0 +1 @@
/nix/store/vdijc3indsq6j6xbridfqjib4pkg6vhs-nix-shell-env

File diff suppressed because it is too large Load Diff

1
.envrc Normal file
View File

@@ -0,0 +1 @@
use flake

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

2541
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

23
Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[package]
name = "bitBeam"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
bytes = "1.10"
chrono = {version = "0.4", features = ["serde"]}
extract = "0.1"
rand = "0.9"
serde = {version = "1.0", features = ["derive"]}
sqlx = { version = "0.8", features = [
"runtime-tokio", # pick exactly one runtime
"tls-rustls", # pick exactly one TLS backend
"any", # for sqlx::any abstraction
"postgres", # Postgres driver
"sqlite", # SQLite driver
"chrono", # (optional) chrono date/time support
"migrate" # for embed migrations
] }
tokio = {version = "1.45", features = ["full"]}
uuid = "1.16"

BIN
bitbeem.sqlite Normal file

Binary file not shown.

BIN
bitbeem.sqlite-shm Normal file

Binary file not shown.

0
bitbeem.sqlite-wal Normal file
View File

48
flake.lock generated Normal file
View File

@@ -0,0 +1,48 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1746576598,
"narHash": "sha256-FshoQvr6Aor5SnORVvh/ZdJ1Sa2U4ZrIMwKBX5k2wu0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b3582c75c7f21ce0b429898980eddbbf05c68e55",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1746239644,
"narHash": "sha256-wMvMBMlpS1H8CQdSSgpLeoCWS67ciEkN/GVCcwk7Apc=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "bd32e88bef6da0e021a42fb4120a8df2150e9b8c",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

59
flake.nix Normal file
View File

@@ -0,0 +1,59 @@
{
description = "A Rust project with development environment and build support";
inputs = {
#nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1";
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = inputs @ { self, nixpkgs, rust-overlay, ... }:
let
supportedSystems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
forEachSupportedSystem = f: nixpkgs.lib.genAttrs supportedSystems (system: f {
pkgs = import nixpkgs {
inherit system;
overlays = [ rust-overlay.overlays.default ];
};
});
in
{
# Define the package (your Rust binary)
packages = forEachSupportedSystem ({ pkgs }: {
default = pkgs.rustPlatform.buildRustPackage {
name = "bitBeam";
src = ./.;
# Specify dependencies (replace with your project's actual dependencies)
buildInputs = [ pkgs.openssl pkgs.pkg-config ];
# Generate this with `cargo generate-lockfile` if you don't have it
cargoLock = {
lockFile = ./Cargo.lock;
};
# Optional: Override the Rust version if needed
nativeBuildInputs = [ pkgs.rust-bin.stable.latest.default ];
};
});
# Development environment (existing setup)
devShells = forEachSupportedSystem ({ pkgs }: {
default = pkgs.mkShell {
packages = with pkgs; [
rust-bin.stable.latest.default
openssl
pkg-config
cargo-deny
cargo-edit
cargo-watch
rust-analyzer
];
RUST_SRC_PATH = "${pkgs.rust-bin.stable.latest.default}/lib/rustlib/src/rust/library";
};
});
};
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

201
src/main.rs Normal file
View File

@@ -0,0 +1,201 @@
use axum::{
body::Bytes,
extract::DefaultBodyLimit,
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Extension, Json, Router,
};
use chrono::{DateTime, Utc};
use rand::Rng;
use serde::Serialize;
use sqlx::{any::AnyPoolOptions, migrate::MigrateDatabase, AnyPool, Encode, FromRow, Sqlite};
use std::path::Path;
use tokio::fs;
use uuid::Uuid;
#[derive(FromRow, Serialize)]
struct File {
id: String,
content_type: String,
upload_time: i64,
download_limit: i32,
download_count: i32,
file_size: i64,
}
struct Config {
db_type: String,
database_url: String,
}
#[tokio::main]
async fn main() {
sqlx::any::install_default_drivers();
// Read and normalize DB type and connection URL
let config = Config {
db_type: std::env::var("BITBEEM_DB_TYPE").unwrap_or_else(|_| "postgres".to_string()),
database_url: match std::env::var("BITBEEM_DB_TYPE").unwrap().as_str() {
"postgres" => std::env::var("BITBEEM_DATABASE_URL")
.expect("BITBEEM_DATABASE_URL must be set for Postgres"),
"sqlite" => std::env::var("BITBEEM_DATABASE_URL")
.expect("BITBEEM_DATABASE_URL must be set for SQLite"),
other => panic!("Unsupported BITBEEM_DB_TYPE: {}", other),
},
};
if config.db_type == "sqlite" {
if !Sqlite::database_exists(&config.database_url)
.await
.unwrap_or(false)
{
println!("Creating database {}", config.database_url);
match Sqlite::create_database(&config.database_url).await {
Ok(_) => println!("Create db success"),
Err(error) => panic!("error: {}", error),
}
} else {
println!("Database already exists");
}
}
// Create a generic AnyPool
let pool: AnyPool = AnyPoolOptions::new()
.max_connections(5)
.connect(&config.database_url)
.await
.expect("could not connect to database");
// Migration SQL
if let Err(_e) = sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
content_type TEXT NOT NULL,
upload_time BIGINT NOT NULL,
download_limit INTEGER NOT NULL,
download_count INTEGER NOT NULL,
file_size BIGINT NOT NULL
);
"#,
)
.execute(&pool)
.await
{
eprintln!("DB created");
};
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.route("/upload", post(upload))
.route("/all_files", get(all_files))
.layer(DefaultBodyLimit::max(100 * 1024 * 1024))
.layer(Extension(pool));
axum::serve(
tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(),
app,
)
.await
.unwrap();
}
/// Handler to return all files as JSON
async fn all_files(Extension(pool): Extension<AnyPool>) -> impl IntoResponse {
// Run the query and map each row into a File
match sqlx::query_as::<_, File>(
r#"
SELECT *
FROM files
"#,
)
.fetch_all(&pool)
.await
{
Ok(files) => (StatusCode::OK, Json(files)).into_response(),
Err(e) => {
eprintln!("DB select all error: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Database select all error",
)
.into_response()
}
}
}
async fn upload(Extension(pool): Extension<AnyPool>, headers: HeaderMap, body: Bytes) -> Response {
let content_type = headers
.get("content-type")
.and_then(|hv| hv.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
let id = {
// Fallback to random UUID if body is too small
let mut rng = rand::rng();
Uuid::from_u128(rng.random::<u128>()).to_string()
};
let dir = Path::new("./media_store");
if let Err(e) = fs::create_dir_all(dir).await {
eprintln!("mkdir error: {}", e);
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Directory creation error",
)
.into_response();
}
let file_path = dir.join(&id);
if let Err(e) = fs::write(&file_path, &body).await {
eprintln!("write error {}: {}", id, e);
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"File write error",
)
.into_response();
}
let file_size = body.len() as i64;
let upload_time = Utc::now().timestamp(); // i64
let download_limit = headers
.get("download_limit") // Option<&HeaderValue>
.and_then(|hv| hv.to_str().ok()) // Option<&str>
.and_then(|s| s.parse::<i32>().ok()) // Option<u32>
.unwrap_or(2); // u32 let download_count = 0;
let download_count = 0;
if let Err(e) = sqlx::query(
r#"
INSERT INTO files
(id, content_type, upload_time, download_limit, download_count, file_size)
VALUES (?, ?, ?, ?, ?, ?)
"#,
)
.bind(&id)
.bind(&content_type)
.bind(&upload_time)
.bind(download_limit)
.bind(download_count)
.bind(file_size as i64)
.execute(&pool)
.await
{
eprintln!("DB insert error {}: {}", id, e);
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Database insert error",
)
.into_response();
}
let uploaded_file = File {
id,
content_type,
upload_time,
download_limit,
download_count,
file_size,
};
Json(uploaded_file).into_response()
}