1use std::collections::HashSet;
4use std::time::Duration;
5
6use reqwest::{Client, StatusCode};
7use thiserror::Error;
8use url::Url;
9
10use crate::{parser, types::{CatalogueHoldings, CatalogueItem, CatalogueSearchResult, Library}};
11
12const OPAC_URL: &str = "https://rabel.jcyl.es/cgi-bin/abnetopac2";
13const SUBCATALOG: &str = "SAL/BPSA";
14const MAX_RESPONSE_BYTES: usize = 5 * 1024 * 1024;
15
16#[derive(Debug, Error)]
17pub enum RabelError {
18 #[error("RABEL request failed: {0}")]
19 Request(#[from] reqwest::Error),
20 #[error("RABEL returned HTTP {0}")]
21 Http(StatusCode),
22 #[error("unexpected RABEL response: {0}")]
23 Parse(String),
24 #[error("invalid record reference")]
25 InvalidRecordReference,
26}
27
28pub struct RabelClient {
29 http: Client,
30 opac_url: Url,
31 subcatalog: String,
32}
33
34impl RabelClient {
35 pub fn new() -> Result<Self, reqwest::Error> {
36 Self::with_endpoint(Url::parse(OPAC_URL).expect("valid OPAC URL"), SUBCATALOG)
37 }
38
39 pub fn for_subcatalog(subcatalog: &str) -> Result<Self, RabelError> {
40 if subcatalog.trim().is_empty() {
41 return Err(RabelError::Parse("subcatalog must not be empty".into()));
42 }
43 Self::with_endpoint(Url::parse(OPAC_URL).expect("valid OPAC URL"), subcatalog)
44 .map_err(RabelError::Request)
45 }
46
47 fn with_endpoint(opac_url: Url, subcatalog: &str) -> Result<Self, reqwest::Error> {
48 let http = Client::builder().cookie_store(true).timeout(Duration::from_secs(20))
49 .user_agent(concat!("eme-rabel/", env!("CARGO_PKG_VERSION"))).build()?;
50 Ok(Self { http, opac_url, subcatalog: subcatalog.to_owned() })
51 }
52
53 async fn read_html(&self, url: Url) -> Result<(Url, String), RabelError> {
54 let response = self.http.get(url).send().await?;
55 if !response.status().is_success() { return Err(RabelError::Http(response.status())); }
56 let final_url = response.url().clone();
57 let html = response.text().await?;
58 if html.len() > MAX_RESPONSE_BYTES { return Err(RabelError::Parse("response exceeds 5 MiB limit".into())); }
59 Ok((final_url, html))
60 }
61
62 async fn search_page(&self, query: &str) -> Result<(Url, String), RabelError> {
63 let response = self.http.get(self.opac_url.clone()).send().await?;
64 if !response.status().is_success() { return Err(RabelError::Http(response.status())); }
65 let bootstrap_url = response.url().clone();
66 let bootstrap_html = response.text().await?;
67 let target = parser::meta_refresh_target(&bootstrap_html)
68 .ok_or_else(|| RabelError::Parse("search bootstrap did not contain a session URL".into()))?;
69 let session_root = bootstrap_url.join(&target)
70 .map_err(|error| RabelError::Parse(format!("invalid session URL: {error}")))?;
71 let (landing_url, landing_html) = self.read_html(session_root).await?;
72 let mut search_url = parser::session_action(&landing_html, &landing_url)
73 .ok_or_else(|| RabelError::Parse(format!("RABEL landing page did not expose a session form action; {}",
74 parser::search_page_diagnostic(&landing_html, &landing_url))))?;
75 search_url.query_pairs_mut().append_pair("SUBC", &self.subcatalog)
76 .append_pair("ACC", "DOSEARCH").append_pair("xsqf01", query);
77 self.read_html(search_url).await
78 }
79
80 pub async fn search_raw(&self, query: &str) -> Result<String, RabelError> {
82 if query.trim().is_empty() { return Err(RabelError::Parse("query must not be empty".into())); }
83 self.search_page(query).await.map(|(_, html)| html)
84 }
85
86 pub async fn get_item_raw(&self, record_ref: &str) -> Result<String, RabelError> {
88 let url = self.validate_record_ref(record_ref)?;
89 self.read_html(url).await.map(|(_, html)| html)
90 }
91
92 pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<CatalogueSearchResult>, RabelError> {
93 if query.trim().is_empty() { return Err(RabelError::Parse("query must not be empty".into())); }
94 if !(1..=20).contains(&limit) { return Err(RabelError::Parse("limit must be between 1 and 20".into())); }
95
96 let fallbacks = fallback_search_queries(query);
97 match self.search_once(query).await {
98 Ok(results) if !results.is_empty() => Ok(results.into_iter().take(limit).collect()),
99 first_attempt => {
100 let mut last_error = match first_attempt {
101 Err(error) => Some(error),
102 Ok(_) => None,
103 };
104 let mut combined = Vec::new();
105 let mut seen = HashSet::new();
106
107 for fallback in fallbacks {
108 match self.search_once(&fallback).await {
109 Ok(results) => {
110 for result in results {
111 if seen.insert(result.record_ref.clone()) {
112 combined.push(result);
113 if combined.len() >= limit { break; }
114 }
115 }
116 }
117 Err(error) => last_error = Some(error),
118 }
119 if combined.len() >= limit { break; }
120 }
121
122 if !combined.is_empty() { return Ok(combined); }
123 if let Some(error) = last_error { return Err(error); }
124 Ok(Vec::new())
125 }
126 }
127 }
128
129 async fn search_once(&self, query: &str) -> Result<Vec<CatalogueSearchResult>, RabelError> {
130 let (session_url, html) = self.search_page(query).await?;
131 parser::search_results(&html, &session_url)
132 }
133
134 pub async fn get_item(&self, record_ref: &str) -> Result<CatalogueItem, RabelError> {
135 let url = self.validate_record_ref(record_ref)?;
136 let (_, html) = self.read_html(url).await?;
137 parser::record(&html)
138 }
139
140 pub async fn get_holdings(&self, record_ref: &str) -> Result<CatalogueHoldings, RabelError> {
142 let url = self.validate_record_ref(record_ref)?;
143 let (_, html) = self.read_html(url).await?;
144 Ok(CatalogueHoldings {
145 copies: parser::holdings(&html),
146 checked_at: chrono::Utc::now(),
147 })
148 }
149
150 pub async fn libraries(&self) -> Result<Vec<Library>, RabelError> {
151 let mut url = self.opac_url.clone();
152 url.query_pairs_mut().append_pair("SUBC", &self.subcatalog);
153 let response = self.http.get(url).send().await?;
154 if !response.status().is_success() { return Err(RabelError::Http(response.status())); }
155 let bootstrap_url = response.url().clone();
156 let bootstrap_html = response.text().await?;
157 if let Ok(libraries) = parser::libraries(&bootstrap_html) { return Ok(libraries); }
158 let target = parser::meta_refresh_target(&bootstrap_html)
159 .ok_or_else(|| RabelError::Parse("library selector not found in RABEL bootstrap page; no session URL to inspect".into()))?;
160 let session_url = bootstrap_url.join(&target)
161 .map_err(|error| RabelError::Parse(format!("invalid session URL: {error}")))?;
162 let (_, html) = self.read_html(session_url).await?;
163 parser::libraries(&html)
164 }
165
166 fn validate_record_ref(&self, value: &str) -> Result<Url, RabelError> {
167 let url = self.opac_url.join(value).map_err(|_| RabelError::InvalidRecordReference)?;
168 if url.scheme() != "https" || url.host_str() != self.opac_url.host_str()
169 || !url.path().starts_with("/cgi-bin/abnetopac2/")
170 || url.query_pairs().all(|(key, _)| key != "ACC") {
171 return Err(RabelError::InvalidRecordReference);
172 }
173 Ok(url)
174 }
175}
176
177fn fallback_search_queries(query: &str) -> Vec<String> {
178 const STOP_WORDS: &[&str] = &[
179 "a", "al", "con", "como", "de", "del", "el", "en", "la", "las",
180 "lo", "los", "para", "por", "un", "una", "unas", "unos", "y",
181 ];
182 let terms = query.split(|character: char| !character.is_alphanumeric())
183 .filter(|term| !term.is_empty())
184 .filter(|term| !STOP_WORDS.contains(&term.to_lowercase().as_str()))
185 .collect::<Vec<_>>();
186 let mut candidates = Vec::new();
187 if terms.len() >= 2 { candidates.push(terms.join(" ")); }
188 let mut individual = terms.into_iter().filter(|term| term.chars().count() >= 4).collect::<Vec<_>>();
189 individual.sort_by_key(|term| std::cmp::Reverse(term.chars().count()));
190 for term in individual {
191 if !candidates.iter().any(|candidate| candidate.eq_ignore_ascii_case(term)) {
192 candidates.push(term.to_owned());
193 }
194 }
195 candidates
196}
197
198#[cfg(test)]
199mod search_query_tests {
200 use super::fallback_search_queries;
201
202 #[test]
203 fn removes_spanish_stop_words_and_adds_single_term_fallbacks() {
204 assert_eq!(fallback_search_queries("La trampa de la diversidad"),
205 vec!["trampa diversidad", "diversidad", "trampa"]);
206 }
207
208 #[test]
209 fn does_not_create_a_fallback_for_stop_words_only() {
210 assert!(fallback_search_queries("la de y").is_empty());
211 }
212
213 #[test]
214 fn keeps_short_title_terms_out_of_broad_fallbacks() {
215 assert_eq!(fallback_search_queries("El sol"), Vec::<String>::new());
216 }
217}