|
| 1 | +use hyper::{Body, Request, Response}; |
| 2 | +use serde_json::Value; |
| 3 | +use std::sync::LazyLock; |
| 4 | + |
| 5 | +use crate::client::{proxy, CLIENT}; |
| 6 | +use crate::server::RequestExt; |
| 7 | + |
| 8 | +// RedGifs token cache: (token, expiry_timestamp) |
| 9 | +static REDGIFS_TOKEN: LazyLock<std::sync::Mutex<(String, i64)>> = LazyLock::new(|| std::sync::Mutex::new((String::new(), 0))); |
| 10 | + |
| 11 | +pub fn is_redgifs_domain(domain: &str) -> bool { |
| 12 | + domain == "redgifs.com" || domain == "www.redgifs.com" || domain.ends_with(".redgifs.com") |
| 13 | +} |
| 14 | + |
| 15 | +/// Handles both video IDs (redirects) and actual video files (proxies) |
| 16 | +pub async fn handler(req: Request<Body>) -> Result<Response<Body>, String> { |
| 17 | + let path = req.param("path").unwrap_or_default(); |
| 18 | + |
| 19 | + if path.ends_with(".mp4") { |
| 20 | + return proxy(req, &format!("https://media.redgifs.com/{}", path)).await; |
| 21 | + } |
| 22 | + |
| 23 | + match fetch_video_url(&format!("https://www.redgifs.com/watch/{}", path)).await.ok() { |
| 24 | + Some(video_url) => { |
| 25 | + let filename = video_url.strip_prefix("https://media.redgifs.com/").unwrap_or(&video_url); |
| 26 | + Ok(Response::builder() |
| 27 | + .status(302) |
| 28 | + .header("Location", format!("/redgifs/{}", filename)) |
| 29 | + .body(Body::empty()) |
| 30 | + .unwrap_or_default()) |
| 31 | + } |
| 32 | + None => Ok(Response::builder().status(404).body("RedGifs video not found".into()).unwrap_or_default()), |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +async fn fetch_video_url(redgifs_url: &str) -> Result<String, String> { |
| 37 | + let video_id = redgifs_url |
| 38 | + .split('/') |
| 39 | + .last() |
| 40 | + .and_then(|s| s.split('?').next()) |
| 41 | + .ok_or("Invalid RedGifs URL")?; |
| 42 | + |
| 43 | + let token = get_token().await?; |
| 44 | + let api_url = format!("https://api.redgifs.com/v2/gifs/{}?views=yes", video_id); |
| 45 | + |
| 46 | + let req = create_request(&api_url, Some(&token))?; |
| 47 | + let res = CLIENT.request(req).await.map_err(|e| e.to_string())?; |
| 48 | + let body_bytes = hyper::body::to_bytes(res.into_body()).await.map_err(|e| e.to_string())?; |
| 49 | + let json: Value = serde_json::from_slice(&body_bytes).map_err(|e| e.to_string())?; |
| 50 | + |
| 51 | + // Prefer HD, fallback to SD |
| 52 | + let hd_url = json["gif"]["urls"]["hd"].as_str(); |
| 53 | + let sd_url = json["gif"]["urls"]["sd"].as_str(); |
| 54 | + |
| 55 | + hd_url |
| 56 | + .or(sd_url) |
| 57 | + .map(String::from) |
| 58 | + .ok_or_else(|| "No video URL in RedGifs response".to_string()) |
| 59 | +} |
| 60 | + |
| 61 | +async fn get_token() -> Result<String, String> { |
| 62 | + let now = std::time::SystemTime::now() |
| 63 | + .duration_since(std::time::UNIX_EPOCH) |
| 64 | + .map_err(|_| "Time error")? |
| 65 | + .as_secs() as i64; |
| 66 | + |
| 67 | + // Return cached token if still valid (without holding lock across await) |
| 68 | + { |
| 69 | + let cache = REDGIFS_TOKEN.lock().map_err(|_| "Lock error")?; |
| 70 | + if !cache.0.is_empty() && now < cache.1 { |
| 71 | + return Ok(cache.0.clone()); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + let req = create_request("https://api.redgifs.com/v2/auth/temporary", None)?; |
| 76 | + let res = CLIENT.request(req).await.map_err(|e| e.to_string())?; |
| 77 | + let body_bytes = hyper::body::to_bytes(res.into_body()).await.map_err(|e| e.to_string())?; |
| 78 | + let json: Value = serde_json::from_slice(&body_bytes).map_err(|e| e.to_string())?; |
| 79 | + let token = json["token"].as_str().map(String::from).ok_or_else(|| "No token in RedGifs response".to_string())?; |
| 80 | + |
| 81 | + let mut cache = REDGIFS_TOKEN.lock().map_err(|_| "Lock error")?; |
| 82 | + cache.0 = token.clone(); |
| 83 | + cache.1 = now + 86000; // 24h - 400s buffer |
| 84 | + Ok(token) |
| 85 | +} |
| 86 | + |
| 87 | +fn create_request(url: &str, token: Option<&str>) -> Result<Request<Body>, String> { |
| 88 | + let mut builder = hyper::Request::get(url) |
| 89 | + .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36") |
| 90 | + .header("referer", "https://www.redgifs.com/") |
| 91 | + .header("origin", "https://www.redgifs.com") |
| 92 | + .header("content-type", "application/json"); |
| 93 | + |
| 94 | + if let Some(t) = token { |
| 95 | + builder = builder.header("Authorization", format!("Bearer {}", t)); |
| 96 | + } |
| 97 | + |
| 98 | + builder.body(Body::empty()).map_err(|e| e.to_string()) |
| 99 | +} |
0 commit comments