uspto_xml 0.2.0

A library for downloading patent and application XML from the USPTO.
Documentation
//! This is an internal module defining the asynchronous [`UsptoClient`]. Its members are exported
//! from the `lib.rs` module.

use std::{fs, path::Path};

use reqwest::Client as ReqwestClient;

use crate::{
  USER_AGENT_STR, USPTO_SEARCH_ENDPOINT, UsptoApiError, get_application_endpoint,
  uspto_data::{FileWrapperResponse, construct_headers, construct_query_params},
};

/// A wrapper for [`reqwest::Client`] that enables downloading patent XML from the USPTO API.
///
/// An API key is required to create a client and make requests to the USPTO API.
pub struct UsptoClient {
  client: ReqwestClient,
}

impl UsptoClient {
  /// Creates a new [`UsptoClient`] with the provided API key.
  ///
  /// Returns [`UsptoApiError`] if the API key is invalid or the client cannot be built.
  ///
  /// # Example
  ///
  /// ```rust,no_run
  /// # use uspto_xml::UsptoClient;
  /// let client = UsptoClient::new("YOUR_API_KEY").unwrap();
  /// ```
  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 })
  }

  /// Downloads the XML for the specified `patent_number` and returns it if successful.
  ///
  /// The `patent_number` must be a U.S. patent number without the country code or punctuation.
  ///
  /// Returns [`UsptoApiError`] if the download fails.
  pub async fn download_patent_xml(&self, patent_number: &str) -> Result<String, UsptoApiError> {
    // Send a request to get the JSON associated with the provided patent number
    let docs_json = self
      .client
      .get(USPTO_SEARCH_ENDPOINT)
      .query(&construct_query_params(patent_number))
      .send()
      .await
      .map_err(UsptoApiError::SendError)?
      .error_for_status()
      .map_err(UsptoApiError::HttpError)?
      .text()
      .await
      .map_err(UsptoApiError::ResponseReadFailed)?;

    self.download_xml_from_json(&docs_json, patent_number).await
  }

  /// Downloads the XML for the specified `patent_number` to `xml_path`.
  ///
  /// The `patent_number` must be a U.S. patent number without the country code or punctuation.
  ///
  /// Returns [`UsptoApiError`] if the download fails or the file cannot be written.
  pub async fn download_patent_xml_to_file<T: AsRef<Path>>(
    &self,
    patent_number: &str,
    xml_path: T,
  ) -> Result<(), UsptoApiError> {
    let xml_text = self.download_patent_xml(patent_number).await?;
    fs::write(xml_path, xml_text).map_err(std::convert::Into::into)
  }

  /// Downloads the XML for the specified `application_number` and returns it if successful.
  ///
  /// The `application_number` must be a U.S. application number (not publication number) without
  /// punctuation.
  ///
  /// Returns [`UsptoApiError`] if the download fails.
  pub async fn download_application_xml(
    &self,
    application_number: &str,
  ) -> Result<String, UsptoApiError> {
    // Send a request to get the JSON associated with the provided application number
    let docs_json = self
      .client
      .get(get_application_endpoint(application_number))
      .send()
      .await
      .map_err(UsptoApiError::SendError)?
      .error_for_status()
      .map_err(UsptoApiError::HttpError)?
      .text()
      .await
      .map_err(UsptoApiError::ResponseReadFailed)?;

    self
      .download_xml_from_json(&docs_json, application_number)
      .await
  }

  /// Downloads the XML for the specified `application_number` to `xml_path`.
  ///
  /// The `application_number` must be a U.S. application number (not publication number) without
  /// punctuation.
  ///
  /// Returns [`UsptoApiError`] if the download fails or the file cannot be written.
  pub async fn download_application_xml_to_file<T: AsRef<Path>>(
    &self,
    application_number: &str,
    xml_path: T,
  ) -> Result<(), UsptoApiError> {
    let xml_text = self.download_application_xml(application_number).await?;
    fs::write(xml_path, xml_text).map_err(std::convert::Into::into)
  }

  /// Internal helper function that parses `docs_json`, extracts the XML URI, and returns it as a
  /// [`String`]. Returns [`Err`] if the parsed response contains no results or if any of the
  /// download operations fail. Returns [`Ok`] if the download succeeeds.
  async fn download_xml_from_json(
    &self,
    docs_json: &str,
    search_input: &str,
  ) -> Result<String, UsptoApiError> {
    // Parse the received JSON and check that it included results
    let parsed: FileWrapperResponse = serde_json::from_str(docs_json)?;
    if parsed.is_empty() {
      return Err(UsptoApiError::NoSearchResults(search_input.to_string()));
    }

    // Extract the URI for the patent XML
    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)?;

    // Request the XML
    self
      .client
      .get(&file_location_uri)
      .send()
      .await
      .map_err(UsptoApiError::SendError)?
      .error_for_status()
      .map_err(UsptoApiError::HttpError)?
      .text()
      .await
      .map_err(UsptoApiError::ResponseReadFailed)
  }
}

/// Downloads the XML for the specified `patent_number` and returns it if successful.
///
/// The `patent_number` must be a U.S. patent number without the country code or punctuation. An API
/// key is required. This key can be obtained from the USPTO and should be kept secret.
///
/// Returns [`UsptoApiError`] if the client creation fails or the download fails.
///
/// This function creates a [`UsptoClient`] for a single download. If multiple downloads are
/// required, creating a single [`UsptoClient`] is more efficient.
pub async fn download_patent_xml(
  patent_number: &str,
  api_key: &str,
) -> Result<String, UsptoApiError> {
  UsptoClient::new(api_key)?
    .download_patent_xml(patent_number)
    .await
}

/// Downloads the XML for the specified `patent_number` to `xml_path`.
///
/// The `patent_number` must be a U.S. patent number without the country code or punctuation. An API
/// key is required. This key can be obtained from the USPTO and should be kept secret.
///
/// Returns [`UsptoApiError`] if the client creation fails, the download fails, or the file cannot
/// be written.
///
/// This function creates a [`UsptoClient`] for a single download. If multiple downloads are
/// required, creating a single [`UsptoClient`] is more efficient.
pub async fn download_patent_xml_to_file<T: AsRef<Path>>(
  patent_number: &str,
  xml_path: T,
  api_key: &str,
) -> Result<(), UsptoApiError> {
  UsptoClient::new(api_key)?
    .download_patent_xml_to_file(patent_number, xml_path)
    .await
}

/// Downloads the XML for the specified `application_number` and returns it if successful.
///
/// The `application_number` must be a U.S. application number (not publication number) without the
/// country code or punctuation. An API key is required. This key can be obtained
/// from the USPTO and should be kept secret.
///
/// Returns [`UsptoApiError`] if the client creation fails or the download fails.
///
/// This function creates a [`UsptoClient`] for a single download. If multiple downloads are
/// required, creating a single [`UsptoClient`] is more efficient.
pub async fn download_application_xml(
  application_number: &str,
  api_key: &str,
) -> Result<String, UsptoApiError> {
  UsptoClient::new(api_key)?
    .download_application_xml(application_number)
    .await
}

/// Downloads the XML for the specified `application_number` to `xml_path`.
///
/// The `application_number` must be a U.S. application number (not publication number) without the
/// country code or punctuation. An API key is required. This key can be obtained
/// from the USPTO and should be kept secret.
///
/// Returns [`UsptoApiError`] if the client creation fails, the download fails, or the file cannot
/// be written.
///
/// This function creates a [`UsptoClient`] for a single download. If multiple downloads are
/// required, creating a single [`UsptoClient`] is more efficient.
pub async fn download_application_xml_to_file<T: AsRef<Path>>(
  application_number: &str,
  xml_path: T,
  api_key: &str,
) -> Result<(), UsptoApiError> {
  UsptoClient::new(api_key)?
    .download_application_xml_to_file(application_number, xml_path)
    .await
}