use std::path::Path;
use anyhow::{Context, Result, bail};
#[derive(Debug, Clone, Default)]
pub struct RefreshSpec {
pub source_page: String,
pub selector: String,
pub cookies: Option<String>,
}
impl RefreshSpec {
#[allow(dead_code)]
pub fn new(source_page: impl Into<String>) -> Self {
Self {
source_page: source_page.into(),
selector: String::new(),
cookies: None,
}
}
#[allow(dead_code)]
pub fn with_selector(mut self, selector: impl Into<String>) -> Self {
self.selector = selector.into();
self
}
#[allow(dead_code)]
pub fn with_cookies(mut self, cookies: impl Into<String>) -> Self {
let c = cookies.into();
if !c.trim().is_empty() {
self.cookies = Some(c);
}
self
}
}
#[allow(dead_code)]
pub fn is_expired_status(status: u16) -> bool {
matches!(status, 401 | 403 | 410)
}
pub fn is_expired_body(body: &str) -> bool {
let b = body.to_lowercase();
b.contains("expired")
|| b.contains("token invalid")
|| b.contains("token expired")
|| b.contains("link expired")
|| b.contains("access denied")
}
pub fn is_expired_error(msg: &str) -> bool {
let m = msg.to_lowercase();
m.contains("403") || m.contains("410") || m.contains("401") || is_expired_body(&m)
}
fn first_url(s: &str) -> Option<String> {
for needle in ["https://", "http://"] {
let mut search = s;
let mut base = 0;
while let Some(pos) = search.find(needle) {
let start = base + pos;
let rest = &s[start..];
let end = rest
.find(|c: char| {
c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>' | ')' | ']' | '\\')
})
.map(|e| start + e)
.unwrap_or(s.len());
let mut url = s[start..end]
.trim_end_matches(['.', ',', ';', '!'])
.to_string();
if url.contains("\\/") {
url = url.replace("\\/", "/");
}
if url.len() > needle.len() + 3 {
return Some(url);
}
base = start + needle.len();
search = &s[base..];
}
}
None
}
pub fn extract_link(html: &str, selector: &str) -> Option<String> {
let sel = selector.trim();
let needle = sel.strip_prefix("regex:").unwrap_or(sel);
if needle.is_empty() {
return first_url(html);
}
if let Some(pos) = html.find(needle) {
let after = &html[pos + needle.len()..];
if let Some(u) = first_url(after) {
if u.starts_with("http://") || u.starts_with("https://") {
return Some(u);
}
}
if let Some(href) = extract_href_after(html, pos) {
return Some(href);
}
}
first_url(html)
}
fn extract_href_after(html: &str, pos: usize) -> Option<String> {
let window = html.get(pos..(pos + 2048).min(html.len()))?;
let mut search = window;
loop {
let i = search.find("href")?;
let mut rest = search[i + 4..].trim_start();
if let Some(r) = rest.strip_prefix('=') {
rest = r.trim_start();
} else {
search = &search[i + 4..];
continue;
}
let quote = rest.chars().next()?;
if quote == '"' || quote == '\'' {
let end = rest[1..].find(quote)?;
return Some(rest[1..1 + end].to_string());
}
let end = rest
.find(|c: char| c.is_whitespace() || c == '>')
.unwrap_or(rest.len());
if end > 0 {
return Some(rest[..end].to_string());
}
return None;
}
}
pub fn absolutize(source_page: &str, link: &str) -> String {
if link.starts_with("http://") || link.starts_with("https://") {
return link.to_string();
}
if let Ok(base) = url::Url::parse(source_page)
&& let Ok(joined) = base.join(link)
{
return joined.to_string();
}
link.to_string()
}
fn client_with_cookies(cookies: Option<&str>) -> Result<reqwest::Client> {
let mut b = reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(10));
if let Some(c) = cookies {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::COOKIE,
reqwest::header::HeaderValue::from_str(c).context("bad --cookies header")?,
);
b = b.default_headers(headers);
}
b.build().context("cannot create HTTP client")
}
pub async fn fetch_source_html(spec: &RefreshSpec) -> Result<String> {
let client = client_with_cookies(spec.cookies.as_deref())?;
let resp = client
.get(&spec.source_page)
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await
.with_context(|| format!("refresh: cannot GET source page {}", spec.source_page))?;
if !resp.status().is_success() {
bail!("refresh: source page HTTP {}", resp.status());
}
resp.text()
.await
.context("refresh: cannot read source page")
}
pub async fn fetch_fresh_link(spec: &RefreshSpec) -> Result<String> {
let html = fetch_source_html(spec).await?;
let raw = extract_link(&html, &spec.selector).with_context(|| {
format!(
"refresh: selector {:?} found no link on {}",
spec.selector, spec.source_page
)
})?;
Ok(absolutize(&spec.source_page, &raw))
}
pub async fn probe_size(url: &str, cookies: Option<&str>) -> Result<Option<u64>> {
let client = client_with_cookies(cookies)?;
let resp = client
.get(url)
.header(reqwest::header::RANGE, "bytes=0-0")
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await
.with_context(|| format!("refresh: size probe failed for {url}"))?;
if resp.status() == reqwest::StatusCode::PARTIAL_CONTENT
&& let Some(v) = resp.headers().get(reqwest::header::CONTENT_RANGE)
&& let Ok(s) = v.to_str()
&& let Some(total) = s
.rsplit('/')
.next()
.and_then(|t| t.trim().parse::<u64>().ok())
{
return Ok(Some(total));
}
Ok(resp
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok()))
}
pub async fn verify_fresh_link(url: &str, total: u64, cookies: Option<&str>) -> Result<()> {
match probe_size(url, cookies).await? {
Some(t) if t == total => Ok(()),
Some(t) => bail!("refresh: size mismatch for {url}: got {t}, want {total}"),
None => bail!("refresh: cannot verify size of {url}"),
}
}
#[allow(dead_code)]
pub async fn download_with_refresh(
url: &str,
spec: &RefreshSpec,
out_path: &Path,
expected_total: Option<u64>,
) -> Result<u64> {
if let Some(parent) = out_path.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
let mut cur = url.to_string();
let mut total = expected_total;
if total.is_none() {
total = probe_size(&cur, spec.cookies.as_deref()).await?;
}
let total = total.with_context(|| format!("refresh: unknown size for {cur}"))?;
let mut refreshes = 0u32;
loop {
let done = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
if done >= total {
return Ok(done.min(total));
}
if done > 0
&& probe_size(&cur, spec.cookies.as_deref())
.await?
.is_some_and(|t| t != total)
{
cur = refresh_once(spec, total, &mut refreshes)?;
continue;
}
let client = client_with_cookies(spec.cookies.as_deref())?;
let resp = client
.get(&cur)
.header(reqwest::header::RANGE, format!("bytes={done}-"))
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await
.with_context(|| format!("refresh: GET {cur} failed"))?;
let status = resp.status().as_u16();
if is_expired_status(status) {
cur = refresh_once(spec, total, &mut refreshes)?;
continue;
}
if status != 200 && status != 206 {
bail!("refresh: unexpected HTTP {status} for {cur}");
}
let body = resp.bytes().await.context("refresh: cannot read body")?;
if body.len() < 8 * 1024
&& let Ok(text) = std::str::from_utf8(&body)
&& is_expired_body(text)
{
cur = refresh_once(spec, total, &mut refreshes)?;
continue;
}
append_bytes(out_path, &body)?;
if status == 200 {
let len = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
if len != total {
bail!("refresh: server ignored Range (got {len}, want {total})");
}
return Ok(len);
}
}
}
#[allow(dead_code)]
fn refresh_once(spec: &RefreshSpec, total: u64, refreshes: &mut u32) -> Result<String> {
if *refreshes >= 3 {
bail!("refresh: link expired again after 3 refreshes");
}
*refreshes += 1;
let fresh = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(fetch_fresh_link(spec))
})?;
let _ = total;
Ok(fresh)
}
pub async fn refresh_url_verified(spec: &RefreshSpec, total: u64) -> Result<String> {
let fresh = fetch_fresh_link(spec).await?;
verify_fresh_link(&fresh, total, spec.cookies.as_deref()).await?;
Ok(fresh)
}
#[allow(dead_code)]
fn append_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.with_context(|| format!("cannot write {}", path.display()))?;
f.write_all(bytes)
.with_context(|| format!("cannot write {}", path.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn expired_classification() {
assert!(is_expired_status(403));
assert!(is_expired_status(410));
assert!(is_expired_status(401));
assert!(!is_expired_status(200));
assert!(!is_expired_status(206));
assert!(!is_expired_status(500));
assert!(is_expired_body("Link expired, get a new one"));
assert!(is_expired_body("TOKEN EXPIRED"));
assert!(!is_expired_body("\x00\x01\x02 binary"));
assert!(is_expired_error("server rejected Range (HTTP 403)"));
assert!(is_expired_error("got 410 Gone"));
assert!(!is_expired_error("connection reset"));
}
#[test]
fn extractor_uses_same_selector() {
let html = r#"<html><body><a id="other" href="https://cdn.example/old.bin">x</a><a id="dl" href="https://cdn.example/fresh.bin">y</a></body></html>"#;
assert_eq!(
extract_link(html, "dl"),
Some("https://cdn.example/fresh.bin".to_string())
);
assert_eq!(
extract_link(html, ""),
Some("https://cdn.example/old.bin".to_string())
);
assert_eq!(
extract_link(html, "regex:dl"),
Some("https://cdn.example/fresh.bin".to_string())
);
assert_eq!(extract_link("no links here", "dl"), None);
}
#[test]
fn relative_links_absolutize_against_source() {
assert_eq!(
absolutize("http://h/page", "/file?token=abc"),
"http://h/file?token=abc"
);
assert_eq!(
absolutize("http://h/page", "http://cdn.example/f.bin"),
"http://cdn.example/f.bin"
);
}
#[allow(dead_code)]
struct Mock {
token: Arc<Mutex<String>>,
payload: Vec<u8>,
}
impl Mock {
async fn routes(token: Arc<Mutex<String>>, payload: Vec<u8>) -> axum::Router {
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use std::collections::HashMap;
#[derive(Clone)]
struct S {
token: Arc<Mutex<String>>,
payload: Vec<u8>,
}
let st = S { token, payload };
async fn page(State(st): State<S>) -> impl IntoResponse {
let t = st.token.lock().unwrap().clone();
format!(
r#"<html><body><a id="dl" href="/file?token={t}">download</a></body></html>"#
)
}
async fn file(
State(st): State<S>,
Query(q): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> impl IntoResponse {
let want = st.token.lock().unwrap().clone();
if q.get("token").map(String::as_str) != Some(want.as_str()) {
return (StatusCode::FORBIDDEN, "link expired").into_response();
}
let total = st.payload.len() as u64;
let range: Option<(u64, u64)> = headers
.get("range")
.and_then(|v| v.to_str().ok())
.and_then(|s| {
let s = s.strip_prefix("bytes=")?;
let (a, b) = s.split_once('-')?;
let from: u64 = a.parse().ok()?;
let to: u64 = if b.is_empty() {
total - 1
} else {
b.parse().ok()?
};
Some((from, to.min(total - 1)))
});
match range {
Some((from, to)) if from < total && from <= to => {
let body = st.payload[from as usize..=to as usize].to_vec();
(
StatusCode::PARTIAL_CONTENT,
[
("content-range", format!("bytes {from}-{to}/{total}")),
("accept-ranges", "bytes".to_string()),
],
body,
)
.into_response()
}
_ => (StatusCode::OK, st.payload.clone()).into_response(),
}
}
axum::Router::new()
.route("/page", axum::routing::get(page))
.route("/file", axum::routing::get(file))
.with_state(st)
}
}
#[tokio::test]
async fn expiring_token_recovers_from_source_page() {
let token = Arc::new(Mutex::new("t0".to_string()));
let payload: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();
let app = Mock::routes(token.clone(), payload.clone()).await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let base = format!("http://{addr}");
let spec = RefreshSpec::new(format!("{base}/page")).with_selector("dl");
let first = fetch_fresh_link(&spec).await.unwrap();
assert!(first.contains("token=t0"));
let half = download_half(&first, 100_000).await.unwrap();
assert_eq!(half, payload[..100_000].to_vec());
*token.lock().unwrap() = "t1".to_string();
let stale_probe = reqwest::Client::new()
.get(&first)
.header("Range", "bytes=100000-")
.send()
.await
.unwrap();
assert_eq!(stale_probe.status().as_u16(), 403);
assert!(is_expired_status(403));
let fresh = fetch_fresh_link(&spec).await.unwrap();
assert!(fresh.contains("token=t1"));
verify_fresh_link(&fresh, payload.len() as u64, None)
.await
.unwrap();
let rest = download_half_range(&fresh, 100_000).await.unwrap();
assert_eq!(rest, payload[100_000..].to_vec());
let mut full = half;
full.extend_from_slice(&rest);
assert_eq!(full, payload);
}
async fn download_half(url: &str, len: u64) -> Result<Vec<u8>> {
let body = reqwest::Client::new()
.get(url)
.header("Range", format!("bytes=0-{}", len - 1))
.send()
.await?
.bytes()
.await?;
Ok(body.to_vec())
}
async fn download_half_range(url: &str, from: u64) -> Result<Vec<u8>> {
let resp = reqwest::Client::new()
.get(url)
.header("Range", format!("bytes={from}-"))
.send()
.await?;
assert_eq!(resp.status().as_u16(), 206);
Ok(resp.bytes().await?.to_vec())
}
#[tokio::test]
async fn full_loop_continues_range_from_done() {
let token = Arc::new(Mutex::new("only".to_string()));
let payload: Vec<u8> = (0..120_000u32).map(|i| (i % 251) as u8).collect();
let app = Mock::routes(token.clone(), payload.clone()).await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let base = format!("http://{addr}");
let spec = RefreshSpec::new(format!("{base}/page")).with_selector("dl");
let first = fetch_fresh_link(&spec).await.unwrap();
let dir = std::env::temp_dir().join(format!("xget-refresh-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let out = dir.join("f.bin");
let n = download_with_refresh(&first, &spec, &out, Some(payload.len() as u64))
.await
.unwrap();
assert_eq!(n, payload.len() as u64);
assert_eq!(std::fs::read(&out).unwrap(), payload);
let _ = std::fs::remove_dir_all(&dir);
}
}