1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165extern crate darksky;
extern crate reqwest;
extern crate serde;
use chrono::{DateTime, Datelike, TimeZone, Utc, Weekday};
use darksky::DarkskyReqwestRequester;
use reqwest::Client;
use serde::Serialize;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use crate::config::DarkskyConfig;
use crate::config::Location;
use crate::AppState;
pub struct ForecastGrabber {
pub exit: Arc<AtomicBool>,
pub worker: Option<thread::JoinHandle<()>>,
}
impl ForecastGrabber {
pub fn new(
state: Arc<Mutex<AppState>>,
config: DarkskyConfig,
locations: Vec<Location>,
) -> ForecastGrabber {
let exit = Arc::new(AtomicBool::new(false));
let worker_exit = exit.clone();
let worker = Some(thread::spawn(move || {
let mut last_fetch: Option<DateTime<Utc>> = None;
let secret = config.secret.unwrap();
'outer: loop {
if worker_exit.load(Ordering::Relaxed) {
info!("Worker received exit signal");
break;
}
let fetch_every = 60;
let minutes = match last_fetch {
Some(d) => Utc::now().signed_duration_since(d).num_minutes(),
None => fetch_every,
};
if minutes >= fetch_every {
last_fetch = Some(Utc::now());
let mut failed = false;
let mut forecasts = Vec::new();
for location in &locations {
info!("Fetching: {}", location.name.clone());
match get_forecast(secret.clone(), location.lat, location.lon) {
Ok(forecast) => {
forecasts.push(BasicWeekendForecast {
location: location.clone(),
days: forecast,
});
}
Err(err) => {
info!("Error fetching: {}", err);
failed = true;
break;
}
}
if worker_exit.load(Ordering::Relaxed) {
info!("Worker received exit signal");
break 'outer;
}
}
if !failed {
let mut s = state.lock().unwrap();
s.forecasts = forecasts;
s.last_fetch = last_fetch;
}
}
std::thread::sleep(Duration::from_secs(1));
}
}));
ForecastGrabber { exit, worker }
}
pub fn exit_join(&mut self) {
info!("Sending exit signal to worker");
self.exit.store(true, Ordering::Relaxed);
if self.worker.take().unwrap().join().is_err() {
error!("Worker thread paniced");
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct BasicWeekendForecast {
pub location: Location,
pub days: Vec<BasicWeather>,
}
#[derive(Clone, Debug, Serialize)]
pub struct BasicWeather {
pub time: String,
pub temperature_low: f64,
pub temperature_high: f64,
pub summary: String,
}
pub fn get_forecast(secret: String, lat: f64, long: f64) -> Result<Vec<BasicWeather>, String> {
let client = Client::builder().build().or_else(|e| {
Err(format!(
"{} ({})",
"Failed to build client".to_string(),
e.to_string()
))
})?;
let req = client.get_forecast(&secret, lat, long).or_else(|e| {
Err(format!(
"{} ({})",
"Request failed".to_string(),
e.to_string()
))
})?;
let mut weathers = Vec::new();
#[allow(clippy::identity_conversion)]
for d in req
.daily
.ok_or_else(|| "No daily forecast".to_string())?
.data
.ok_or_else(|| "No Data".to_string())?
{
let dt = Utc.timestamp(d.time as i64, 0);
match dt.weekday() {
Weekday::Fri | Weekday::Sat | Weekday::Sun => {}
_ => continue,
}
if d.temperature_low.is_none() || d.temperature_high.is_none() || d.summary.is_none() {
continue;
}
let weather = BasicWeather {
time: dt.format("%a %h %e").to_string(),
temperature_low: d.temperature_low.unwrap(),
temperature_high: d.temperature_high.unwrap(),
summary: d.summary.unwrap(),
};
weathers.push(weather);
}
Ok(weathers)
}