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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
//
// A wrapper around https://git.estrogen.zone/dumbswitch.git to provide nice space api responses
// Copyright (C) 2025 memdmp
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
//
use std::env;
use std::io::Error;
use std::net::SocketAddr;
use std::sync::LazyLock;
use std::time::Duration;
use http_body_util::{BodyExt, Empty, Full};
use hyper::Uri;
use hyper::body::Incoming;
use hyper::header::HeaderValue;
use hyper::{Request, Response, body::Bytes, server::conn::http1, service::service_fn};
use hyper_util::rt::TokioIo;
use serde_json::{Map, Value};
use tokio::net::TcpStream;
use tokio::{net::TcpListener, sync::RwLock, task, time};
static RAW_JSON: &'static str = include_str!("../api.json");
static PARSED_JSON: LazyLock<RwLock<serde_json::Value>> =
LazyLock::new(|| RwLock::new(serde_json::from_str(RAW_JSON).expect("JSON parse error")));
type StdResult<T, E> = std::result::Result<T, E>;
type Result<T> = StdResult<T, Box<dyn std::error::Error + Send + Sync>>;
async fn respond(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>> {
let str = PARSED_JSON.read().await.to_string();
let len = str.len();
let mut res = Response::new(Full::new(Bytes::from(str)));
res
.headers_mut()
.append("Content-Type", HeaderValue::from_static("application/json"));
let len = HeaderValue::from_str(&len.to_string());
if len.is_ok() {
res.headers_mut().append("Content-Length", len.unwrap());
}
Ok(res)
}
async fn fetch_url(url: hyper::Uri) -> Result<Response<Incoming>> {
if url.scheme_str() != Some("http") {
return Err(Box::new(Error::new(
std::io::ErrorKind::InvalidInput,
"This function only works with HTTP URIs.",
)));
}
let host = url.host().expect("uri has no host");
let port = url.port_u16().unwrap_or(80);
let addr = format!("{}:{}", host, port);
let stream = TcpStream::connect(addr).await?;
let io = TokioIo::new(stream);
let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?;
tokio::task::spawn(async move {
if let Err(err) = conn.await {
println!("Connection failed: {:?}", err);
}
});
let authority = url.authority().unwrap().clone();
let path = url.path();
let req = Request::builder()
.uri(path)
.header(hyper::header::HOST, authority.as_str())
.body(Empty::<Bytes>::new())?;
Ok(sender.send_request(req).await?)
}
fn get_space_open_request_target_uri() -> Uri {
env::var("OPEN_REQUEST_TO")
.unwrap_or("http://10.0.0.77:8080/".to_string())
.parse::<hyper::Uri>()
.unwrap()
}
async fn get_is_open() -> Result<bool> {
let mut res = fetch_url(get_space_open_request_target_uri()).await?;
let mut out = "".to_string();
while let Some(next) = res.frame().await {
let frame = next?;
if let Some(chunk) = frame.data_ref() {
out = format!("{out}{}", std::str::from_utf8(chunk).unwrap());
}
}
let state = out.trim().starts_with("a");
Ok(state)
}
#[tokio::main]
async fn main() -> Result<()> {
{
let state = {
let mut parsed_json = PARSED_JSON.write().await;
if !parsed_json.is_object() {
panic!("api.json must have top-level object!");
}
let parsed_json_obj = parsed_json.as_object_mut().unwrap();
let state = parsed_json_obj.get_mut("state");
let blank_map = Map::new();
let state = if state.is_some() {
state.unwrap()
} else {
&mut Value::Object(blank_map)
};
let state_obj = state
.as_object_mut()
.expect("State is non-undefined non-object.");
state_obj.remove_entry("open");
state.clone()
};
// ensure state is present
let mut parsed_json = PARSED_JSON.write().await;
let parsed_json_obj = parsed_json.as_object_mut().unwrap();
parsed_json_obj.insert("state".to_string(), state);
}
task::spawn(async {
loop {
{
let is_open = get_is_open().await;
let mut parsed_json = PARSED_JSON.write().await;
let state = parsed_json.get_mut("state");
if state.is_none() {
panic!("State is none!");
};
let state = state.unwrap().as_object_mut();
if state.is_none() {
panic!("State was turned into non-object!");
}
let state = state.unwrap();
if is_open.is_ok() {
let is_open = is_open.unwrap();
state.insert("open".to_string(), serde_json::Value::Bool(is_open));
} else {
state.remove("open");
eprintln!("Failed to fetch open status: {:#?}", is_open.unwrap_err());
}
}
time::sleep(Duration::from_secs(1)).await;
}
});
let addr: SocketAddr = env::var("LISTEN_ON")
.unwrap_or("127.0.0.1:3000".to_string())
.parse()?;
// We create a TcpListener and bind it to 127.0.0.1:3000
let listener = TcpListener::bind(addr).await?;
println!(
"Listening on: LISTEN_ON={addr:#?}
Sending fetch requests to: OPEN_REQUEST_TO={:#?}",
get_space_open_request_target_uri()
);
// We start a loop to continuously accept incoming connections
loop {
let (stream, _) = listener.accept().await?;
// Use an adapter to access something implementing `tokio::io` traits as if they implement
// `hyper::rt` IO traits.
let io = TokioIo::new(stream);
// Spawn a tokio task to serve multiple connections concurrently
tokio::task::spawn(async move {
// Finally, we bind the incoming connection to our `hello` service
if let Err(err) = http1::Builder::new()
// `service_fn` converts our function in a `Service`
.serve_connection(io, service_fn(respond))
.await
{
eprintln!("Error serving connection: {:?}", err);
}
});
}
}
|