mirror of
https://github.com/djibux/BoilR.git
synced 2026-09-01 05:53:41 +02:00
Refactor cached search into steamgriddb mod
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
use std::{collections::HashMap, fs::File, io::Write, path::Path};
|
||||
|
||||
type SearchMap = HashMap<u32, (String,usize)>;
|
||||
|
||||
|
||||
|
||||
pub struct CachedSearch<'a> {
|
||||
search_map: SearchMap,
|
||||
client: &'a steamgriddb_api::Client,
|
||||
}
|
||||
|
||||
impl<'a> CachedSearch<'a> {
|
||||
pub fn new(client: &steamgriddb_api::Client) -> CachedSearch {
|
||||
CachedSearch {
|
||||
search_map: get_search_map(),
|
||||
client,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
save_search_map(&self.search_map);
|
||||
}
|
||||
|
||||
pub async fn search(
|
||||
&mut self,
|
||||
app_id: u32,
|
||||
query: &str,
|
||||
) -> Result<Option<usize>, Box<dyn std::error::Error>> {
|
||||
|
||||
let cached_result = self.search_map.get(&app_id);
|
||||
if let Some(result) = cached_result {
|
||||
return Ok(Some(result.1));
|
||||
}
|
||||
|
||||
let search = self.client.search(query).await?;
|
||||
if search.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let first_item = &search[0];
|
||||
let assumed_id = first_item.id;
|
||||
self.search_map.insert(app_id, (query.to_owned(),assumed_id));
|
||||
|
||||
Ok(Some(assumed_id))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_search_map() -> SearchMap {
|
||||
let path = Path::new("cache.json");
|
||||
if path.exists() {
|
||||
let string = std::fs::read_to_string(path).unwrap();
|
||||
let search_map =
|
||||
serde_json::from_str::<SearchMap>(&string).expect("Failed to parse cache.json");
|
||||
search_map
|
||||
} else {
|
||||
SearchMap::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn save_search_map(search_map: &SearchMap) {
|
||||
let string = serde_json::to_string(search_map).unwrap();
|
||||
let mut file = File::create("cache.json").unwrap();
|
||||
file.write_all(string.as_bytes()).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
pub enum ImageType {
|
||||
Hero,
|
||||
Grid,
|
||||
Logo,
|
||||
}
|
||||
|
||||
impl ImageType {
|
||||
pub fn file_name(&self, app_id: u32) -> String {
|
||||
match self {
|
||||
ImageType::Hero => format!("{}_hero.png", app_id),
|
||||
ImageType::Grid => format!("{}p.png", app_id),
|
||||
ImageType::Logo => format!("{}_logo.png", app_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,7 @@
|
||||
mod settings;
|
||||
pub use settings::SteamGridDbSettings;
|
||||
mod image_type;
|
||||
mod cached_search;
|
||||
|
||||
pub use image_type::ImageType;
|
||||
pub use settings::SteamGridDbSettings;
|
||||
pub use cached_search::CachedSearch;
|
||||
Reference in New Issue
Block a user