use std::{fs, path::Path};
use reqwest::blocking::Client as ReqwestClient;
use crate::{
USER_AGENT_STR, USPTO_SEARCH_ENDPOINT, UsptoApiError, get_application_endpoint,
uspto_data::{FileWrapperResponse, construct_headers, construct_query_params},
};
pub struct UsptoClient {
client: ReqwestClient,
}
impl UsptoClient {
pub fn new(api_key: &str) -> Result<Self, UsptoApiError> {
let headers = construct_headers(api_key)?;
let client = ReqwestClient::builder()
.default_headers(headers)
.user_agent(USER_AGENT_STR)
.build()
.map_err(UsptoApiError::ClientBuildError)?;
Ok(Self { client })
}
pub fn download_patent_xml<T: AsRef<Path>>(
&self,
patent_number: &str,
xml_path: T,
) -> Result<(), UsptoApiError> {
let docs_json = self
.client
.get(USPTO_SEARCH_ENDPOINT)
.query(&construct_query_params(patent_number))
.send()
.map_err(UsptoApiError::SendError)?
.error_for_status()
.map_err(UsptoApiError::HttpError)?
.text()
.map_err(UsptoApiError::ResponseReadFailed)?;
self.download_xml_from_json(xml_path, &docs_json, patent_number)
}
pub fn download_application_xml<T: AsRef<Path>>(
&self,
application_number: &str,
xml_path: T,
) -> Result<(), UsptoApiError> {
let docs_json = self
.client
.get(get_application_endpoint(application_number))
.send()
.map_err(UsptoApiError::SendError)?
.error_for_status()
.map_err(UsptoApiError::HttpError)?
.text()
.map_err(UsptoApiError::ResponseReadFailed)?;
self.download_xml_from_json(xml_path, &docs_json, application_number)
}
fn download_xml_from_json<T: AsRef<Path>>(
&self,
xml_path: T,
docs_json: &str,
search_input: &str,
) -> Result<(), UsptoApiError> {
let parsed: FileWrapperResponse = serde_json::from_str(docs_json)?;
if parsed.is_empty() {
return Err(UsptoApiError::NoSearchResults(search_input.to_string()));
}
let file_location_uri = parsed
.patent_file_wrapper_data_bag
.into_iter()
.filter_map(|bag| bag.grant_document_meta_data)
.map(|meta| meta.file_location_uri)
.find(|s| !s.is_empty())
.ok_or_else(|| UsptoApiError::FileUriNotFound)?;
let xml_text = self
.client
.get(&file_location_uri)
.send()
.map_err(UsptoApiError::SendError)?
.error_for_status()
.map_err(UsptoApiError::HttpError)?
.text()
.map_err(UsptoApiError::ResponseReadFailed)?;
fs::write(xml_path, xml_text)?;
Ok(())
}
}
pub fn download_patent_xml<T: AsRef<Path>>(
patent_number: &str,
xml_path: T,
api_key: &str,
) -> Result<(), UsptoApiError> {
UsptoClient::new(api_key)?.download_patent_xml(patent_number, xml_path)
}
pub fn download_application_xml<T: AsRef<Path>>(
application_number: &str,
xml_path: T,
api_key: &str,
) -> Result<(), UsptoApiError> {
UsptoClient::new(api_key)?.download_application_xml(application_number, xml_path)
}