//! Wayback Machine availability lookups (passive, archive.org API).
use anyhow::{Context, Result, bail};
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveHit {
pub url: String,
pub timestamp: String,
pub date: String,
pub status: String,
}
/// `20130919044612` → `2013-09-19`.
pub fn format_timestamp(ts: &str) -> String {
if ts.len() >= 8 && ts.chars().all(|c| c.is_ascii_digit()) {
format!("{}-{}-{}", &ts[0..4], &ts[4..6], &ts[6..8])
} else {
ts.to_string()
}
}
/// Query the availability API for the closest snapshot of `url`.
pub async fn lookup(client: &Client, url: &str) -> Result<Option<ArchiveHit>> {
let api = format!(
"https://archive.org/wayback/available?url={}",
utf8_percent_encode(url, NON_ALPHANUMERIC)
);
let resp = client.get(&api).send().await.context("wayback request")?;
let status = resp.status();
if !status.is_success() {
bail!("wayback API returned HTTP {status}");
}
let text = resp.text().await.context("wayback body")?;
let v: Value = serde_json::from_str(&text).context("wayback JSON")?;
Ok(parse_response(&v))
}
pub fn parse_response(v: &Value) -> Option<ArchiveHit> {
let closest = v.pointer("/archived_snapshots/closest")?;
if closest.get("available").and_then(Value::as_bool) == Some(false) {
return None;
}
let url = closest
.get("url")?
.as_str()?
.replace("http://web.archive.org", "https://web.archive.org");
let ts = closest
.get("timestamp")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
Some(ArchiveHit {
url,
date: format_timestamp(&ts),
timestamp: ts,
status: closest
.get("status")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_api_shape() {
let v: Value = serde_json::from_str(r#"{"url":"x","archived_snapshots":{"closest":{"status":"200","available":true,"url":"http://web.archive.org/web/20130919044612/http://example.com/","timestamp":"20130919044612"}}}"#).unwrap();
let hit = parse_response(&v).unwrap();
assert_eq!(hit.date, "2013-09-19");
assert!(hit.url.starts_with("https://"));
let empty: Value = serde_json::from_str(r#"{"url":"x","archived_snapshots":{}}"#).unwrap();
assert!(parse_response(&empty).is_none());
}
}