game_manager_lib/services/
images.rs1use crate::constants::{COVERS_DIR_NAME, COVER_IMAGE_EXTENSION};
7use crate::errors::AppError;
8use std::fs;
9use std::path::PathBuf;
10use tauri::{AppHandle, Manager};
11
12fn get_covers_dir(app: &AppHandle) -> Result<PathBuf, AppError> {
14 let app_data_dir = app.path().app_data_dir().map_err(|e| {
16 AppError::IoError(
17 std::io::Error::new(std::io::ErrorKind::NotFound, e.to_string()).to_string(),
18 )
19 })?;
20
21 let covers_dir = app_data_dir.join(COVERS_DIR_NAME);
22
23 if !covers_dir.exists() {
25 fs::create_dir_all(&covers_dir).map_err(|e| AppError::IoError(e.to_string()))?;
26 }
27
28 Ok(covers_dir)
29}
30
31#[tauri::command]
35pub async fn cache_cover_image(
36 app: AppHandle,
37 url: String,
38 game_id: String,
39) -> Result<String, AppError> {
40 let covers_dir = get_covers_dir(&app)?;
42 let file_name = format!("{}.jpg", game_id);
44 let file_path = covers_dir.join(&file_name);
45
46 if file_path.exists() {
48 return Ok(file_path.to_string_lossy().to_string());
49 }
50
51 let response = reqwest::get(&url)
54 .await
55 .map_err(|e| AppError::NetworkError(e.to_string()))?;
56
57 let bytes = response
58 .bytes()
59 .await
60 .map_err(|e| AppError::NetworkError(e.to_string()))?;
61
62 fs::write(&file_path, bytes).map_err(|e| AppError::IoError(e.to_string()))?;
64
65 Ok(file_path.to_string_lossy().to_string())
66}
67
68#[tauri::command]
72pub fn check_local_cover(app: AppHandle, game_id: String) -> Option<String> {
73 let covers_dir = get_covers_dir(&app).ok()?;
74 let path = covers_dir.join(format!("{}{}", game_id, COVER_IMAGE_EXTENSION));
75
76 if path.exists() {
77 Some(path.to_string_lossy().to_string())
78 } else {
79 None
80 }
81}
82
83#[tauri::command]
85pub fn clear_cover_cache(app: AppHandle) -> Result<String, AppError> {
86 let covers_dir = get_covers_dir(&app)?;
87
88 if covers_dir.exists() {
90 fs::remove_dir_all(&covers_dir).map_err(|e| AppError::IoError(e.to_string()))?;
91 fs::create_dir_all(&covers_dir).map_err(|e| AppError::IoError(e.to_string()))?;
92 }
93
94 Ok("Cache de imagens limpo com sucesso.".to_string())
95}