game_manager_lib/services/integration/
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> {
151 let identifier = if query.chars().all(char::is_numeric) {
152 query
153 } else {
154 query
155 .to_lowercase()
156 .replace(" ", "-")
157 .replace(":", "")
158 .replace("'", "")
159 .replace("&", "")
160 .replace(".", "")
161 };
162
163 let url = format!(
164 "https://api.rawg.io/api/games/{}?key={}",
165 identifier, api_key
166 );
167
168 let res = HTTP_CLIENT
169 .get(&url)
170 .send()
171 .await
172 .map_err(|e| e.to_string())?;
173
174 if res.status().is_success() {
175 let details: GameDetails = res.json().await.map_err(|e| e.to_string())?;
176 Ok(details)
177 } else if res.status().as_u16() == 404 {
178 Err("Jogo não encontrado na RAWG".into())
179 } else {
180 Err(format!("Erro RAWG Details: {}", res.status()))
181 }
182}
183
184pub async fn fetch_trending_games(app: &AppHandle, api_key: &str) -> Result<Vec<RawgGame>, String> {
189 let current_year = chrono::Utc::now().year();
190 let last_year = current_year - 1;
191 let cache_key = "rawg_list_trending";
192
193 let url = format!(
194 "https://api.rawg.io/api/games?key={}&dates={}-01-01,{}-12-31&ordering=-added&page_size={}",
195 api_key, last_year, current_year, RAWG_TRENDING_PAGE_SIZE
196 );
197
198 match HTTP_CLIENT.get(&url).send().await {
200 Ok(res) => {
201 if res.status().is_success() {
202 let data: RawgResponse = res.json().await.map_err(|e| e.to_string())?;
203
204 if let Ok(conn) = app.state::<AppState>().cache_db.lock() {
206 if let Ok(json) = serde_json::to_string(&data.results) {
207 let _ = cache::save_cached_api_data(&conn, "rawg", cache_key, &json);
208 }
209 }
210
211 return Ok(data.results);
212 }
213 }
214 Err(_) => {
215 }
217 }
218
219 if let Ok(conn) = app.state::<AppState>().cache_db.lock() {
221 if let Some(payload) = cache::get_stale_api_data(&conn, "rawg", cache_key) {
222 if let Ok(cached_games) = serde_json::from_str::<Vec<RawgGame>>(&payload) {
223 return Ok(cached_games);
224 }
225 }
226 }
227
228 Err("Não foi possível carregar os jogos em alta (sem conexão e sem cache).".to_string())
229}
230
231pub async fn fetch_upcoming_games(app: &AppHandle, api_key: &str) -> Result<Vec<RawgGame>, String> {
236 let current_date = chrono::Utc::now();
237 let next_year = current_date.year() + 1;
238 let date_start = current_date.format("%Y-%m-%d").to_string();
239 let date_end = format!("{}-12-31", next_year);
240 let cache_key = "rawg_list_upcoming";
241
242 let url = format!(
243 "https://api.rawg.io/api/games?key={}&dates={},{}&ordering=-added&page_size={}",
244 api_key, date_start, date_end, RAWG_UPCOMING_PAGE_SIZE
245 );
246
247 if let Ok(res) = HTTP_CLIENT.get(&url).send().await {
249 if res.status().is_success() {
250 let data: RawgResponse = res.json().await.map_err(|e| e.to_string())?;
251
252 if let Ok(conn) = app.state::<AppState>().cache_db.lock() {
254 if let Ok(json) = serde_json::to_string(&data.results) {
255 let _ = cache::save_cached_api_data(&conn, "rawg", cache_key, &json);
256 }
257 }
258
259 return Ok(data.results);
260 }
261 }
262
263 if let Ok(conn) = app.state::<AppState>().cache_db.lock() {
265 if let Some(payload) = cache::get_stale_api_data(&conn, "rawg", cache_key) {
266 if let Ok(cached_games) = serde_json::from_str::<Vec<RawgGame>>(&payload) {
267 return Ok(cached_games);
268 }
269 }
270 }
271
272 Err("Não foi possível carregar lançamentos (sem conexão e sem cache).".to_string())
273}