use crate::WATTPAD; use anyhow::{Context, Result}; use chrono::{DateTime, Local}; use lazy_static::lazy_static; use std::{collections::HashMap, sync::Mutex}; use wattpad::{Part, Story}; lazy_static! { static ref STORY_CACHE: Mutex)>> = Mutex::new(HashMap::new()); } pub async fn get_story(id: &str) -> Result { let current_time = chrono::Local::now(); if let Some(cache_item) = STORY_CACHE .lock() .expect("Failed to lock StoryCache hashmap (somehow)") .get(id) { let time_diff = current_time.signed_duration_since(cache_item.1); if time_diff.num_minutes() <= 15 { tracing::debug!("Cache hit for story {}", id); return Ok(cache_item.0.clone()); } } tracing::debug!("Caching story {}", id); let story = WATTPAD.get_story(id).await.context("Failed to get story")?; STORY_CACHE .lock() .expect("Failed to lock StoryCache hashmap (somehow)") .insert(id.to_string(), (story.clone(), current_time)); Ok(story) }