Skip to content

Commit

Permalink
feat: show log level
Browse files Browse the repository at this point in the history
  • Loading branch information
Fay Ash authored and Fay Ash committed Mar 13, 2024
1 parent bef4d4e commit 112cc06
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 62 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "pretty-derby"
authors = ["Phie Ash"]
description = "Hachimi hachimi hachimi~"
version = "0.4.0"
version = "0.4.1"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
21 changes: 11 additions & 10 deletions src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@ use serde_json::json;
use sha1::{digest::FixedOutputReset, Digest, Sha1};
use std::{collections::HashMap, error::Error};

const URL_CURRENT: &'static str = "https://cpes.legym.cn/education/semester/getCurrent";
const URL_GETRUNNINGLIMIT: &'static str = "https://cpes.legym.cn/running/app/getRunningLimit";
const URL_GETVERSION: &'static str =
const URL_CURRENT: &str = "https://cpes.legym.cn/education/semester/getCurrent";
const URL_GETRUNNINGLIMIT: &str = "https://cpes.legym.cn/running/app/getRunningLimit";
const URL_GETVERSION: &str =
"https://cpes.legym.cn/authorization/mobileApp/getLastVersion?platform=2";
const URL_LOGIN: &'static str = "https://cpes.legym.cn/authorization/user/manage/login";
const URL_UPLOADRUNNING: &'static str = "https://cpes.legym.cn/running/app/v2/uploadRunningDetails";
const URL_LOGIN: &str = "https://cpes.legym.cn/authorization/user/manage/login";
const URL_UPLOADRUNNING: &str = "https://cpes.legym.cn/running/app/v2/uploadRunningDetails";

const ORGANIZATION: HeaderName = HeaderName::from_static("organization");
const HEADERS: [(HeaderName, &'static str); 9] = [

const HEADERS: [(HeaderName, &str); 9] = [
(ACCEPT, "*/*"),
(ACCEPT_ENCODING, "gzip, deflate, br"),
(ACCEPT_LANGUAGE, "zh-CN, zh-Hans;q=0.9"),
Expand All @@ -31,7 +32,7 @@ const HEADERS: [(HeaderName, &'static str); 9] = [
];

const CALORIE_PER_MILEAGE: f64 = 58.3;
const SALT: &'static str = "itauVfnexHiRigZ6";
const SALT: &str = "itauVfnexHiRigZ6";

pub struct Account {
client: Client,
Expand Down Expand Up @@ -98,7 +99,7 @@ impl Account {
let signdigital = {
self.hasher
.update((username.to_string() + &password + "1" + SALT).as_bytes());
hex::encode(self.hasher.finalize_fixed_reset().to_vec())
hex::encode(self.hasher.finalize_fixed_reset())
};
let json = json!({
"entrance": "1",
Expand Down Expand Up @@ -333,10 +334,10 @@ impl Account {
+ &((mileage * 1000. / pace / 2.) as i64).to_string()
+ &mileage.to_string()
+ "1"
+ &SALT.to_string())
+ SALT)
.as_bytes(),
);
hex::encode(self.hasher.finalize_fixed_reset().to_vec())
hex::encode(self.hasher.finalize_fixed_reset())
};
let json = json!({
"appVersion": self.version,
Expand Down
4 changes: 2 additions & 2 deletions src/account/routine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use std::{error::Error, fs, path::Path};
use wkt::TryFromWkt;

const DEFAULT_ROUTINE: &'static str = include_str!("../../data/default_routine.csv");
const DEFAULT_ROUTINE: &str = include_str!("../../data/default_routine.csv");

#[derive(Serialize)]
pub struct LGPoint {
Expand Down Expand Up @@ -51,7 +51,7 @@ pub fn get_routine(
longitude: point.x() + rng.gen_range(-2e-5..2e-5),
latitude: point.y() + rng.gen_range(-1e-5..1e-5),
};
mileage -= last.unwrap().geodesic_distance(&point) / 1000.;
mileage -= last.unwrap().geodesic_distance(point) / 1000.;
last = Some(point);

res.push(new);
Expand Down
21 changes: 20 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod pretty_tui;
use account::Account;
use clap::{ArgAction, CommandFactory, Parser};
use clap_complete::{generate, Shell};
use log::{error, Level, LevelFilter};
use log::{debug, error, Level, LevelFilter};
use pretty_logger::{CliLogger, TuiLogger};
use pretty_tui::Tui;
use std::{error::Error, io, sync::Arc};
Expand Down Expand Up @@ -57,6 +57,15 @@ async fn main() -> Result<(), Box<dyn Error>> {
let logger = CliLogger::new(level, stdout);
log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(filter))?;

debug!(
"{} level is enabled.",
match cli.verbose {
0 => "Info",
1 => "Debug",
_ => "Trace",
}
);

let username = cli.username.unwrap();
let password = rpassword::prompt_password(format!("Password for {}: ", username))?;
let mileage = cli.mileage.unwrap();
Expand All @@ -76,6 +85,16 @@ async fn main() -> Result<(), Box<dyn Error>> {
let logger = Arc::new(TuiLogger::new(level));
let mut tui = Tui::new(backend, logger.clone())?;
log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(filter))?;

debug!(
"{} level is enabled.",
match cli.verbose {
0 => "Info",
1 => "Debug",
_ => "Trace",
}
);

tui.welcome()?;
let mut t = tui.main()?;
loop {
Expand Down
101 changes: 53 additions & 48 deletions src/pretty_tui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use tui::{
Frame, Terminal,
};

const TITLE: &'static str = r#"
const TITLE: &str = r#"
╭────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ │
│ ██████╗ ██████╗ ███████╗████████╗████████╗██╗ ██╗ ██████╗ ███████╗██████╗ ██████╗ ██╗ ██╗ │
Expand All @@ -28,7 +28,7 @@ const TITLE: &'static str = r#"
╰────────────────────────────────────────────────────────────────────────────────────────────────────╯
"#;

const TITLE2: &'static str = r#"
const TITLE2: &str = r#"
██████╗ ██████╗ ███████╗████████╗████████╗██╗ ██╗ ██████╗ ███████╗██████╗ ██████╗ ██╗ ██╗
██╔══██╗██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝╚██╗ ██╔╝ ██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝
██████╔╝██████╔╝█████╗ ██║ ██║ ╚████╔╝ ██║ ██║█████╗ ██████╔╝██████╔╝ ╚████╔╝
Expand All @@ -37,7 +37,7 @@ const TITLE2: &'static str = r#"
╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝
"#;

const _TITLE3: &'static str = r#"
const _TITLE3: &str = r#"
██████╗ ██████╗ ███████╗████████╗████████╗██╗ ██╗
██╔══██╗██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝╚██╗ ██╔╝
██████╔╝██████╔╝█████╗ ██║ ██║ ╚████╔╝
Expand Down Expand Up @@ -87,8 +87,10 @@ pub struct Tui<'a, B: Backend> {
terminal: Rc<RefCell<Terminal<B>>>,
}

type PrettyTuiResult<A> = Result<A, Box<dyn Error>>;

impl<'a, B: Backend + Write> Tui<'a, B> {
pub fn new(mut backend: B, logger: Arc<TuiLogger<'a>>) -> Result<Self, Box<dyn Error>> {
pub fn new(mut backend: B, logger: Arc<TuiLogger<'a>>) -> PrettyTuiResult<Self> {
enable_raw_mode()?;
execute!(backend, EnterAlternateScreen)?;

Expand All @@ -107,7 +109,7 @@ impl<'a, B: Backend + Write> Tui<'a, B> {
}

impl<B: Backend + Write> Tui<'_, B> {
pub fn quit(&self) -> Result<(), Box<dyn Error>> {
pub fn quit(&self) -> PrettyTuiResult<()> {
disable_raw_mode()?;
execute!(
self.terminal.borrow_mut().backend_mut(),
Expand All @@ -117,7 +119,7 @@ impl<B: Backend + Write> Tui<'_, B> {
Ok(())
}

pub fn welcome(&self) -> Result<(), Box<dyn Error>> {
pub fn welcome(&self) -> PrettyTuiResult<()> {
loop {
self.terminal
.borrow_mut()
Expand Down Expand Up @@ -166,7 +168,7 @@ impl<B: Backend + Write> Tui<'_, B> {
frame.render_widget(para, chunks[3]);
}

pub fn main(&mut self) -> Result<Option<(String, String, u16)>, Box<dyn Error>> {
pub fn main(&mut self) -> PrettyTuiResult<Option<(String, String, u16)>> {
loop {
{
// WARN: Should make sure that the terminal dies immediately
Expand All @@ -181,7 +183,7 @@ impl<B: Backend + Write> Tui<'_, B> {
}
match self.input_mode {
InputMode::Normal => {
if let Some(_) = self.handle_normal(key.code) {
if self.handle_normal(key.code).is_some() {
return Ok(None);
}
}
Expand Down Expand Up @@ -249,7 +251,11 @@ impl<B: Backend + Write> Tui<'_, B> {
}
Widget::Mileage => {
self.input_mode = InputMode::Normal;
Some((self.account.clone(), self.password.clone(), self.mileage_percent))
Some((
self.account.clone(),
self.password.clone(),
self.mileage_percent,
))
}
},
KeyCode::Tab => match self.selected {
Expand All @@ -262,7 +268,7 @@ impl<B: Backend + Write> Tui<'_, B> {
self.select(KeyCode::Down);
None
}
_ => None
_ => None,
},
KeyCode::Backspace => match self.selected {
Widget::Account => {
Expand Down Expand Up @@ -330,11 +336,13 @@ impl<B: Backend + Write> Tui<'_, B> {
None
}
Widget::Account | Widget::Password => {
if self.cursorpos < match self.selected {
Widget::Account => self.account.len(),
Widget::Password => self.password.len(),
_ => 0,
} as u16 {
if self.cursorpos
< match self.selected {
Widget::Account => self.account.len(),
Widget::Password => self.password.len(),
_ => 0,
} as u16
{
self.cursorpos += 1;
}
None
Expand All @@ -346,12 +354,11 @@ impl<B: Backend + Write> Tui<'_, B> {

fn select(&mut self, direction: KeyCode) {
match self.selected {
Widget::Account => match direction {
KeyCode::Down => {
Widget::Account => {
if let KeyCode::Down = direction {
self.selected = Widget::Password;
}
_ => {}
},
}

Widget::Password => match direction {
KeyCode::Up => {
Expand All @@ -363,16 +370,15 @@ impl<B: Backend + Write> Tui<'_, B> {
_ => {}
},

Widget::Mileage => match direction {
KeyCode::Up => {
Widget::Mileage => {
if let KeyCode::Up = direction {
self.selected = Widget::Password;
}
_ => {}
},
}
}
}

fn ui_main(&self, frame: &mut Frame<B>) -> Result<(), Box<dyn Error>> {
fn ui_main(&self, frame: &mut Frame<B>) -> PrettyTuiResult<()> {
let chunks = Layout::default()
.margin(2)
.direction(Direction::Vertical)
Expand Down Expand Up @@ -432,24 +438,20 @@ impl<B: Backend + Write> Tui<'_, B> {
],
};

match self.selected {
Widget::Mileage => match self.input_mode {
InputMode::Editing => {
help.push(Spans::from(vec![
Span::styled("<Left>, h: ", Style::default().add_modifier(Modifier::BOLD)),
Span::raw("reduce"),
]));
help.push(Spans::from(vec![
Span::styled(
"<Right>, l: ",
Style::default().add_modifier(Modifier::BOLD),
),
Span::raw("increase"),
]));
}
_ => {}
},
_ => {}
if let Widget::Mileage = self.selected {
if let InputMode::Editing = self.input_mode {
help.push(Spans::from(vec![
Span::styled("<Left>, h: ", Style::default().add_modifier(Modifier::BOLD)),
Span::raw("reduce"),
]));
help.push(Spans::from(vec![
Span::styled(
"<Right>, l: ",
Style::default().add_modifier(Modifier::BOLD),
),
Span::raw("increase"),
]));
}
};

{
Expand Down Expand Up @@ -515,13 +517,16 @@ impl<B: Backend + Write> Tui<'_, B> {
frame.render_widget(password, chunks[1]);
frame.render_widget(mileage, chunks[2]);

match self.input_mode {
InputMode::Editing => match self.selected {
Widget::Account => frame.set_cursor(chunks[0].x + self.cursorpos + 1, chunks[0].y + 1),
Widget::Password => frame.set_cursor(chunks[1].x + self.cursorpos + 1, chunks[1].y + 1),
if let InputMode::Editing = self.input_mode {
match self.selected {
Widget::Account => {
frame.set_cursor(chunks[0].x + self.cursorpos + 1, chunks[0].y + 1)
}
Widget::Password => {
frame.set_cursor(chunks[1].x + self.cursorpos + 1, chunks[1].y + 1)
}
_ => {}
},
_ => {}
}
}

Ok(())
Expand Down

0 comments on commit 112cc06

Please sign in to comment.