Skip to content

Commit

Permalink
Add food tracking widget
Browse files Browse the repository at this point in the history
  • Loading branch information
sverrejb committed Feb 14, 2024
1 parent 24d464f commit 1704fe9
Show file tree
Hide file tree
Showing 10 changed files with 534 additions and 132 deletions.
35 changes: 0 additions & 35 deletions src/food/ADCimwTiJkUkM3TOKT7w9g.json

This file was deleted.

24 changes: 0 additions & 24 deletions src/food/ADCimwTiJkUkM3TOKT7w9g_done.json

This file was deleted.

12 changes: 8 additions & 4 deletions src/food/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html>

<head>
<title>Tracking Form</title>
<style>
Expand Down Expand Up @@ -33,7 +34,7 @@
}

input[type="text"] {
width: 100%;
width: 95%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
Expand All @@ -47,21 +48,24 @@
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 1rem;
}

input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>

<body>
<div class="container">
<h1>Tantalizing Thursday treat tracker</h1>
<form action="/id" method="post">
<form action="/tracking" method="post">
<label for="tracking-url">Tracking URL:</label>
<input type="text" id="tracking-url" name="tracking-url" required>
<input type="text" id="tracking-url" name="url" required>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>

</html>
101 changes: 88 additions & 13 deletions src/food/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,95 @@
use std::{error, io::Cursor, thread};

use tide::Request;
mod server;
mod wolt_models;
use self::wolt_models::WoltTracking;
use crate::ui::*;
use chrono::Local;
use log::{error, info};
use reqwest::Url;
use slint::Weak;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::thread;
use tokio::runtime::Runtime;

pub fn setup() {
thread::spawn(move || Runtime::new().unwrap().block_on(food_endpoint_server()));
pub fn setup(main_window: &MainWindow) {
let window_weak = main_window.as_weak();
let (tx, rx) = mpsc::channel();
//spawn server worker thread
thread::spawn(move || {
Runtime::new()
.unwrap()
.block_on(server::food_endpoint_server(tx))
});
//thread for tracking food
thread::spawn(move || {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(food_worker_loop(window_weak, rx))
});
}

async fn food_worker_loop(window: Weak<MainWindow>, rx: Receiver<Url>) {
let mut current_url: Option<Url> = None;
loop {
match rx.try_recv() {
Ok(tracking_url) => {
//TODO: Use logging instead of println
info!("Got new tracking url: {}", tracking_url);
current_url = Some(tracking_url);
}
Err(TryRecvError::Empty) => (),
Err(TryRecvError::Disconnected) => {
error!("Food tracking channel disconnected. Panicing...");
panic!();
}
}

let food_tracking = track_food(&current_url).await;
// If food_tracking is None, we either have no url or the tracking is done.
// Default FoodTracking is empty and hidden in the UI.
let food_tracking = food_tracking.unwrap_or_else(|| FoodTracking::default());
display_tracking(&window, food_tracking);
//TODO: Adjust timeout, maybe dynamic
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
}

async fn track_food(url: &Option<Url>) -> Option<FoodTracking> {
let tracking_url = match url {
Some(url) => url,
// No URL, nothing to track.
None => return None,
};

let food_tracking = get_tracking_data(&tracking_url).await;

match food_tracking {
Ok(tracking_data) => {
//TODO: maybe show status before tracking ETA is present?
if tracking_data.status == "delivered" || tracking_data.delivery_eta.is_none() {
return None;
}
let remaining_time =
((tracking_data.delivery_eta.unwrap()) - Local::now()).num_minutes();
Some(FoodTracking {
active: true,
minutes_remaining: remaining_time.to_string().into(),
resturant_name: tracking_data.from_location.name.en.into(),
})
}

//TODO: Log error
Err(_e) => None,
}
}

async fn food_endpoint_server() -> tide::Result<()> {
let mut app = tide::new();
app.at("/id").post(get_tracking_ID);
app.at("/").serve_file("src/food/index.html")?;
app.listen("127.0.0.1:1337").await?;
Ok(())
async fn get_tracking_data(url: &Url) -> Result<WoltTracking, reqwest::Error> {
let response = reqwest::get(url.clone()).await?;
let wolt_tracking_data = response.json::<WoltTracking>().await?;
Ok(wolt_tracking_data)
}

async fn get_tracking_ID(mut req: Request<()>) -> tide::Result {
Ok(format!("Food!").into())
fn display_tracking(window_weak: &Weak<MainWindow>, food_tracking: FoodTracking) {
window_weak
.upgrade_in_event_loop(move |window: MainWindow| window.set_foodTracking(food_tracking))
.unwrap();
}
26 changes: 26 additions & 0 deletions src/food/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::sync::mpsc::Sender;

use reqwest::Url;
use serde::Deserialize;
use tide::Request;

pub async fn food_endpoint_server(tx: Sender<Url>) -> tide::Result<()> {
let mut app = tide::new();
app.at("/tracking")
.post(move |req| start_tracking(tx.clone(), req));
app.at("/food").serve_file("src/food/index.html")?;
app.listen("127.0.0.1:1337").await?;
Ok(())
}

async fn start_tracking(tx: Sender<Url>, mut req: Request<()>) -> tide::Result {
let tracking: Tracking = req.body_form().await?;
// Pass tracking url to the worker thread
tx.send(tracking.url.clone()).unwrap();
Ok(format!("Got it! Tracking food delivery from {}", tracking.url).into())
}

#[derive(Debug, Deserialize)]
struct Tracking {
url: Url,
}
Loading

0 comments on commit 1704fe9

Please sign in to comment.