mirror of
https://github.com/hulthe/inkopslista.git
synced 2026-08-03 23:11:28 +02:00
Rename crate folders
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
use anyhow::{Context, Ok};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
|
||||
pub struct Config {
|
||||
pub address: String,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address: "http://localhost:8000".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
const CONFIG_FILE_NAME: &'static str = "config.json";
|
||||
const XDG_PREFIX: &'static str = "inköpslista";
|
||||
|
||||
pub fn save_config(address: String) -> Result<(), anyhow::Error> {
|
||||
let xdg_dirs = xdg::BaseDirectories::with_prefix(XDG_PREFIX);
|
||||
let conf = Config { address: address };
|
||||
let conf = serde_json::to_string(&conf).context("unable to serialize config")?;
|
||||
|
||||
let path = xdg_dirs
|
||||
.place_config_file(CONFIG_FILE_NAME)
|
||||
.context("unable to create config directory")?;
|
||||
|
||||
tokio::spawn(async {
|
||||
let res = tokio::fs::write(path, conf)
|
||||
.await
|
||||
.context("unable to write config file");
|
||||
if let Err(err) = res {
|
||||
eprintln!("{err:?}");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_config() -> Result<Config, anyhow::Error> {
|
||||
let xdg_dirs = xdg::BaseDirectories::with_prefix(XDG_PREFIX);
|
||||
let file = xdg_dirs
|
||||
.get_config_file(CONFIG_FILE_NAME)
|
||||
.context("no config file")?;
|
||||
let content = tokio::fs::read_to_string(file)
|
||||
.await
|
||||
.context("failed to read config file")?;
|
||||
|
||||
let conf: Config = serde_json::from_str(&content).context("Unable to deserealize contect")?;
|
||||
Ok(conf)
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
// Prevent console window in addition to Slint window in Windows release builds when, e.g., starting the app via file manager. Ignored on other platforms.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
mod config;
|
||||
use std::{
|
||||
rc::Rc,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use inkopslista_lib::{Item, ItemData};
|
||||
use reqwest::Url;
|
||||
use slint::{Model, ModelRc, ToSharedString, VecModel};
|
||||
|
||||
use crate::config::{Config, get_config, save_config};
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
// TODO: use anyhow
|
||||
type MagicAnyError = anyhow::Error;
|
||||
|
||||
/// GET "/api/list" from the server
|
||||
async fn get_list(conf: &Mutex<Config>) -> Result<Vec<Item>, MagicAnyError> {
|
||||
// TODO: don't hardcode url
|
||||
let base = Url::parse(&conf.lock().unwrap().address)?;
|
||||
let url = base.join("/api/list")?;
|
||||
let list = reqwest::get(url).await?.json::<Vec<Item>>().await?;
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Add or update an item in the list
|
||||
async fn put_list(item: &str, data: &ItemData, conf: &Mutex<Config>) -> Result<(), MagicAnyError> {
|
||||
let client = reqwest::Client::new();
|
||||
let base = Url::parse(&conf.lock().unwrap().address)?.join("/api/list/")?;
|
||||
let url = base.join(item)?;
|
||||
let _response = client
|
||||
.put(url)
|
||||
.json(data)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_item(item: &str, conf: &Mutex<Config>) -> Result<(), MagicAnyError> {
|
||||
let client = reqwest::Client::new();
|
||||
let base = Url::parse(&conf.lock().unwrap().address)?.join("/api/list/")?;
|
||||
let url = base.join(item)?;
|
||||
let _response = client.delete(url).send().await?.error_for_status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert shopping list to slint types
|
||||
fn update_slint_list(new_list: Vec<Item>, list: &VecModel<SItem>) {
|
||||
list.clear();
|
||||
new_list
|
||||
.iter()
|
||||
.map(|item| SItem {
|
||||
name: item.name.to_shared_string(),
|
||||
checked: item.data.checked,
|
||||
})
|
||||
.for_each(|item| list.push(item));
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), MagicAnyError> {
|
||||
let ui = App::new()?;
|
||||
let state = ui.global::<State>();
|
||||
let list = Rc::new(VecModel::default());
|
||||
state.set_list(ModelRc::new(list.clone()));
|
||||
let conf = get_config()
|
||||
.await
|
||||
.inspect_err(|err| eprintln!("{err:?}"))
|
||||
.unwrap_or_default();
|
||||
state.set_server_address(conf.address.to_shared_string());
|
||||
let conf = Arc::new(Mutex::new(conf));
|
||||
// HACK: load shopping list from server on start
|
||||
|
||||
let conf2 = conf.clone();
|
||||
match get_list(&conf2).await {
|
||||
Ok(new_list) => update_slint_list(new_list, &list),
|
||||
Err(e) => {
|
||||
eprintln!("{e:?}");
|
||||
}
|
||||
}
|
||||
let list2 = list.clone();
|
||||
let conf2 = conf.clone();
|
||||
state.on_add_to_list(move |item| {
|
||||
if list2.iter().any(|item2| item2.name == item) {
|
||||
return;
|
||||
// TODO: implement increment when number is added
|
||||
}
|
||||
list2.push(SItem {
|
||||
checked: false,
|
||||
name: item.clone(),
|
||||
});
|
||||
let conf2 = conf2.clone();
|
||||
tokio::spawn(async move {
|
||||
// TODO: add number to increment
|
||||
let res = put_list(&item, &ItemData { checked: false }, &conf2).await;
|
||||
if let Err(err) = res {
|
||||
eprintln!("{err:?}");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let conf2 = conf.clone();
|
||||
let list2 = list.clone();
|
||||
state.on_check_item(move |item| {
|
||||
let positem = list2
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, item2)| item2.name == item);
|
||||
let (pos, mut item) = match positem {
|
||||
Some(positem) => positem,
|
||||
None => return,
|
||||
};
|
||||
item.checked = !item.checked;
|
||||
list2.set_row_data(pos, item.clone());
|
||||
let conf2 = conf2.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let res = put_list(
|
||||
&item.name,
|
||||
&ItemData {
|
||||
checked: item.checked,
|
||||
},
|
||||
&conf2,
|
||||
)
|
||||
.await;
|
||||
if let Err(err) = res {
|
||||
eprintln!("{err:?}");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let conf2 = conf.clone();
|
||||
let list2 = list.clone();
|
||||
state.on_delete_checked(move || {
|
||||
let poss: Vec<_> = list2
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, item)| item.checked)
|
||||
.map(|(pos, item)| (pos, item.name))
|
||||
.collect();
|
||||
for &(pos, _) in poss.iter().rev() {
|
||||
list2.remove(pos);
|
||||
}
|
||||
|
||||
let conf2 = conf2.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
for (_, name) in poss {
|
||||
let res = delete_item(&name, &conf2).await;
|
||||
if let Err(err) = res {
|
||||
eprintln!("{err:?}");
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
state.on_set_server_address(move |address| {
|
||||
let _ = save_config(address.to_string());
|
||||
conf.lock().unwrap().address = address.to_string();
|
||||
|
||||
// create type for config file ✅
|
||||
// derives serde ✅
|
||||
// add library that gives us folder to save file in xdg typ ✅
|
||||
// write funciton that uses library to save file to folder place_config_file() ✅
|
||||
// call function on callback through tokio
|
||||
// write function to load file get_config_file(path) finns i xdg ✅
|
||||
// call function on start ✅
|
||||
// use config on get put delete server stuffs. (instead of the static string) ✅
|
||||
});
|
||||
|
||||
ui.run()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user