use std::fmt;
use std::ops::Not;
use chrono::{DateTime, Utc};
use reqwest::Method;
use reqwest::header::{CONTENT_TYPE, HeaderMap};
use serde::{Deserialize, Serialize, Serializer};
use crate::client::{self, with_json};
use crate::error::{Error, transport};
use crate::time_portal::TimePortal;
use crate::time_portal::entities::TypedEntity;
const SEARCH: &str = "/search";
const FETCH: &str = "/fetch";
const MEMENTO_DATETIME: &str = "memento-datetime";
const FETCH_STATUS_CODE: &str = "x-fetch-status-code";
const FETCH_STATUS_MESSAGE: &str = "x-fetch-status-message";
const NO_SITE: u16 = 0;
const UNREAD_MESSAGE: &str = "The page could not be read.";
const PAGE_FORMAT: &str = "page";
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct SearchRequest {
pub query: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub num_results: Option<u32>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub domains: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub exclude_domains: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub languages: Vec<String>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "optional_instant"
)]
pub published_after: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub categories: Vec<Category>,
#[serde(skip_serializing_if = "Not::not")]
pub include_text: bool,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl SearchRequest {
pub fn new(query: impl Into<String>) -> Self {
SearchRequest {
query: query.into(),
num_results: None,
domains: Vec::new(),
exclude_domains: Vec::new(),
languages: Vec::new(),
published_after: None,
categories: Vec::new(),
include_text: false,
extra: serde_json::Map::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Category {
News,
Finance,
Legal,
Publications,
Companies,
People,
Maps,
#[serde(untagged)]
Other(String),
}
fn optional_instant<S: Serializer>(at: &Option<DateTime<Utc>>, s: S) -> Result<S::Ok, S::Error> {
match at {
Some(at) => s.serialize_str(&client::instant(*at)),
None => s.serialize_none(),
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SearchResponse {
pub as_of: String,
pub request_id: String,
pub results: Vec<SearchResult>,
#[serde(default)]
pub entities: Vec<Entity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SearchResult {
pub title: String,
pub url: String,
pub snippet: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default)]
pub published_at: Option<String>,
#[serde(default)]
pub domain: Option<String>,
#[serde(default)]
pub language: Option<String>,
#[serde(default)]
pub entity: Option<Entity>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct FetchRequest {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_characters: Option<u32>,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl FetchRequest {
pub fn new(url: impl Into<String>) -> Self {
FetchRequest {
url: url.into(),
max_characters: None,
extra: serde_json::Map::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FetchResponse {
pub as_of: String,
pub request_id: String,
#[serde(default)]
pub status: PageStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page_error: Option<PageError>,
#[serde(default)]
pub id: Option<String>,
pub url: String,
pub final_url: String,
pub title: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub author: Option<String>,
#[serde(default)]
pub published_at: Option<String>,
#[serde(default)]
pub language: Option<String>,
pub content: String,
pub truncated: bool,
#[serde(default)]
pub entity: Option<Entity>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PageStatus {
#[default]
Success,
Error,
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PageError {
#[serde(default)]
pub http_status_code: Option<u16>,
pub message: String,
}
impl fmt::Display for PageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)?;
match self.http_status_code {
Some(code) => write!(f, " (HTTP {code})"),
None => Ok(()),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Entity {
pub id: String,
#[serde(rename = "type")]
pub kind: String,
pub schema_version: u32,
pub updated_at: String,
pub properties: serde_json::Value,
}
impl Entity {
pub fn typed(&self) -> Result<TypedEntity, serde_json::Error> {
TypedEntity::read(&self.kind, self.schema_version, &self.properties)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Document {
pub status: PageStatus,
pub page_error: Option<PageError>,
pub content_type: Option<String>,
pub memento_datetime: Option<String>,
pub body: Vec<u8>,
}
fn header(headers: &HeaderMap, name: &str) -> Option<String> {
Some(headers.get(name)?.to_str().ok()?.to_owned())
}
fn page_outcome(headers: &HeaderMap) -> (PageStatus, Option<PageError>) {
let Some(code) = header(headers, FETCH_STATUS_CODE) else {
return (PageStatus::Success, None);
};
let Ok(code) = code.trim().parse::<u16>() else {
return (PageStatus::Unknown, None);
};
if (200..300).contains(&code) {
return (PageStatus::Success, None);
}
let error = PageError {
http_status_code: (code != NO_SITE).then_some(code),
message: header(headers, FETCH_STATUS_MESSAGE).unwrap_or_else(|| UNREAD_MESSAGE.into()),
};
(PageStatus::Error, Some(error))
}
#[derive(Serialize)]
struct PageRequest<'a> {
url: &'a str,
format: &'static str,
}
impl TimePortal {
pub async fn search(&self, request: &SearchRequest) -> Result<SearchResponse, Error> {
let http = with_json(self.held(Method::POST, SEARCH), request)?;
self.client.json(http).await
}
pub async fn fetch(&self, request: &FetchRequest) -> Result<FetchResponse, Error> {
let http = with_json(self.held(Method::POST, FETCH), request)?;
self.client.json(http).await
}
pub async fn page(&self, url: &str) -> Result<Document, Error> {
let body = PageRequest {
url,
format: PAGE_FORMAT,
};
let http = with_json(self.held(Method::POST, FETCH), &body)?;
let resp = self.client.send(http).await?;
let (status, page_error) = page_outcome(resp.headers());
Ok(Document {
status,
page_error,
content_type: header(resp.headers(), CONTENT_TYPE.as_str()),
memento_datetime: header(resp.headers(), MEMENTO_DATETIME),
body: resp.bytes().await.map_err(transport)?.into(),
})
}
}