Skip to main content

agent_server/api/
books.rs

1//! Authenticated CRUD API for the current user's personal book collection.
2use std::sync::Arc;
3use actix_web::{HttpRequest,HttpResponse,Responder,Scope,delete,get,post,put,web::{self,Data,Json,Path}};
4use agent_storage::{FileUserIdentityStore,UserIdentityStore};
5use books_tool::{BookInput,BookStore,BookStoreError,BookUpdate};
6use rabel_tool::{RabelClient, RabelError};
7use serde::Deserialize;
8pub(super) fn actor(r:&HttpRequest,a:&crate::auth::TelegramAuth,i:&FileUserIdentityStore)->Result<String,HttpResponse>{
9 let owner=a.owner_for_request(r).ok_or_else(||HttpResponse::Unauthorized().finish())?;
10 let subject=owner.strip_prefix("telegram:").filter(|v|!v.is_empty()).ok_or_else(||HttpResponse::Unauthorized().finish())?;
11 let identity=i.find_identity("telegram",subject).map_err(|_|HttpResponse::InternalServerError().finish())?.ok_or_else(||HttpResponse::Unauthorized().finish())?;
12 Ok(identity.user_id.to_string())
13}
14pub(super) fn book_error(e:BookStoreError)->HttpResponse{match e{BookStoreError::NotFound=>HttpResponse::NotFound().finish(),BookStoreError::Invalid(m)=>HttpResponse::BadRequest().body(m),_=>HttpResponse::InternalServerError().finish()}}
15#[derive(Deserialize)]
16struct CatalogueSearchQuery { q: String }
17
18#[get("/catalogue/search")]
19async fn search_catalogue(
20    request: HttpRequest,
21    auth: Data<crate::auth::TelegramAuth>,
22    identities: Data<Arc<FileUserIdentityStore>>,
23    query: web::Query<CatalogueSearchQuery>,
24) -> impl Responder {
25    if let Err(response) = actor(&request, &auth, &identities) { return response; }
26    if query.q.trim().is_empty() { return HttpResponse::BadRequest().body("q must not be empty"); }
27    let client = match RabelClient::new() {
28        Ok(client) => client,
29        Err(_) => return HttpResponse::InternalServerError().finish(),
30    };
31    match client.search(&query.q, 20).await {
32        Ok(results) => HttpResponse::Ok().json(results),
33        Err(error) => {
34            // Keep the response useful without exposing the searched term or
35            // session-scoped OPAC URL (both can appear in reqwest diagnostics).
36            let message = match error {
37                RabelError::Http(status) => format!("RABEL returned HTTP {status}"),
38                RabelError::Request(_) => "Could not connect to RABEL".to_owned(),
39                RabelError::Parse(diagnostic) => format!("RABEL returned an unexpected catalogue response: {diagnostic}"),
40                RabelError::InvalidRecordReference => "RABEL returned an invalid record reference".to_owned(),
41            };
42            tracing::warn!(error = %message, "RABEL catalogue search failed");
43            HttpResponse::BadGateway().body(message)
44        },
45    }
46}
47
48#[post("/{id}/refresh-catalogue")]
49async fn refresh_catalogue(
50    request: HttpRequest,
51    auth: Data<crate::auth::TelegramAuth>,
52    identities: Data<Arc<FileUserIdentityStore>>,
53    store: Data<BookStore>,
54    id: Path<String>,
55) -> impl Responder {
56    let user = match actor(&request, &auth, &identities) {
57        Ok(user) => user,
58        Err(response) => return response,
59    };
60    let book = match store.get(&user, &id).await {
61        Ok(book) => book,
62        Err(error) => return book_error(error),
63    };
64    let client = match RabelClient::new() {
65        Ok(client) => client,
66        Err(_) => return HttpResponse::InternalServerError().finish(),
67    };
68    let query = book.isbn.as_deref().unwrap_or(&book.title);
69    let results = match client.search(query, 20).await {
70        Ok(results) => results,
71        Err(error) => {
72            tracing::warn!(error = %error, book_id = %book.id, "RABEL catalogue refresh search failed");
73            return HttpResponse::BadGateway().body("Could not search RABEL for this book");
74        }
75    };
76
77    let wanted_isbn = book.isbn.as_deref().map(normalize_isbn);
78    let mut matched_items = Vec::new();
79    for result in results {
80        if wanted_isbn.as_ref().is_some_and(|wanted| {
81            result.isbn.as_deref().is_some_and(|candidate| normalize_isbn(candidate) != *wanted)
82        }) {
83            continue;
84        }
85        let item = match client.get_item(&result.record_ref).await {
86            Ok(item) => item,
87            Err(error) => {
88                tracing::debug!(error = %error, "Skipping unreadable RABEL record during refresh");
89                continue;
90            }
91        };
92        let matches = if let Some(wanted) = &wanted_isbn {
93            item.isbn.as_deref().or(result.isbn.as_deref())
94                .is_some_and(|candidate| normalize_isbn(candidate) == *wanted)
95        } else {
96            item.title.as_deref().is_some_and(|title| catalogue_title_matches(&book.title, title))
97        };
98        if matches {
99            matched_items.push(item);
100        }
101    }
102
103    // If the stored ISBN is absent from RABEL's search index or stale, make
104    // one conservative fallback pass and accept only an exact parsed-title match.
105    if matched_items.is_empty() && wanted_isbn.is_some() {
106        if let Ok(fallback_results) = client.search(&book.title, 20).await {
107            for result in fallback_results {
108                let item = match client.get_item(&result.record_ref).await {
109                    Ok(item) => item,
110                    Err(_) => continue,
111                };
112                if item.title.as_deref().is_some_and(|title| catalogue_title_matches(&book.title, title)) {
113                    matched_items.push(item);
114                }
115            }
116        }
117    }
118
119    let item = match matched_items.len() {
120        0 => return HttpResponse::NotFound().body("No exact matching RABEL record was found; collection data was left unchanged"),
121        1 => matched_items.pop().expect("one matched catalogue record"),
122        _ => return HttpResponse::Conflict().body("Multiple RABEL records match this book; collection data was left unchanged"),
123    };
124    let metadata_update = BookUpdate {
125        title: item.title.clone(),
126        authors: Some(item.authors.clone()),
127        isbn: Some(item.isbn.clone()),
128        publisher: Some(item.publisher.clone()),
129        publication_year: Some(item.publication_year),
130        responsibility: Some(item.responsibility.clone()),
131        publication_statement: Some(item.publication_statement.clone()),
132        physical_description: Some(item.physical_description.clone()),
133        series: Some(item.series.clone()),
134        notes: Some(item.notes.clone()),
135        subjects: Some(item.subjects.clone()),
136        ..Default::default()
137    };
138    match store.update(&user, &book.id, metadata_update).await {
139        Ok(updated) => HttpResponse::Ok().json(serde_json::json!({
140            "book": updated,
141            "catalogue_item": item
142        })),
143        Err(error) => book_error(error),
144    }
145}
146
147#[get("/{id}/holdings")]
148async fn holdings(
149    request: HttpRequest,
150    auth: Data<crate::auth::TelegramAuth>,
151    identities: Data<Arc<FileUserIdentityStore>>,
152    store: Data<BookStore>,
153    id: Path<String>,
154) -> impl Responder {
155    let user = match actor(&request, &auth, &identities) {
156        Ok(user) => user,
157        Err(response) => return response,
158    };
159    let book = match store.get(&user, &id).await {
160        Ok(book) => book,
161        Err(error) => return book_error(error),
162    };
163    let selected_libraries = match store.preferred_libraries(&user).await {
164        Ok(selected_libraries) => selected_libraries,
165        Err(store_error) => return book_error(store_error),
166    };
167    let mut library_results = Vec::with_capacity(selected_libraries.len());
168    for (library_id, library_name) in selected_libraries {
169        let client = match RabelClient::for_subcatalog(&library_id) {
170            Ok(client) => client,
171            Err(error) => {
172                library_results.push(serde_json::json!({
173                    "library_id": library_id,
174                    "library_name": library_name,
175                    "status": "error",
176                    "error": error.to_string(),
177                    "copies": []
178                }));
179                continue;
180            }
181        };
182        let query = book.isbn.as_deref().unwrap_or(&book.title);
183        let results = match client.search(query, 20).await {
184            Ok(results) => results,
185            Err(error) => {
186                library_results.push(serde_json::json!({
187                    "library_id": library_id,
188                    "library_name": library_name,
189                    "status": "error",
190                    "error": error.to_string(),
191                    "copies": []
192                }));
193                continue;
194            }
195        };
196        let wanted_isbn = book.isbn.as_deref().map(normalize_isbn);
197        let mut matching_records = wanted_isbn.as_ref().map(|isbn| {
198            results.iter().filter(|result| {
199                result.isbn.as_deref().is_some_and(|candidate| normalize_isbn(candidate) == *isbn)
200            }).cloned().collect::<Vec<_>>()
201        }).unwrap_or_default();
202        if matching_records.is_empty() {
203            // ISBN is preferred, but some catalogue records omit it. Fall back
204            // only to exact normalized title matches, never the first hit.
205            matching_records = results.iter()
206                .filter(|result| catalogue_title_matches(&result.title, &book.title))
207                .cloned().collect();
208        }
209        if matching_records.is_empty() {
210            library_results.push(serde_json::json!({
211                "library_id": library_id,
212                "library_name": library_name,
213                "status": "not_found",
214                "records": []
215            }));
216            continue;
217        }
218
219        // Do not hide ambiguous editions: fetch the full bibliographic record
220        // and copy-level holdings for every exact candidate in this library.
221        let mut records = Vec::with_capacity(matching_records.len());
222        for candidate in matching_records {
223            let item = match client.get_item(&candidate.record_ref).await {
224                Ok(item) => item,
225                Err(error) => {
226                    records.push(serde_json::json!({
227                        "catalogue_title": candidate.title,
228                        "isbn": candidate.isbn,
229                        "status": "record_error",
230                        "error": error.to_string(),
231                        "copies": []
232                    }));
233                    continue;
234                }
235            };
236            // Validate the parsed title too. A search result heading can
237            // include author/responsibility text around the actual title.
238            let title_matches = item.title.as_deref()
239                .is_some_and(|title| catalogue_title_matches(&candidate.title, title)
240                    && catalogue_title_matches(&book.title, title));
241            let isbn_matches = wanted_isbn.as_ref().is_some_and(|wanted| {
242                item.isbn.as_deref().or(candidate.isbn.as_deref())
243                    .is_some_and(|isbn| normalize_isbn(isbn) == *wanted)
244            });
245            if !title_matches && !isbn_matches { continue; }
246
247            match client.get_holdings(&candidate.record_ref).await {
248                Ok(holdings) => records.push(serde_json::json!({
249                    "catalogue_title": item.title,
250                    "authors": item.authors,
251                    "isbn": item.isbn,
252                    "publisher": item.publisher,
253                    "publication_year": item.publication_year,
254                    "publication_statement": item.publication_statement,
255                    "physical_description": item.physical_description,
256                    "series": item.series,
257                    "checked_at": holdings.checked_at,
258                    "copies": holdings.copies
259                })),
260                Err(error) => records.push(serde_json::json!({
261                    "catalogue_title": item.title,
262                    "authors": item.authors,
263                    "isbn": item.isbn,
264                    "publisher": item.publisher,
265                    "publication_year": item.publication_year,
266                    "publication_statement": item.publication_statement,
267                    "physical_description": item.physical_description,
268                    "series": item.series,
269                    "status": "holdings_error",
270                    "error": error.to_string(),
271                    "copies": []
272                })),
273            }
274        }
275        let status = match records.len() {
276            0 => "not_found",
277            1 => "found",
278            _ => "ambiguous",
279        };
280        library_results.push(serde_json::json!({
281            "library_id": library_id,
282            "library_name": library_name,
283            "status": status,
284            "records": records
285        }));
286    }
287    HttpResponse::Ok().json(serde_json::json!({
288        "book_id": book.id,
289        "libraries": library_results
290    }))
291}
292
293fn normalize_isbn(value: &str) -> String {
294    value.chars().filter(|character| character.is_ascii_alphanumeric())
295        .map(|character| character.to_ascii_uppercase()).collect()
296}
297
298fn normalize_title(value: &str) -> String {
299    value.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
300}
301
302/// Search-result link text can prepend the author to the title and append a
303/// responsibility statement. Match the parsed title only as a complete value
304/// or as a suffix of that bibliographic prefix, never as an arbitrary substring.
305fn catalogue_title_matches(search_title: &str, parsed_title: &str) -> bool {
306    let search_prefix = search_title.split(" / ").next().unwrap_or(search_title);
307    let search = normalize_title(search_prefix);
308    let parsed = normalize_title(parsed_title);
309    search == parsed || (parsed.split_whitespace().count() >= 2 && search.ends_with(&format!(" {parsed}")))
310}
311
312#[get("")] async fn list(r:HttpRequest,a:Data<crate::auth::TelegramAuth>,i:Data<Arc<FileUserIdentityStore>>,s:Data<BookStore>)->impl Responder{let u=match actor(&r,&a,&i){Ok(v)=>v,Err(e)=>return e};match s.list(&u).await{Ok(v)=>HttpResponse::Ok().json(v),Err(e)=>book_error(e)}}
313#[post("")] async fn add(r:HttpRequest,a:Data<crate::auth::TelegramAuth>,i:Data<Arc<FileUserIdentityStore>>,s:Data<BookStore>,b:Json<BookInput>)->impl Responder{let u=match actor(&r,&a,&i){Ok(v)=>v,Err(e)=>return e};match s.add(&u,b.into_inner()).await{Ok(v)=>HttpResponse::Created().json(v),Err(e)=>book_error(e)}}
314#[get("/{id}")] async fn get(r:HttpRequest,a:Data<crate::auth::TelegramAuth>,i:Data<Arc<FileUserIdentityStore>>,s:Data<BookStore>,id:Path<String>)->impl Responder{let u=match actor(&r,&a,&i){Ok(v)=>v,Err(e)=>return e};match s.get(&u,&id).await{Ok(v)=>HttpResponse::Ok().json(v),Err(e)=>book_error(e)}}
315#[put("/{id}")] async fn update(r:HttpRequest,a:Data<crate::auth::TelegramAuth>,i:Data<Arc<FileUserIdentityStore>>,s:Data<BookStore>,id:Path<String>,b:Json<BookUpdate>)->impl Responder{let u=match actor(&r,&a,&i){Ok(v)=>v,Err(e)=>return e};match s.update(&u,&id,b.into_inner()).await{Ok(v)=>HttpResponse::Ok().json(v),Err(e)=>book_error(e)}}
316#[delete("/{id}")] async fn remove(r:HttpRequest,a:Data<crate::auth::TelegramAuth>,i:Data<Arc<FileUserIdentityStore>>,s:Data<BookStore>,id:Path<String>)->impl Responder{let u=match actor(&r,&a,&i){Ok(v)=>v,Err(e)=>return e};match s.remove(&u,&id).await{Ok(())=>HttpResponse::NoContent().finish(),Err(e)=>book_error(e)}}
317pub fn books_api()->Scope{web::scope("/books").service(search_catalogue).service(list).service(add).service(refresh_catalogue).service(holdings).service(get).service(update).service(remove)}