Skip to content

Commit

Permalink
Improved index
Browse files Browse the repository at this point in the history
  • Loading branch information
kellpossible committed Sep 10, 2023
1 parent 5bf1b68 commit a8f6de7
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 32 deletions.
15 changes: 7 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ use axum::{
};

pub fn map_eyre_error(error: eyre::Error) -> ErrorResponse {
tracing::error!("{error:?}");
let error = format!("{error:?}");
ErrorResponse::from((
StatusCode::INTERNAL_SERVER_ERROR,
Html(
ansi_to_html::convert_escaped(&error)
.unwrap_or(error)
.replace('\n', "<br>"),
),
))
let mut html = ansi_to_html::convert_escaped(&error)
.unwrap_or(error)
.replace('\n', "<br>");
html.insert_str(0, "<pre>");
html.push_str("</pre>");
ErrorResponse::from((StatusCode::INTERNAL_SERVER_ERROR, Html(html)))
}

pub fn map_std_error(error: impl std::error::Error) -> ErrorResponse {
Expand Down
4 changes: 4 additions & 0 deletions src/forecasts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ async fn handler_impl(
None => return Ok(StatusCode::NOT_FOUND.into_response()),
};

dbg!(&file_metadata);

let view = match file_metadata.mime_type.as_str() {
"application/pdf" => ForecastFileView::Download,
"application/vnd.google-apps.spreadsheet" => ForecastFileView::Html,
Expand Down Expand Up @@ -329,6 +331,8 @@ async fn handler_impl(
let cached_last_modified: OffsetDateTime = cached_forecast_file.last_modified.into();
let server_last_modified: &OffsetDateTime = &file_metadata.modified_time;
tracing::debug!("cached last modified {cached_last_modified}, server last modified {server_last_modified}");
// This logic is a bit buggy on google's side it seems, sometimes they change document
// but don't update modified time.
if cached_last_modified == *server_last_modified {
Some(cached_forecast_file.file_blob)
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/i18n.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use i18n_embed::{
};
use rust_embed::RustEmbed;
use serde::Deserialize;
use time::OffsetDateTime;
use std::{str::FromStr, sync::Arc};
use time::OffsetDateTime;

use crate::{error::map_std_error, serde::string, state::AppState};

Expand Down
70 changes: 55 additions & 15 deletions src/index.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use axum::{extract::State, response::IntoResponse, Extension};
use color_eyre::Help;
use eyre::Context;
use eyre::{bail, Context, ContextCompat};
use http::StatusCode;
use i18n_embed::LanguageLoader;
use serde::Serialize;
use unic_langid::LanguageIdentifier;

use crate::{
error::map_eyre_error,
forecasts::{parse_forecast_name, ForecastDetails, ForecastFileDetails},
google_drive::{self, ListFileMetadata},
i18n::{I18nLoader, self},
i18n::{self, I18nLoader},
state::AppState,
templates::{render, TemplatesWithContext},
};
Expand Down Expand Up @@ -40,16 +41,14 @@ pub struct ForecastFile {
#[derive(Clone, Serialize, Debug)]
pub struct FormattedForecastFileDetails {
pub forecast: FormattedForecastDetails,
pub language: Option<String>,
pub language: Option<LanguageIdentifier>,
}

impl FormattedForecastFileDetails {
fn format(value: ForecastFileDetails, i18n: &I18nLoader) -> Self {
Self {
forecast: FormattedForecastDetails::format(value.forecast, i18n),
language: value.language.map(|language| {
format_language_name(&language).unwrap_or_else(|| language.to_string())
}),
language: value.language,
}
}
}
Expand All @@ -63,19 +62,24 @@ pub struct FormattedForecastDetails {
}

impl FormattedForecastDetails {
fn format(forecast: ForecastDetails, i18n: &I18nLoader) -> Self {
let formatted_time = i18n::format_time(forecast.time, i18n);
fn format(details: ForecastDetails, i18n: &I18nLoader) -> Self {
let formatted_time = i18n::format_time(details.time, i18n);
Self {
area: forecast.area,
area: details.area,
formatted_time,
time: forecast.time,
forecaster: forecast.forecaster,
time: details.time,
forecaster: details.forecaster,
}
}
}

#[derive(Serialize, Debug)]
pub struct Forecast {
pub details: FormattedForecastDetails,
pub file: ForecastFile,
}

pub struct ForecastAccumulator {
pub details: FormattedForecastDetails,
pub files: Vec<ForecastFile>,
}
Expand Down Expand Up @@ -103,7 +107,7 @@ pub async fn handler(
return Ok(StatusCode::INTERNAL_SERVER_ERROR.into_response());
}
};
let (mut forecasts, errors): (Vec<Forecast>, Vec<String>) = files
let (forecasts, mut errors): (Vec<ForecastAccumulator>, Vec<String>) = files
.into_iter()
.map(|file| {
let filename = &file.name;
Expand Down Expand Up @@ -137,16 +141,52 @@ pub async fn handler(
match result {
Ok(forecast_file) => {
if let Some(i) = acc.0.iter().position(|forecast| forecast.details == forecast_file.details.forecast) {
acc.0.get_mut(i).unwrap().files.push(forecast_file)

let forecast_acc = acc.0.get_mut(i).unwrap();
forecast_acc.files.push(forecast_file);

} else {
acc.0.push(Forecast { details: forecast_file.details.forecast.clone(), files: vec![forecast_file] });
acc.0.push(ForecastAccumulator { details: forecast_file.details.forecast.clone(), files: vec![forecast_file] });
}
}
Err(error) => acc.1.push(format!("{error:?}")),
Err(error) => acc.1.push(format!("{error:#?}")),
}
acc
});

let mut forecasts: Vec<Forecast> = forecasts
.into_iter()
.map(|forecast_acc| {
let file: ForecastFile = if forecast_acc.files.len() > 1 {
forecast_acc
.files
.into_iter()
.filter(|file| {
if let Some(language) = &file.details.language {
return language.language == i18n.current_language().language;
}
true
})
.next()
} else {
forecast_acc.files.into_iter().next()
}
.wrap_err_with(|| {
format!(
"Expected there to be at least one forecast file for this forecast {:#?}",
forecast_acc.details
)
})?;

Ok(Forecast {
details: forecast_acc.details,
file,
})
})
.collect::<eyre::Result<_>>()
.wrap_err("Error converting accumulated forecast")
.map_err(map_eyre_error)?;

forecasts.sort_by(|a, b| b.details.time.cmp(&a.details.time));

let index = Index { forecasts, errors };
Expand Down
13 changes: 5 additions & 8 deletions src/templates/index.html
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
{% from "macros/language_select.html" import language_select %}
{% extends "base.html" %}
{% macro forecast_block(forecast, emphasize=false) %}
<h3 class="text-xl font-bold">{{ forecast.details.formatted_time }}</h3>
{% for file in forecast.files %}
<a class="text-blue-600 hover:text-blue-800 visited:text-purple-600 {% if emphasize %}text-xl font-bold{% endif %}"
href="/forecasts/{{ file.file.name | urlencode }}">
{% if file.view == "Download" %}Download PDF ({{ file.details.language }}){% endif %}
{% if file.view == "Html" %}View Forecast{% endif %}
<p>
<a class="text-xl font-bold text-blue-600 hover:text-blue-800 visited:text-purple-600 {% if emphasize %}text-xl font-bold{% endif %}"
href="/forecasts/{{ forecast.file.file.name | urlencode }}">
{{ forecast.details.formatted_time }}
</a>
{% if not loop.last %}|{% endif %}
{% endfor %}
</p>
{% endmacro %}
{% set page_title = fl("gudauri-avalanche-forecast-heading") %}
{% block title %}
Expand Down

0 comments on commit a8f6de7

Please sign in to comment.