From 2303b4d71de5ef42598ea732303e00e6b988aa19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Gr=C3=BCnewald?= Date: Wed, 11 Dec 2024 21:48:38 +0100 Subject: [PATCH] Use NaiveDateTime to fix weird offsets --- src/main.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index fc59bd3..808fec4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ use rocket::{Rocket,Build,launch,get,routes,fs::{FileServer}}; use std::{fs::OpenOptions, io::BufReader, collections::HashMap}; use chrono::prelude::*; +const TELEGRAM_TIMESTAMP_FORMAT: &str = "%FT%X"; #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -18,17 +19,19 @@ enum MediaType { #[derive(Debug, Clone)] struct ScoredChatMessage { pub chat_message: ChatMessage, - pub last_used: i64, + pub last_used: NaiveDateTime, pub times: u32 } -impl From for ScoredChatMessage { - fn from(item: ChatMessage) -> ScoredChatMessage { - ScoredChatMessage { - chat_message: item.clone(), - last_used: item.date_unixtime.parse().expect("Could not parse date_unixtime"), +impl TryFrom for ScoredChatMessage { + type Error = chrono::format::ParseError; + + fn try_from(value: ChatMessage) -> Result { + Ok(ScoredChatMessage { + chat_message: value.clone(), + last_used: NaiveDateTime::parse_from_str(&value.date, TELEGRAM_TIMESTAMP_FORMAT)?, times: 1 - } + }) } } @@ -37,7 +40,7 @@ impl From for Markup { fn from(item: ScoredChatMessage) -> Markup { if let Some(mime_type) = &item.chat_message.mime_type { let message_file = item.chat_message.file.expect("No sticker file"); - let message_date = DateTime::from_timestamp(item.last_used, 0).expect("Could not parse items"); + let message_date = item.last_used; match mime_type.as_str() { "image/webp" => { return html! { @@ -84,7 +87,8 @@ struct ChatMessage { pub media_type: Option, pub mime_type: Option, pub file: Option, - pub date_unixtime: String + pub date_unixtime: String, + pub date: String } @@ -113,8 +117,10 @@ fn index() -> Markup { .filter(|m| matches!(m.media_type, Some(MediaType::Sticker))) .fold(HashMap::new(), |mut acc: HashMap, message| { if let Some(ref file) = message.file { - let message_date = (&message.date_unixtime).parse().expect("Could not parse date_unixtime"); - let entry = acc.entry(file.to_owned()).or_insert_with(|| ScoredChatMessage::from(message)); + let message_date = NaiveDateTime::parse_from_str(&message.date, TELEGRAM_TIMESTAMP_FORMAT) + .expect("Could not parse date"); + let entry = acc.entry(file.to_owned()).or_insert_with(|| ScoredChatMessage::try_from(message) + .expect("Could not parse date")); entry.last_used = entry.last_used.max(message_date); entry.times += 1; }