Skip to content

Commit

Permalink
Merge pull request #4 from stchris/feature/show-versions
Browse files Browse the repository at this point in the history
Show aleph and followthemoney versions
  • Loading branch information
stchris committed Jan 24, 2024
2 parents c0f45ea + 48ca17c commit a18f2ca
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 28 deletions.
35 changes: 31 additions & 4 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::models::Status;
use crate::models::{Metadata, Status};
use chrono::{DateTime, Local};
use ratatui::widgets::TableState;
use reqwest::header::AUTHORIZATION;
Expand All @@ -11,6 +11,7 @@ use std::fs::read_to_string;
#[derive(Debug)]
pub struct App {
pub status: Status,
pub metadata: Metadata,
pub config: Config,
pub current_profile: usize,
pub should_quit: bool,
Expand All @@ -20,6 +21,7 @@ pub struct App {
pub current_view: CurrentView,
pub profile_tablestate: TableState,
pub last_fetch: DateTime<Local>,
pub is_fetching: bool,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -162,24 +164,42 @@ impl App {
current_view: CurrentView::Main,
profile_tablestate: TableState::default(),
last_fetch,
metadata: Metadata::default(),
is_fetching: false,
}
}

pub(crate) fn update_status(&mut self) -> color_eyre::Result<()> {
pub(crate) fn fetch(&mut self) -> color_eyre::Result<()> {
self.is_fetching = true;
let client = reqwest::blocking::Client::new();
let auth_header = format!("Bearer {}", self.current_profile().token);

let url = format!(
"{}/api/2/status",
self.config.profiles[self.current_profile].url
);
let auth_header = format!("Bearer {}", self.current_profile().token);
let status = client
.get(url)
.header(AUTHORIZATION, auth_header)
.header(AUTHORIZATION, auth_header.to_string())
.send()?
.error_for_status()?
.json()?;
self.status = status;

let url = format!(
"{}/api/2/metadata",
self.config.profiles[self.current_profile].url
);
let metadata = client
.get(url)
.header(AUTHORIZATION, auth_header)
.send()?
.error_for_status()?
.json()?;
self.metadata = metadata;

self.error_message = "".to_string();
self.is_fetching = false;
Ok(())
}

Expand Down Expand Up @@ -211,6 +231,7 @@ impl App {
.is_some()
{
self.current_profile += 1;
self.clear_state();
}
}

Expand All @@ -223,6 +244,7 @@ impl App {
.is_some()
{
self.current_profile -= 1;
self.clear_state();
}
}

Expand All @@ -239,6 +261,11 @@ impl App {
self.collection_tablestate.select(Some(index + 1));
}
}

fn clear_state(&mut self) {
self.status = Status::default();
self.metadata = Metadata::default();
}
}

impl Default for App {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ use ratatui::prelude::{CrosstermBackend, Terminal};
use tui::Tui;
fn main() -> Result<()> {
let mut app = App::new();
app.update_status()
app.fetch()
.unwrap_or_else(|e| app.error_message = e.to_string());

let backend = CrosstermBackend::new(std::io::stderr());
let terminal = Terminal::new(backend)?;
let events = EventHandler::new(250);
let events = EventHandler::new(50);
let mut tui = Tui::new(terminal, events);
tui.enter()?;

Expand Down
25 changes: 25 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ pub struct Status {
pub total: u32,
}

#[derive(Debug, Default, Deserialize, Clone)]
pub struct MetadataApp {
pub title: Option<String>,
pub version: Option<String>,
pub ftm_version: Option<String>,
}

#[derive(Debug, Default, Deserialize, Clone)]
pub struct Metadata {
pub status: String,
pub maintenance: bool,
pub app: MetadataApp,
}

#[cfg(test)]
mod tests {
use std::fs::read_to_string;
Expand All @@ -57,4 +71,15 @@ mod tests {
let test = read_to_string("testdata/results.json").unwrap();
let _: Status = serde_json::from_str(&test).unwrap();
}

#[test]
fn test_metadata_deserialization() {
let test = read_to_string("testdata/metadata.json").unwrap();
let meta: Metadata = serde_json::from_str(&test).unwrap();
assert!(meta.status == "ok");
assert!(meta.maintenance == false);
assert!(meta.app.title.unwrap() == "OCCRP Aleph");
assert!(meta.app.version.unwrap() == "3.15.5");
assert!(meta.app.ftm_version.unwrap() == "3.5.8");
}
}
55 changes: 40 additions & 15 deletions src/ui.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use chrono::{NaiveDateTime, Utc};
use chrono_humanize::HumanTime;
use chrono_humanize::{Accuracy, HumanTime, Tense};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
prelude::Frame,
style::{Color, Modifier, Style, Stylize},
text::Text,
text::Line,
widgets::{Block, Borders, Paragraph, Row, Table},
};

Expand Down Expand Up @@ -37,26 +37,43 @@ pub fn render(app: &mut App, f: &mut Frame) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3),
Constraint::Length(4),
Constraint::Min(1),
Constraint::Length(1),
Constraint::Length(1),
])
.split(f.size());
let title_block = Block::default()
.borders(Borders::ALL)
.border_type(ratatui::widgets::BorderType::Rounded)
.style(Style::default());

let title = Paragraph::new(Text::styled(
format!(
"{}: {} jobs running",
app.current_profile().name,
app.status.total
let text = vec![
Line::from(match &app.metadata.app.title {
Some(title) => format!(
"{} ({}): {} jobs running",
title,
app.current_profile().name,
app.status.total
),
None => format!(
"({}): {} jobs running",
app.current_profile().name,
app.status.total
),
}),
Line::from(
match (&app.metadata.app.version, &app.metadata.app.ftm_version) {
(Some(aleph), Some(ftm)) => format!("version: {}, followthemoney: {}", aleph, ftm),
(None, Some(ftm)) => format!("followthemoney: {}", ftm),
(Some(aleph), None) => format!("version: {}", aleph),
(None, None) => String::default(),
},
),
Style::default().fg(Color::Green),
))
.block(title_block);

];
let title = Paragraph::new(text)
.style(Style::default().fg(Color::Green))
.block(title_block);
f.render_widget(title, chunks[0]);

let mut rows = Vec::new();
Expand All @@ -67,8 +84,7 @@ pub fn render(app: &mut App, f: &mut Frame) {
let last_update = NaiveDateTime::parse_from_str(&t, "%Y-%m-%dT%H:%M:%S.%f")
.expect("Failed to parse last_update timestamp");
let last_update = last_update - now;
let last_update = HumanTime::from(last_update).to_string();
last_update
HumanTime::from(last_update).to_text_en(Accuracy::Precise, Tense::Present)
}
None => "".to_string(),
};
Expand Down Expand Up @@ -131,9 +147,18 @@ pub fn render(app: &mut App, f: &mut Frame) {
Block::default().title(format!("aleph-tui version {}", app.version)),
status_bar_chunks[0],
);
let fetching_icon = match app.is_fetching {
true => "📥",
false => "",
};
let last_fetch_text = format!(
"last fetch: {} {}",
HumanTime::from(app.last_fetch),
fetching_icon
);
f.render_widget(
Block::default()
.title(format!("last fetch: {}", HumanTime::from(app.last_fetch)))
.title(last_fetch_text)
.title_alignment(Alignment::Right),
status_bar_chunks[1],
);
Expand Down
12 changes: 5 additions & 7 deletions src/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@ pub fn update(app: &mut App, key_event: KeyEvent) {
pub(crate) fn fetch(app: &mut App) {
let elapsed = Local::now() - app.last_fetch;
if elapsed.num_seconds() > app.config.fetch_interval {
match app.update_status() {
Ok(()) => {
app.last_fetch = Local::now();
app.error_message = String::default();
}
Err(e) => app.error_message = e.to_string(),
}
app.error_message = match app.fetch() {
Ok(()) => String::default(),
Err(e) => e.to_string(),
};
app.last_fetch = Local::now();
}
}
24 changes: 24 additions & 0 deletions testdata/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"status": "ok",
"maintenance": false,
"app": {
"title": "OCCRP Aleph",
"version": "3.15.5",
"ftm_version": "3.5.8",
"banner": null,
"ui_uri": "https://aleph.my.domain",
"messages_url": "https://status.aleph.my.domain/messages.json",
"publish": true,
"logo": "https://aleph.my.domain/common/logo/WhiteTransparent_globe.png",
"favicon": "https://aleph.my.domain/common/logo/RedTransparent_globe.png",
"locale": "en",
"locales": {
"ru": "\u0440\u0443\u0441\u0441\u043a\u0438\u0439",
"es": "espa\u00f1ol",
"de": "Deutsch",
"en": "English",
"ar": "\u0627\u0644\u0639\u0631\u0628\u064a\u0629",
"fr": "fran\u00e7ais"
}
}
}

0 comments on commit a18f2ca

Please sign in to comment.