Skip to content

Commit

Permalink
switch to reqwest
Browse files Browse the repository at this point in the history
  • Loading branch information
shnarazk committed Apr 9, 2023
1 parent cbad358 commit d304897
Showing 1 changed file with 82 additions and 26 deletions.
108 changes: 82 additions & 26 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use {
bevy::{
prelude::*,
tasks::{AsyncComputeTaskPool, Task},
// tasks::{AsyncComputeTaskPool, Task},
tasks::{IoTaskPool, Task},
winit::WinitSettings,
},
// chrono::DateTime,
clap::Parser,
hyper::Client,
hyper_tls::HttpsConnector,
// hyper::Client,
// hyper_tls::HttpsConnector,
serde_json::Value,
};

Expand All @@ -29,24 +30,17 @@ const ACTIVE_CHANNEL_COLOR: Color = Color::rgb(1., 0.066, 0.349);
const JUSTIFY_CONTENT_COLOR: Color = Color::rgb(0.102, 0.522, 1.);
const MARGIN: Val = Val::Px(2.);

#[derive(Clone, Component, Debug, Default, Parser)]
#[derive(Clone, Component, Debug, Default, Eq, PartialEq, Parser)]
#[clap(author, version, about)]
struct AppConfig {
/// area code
#[clap(short = 'a')]
area: Option<String>,
/// service (channel)
#[clap(short = 's')]
service: Option<String>,
/// date
#[clap(short = 'd')]
date: Option<String>,
#[clap(short = 'a', default_value = "400")]
area: u32,
/// API key
#[clap(short = 'k', long = "key", env)]
apikey: String,
/// Just download the csv w/o GUI
#[clap(long = "headless")]
headless: bool,
#[clap(short = 's', long = "service", env)]
service: String,
}

fn main() {
Expand Down Expand Up @@ -319,7 +313,22 @@ fn button_system(
Interaction::Clicked => {
let text = text_query.get_mut(children[0]).unwrap();
let label = text.sections[0].value.as_str();
config.service = Some(label.to_string());
config.service = label.to_string();

{
let pool = IoTaskPool::get();
let config = config.clone();
let label = label.to_string();
dbg!();
let _task = pool.spawn(async move {
dbg!();
let Ok(json) = fetch_json_reqwest(&config, &label).await else {
dbg!();
return serde_json::from_str("{status: \"no data\"}").unwrap();
};
dbg!(json)
});
}
}
_ => (),
}
Expand All @@ -331,9 +340,8 @@ fn button_system2(
mut interaction_query: Query<(&Children, &mut BackgroundColor), With<Button>>,
mut text_query: Query<&mut Text>,
) {
let null = "".to_string();
let config = config_query.get_single().unwrap();
let service = config.service.as_ref().unwrap_or(&null).to_string();
let service = config.service.clone();
for (children, mut color) in &mut interaction_query {
let text = text_query.get_mut(children[0]).unwrap();
let label = text.sections[0].value.as_str();
Expand All @@ -347,23 +355,26 @@ fn button_system2(

#[derive(Component)]
struct ProgramJson(Task<Value>);

// we need despawn 'task' after reading the content after updating screen.
fn spawn_tasks(_commands: Commands) {
// let thread_pool = AsyncComputeTaskPool::get();
// let task = thread_pool.spawn(async move {
// let config = AppConfig::default();
// let Ok(json) = load_json(&config, "g1").await else {
// return serde_json::from_str("{status: \"no data\"}").unwrap();
// };
// json
// });
let thread_pool = IoTaskPool::get();
let config = AppConfig::default();
let service = "g1".to_string();
let _task = thread_pool.spawn(async move {
let Ok(json) = fetch_json_reqwest(&config, &service).await else {
return serde_json::from_str("{status: \"no data\"}").unwrap();
};
json
});
// commands.spawn(ProgramJson(task));
}

fn handle_tasks(mut _commands: Commands, mut _tasks: Query<(Entity, &mut ProgramJson)>) {
// TODO:
}

/*
#[allow(dead_code)]
async fn load_json(config: &AppConfig, service: &str) -> hyper::Result<Value> {
let area = config.area.as_deref().unwrap_or("400");
Expand All @@ -383,3 +394,48 @@ async fn load_json(config: &AppConfig, service: &str) -> hyper::Result<Value> {
// dbg!(&json);
Ok(json)
}
*/

async fn fetch_json_reqwest(config: &AppConfig, service: &String) -> Result<Value, ()> {
let base = format!(
"https://api.nhk.or.jp/v2/pg/now/{}/{}.json?key={}",
config.area, service, &config.apikey
);
println!("1️⃣:build");
let client = reqwest::Client::builder()
// .timeout(core::time::Duration::from_secs(8))
// .connect_timeout(core::time::Duration::from_secs(8))
// .pool_idle_timeout(core::time::Duration::from_secs(4))
// .tcp_keepalive(None)
.build()
.unwrap();
println!("2️⃣:send");
let buf = client
.get(base)
.send()
.await
.unwrap()
.bytes()
.await
.unwrap();
println!("3️⃣:received");

let str = String::from_utf8_lossy(buf.as_ref());
let json: Value = serde_json::from_str(str.to_string().as_str()).expect("invalid json");
Ok(json)
}

#[allow(dead_code)]
fn parse_json(json: &Value) -> Option<(Value, String)> {
if let Some(list) = json.get("nowonair_list") {
for ch in ["g1", "e1", "r1", "r2", "r3"] {
if let Some(target) = list.get(ch) {
return Some((target.clone(), ch.to_string()));
}
}
}
if json.get("NO").is_some() {
return Some((json.clone(), "".to_string()));
}
None
}

0 comments on commit d304897

Please sign in to comment.