Skip to content

Commit

Permalink
fixed a lot of tech debt
Browse files Browse the repository at this point in the history
Signed-off-by: Ashwin Naren <[email protected]>
  • Loading branch information
arihant2math committed Dec 5, 2023
1 parent 377cec6 commit 1226841
Show file tree
Hide file tree
Showing 20 changed files with 389 additions and 238 deletions.
9 changes: 4 additions & 5 deletions internal/backend/src/meteo/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use local::location::Coordinates;
use networking;
use networking::Resp;
use serde::{Deserialize, Serialize};

use shared_deps::simd_json;

use crate::meteo::json::{MeteoAirQualityJson, MeteoForecastJson};
use local::location::Coordinates;
use networking;
use networking::Resp;

pub mod forecast;
mod json;
Expand All @@ -20,7 +19,7 @@ fn get_api_urls(location: &Coordinates, metric: bool) -> [String; 2] {
let hourly = "temperature_2m,rain,showers,snowfall,cloudcover,dewpoint_2m,apparent_temperature,pressure_msl,visibility,windspeed_10m,winddirection_10m,precipitation_probability";
let daily = "temperature_2m_max,temperature_2m_min";
let units = if metric {
"" // TODO: Strong units here
""
} else {
"&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch"
};
Expand Down
14 changes: 7 additions & 7 deletions internal/backend/src/openweathermap/current.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use chrono::{DateTime, Duration};
use shared_deps::simd_json;
use std::collections::HashMap;

use crate::openweathermap::json::{OpenWeatherMapAirQualityJson, OpenWeatherMapJson};
use crate::WeatherCondition;
use crate::WindData;
use crate::{get_conditions_sentence, WeatherData};
use std::collections::HashMap;
use chrono::{DateTime, Duration};
use crate::openweathermap::json::{OpenWeatherMapAirQualityJson, OpenWeatherMapJson};
use crate::openweathermap_shared::json::PrecipitationJson;
use crate::weather_data::PrecipitationData;
use crate::WeatherCondition;
use crate::WindData;

pub fn get_current(
data: OpenWeatherMapJson,
Expand Down Expand Up @@ -41,12 +41,12 @@ pub fn get_current(
rain_data: PrecipitationData {
amount: data.rain.unwrap_or(PrecipitationJson::default()).one_hour as f32,
time: Duration::hours(1),
probability: 100, // TODO: really?
probability: 100
},
snow_data: PrecipitationData {
amount: data.snow.unwrap_or(PrecipitationJson::default()).one_hour as f32,
time: Duration::hours(1),
probability: 100, // TODO: really?
probability: 100
},
})
}
14 changes: 7 additions & 7 deletions internal/backend/src/openweathermap_onecall/forecast.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::openweathermap_onecall::current::get_current;
use shared_deps::bincode;
use crate::openweathermap_onecall::get_combined_data_formatted;
use crate::openweathermap_onecall::future::get_future;
use crate::WeatherData;
use crate::WeatherForecast;
use local::location;
use local::settings::Settings;
use local::weather_file::WeatherFile;
use location::Coordinates;
use shared_deps::bincode;
use std::collections::HashMap;

use crate::openweathermap_onecall::current::get_current;
use crate::openweathermap_onecall::future::get_future;
use crate::openweathermap_onecall::get_combined_data_formatted;
use crate::WeatherData;
use crate::WeatherForecast;

pub fn get_forecast(
coordinates: &Coordinates,
Expand All @@ -35,7 +35,7 @@ pub fn get_forecast(
item,
&data.daily[count / 24],
weather_codes.clone(),
)?); //TODO: Test
)?);
}
let loc = location::reverse_geocode(coordinates)?;
Ok(WeatherForecast {
Expand Down
7 changes: 3 additions & 4 deletions internal/backend/src/openweathermap_onecall/json.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::openweathermap_shared::json::PrecipitationJson;
use crate::openweathermap_shared::json::OpenWeatherMapConditionJson;
use serde::{Deserialize, Serialize};

use crate::openweathermap_shared::json::PrecipitationJson;

#[derive(Clone, Serialize, Deserialize)]
pub struct MomentJson {
Expand Down Expand Up @@ -60,7 +59,7 @@ pub struct DailyJson {
pub moonrise: i64,
pub moonset: i64,
pub moon_phase: f64,
pub temp: HashMap<String, f64>, // TODO: Optimize this into actual structs
pub temp: HashMap<String, f64>,
pub feels_like: HashMap<String, f64>,
pub pressure: i64,
pub humidity: i64,
Expand Down
5 changes: 2 additions & 3 deletions internal/cli/src/arguments.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use clap::{Args, Parser, Subcommand};

// TODO: Arguments to add
// - alternative to weather config
// - warnings and downloads in weather config
mod global;

use clap::{Args, Parser, Subcommand};

#[derive(Clone, Parser)]
#[command(version, author, about, name = "weathercli")]
pub struct App {
Expand Down
25 changes: 12 additions & 13 deletions internal/cli/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
pub mod backend_commands;
pub mod layout_commands;
pub mod util;

use std::str::FromStr;
use std::thread;

use shared_deps::simd_json;

use crate::arguments::CacheOpts;
use crate::{print_out, Datasource};
use backend::{meteo, nws, openweathermap, openweathermap_onecall, WeatherForecast};
use chrono::{DateTime, Duration, Utc};
use custom_backend::dynamic_library_loader::ExternalBackends;
use local::cache::prune;
use local::location::Coordinates;
use local::settings::Settings;
use local::weather_file::WeatherFile;
use log::{debug, error, warn};
use shared_deps::serde_json::Value;
use shared_deps::simd_json;
use std::path::Path;
use chrono::{DateTime, Duration, Utc};
use std::str::FromStr;
use std::thread;
use terminal::prompt;
use weather_dirs::resources_dir;

use crate::{Datasource, print_out};
use crate::arguments::CacheOpts;

pub mod backend_commands;
pub mod layout_commands;
pub mod util;

fn get_requested_time(time: Option<String>) -> DateTime<Utc> {
match time {
Some(t) => {
Expand Down Expand Up @@ -139,7 +138,7 @@ pub fn cache(opts: CacheOpts) -> crate::Result<()> {
}

pub fn about() {
println!("Weather, in your terminal"); // TODO: Incorperate command
println!("Weather, in your terminal");
println!("Version: {}", env!("CARGO_PKG_VERSION"));
}

Expand Down
32 changes: 15 additions & 17 deletions internal/cli/src/commands/backend_commands.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use crate::arguments::BackendOpts;
use custom_backend::dynamic_library_loader::is_valid_ext;
use local::list_dir;
use local::settings::Settings;
use local::weather_file::WeatherFile;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use terminal::color;
use terminal::prompt;
use weather_dirs::custom_backends_dir;

use crate::arguments::BackendOpts;

fn install(path: String) -> crate::Result<()> {
// TODO: Add validity checks (prompt user for permission first)
let real_path = PathBuf::from_str(&path).unwrap();
Expand All @@ -20,15 +22,13 @@ fn install(path: String) -> crate::Result<()> {
Ok(())
}

fn list(settings: Settings) -> crate::Result<()> {
fn list(settings: &mut Settings) -> crate::Result<()> {
let paths = list_dir(custom_backends_dir()?)?;
for path in paths {
// TODO: Check which ones are valid (hard to do)
// magic bytes
let _dll_bytes = vec![77, 90];
let file_name = &*path;
if is_valid_ext(file_name) {
let valid = settings.enable_custom_backends;
let mut valid = settings.enable_custom_backends && is_valid_file(custom_backends_dir()?.join(file_name).as_path().to_str().unwrap());
if valid {
println!("{}{file_name}", color::FORE_GREEN);
} else {
Expand All @@ -39,8 +39,8 @@ fn list(settings: Settings) -> crate::Result<()> {
Ok(())
}

fn select(settings: Settings) -> crate::Result<()> {
let selected = settings.default_backend;
fn select(settings: &mut Settings) -> crate::Result<()> {
let selected = &settings.default_backend;
let mut settings = Settings::new()?;
let choices = ["openweathermap", "meteo", "nws", "openweathermap_onecall"];
let selected_usize = choices.iter().position(|&i| i == selected).unwrap_or(0);
Expand All @@ -50,11 +50,11 @@ fn select(settings: Settings) -> crate::Result<()> {
Ok(())
}

fn open_weather_map_api_key(settings: Settings) -> crate::Result<()> {
let original = settings.open_weather_map_api_key;
fn open_weather_map_api_key(settings: &mut Settings) -> crate::Result<()> {
let original = &settings.open_weather_map_api_key;
let mut s = prompt::input(
Some("Enter your openweathermap api key: ".to_string()),
Some(original),
Some(original.to_string()),
)?;
s = s.trim().to_string();
if s.len() != 32 {
Expand All @@ -63,23 +63,21 @@ fn open_weather_map_api_key(settings: Settings) -> crate::Result<()> {
)?;
}
// TODO: verify key first
println!("{}Saving api key as {s}", color::FORE_BLUE); // TODO: Fix
let mut settings = Settings::new()?; // TODO: Fix excess read (pass in mutable ref)
println!("{}Saving api key as {s}", color::FORE_BLUE); // TODO: bold
settings.open_weather_map_api_key = s;
settings.write()?;
Ok(())
}

fn bing_maps_api_key(settings: Settings) -> crate::Result<()> {
let original = settings.bing_maps_api_key;
fn bing_maps_api_key(settings: &mut Settings) -> crate::Result<()> {
let original = &settings.bing_maps_api_key;
let mut s = prompt::input(
Some("Enter your bing maps api key: ".to_string()),
Some(original),
Some(original.to_string()),
)?;
s = s.trim().to_string();
// TODO: verify key
println!("{}Saving api key as {s}", color::FORE_BLUE);
let mut settings = Settings::new()?; // TODO: Fix excess read
settings.bing_maps_api_key = s;
settings.write()?;
Ok(())
Expand All @@ -92,7 +90,7 @@ fn delete() -> crate::Result<()> {
Ok(())
}

pub fn subcommand(arg: BackendOpts, settings: Settings) -> crate::Result<()> {
pub fn subcommand(arg: BackendOpts, settings: &mut Settings) -> crate::Result<()> {
match arg {
BackendOpts::Install(opts) => install(opts.path)?,
BackendOpts::List => list(settings)?,
Expand Down
33 changes: 27 additions & 6 deletions internal/custom_backend/src/dynamic_library_loader.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use std::{collections::HashMap, ffi::OsStr, io, rc::Rc};

use libloading::Library;
use log::{debug, error, trace};

use crate::{PluginDeclaration, WeatherForecastPlugin};
use backend::WeatherForecast;
use libloading::Library;
use local::location::Coordinates;
use local::settings::Settings;
use local::weather_file::WeatherFile;
use log::{debug, error, trace};
use std::{collections::HashMap, ffi::OsStr, io, rc::Rc};
use weather_dirs::custom_backends_dir;
use weather_error::Error;
use weather_error::InvocationError;

use crate::{PluginDeclaration, WeatherForecastPlugin};

#[cfg(target_os = "windows")]
pub fn is_valid_ext(f: &str) -> bool {
f.ends_with(".dll")
Expand All @@ -25,6 +26,26 @@ pub fn is_valid_ext(f: &str) -> bool {
f.ends_with(".dylib")
}

#[cfg(target_os = "windows")]
pub fn is_valid_file(f: &str) -> bool {
let file = WeatherFile::new(custom_backends_dir()?.join(file_name).as_path().to_str().unwrap())?;
file.data.starts_with(&[0x4d, 0x5a])
}

#[cfg(target_os = "linux")]
pub fn is_valid_file(f: &str) -> bool {
let file = WeatherFile::new(custom_backends_dir()?.join(file_name).as_path().to_str().unwrap())?;
file.data.starts_with(&[0x7f, 0x45, 0x4c, 0x46]) // TODO: untested

}

#[cfg(target_os = "macos")]
pub fn is_valid_file(f: &str) -> bool {
let file = WeatherFile::new(custom_backends_dir()?.join(file_name).as_path().to_str().unwrap())?;
file.data.starts_with(&[0xcf, 0xfa, 0xed, 0xfe]) // TODO: untested
}


pub fn load(paths: Vec<String>) -> ExternalBackends {
let mut backends = ExternalBackends::new();
unsafe {
Expand Down
Loading

0 comments on commit 1226841

Please sign in to comment.