1use reqwest::Url;
2use std::path::Path;
3use std::time::Instant;
4use tokio::io::AsyncWriteExt as _;
5
6use crate::config::normalize_romm_origin;
7use crate::core::interrupt::CancelledByUser;
8use crate::error::{ApiError, DownloadError};
9
10use super::response::{api_error_from_response, read_error_response_text};
11use super::RommClient;
12
13impl RommClient {
14 pub async fn download_rom<F>(
16 &self,
17 rom_id: u64,
18 save_path: &Path,
19 mut on_progress: F,
20 ) -> Result<(), DownloadError>
21 where
22 F: FnMut(u64, u64) + Send,
23 {
24 self.download_rom_with_cancel(rom_id, save_path, |_, _| false, &mut on_progress)
25 .await
26 }
27
28 pub async fn download_rom_with_cancel<F, C>(
29 &self,
30 rom_id: u64,
31 save_path: &Path,
32 is_cancelled: C,
33 on_progress: &mut F,
34 ) -> Result<(), DownloadError>
35 where
36 F: FnMut(u64, u64) + Send,
37 C: FnMut(u64, u64) -> bool + Send,
38 {
39 let filename = filename_hint(save_path);
40 let query = vec![
41 ("rom_ids".to_string(), rom_id.to_string()),
42 ("filename".to_string(), filename),
43 ];
44 self.download_url_with_query_with_cancel(
45 "/api/roms/download",
46 &query,
47 save_path,
48 is_cancelled,
49 on_progress,
50 )
51 .await
52 }
53
54 pub async fn download_url_with_cancel<F, C>(
56 &self,
57 url: &str,
58 save_path: &Path,
59 is_cancelled: C,
60 on_progress: &mut F,
61 ) -> Result<(), DownloadError>
62 where
63 F: FnMut(u64, u64) + Send,
64 C: FnMut(u64, u64) -> bool + Send,
65 {
66 self.download_url_with_query_with_cancel(url, &[], save_path, is_cancelled, on_progress)
67 .await
68 }
69
70 pub async fn download_url_with_query_with_cancel<F, C>(
72 &self,
73 url: &str,
74 query: &[(String, String)],
75 save_path: &Path,
76 mut is_cancelled: C,
77 on_progress: &mut F,
78 ) -> Result<(), DownloadError>
79 where
80 F: FnMut(u64, u64) + Send,
81 C: FnMut(u64, u64) -> bool + Send,
82 {
83 let url = self.resolve_download_url(url)?;
84 let filename = filename_hint(save_path);
85 let mut headers = self.build_headers()?;
86
87 let existing_len = tokio::fs::metadata(save_path)
88 .await
89 .map(|m| m.len())
90 .unwrap_or(0);
91
92 if existing_len > 0 {
93 let range = format!("bytes={existing_len}-");
94 if let Ok(v) = reqwest::header::HeaderValue::from_str(&range) {
95 headers.insert(reqwest::header::RANGE, v);
96 }
97 }
98
99 if let Some(parent) = save_path.parent() {
100 tokio::fs::create_dir_all(parent)
101 .await
102 .map_err(|e| DownloadError::IoContext {
103 context: format!("create download parent dir {parent:?}"),
104 source: e,
105 })?;
106 }
107
108 let t0 = Instant::now();
109 let mut resp = self
110 .http
111 .get(&url)
112 .headers(headers)
113 .query(query)
114 .send()
115 .await?;
116
117 let status = resp.status();
118 if self.verbose {
119 tracing::info!(
120 "[romm-cli] GET {} filename={:?} -> {} ({}ms)",
121 crate::log_redact::redact_url_for_log(&url),
122 filename,
123 status.as_u16(),
124 t0.elapsed().as_millis()
125 );
126 }
127 if !status.is_success() {
128 let body = read_error_response_text(resp).await;
129 return Err(DownloadError::Api(api_error_from_response(status, &body)));
130 }
131
132 let (mut received, total, mut file) = if status == reqwest::StatusCode::PARTIAL_CONTENT {
133 let remaining = resp.content_length().unwrap_or(0);
134 let total = existing_len + remaining;
135 let file = tokio::fs::OpenOptions::new()
136 .append(true)
137 .open(save_path)
138 .await
139 .map_err(|e| DownloadError::IoContext {
140 context: format!("open file for append {save_path:?}"),
141 source: e,
142 })?;
143 (existing_len, total, file)
144 } else {
145 let total = resp.content_length().unwrap_or(0);
146 let file =
147 tokio::fs::File::create(save_path)
148 .await
149 .map_err(|e| DownloadError::IoContext {
150 context: format!("create file {save_path:?}"),
151 source: e,
152 })?;
153 (0u64, total, file)
154 };
155
156 if is_cancelled(received, total) {
157 return Err(DownloadError::Cancelled(CancelledByUser));
158 }
159
160 while let Some(chunk) = resp.chunk().await? {
161 if is_cancelled(received, total) {
162 return Err(DownloadError::Cancelled(CancelledByUser));
163 }
164 file.write_all(&chunk)
165 .await
166 .map_err(|e| DownloadError::IoContext {
167 context: format!("write chunk {save_path:?}"),
168 source: e,
169 })?;
170 received += chunk.len() as u64;
171 on_progress(received, total);
172 }
173
174 Ok(())
175 }
176
177 fn resolve_download_url(&self, url: &str) -> Result<String, DownloadError> {
178 let trimmed = url.trim();
179 if trimmed.is_empty() {
180 return Err(DownloadError::Api(ApiError::UnexpectedResponse(
181 "download URL cannot be empty".into(),
182 )));
183 }
184 if let Ok(parsed) = Url::parse(trimmed) {
185 return Ok(parsed.to_string());
186 }
187
188 let base = Url::parse(&normalize_romm_origin(&self.base_url)).map_err(|e| {
189 DownloadError::Api(ApiError::UnexpectedResponse(format!(
190 "invalid RomM base URL: {e}"
191 )))
192 })?;
193 let joined = base.join(trimmed).map_err(|e| {
194 DownloadError::Api(ApiError::UnexpectedResponse(format!(
195 "could not resolve download URL {trimmed:?}: {e}"
196 )))
197 })?;
198 Ok(joined.to_string())
199 }
200}
201
202fn filename_hint(save_path: &Path) -> String {
203 save_path
204 .file_name()
205 .and_then(|n| n.to_str())
206 .unwrap_or("download.bin")
207 .to_string()
208}