mirror of
https://github.com/hulthe/inkopslista.git
synced 2026-09-18 18:03:39 +02:00
Compare commits
7
Commits
7501f1e824
...
axum
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b874f0c577 | ||
|
|
5adfcc1ceb | ||
|
|
22cf928852 | ||
|
|
c7782c82c4 | ||
|
|
5be85370fb | ||
|
|
5a1506feea | ||
|
|
932b5cd266 |
@@ -3,3 +3,5 @@ target/
|
||||
**/*.rs.bk
|
||||
|
||||
*.sqlite
|
||||
|
||||
dabase
|
||||
Generated
+1581
-1759
File diff suppressed because it is too large
Load Diff
+1
-2
@@ -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"
|
||||
|
||||
+2
-2
@@ -39,7 +39,7 @@ serde_json = "1.0.148"
|
||||
anyhow = "1.0.100"
|
||||
|
||||
[dependencies.slint]
|
||||
version = "1.15.1"
|
||||
version = "1.17.1"
|
||||
default-features = false
|
||||
features = [
|
||||
"live-preview",
|
||||
@@ -63,4 +63,4 @@ wasm-bindgen-futures = "0.4.56"
|
||||
web-sys = "0.3.83"
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "1.15.1"
|
||||
slint-build = "1.17.1"
|
||||
|
||||
+3
-1
@@ -18,6 +18,8 @@ pub use fs::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod fs {
|
||||
use crate::runtime::spawn;
|
||||
|
||||
use super::Config;
|
||||
use anyhow::{Context, Ok};
|
||||
|
||||
@@ -33,7 +35,7 @@ mod fs {
|
||||
.place_config_file(CONFIG_FILE_NAME)
|
||||
.context("unable to create config directory")?;
|
||||
|
||||
tokio::spawn(async {
|
||||
spawn(async {
|
||||
let res = tokio::fs::write(path, conf)
|
||||
.await
|
||||
.context("unable to write config file");
|
||||
|
||||
+58
-1
@@ -16,7 +16,7 @@ use std::{
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use inkopslista_lib::{Item, ItemData};
|
||||
use inkopslista_lib::{ButtonItem, Item, ItemData};
|
||||
use reqwest::Url;
|
||||
use slint::{ComponentHandle, Model, ModelRc, ToSharedString, VecModel};
|
||||
|
||||
@@ -35,6 +35,13 @@ async fn get_list(conf: &Mutex<Config>) -> Result<Vec<Item>, anyhow::Error> {
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
async fn get_favorites(conf: &Mutex<Config>) -> Result<Vec<ButtonItem>, anyhow::Error> {
|
||||
let base = Url::parse(&conf.lock().unwrap().address)?;
|
||||
let url = base.join("/api/favorites")?;
|
||||
let favs = reqwest::get(url).await?.json::<Vec<ButtonItem>>().await?;
|
||||
Ok(favs)
|
||||
}
|
||||
|
||||
/// Add or update an item in the list
|
||||
async fn put_list(item: &str, data: &ItemData, conf: &Mutex<Config>) -> Result<(), anyhow::Error> {
|
||||
let client = reqwest::Client::new();
|
||||
@@ -57,6 +64,26 @@ async fn delete_item(item: &str, conf: &Mutex<Config>) -> Result<(), anyhow::Err
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn put_category(
|
||||
itemname: &str,
|
||||
category: &str,
|
||||
conf: &Mutex<Config>,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let client = reqwest::Client::new();
|
||||
let url: Url = format!(
|
||||
"{address}/api/favorites/{itemname}/category",
|
||||
address = conf.lock().unwrap().address
|
||||
)
|
||||
.parse()?;
|
||||
let _response = client
|
||||
.put(url)
|
||||
.body(category.to_string())
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert shopping list to slint types
|
||||
fn update_slint_list(new_list: Vec<Item>, list: &VecModel<ui::SItem>) {
|
||||
list.clear();
|
||||
@@ -70,6 +97,17 @@ fn update_slint_list(new_list: Vec<Item>, list: &VecModel<ui::SItem>) {
|
||||
.for_each(|item| list.push(item));
|
||||
}
|
||||
|
||||
fn update_slint_favs(new_favs: Vec<ButtonItem>, favs: &VecModel<ui::SButtonItem>) {
|
||||
favs.clear();
|
||||
new_favs
|
||||
.into_iter()
|
||||
.map(|item| ui::SButtonItem {
|
||||
name: item.name.into(),
|
||||
category: item.category.unwrap_or_default().to_shared_string(),
|
||||
})
|
||||
.for_each(|item| favs.push(item));
|
||||
}
|
||||
|
||||
fn refresh_list(conf: &Arc<Mutex<Config>>, app_weak: &slint::Weak<ui::App>, io: &Io) {
|
||||
let conf = conf.clone();
|
||||
let app_weak = app_weak.clone();
|
||||
@@ -81,6 +119,13 @@ fn refresh_list(conf: &Arc<Mutex<Config>>, app_weak: &slint::Weak<ui::App>, io:
|
||||
list.as_any().downcast_ref().expect("list is a VecModel");
|
||||
update_slint_list(new_list, list);
|
||||
});
|
||||
let new_favs = get_favorites(&conf).await?;
|
||||
let _ = app_weak.upgrade_in_event_loop(|app| {
|
||||
let favs: ModelRc<ui::SButtonItem> = app.global::<ui::State>().get_favorites();
|
||||
let favs: &VecModel<ui::SButtonItem> =
|
||||
favs.as_any().downcast_ref().expect("favs is a vec model");
|
||||
update_slint_favs(new_favs, favs);
|
||||
});
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@@ -90,7 +135,9 @@ pub fn run() -> Result<(), anyhow::Error> {
|
||||
let io_ = Io::new(&app);
|
||||
let state = app.global::<ui::State>();
|
||||
let list_shared = Rc::new(VecModel::default());
|
||||
let fav_shared = Rc::new(VecModel::default());
|
||||
state.set_list(ModelRc::new(list_shared.clone()));
|
||||
state.set_favorites(ModelRc::new(fav_shared.clone()));
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let conf = runtime::RT
|
||||
@@ -275,6 +322,16 @@ pub fn run() -> Result<(), anyhow::Error> {
|
||||
}
|
||||
});
|
||||
|
||||
let conf = conf_shared.clone();
|
||||
let io = io_.clone();
|
||||
|
||||
state.on_set_cat(move |itemname, cat| {
|
||||
let conf = conf.clone();
|
||||
|
||||
io.spawn(async move || put_category(&itemname, &cat, &conf).await);
|
||||
return;
|
||||
});
|
||||
|
||||
state.on_set_server_address(move |address| {
|
||||
conf_shared.lock().unwrap().address = address.to_string();
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
+44
-24
@@ -7,13 +7,14 @@ import {
|
||||
CheckBox,
|
||||
ScrollView,
|
||||
GridBox,
|
||||
HorizontalBox,
|
||||
ComboBox,
|
||||
Palette, Spinner, SpinBox,
|
||||
} from "std-widgets.slint";
|
||||
import { SettingsView } from "settings.slint";
|
||||
import { ConnectionStatus, State, SItem } from "state.slint";
|
||||
import { ConnectionStatus, State, SItem, SButtonItem } from "state.slint";
|
||||
export { ConnectionStatus, State, SItem }
|
||||
|
||||
|
||||
component GoodListItem inherits Rectangle {
|
||||
in-out property <SItem> item;
|
||||
background: Palette.alternate-background;
|
||||
@@ -178,43 +179,25 @@ component GoodsListAdd {
|
||||
}
|
||||
|
||||
component GoodButtons inherits ScrollView {
|
||||
in property <[string]> favorites: [
|
||||
"Balsam",
|
||||
"Broccolli",
|
||||
"Bröd",
|
||||
"Bullens",
|
||||
"Krossade Tomater",
|
||||
"Kyckling",
|
||||
"Matgrädde",
|
||||
"Mjölk",
|
||||
"Nästejp",
|
||||
"Ost",
|
||||
"Schampo",
|
||||
"Smör",
|
||||
"Spenat",
|
||||
"Tandkräm",
|
||||
"Toalettpapper",
|
||||
"Ägg",
|
||||
];
|
||||
in property <length> button-min-width: 100pt;
|
||||
in property <length> button-height: 60pt;
|
||||
in property <length> button-spacing: 10pt;
|
||||
|
||||
property <int> count-x: floor(root.width / (button-min-width + button-spacing));
|
||||
property <int> count-y: ceil(favorites.length / count-x);
|
||||
property <int> count-y: ceil(State.favorites.length / count-x);
|
||||
property <length> button-width: ((self.width + button-spacing ) / count-x) - button-spacing;
|
||||
|
||||
viewport-height: (count-y * (button-height + button-spacing));
|
||||
mouse-drag-pan-enabled: true;
|
||||
|
||||
for item[idx] in favorites: Button {
|
||||
for item[idx] in State.favorites: Button {
|
||||
x: floor(mod(idx, count-x)) * (root.button-width + root.button-spacing);
|
||||
y: floor(idx / count-x) * (root.button-height + root.button-spacing);
|
||||
width: root.button-width;
|
||||
height: root.button-height;
|
||||
text: item;
|
||||
text: item.name;
|
||||
clicked => {
|
||||
State.add-to-list(item);
|
||||
State.add-to-list(item.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,10 +304,40 @@ component ShopView inherits VerticalLayout {
|
||||
}
|
||||
}
|
||||
|
||||
component CatItem inherits HorizontalBox {
|
||||
in-out property <SButtonItem> item;
|
||||
|
||||
Text {
|
||||
text: item.name;
|
||||
vertical-alignment: center;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
ComboBox {
|
||||
model: ["kyl", "skafferi", "frys", "övrigt"];
|
||||
current-value: item.category;
|
||||
width: 60%;
|
||||
selected(category) => { State.set-cat(item.name, category) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
component CatView inherits VerticalLayout {
|
||||
in-out property <[SButtonItem]> cats;
|
||||
|
||||
for item in cats: CatItem {
|
||||
item: item;
|
||||
}
|
||||
}
|
||||
|
||||
export component App inherits Window {
|
||||
|
||||
title: "Inköpslista";
|
||||
icon: @image-url("../images/icon.svg");
|
||||
|
||||
preferred-height: 700px;
|
||||
preferred-width: 480px;
|
||||
|
||||
TabWidget {
|
||||
Tab {
|
||||
title: "Add";
|
||||
@@ -340,6 +353,13 @@ export component App inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
Tab {
|
||||
title: "Categories";
|
||||
CatView {
|
||||
cats <=> State.favorites;
|
||||
}
|
||||
}
|
||||
|
||||
Tab {
|
||||
title: "Settings";
|
||||
SettingsView { }
|
||||
|
||||
@@ -4,6 +4,11 @@ export struct SItem {
|
||||
amount: int,
|
||||
}
|
||||
|
||||
export struct SButtonItem{
|
||||
name: string,
|
||||
category: string,
|
||||
}
|
||||
|
||||
export enum ConnectionStatus {
|
||||
Idle,
|
||||
Syncing,
|
||||
@@ -22,7 +27,13 @@ export global State {
|
||||
callback delete-checked();
|
||||
callback inc-amount(string);
|
||||
callback dec-amount(string);
|
||||
callback set-cat(string, string);
|
||||
in-out property <string> server-address;
|
||||
in property <[SButtonItem]> favorites: [
|
||||
{ name: "mjölk", category: "kyl" },
|
||||
{ name: "ost", category: "kyl" },
|
||||
];
|
||||
|
||||
callback set-server-address(string);
|
||||
set-server-address(address) => {
|
||||
server-address = address;
|
||||
|
||||
+6
-2
@@ -7,9 +7,13 @@ pub struct Item {
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
|
||||
|
||||
pub struct ItemData {
|
||||
pub checked: bool,
|
||||
pub amount: i64,
|
||||
// TODO: add number
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
|
||||
pub struct ButtonItem {
|
||||
pub name: String,
|
||||
pub category: Option<String>,
|
||||
}
|
||||
|
||||
+5
-2
@@ -1,11 +1,14 @@
|
||||
[package]
|
||||
name = "inkopslista-srv"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
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"] }
|
||||
|
||||
+11
-1
@@ -3,4 +3,14 @@ CREATE TABLE
|
||||
itemname TEXT NOT NULL PRIMARY KEY,
|
||||
checked INT NOT NULL, -- actually a boolean
|
||||
amount INT NOT NULL
|
||||
) STRICT;
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE
|
||||
IF NOT EXISTS adds (
|
||||
itemname TEXT NOT NULL,
|
||||
date_added INT NOT NULL,
|
||||
PRIMARY KEY (itemname, date_added)
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE
|
||||
IF NOT EXISTS categories (itemname TEXT NOT NULL PRIMARY KEY, category TEXT) STRICT;
|
||||
+99
-46
@@ -1,32 +1,25 @@
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
|
||||
use std::{env, path::Path};
|
||||
|
||||
use inkopslista_lib::{Item, ItemData};
|
||||
use rocket::{
|
||||
fs::{FileServer, NamedFile},
|
||||
serde::json::Json,
|
||||
shield::Shield,
|
||||
State,
|
||||
};
|
||||
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 sqlite::ConnectionThreadSafe;
|
||||
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,43 +40,103 @@ fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
|
||||
Json(list)
|
||||
}
|
||||
|
||||
#[put("/api/list/<item>", data = "<data>")]
|
||||
fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>) {
|
||||
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
|
||||
FROM adds
|
||||
WHERE (date(julianday('now')) - date(date_added, 'unixepoch')) < 184
|
||||
GROUP BY itemname
|
||||
HAVING day_count > {num_days})
|
||||
SELECT favorites.itemname, category FROM favorites LEFT OUTER JOIN categories ON favorites.itemname = categories.itemname", num_days = opt.num_days);
|
||||
let list: Vec<ButtonItem> = db
|
||||
.prepare(query)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let row = row.unwrap();
|
||||
ButtonItem {
|
||||
name: row.read::<&str, _>("itemname").to_string(),
|
||||
category: row
|
||||
.try_read::<&str, _>("category")
|
||||
.ok()
|
||||
.map(ToString::to_string),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Json(list)
|
||||
}
|
||||
|
||||
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, 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() {}
|
||||
}
|
||||
|
||||
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();
|
||||
statement.bind((5, data.amount)).unwrap();
|
||||
while let Ok(sqlite::State::Row) = statement.next() {}
|
||||
}
|
||||
|
||||
#[delete("/api/list/<item>")]
|
||||
fn delete_item(item: &str, db: &State<ConnectionThreadSafe>) {
|
||||
// TODO: Eror handling
|
||||
let query = "DELETE FROM list WHERE itemname = ?";
|
||||
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() {}
|
||||
}
|
||||
|
||||
#[launch]
|
||||
fn rocket() -> _ {
|
||||
let db_path = env::var("DB_PATH").unwrap();
|
||||
let db = sqlite::Connection::open_thread_safe(db_path).unwrap();
|
||||
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.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,
|
||||
}
|
||||
|
||||
#[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])
|
||||
.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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user