2 Commits
Author SHA1 Message Date
hulthe b874f0c577 Replace rocket with axum 2026-08-20 23:59:51 +02:00
Ida Dahl 5adfcc1ceb Merge pull request #3 from hulthe/automatic-buttons
Automatic buttons
2026-08-19 23:51:58 +02:00
5 changed files with 238 additions and 779 deletions
Generated
+184 -719
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -63,8 +63,7 @@ RUN wasm-pack build --release --target web
FROM scratch
ENV RUST_LOG="info"
ENV ROCKET_ADDRESS="0.0.0.0"
ENV ROCKET_PORT="8000"
ENV BIND="0.0.0.0:8000"
VOLUME ["/data"]
ENV DB_PATH="/data/db.sqlite"
+1 -1
View File
@@ -71,7 +71,7 @@ async fn put_category(
) -> Result<(), anyhow::Error> {
let client = reqwest::Client::new();
let url: Url = format!(
"{address}/api/favourites/{itemname}/category",
"{address}/api/favorites/{itemname}/category",
address = conf.lock().unwrap().address
)
.parse()?;
+3 -1
View File
@@ -4,9 +4,11 @@ version = "0.1.0"
edition = "2024"
[dependencies]
rocket = { version = "0.5.1", features = ["json"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
inkopslista-lib = { path = "../lib" }
sqlite = "0.37.0"
clap = { version = "4.6.6", features = ["derive", "env"] }
axum = { version = "0.8.9", features = ["http1"] }
tower-http = { version = "0.7.0", features = ["fs", "trace", "compression-gzip"] }
tokio = { version = "1.53.1", features = ["full"] }
+49 -56
View File
@@ -1,32 +1,25 @@
#[macro_use]
extern crate rocket;
use axum::extract::{Path, State};
use axum::response::Html;
use axum::routing::method_routing::{get, put};
use axum::{Json, Router};
use clap::Parser;
use inkopslista_lib::{ButtonItem, Item, ItemData};
use rocket::{
State,
fs::{FileServer, NamedFile},
serde::json::Json,
shield::Shield,
};
use sqlite::ConnectionThreadSafe;
use std::path::{Path, PathBuf};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tower_http::services::ServeDir;
/// The directory where the web files for the gui is stored.
fn www_path() -> &'static Path {
Path::new("./www")
fn www_path() -> &'static std::path::Path {
std::path::Path::new("./www")
}
/// Serve `index.html` from [`www_path`].
#[get("/")]
async fn index() -> NamedFile {
NamedFile::open(www_path().join("index.html"))
.await
.expect("index.html")
async fn index() -> Html<&'static str> {
Html(include_str!("../../gui/index.html"))
}
#[get("/api/list")]
fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
async fn get_list(State(db): State<Arc<ConnectionThreadSafe>>) -> Json<Vec<Item>> {
// TODO errorhandling
let query = "SELECT * FROM list;";
let list = db
@@ -47,8 +40,7 @@ fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
Json(list)
}
#[get("/api/favorites")]
fn get_favorites(db: &State<ConnectionThreadSafe>) -> Json<Vec<ButtonItem>> {
async fn get_favorites(State(db): State<Arc<ConnectionThreadSafe>>) -> Json<Vec<ButtonItem>> {
let opt = Opt::parse();
let query = format!("WITH favorites as (SELECT itemname, COUNT(date_added) day_count
@@ -75,24 +67,30 @@ fn get_favorites(db: &State<ConnectionThreadSafe>) -> Json<Vec<ButtonItem>> {
Json(list)
}
#[put("/api/favourites/<itemname>/category", data = "<category>")]
fn put_category(db: &State<ConnectionThreadSafe>, itemname: &str, category: &str) {
async fn put_category(
State(db): State<Arc<ConnectionThreadSafe>>,
Path(item): Path<String>,
category: String,
) {
let query = "INSERT INTO categories VALUES (?, ?) ON CONFLICT DO UPDATE SET category = ?";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, itemname)).unwrap();
statement.bind((2, category)).unwrap();
statement.bind((3, category)).unwrap();
statement.bind((1, item.as_str())).unwrap();
statement.bind((2, category.as_str())).unwrap();
statement.bind((3, category.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[put("/api/list/<item>", data = "<data>")]
fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>) {
async fn put_list(
State(db): State<Arc<ConnectionThreadSafe>>,
Path(item): Path<String>,
Json(data): Json<ItemData>,
) {
// TODO: errorhandling
// TODO: transaction
let query =
"INSERT INTO list VALUES(?, ?, ?) ON CONFLICT DO UPDATE SET checked = ?, amount = ?;";
let mut statement = db.prepare(query).unwrap();
let data = data.into_inner();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
statement.bind((2, data.checked as i64)).unwrap();
statement.bind((3, data.amount)).unwrap();
statement.bind((4, data.checked as i64)).unwrap();
@@ -100,50 +98,45 @@ fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>)
while let Ok(sqlite::State::Row) = statement.next() {}
let query = "INSERT INTO adds VALUES(?, strftime('%s','now')) ON CONFLICT DO NOTHING";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[delete("/api/list/<item>")]
fn delete_item(item: &str, db: &State<ConnectionThreadSafe>) {
async fn delete_item(State(db): State<Arc<ConnectionThreadSafe>>, Path(item): Path<String>) {
// TODO: Eror handling
let query = "DELETE FROM list WHERE itemname = ?";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[derive(Parser)]
struct Opt {
#[clap(long, env = "BIND", default_value = "127.0.0.1:8000")]
bind: SocketAddr,
#[clap(long, env = "DB_PATH")]
db_path: PathBuf,
#[clap(long, env = "NUM_DAYS", default_value = "5")]
num_days: u32,
}
#[launch]
fn rocket() -> _ {
#[tokio::main]
async fn main() {
let opt = Opt::parse();
let db = sqlite::Connection::open_thread_safe(opt.db_path).unwrap();
db.execute(include_str!("db/init.sql"))
.expect("unable to initialize database");
rocket::build()
.attach(
Shield::default()
// Allow content to be served through iframes
.disable::<rocket::shield::Frame>(),
)
.manage(db)
.mount(
"/",
routes![
index,
get_list,
put_list,
delete_item,
get_favorites,
put_category
],
)
.mount("/", FileServer::from(www_path()))
let db = Arc::new(db);
let app = Router::new()
.route("/", get(index))
.route("/api/list", get(get_list))
.route("/api/list/{item}", put(put_list).delete(delete_item))
.route("/api/favorites", get(get_favorites))
.route("/api/favorites/{item}/category", put(put_category))
.fallback_service(ServeDir::new(www_path()))
.with_state(db);
let listener = tokio::net::TcpListener::bind(opt.bind).await.unwrap();
axum::serve(listener, app).await.unwrap();
}