game_manager_lib\services/
rawg.rs1use crate::constants::{RAWG_SEARCH_PAGE_SIZE, RAWG_TRENDING_PAGE_SIZE, RAWG_UPCOMING_PAGE_SIZE};
10use crate::database::AppState;
11use crate::services::cache;
12use crate::utils::http_client::HTTP_CLIENT;
13use chrono::Datelike;
14use serde::{Deserialize, Serialize};
15use tauri::{AppHandle, Manager};
16
17#[derive(Debug, Serialize, Deserialize)]
20pub struct RawgTag {
21 pub id: i32,
22 pub name: String,
23 pub slug: String,
24 pub language: Option<String>,
25 pub games_count: i32,
26 pub image_background: Option<String>,
27}
28#[derive(Debug, Serialize, Deserialize)]
29pub struct RawgDeveloper {
30 pub id: i32,
31 pub name: String,
32 pub slug: String,
33}
34#[derive(Debug, Serialize, Deserialize)]
35pub struct RawgPublisher {
36 pub id: i32,
37 pub name: String,
38 pub slug: String,
39}
40#[derive(Debug, Deserialize, Serialize)]
41pub struct RawgGenre {
42 pub name: String,
43}
44
45#[derive(Debug, Serialize, Deserialize)]
46pub struct EsrbRating {
47 pub id: Option<i32>,
48 pub name: String,
49 pub slug: Option<String>,
50}
51
52#[derive(Debug, Serialize, Deserialize)]
54pub struct StoreInfo {
55 pub id: i32,
56 pub name: String,
57 pub slug: String,
58}
59
60#[derive(Debug, Serialize, Deserialize)]
62pub struct StoreWrapper {
63 pub id: i32,
64 pub url: String,
65 pub store: StoreInfo,
66}
67
68#[derive(Debug, Deserialize, Serialize)]
70struct RawgResponse {
71 results: Vec<RawgGame>,
72}
73
74#[derive(Debug, Deserialize, Serialize)]
76pub struct RawgGame {
77 pub id: u32,
78 pub name: String,
79 #[serde(rename(deserialize = "background_image", serialize = "backgroundImage"))]
80 pub background_image: Option<String>,
81 pub rating: f32,
82 pub released: Option<String>,
83 pub genres: Vec<RawgGenre>,
84 #[serde(default)]
85 pub tags: Vec<RawgTag>,
86 pub slug: String,
87}
88
89#[derive(Debug, Serialize, Deserialize)]
93pub struct GameDetails {
94 pub id: i32,
95 pub name: String,
96 #[serde(rename(deserialize = "description_raw", serialize = "descriptionRaw"))]
97 pub description_raw: Option<String>,
98 pub metacritic: Option<i32>,
99 pub website: Option<String>,
100 pub released: Option<String>,
101 pub background_image: Option<String>,
102 #[serde(default)]
103 pub genres: Vec<RawgGenre>,
104 #[serde(default)]
105 pub tags: Vec<RawgTag>,
106 #[serde(default)]
107 pub developers: Vec<RawgDeveloper>,
108 #[serde(default)]
109 pub publishers: Vec<RawgPublisher>,
110 #[serde(default)]
111 pub reddit_url: Option<String>,
112 #[serde(default)]
113 pub metacritic_url: Option<String>,
114 #[serde(default)]
115 pub stores: Vec<StoreWrapper>,
116 #[serde(default)]
117 pub esrb_rating: Option<EsrbRating>,
118}
119
120pub async fn search_games(api_key: &str, query: &str) -> Result<Vec<RawgGame>, String> {
126 let url = format!(
127 "https://api.rawg.io/api/games?key={}&search={}&page_size={}",
128 api_key,
129 urlencoding::encode(query),
130 RAWG_SEARCH_PAGE_SIZE
131 );
132
133 let res = HTTP_CLIENT
134 .get(&url)
135 .send()
136 .await
137 .map_err(|e| e.to_string())?;
138
139 if !res.status().is_success() {
140 return Err(format!("Erro RAWG Search: {}", res.status()));
141 }
142
143 let data: RawgResponse = res.json().await.map_err(|e| e.to_string())?;
144 Ok(data.results)
145}
146
147pub async fn fetch_game_details(api_key: &str, query: String) -> Result<GameDetails, String> {
152 let identifier = if query.chars().all(char::is_numeric) {
153 query
154 } else {
155 query
156 .to_lowercase()
157 .replace(" ", "-")
158 .replace(":", "")
159 .replace("'", "")
160 .replace("&", "")
161 .replace(".", "")
162 };
163
164 let url = format!(
165 "https://api.rawg.io/api/games/{}?key={}",
166 identifier, api_key
167 );
168
169 let res = HTTP_CLIENT
170 .get(&url)
171 .send()
172 .await
173 .map_err(|e| e.to_string())?;
174
175 if res.status().is_success() {
176 let details: GameDetails = res.json().await.map_err(|e| e.to_string())?;
177 Ok(details)
178 } else if res.status().as_u16() == 404 {
179 Err("Jogo não encontrado na RAWG".into())
180 } else {
181 Err(format!("Erro RAWG Details: {}", res.status()))
182 }
183}
184
185pub async fn fetch_trending_games(app: &AppHandle, api_key: &str) -> Result<Vec<RawgGame>, String> {
190 let current_year = chrono::Utc::now().year();
191 let last_year = current_year - 1;
192 let cache_key = "rawg_list_trending";
193
194 let url = format!(
195 "https://api.rawg.io/api/games?key={}&dates={}-01-01,{}-12-31&ordering=-added&page_size={}",
196 api_key, last_year, current_year, RAWG_TRENDING_PAGE_SIZE
197 );
198
199 match HTTP_CLIENT.get(&url).send().await {
201 Ok(res) => {
202 if res.status().is_success() {
203 let data: RawgResponse = res.json().await.map_err(|e| e.to_string())?;
204
205 if let Ok(conn) = app.state::<AppState>().metadata_db.lock() {
207 if let Ok(json) = serde_json::to_string(&data.results) {
208 let _ = cache::save_cached_api_data(&conn, "rawg", cache_key, &json);
209 }
210 }
211
212 return Ok(data.results);
213 }
214 }
215 Err(_) => {
216 }
218 }
219
220 if let Ok(conn) = app.state::<AppState>().metadata_db.lock() {
222 if let Some(payload) = cache::get_stale_api_data(&conn, "rawg", cache_key) {
223 if let Ok(cached_games) = serde_json::from_str::<Vec<RawgGame>>(&payload) {
224 return Ok(cached_games);
225 }
226 }
227 }
228
229 Err("Não foi possível carregar os jogos em alta (sem conexão e sem cache).".to_string())
230}
231
232pub async fn fetch_upcoming_games(app: &AppHandle, api_key: &str) -> Result<Vec<RawgGame>, String> {
237 let current_date = chrono::Utc::now();
238 let next_year = current_date.year() + 1;
239 let date_start = current_date.format("%Y-%m-%d").to_string();
240 let date_end = format!("{}-12-31", next_year);
241 let cache_key = "rawg_list_upcoming";
242
243 let url = format!(
244 "https://api.rawg.io/api/games?key={}&dates={},{}&ordering=-added&page_size={}",
245 api_key, date_start, date_end, RAWG_UPCOMING_PAGE_SIZE
246 );
247
248 match HTTP_CLIENT.get(&url).send().await {
250 Ok(res) => {
251 if res.status().is_success() {
252 let data: RawgResponse = res.json().await.map_err(|e| e.to_string())?;
253
254 if let Ok(conn) = app.state::<AppState>().metadata_db.lock() {
256 if let Ok(json) = serde_json::to_string(&data.results) {
257 let _ = cache::save_cached_api_data(&conn, "rawg", cache_key, &json);
258 }
259 }
260
261 return Ok(data.results);
262 }
263 }
264 Err(_) => {} }
266
267 if let Ok(conn) = app.state::<AppState>().metadata_db.lock() {
269 if let Some(payload) = cache::get_stale_api_data(&conn, "rawg", cache_key) {
270 if let Ok(cached_games) = serde_json::from_str::<Vec<RawgGame>>(&payload) {
271 return Ok(cached_games);
272 }
273 }
274 }
275
276 Err("Não foi possível carregar lançamentos (sem conexão e sem cache).".to_string())
277}