mcat 0.6.0

Terminal image, video, and Markdown viewer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use anyhow::{Context, Result};
use futures::StreamExt;
use regex::Regex;
use reqwest::{Client, Response};
use scraper::Html;
use std::sync::{LazyLock, OnceLock};
use std::time::Duration;

use tracing::{debug, info, warn};

use crate::{
    mcat_file::{McatFile, McatKind},
    prompter::MultiBar,
};

static GITHUB_BLOB_URL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^.*github\.com.*[\\\/]blob[\\\/].*$").unwrap());

pub static TIMEOUT: OnceLock<Duration> = OnceLock::new();

fn timeout() -> Duration {
    TIMEOUT.get().copied().unwrap_or(Duration::from_secs(5))
}

static HTTP_CLIENT: LazyLock<Client> = LazyLock::new(|| {
    Client::builder()
        .connect_timeout(timeout())
        .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
        .build()
        .unwrap_or_default()
});

#[derive(Default)]
pub struct MediaScrapeOptions {
    pub max_content_length: Option<u64>,
}

pub async fn scrape_biggest_media(
    url: &str,
    options: &MediaScrapeOptions,
    bar: Option<&MultiBar>,
) -> Result<McatFile> {
    let client = &HTTP_CLIENT;

    let url = if GITHUB_BLOB_URL.is_match(url) {
        url.replace("github.com", "raw.githubusercontent.com")
            .replace("/blob/", "/")
    } else {
        url.to_string()
    };

    let response = match get_response(client, &url, bar).await {
        Ok(r) => r,
        Err(e) => {
            warn!(url = %url, error = %e.root_cause(), "failed to fetch");
            return Err(e);
        }
    };

    let mime = get_mime(&response);
    let format = mime.as_deref().and_then(|m| {
        if m == "application/octet-stream" {
            ext_from_url(&url).as_deref().and_then(McatKind::from_ext)
        } else {
            format_from_mime(m)
        }
    });

    match format {
        // html, try to scrape for something
        Some(McatKind::Html) => {
            let html = response.text().await?;
            let result = scrape_html(client, &url, &html, options, bar).await;
            match &result {
                Ok(file) => {
                    info!(url = %url, kind = ?file.kind, size = file.bytes.len(), "scraped media")
                }
                Err(e) => warn!(url = %url, error = %e, "no media found on page"),
            }
            result
        }
        // known type, just download
        Some(fmt) => {
            let data = match download(response, options, bar).await {
                Ok(d) => d,
                Err(e) => {
                    warn!(url = %url, error = ?e, "download failed");
                    return Err(e);
                }
            };
            let mut file = McatFile::from_bytes(data, None, ext_from_url(&url), Some(url), true)?;
            if file.kind == McatKind::PreMarkdown {
                file.kind = fmt;
            }
            info!(url = %file.id.as_deref().unwrap_or_default(), kind = ?file.kind, size = file.bytes.len(), "downloaded media");
            Ok(file)
        }
        None => {
            warn!(url = %url, "no media format detected");
            anyhow::bail!("no media found at {}", url)
        }
    }
}

fn ext_from_url(url: &str) -> Option<String> {
    url.split('?')
        .next()
        .and_then(|u| u.split('/').next_back())
        .and_then(|f| f.split('.').next_back())
        .map(|e| e.to_string())
}

fn get_mime(response: &Response) -> Option<String> {
    response
        .headers()
        .get("Content-Type")
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(';').next().unwrap_or(s).trim().to_string())
}

fn get_content_length(response: &Response) -> Option<u64> {
    response
        .headers()
        .get("content-length")
        .and_then(|h| h.to_str().ok())
        .and_then(|s| s.parse().ok())
}

async fn download(
    response: Response,
    options: &MediaScrapeOptions,
    bar: Option<&MultiBar>,
) -> Result<Vec<u8>> {
    let idle_timeout = timeout();
    let content_length = get_content_length(&response);

    if let (Some(max), Some(len)) = (options.max_content_length, content_length) {
        anyhow::ensure!(len <= max, "content length {len} exceeds max {max}");
    }

    let handle = bar.map(|b| b.add(content_length, None));

    let mut data = Vec::new();
    let mut stream = response.bytes_stream();
    loop {
        let chunk = match tokio::time::timeout(idle_timeout, stream.next()).await {
            Ok(Some(chunk)) => chunk?,
            Ok(None) => break,
            Err(_) => anyhow::bail!("download stalled (no data for {}s)", idle_timeout.as_secs()),
        };
        data.extend_from_slice(&chunk);
        if let Some(max) = options.max_content_length {
            anyhow::ensure!(
                data.len() as u64 <= max,
                "download exceeded max content length"
            );
        }
        if let Some(ref h) = handle {
            h.set_position(data.len() as u64);
        }
    }

    if let Some(h) = handle {
        h.finish();
    }
    Ok(data)
}

async fn scrape_html(
    client: &Client,
    base_url: &str,
    html: &str,
    options: &MediaScrapeOptions,
    bar: Option<&MultiBar>,
) -> Result<McatFile> {
    let document = Html::parse_document(html);
    let base = reqwest::Url::parse(base_url)?;

    // collect candidates as (url, area)
    let mut candidates: Vec<(String, u64)> = Vec::new();

    for selector in &[
        "img[src]",
        "video[src]",
        "video source[src]",
        "object[type='image/svg+xml'][data]",
        "embed[type='image/svg+xml'][src]",
    ] {
        if let Ok(sel) = scraper::Selector::parse(selector) {
            for el in document.select(&sel) {
                let src = el.value().attr("src").or_else(|| el.value().attr("data"));
                let Some(src) = src else { continue };
                let Ok(url) = base.join(src) else { continue };

                let (w, h) = resolve_dimensions(&el);
                let area = w * h;

                candidates.push((url.to_string(), area));
            }
        }
    }

    anyhow::ensure!(!candidates.is_empty(), "no media found on page");

    let best_url = candidates
        .iter()
        .max_by_key(|(_, area)| *area)
        .map(|(url, _)| url.clone())
        .context("no valid media found on page")?;
    debug!(url = %best_url, "selected best candidate");

    let response = get_response(client, &best_url, bar).await?;
    let mime = get_mime(&response);
    let format = mime.as_deref().and_then(format_from_mime);
    let data = download(response, options, bar).await?;

    let mut file = McatFile::from_bytes(
        data,
        None,
        ext_from_url(&best_url),
        Some(base_url.to_owned()),
        true,
    )?;
    if let Some(fmt) = format {
        file.kind = fmt;
    }

    Ok(file)
}

async fn get_response(client: &Client, url: &str, bar: Option<&MultiBar>) -> Result<Response> {
    let handle = bar.map(|b| b.add(None, Some(&format!("Fetching {url}..."))));

    let request = client.get(url).send();
    tokio::pin!(request);

    let response = tokio::select! {
        result = &mut request => result?,
            _ = tokio::time::sleep(Duration::from_millis(300)) => {
            if let Some(ref h) = handle {
                h.enable_steady_tick(Duration::from_millis(100));
            }
            request.await?
        }
    };

    if let Some(h) = handle {
        h.finish();
    }
    anyhow::ensure!(response.status().is_success(), response.status());

    Ok(response)
}

fn resolve_dimensions(el: &scraper::ElementRef) -> (u64, u64) {
    let (w_style, h_style) = extract_style_dims(el.value().attr("style"));
    let w_raw = el.value().attr("width").or(w_style.as_deref());
    let h_raw = el.value().attr("height").or(h_style.as_deref());

    let (w_raw, h_raw) = match (w_raw, h_raw) {
        (Some(w), Some(h)) => (w, h),
        _ => return (0, 0),
    };

    let parent_w = resolve_parent_dim(el, "width");
    let parent_h = resolve_parent_dim(el, "height");

    let w = dim_to_px(w_raw, parent_w);
    let h = dim_to_px(h_raw, parent_h);
    (w, h)
}

fn extract_style_dims(style: Option<&str>) -> (Option<String>, Option<String>) {
    let Some(style) = style else {
        return (None, None);
    };
    let mut w = None;
    let mut h = None;
    for prop in style.split(';') {
        let prop = prop.trim();
        if let Some((key, val)) = prop.split_once(':') {
            let key = key.trim();
            let val = val.trim();
            match key {
                "width" | "max-width" if w.is_none() => w = Some(val.to_string()),
                "height" | "max-height" if h.is_none() => h = Some(val.to_string()),
                _ => {}
            }
        }
    }
    (w, h)
}

fn get_element_dim(element: &scraper::node::Element, dim: &str) -> Option<String> {
    // check attribute first, then style
    if let Some(v) = element.attr(dim) {
        return Some(v.to_string());
    }
    let style = element.attr("style")?;
    for prop in style.split(';') {
        let prop = prop.trim();
        if let Some((key, val)) = prop.split_once(':') {
            let key = key.trim();
            let val = val.trim();
            if key == dim || key == format!("max-{dim}") {
                return Some(val.to_string());
            }
        }
    }
    None
}

fn get_style_prop(element: &scraper::node::Element, prop: &str) -> Option<String> {
    let style = element.attr("style")?;
    for part in style.split(';') {
        let part = part.trim();
        if let Some((key, val)) = part.split_once(':')
            && key.trim() == prop
        {
            return Some(val.trim().to_string());
        }
    }
    None
}

fn resolve_parent_dim(el: &scraper::ElementRef, dim: &str) -> f64 {
    let default = if dim == "width" { 1920.0 } else { 1080.0 };
    let mut node = el.parent();
    while let Some(n) = node {
        if let Some(element) = n.value().as_element() {
            if let Some(v) = get_element_dim(element, dim)
                && let Some(px) = try_parse_absolute(&v)
            {
                return px;
            }
            // if no explicit dim, try to derive from aspect-ratio + the other dim
            if let Some(ar) = get_style_prop(element, "aspect-ratio")
                && let Ok(ar) = ar.parse::<f64>()
                && ar > 0.0
            {
                let other_dim = if dim == "height" { "width" } else { "height" };
                if let Some(v) = get_element_dim(element, other_dim)
                    && let Some(other_px) = try_parse_absolute(&v)
                {
                    // aspect-ratio = width / height
                    return if dim == "height" {
                        other_px / ar
                    } else {
                        other_px * ar
                    };
                }
            }
        }
        node = n.parent();
    }
    default
}

fn try_parse_absolute(value: &str) -> Option<f64> {
    let s = value.trim();
    let font_size: f64 = 14.0; // yeah just assumming..

    if s.ends_with('%') || s.ends_with("vw") || s.ends_with("vh") {
        return None; // relative, keep walking up
    }

    let px = if let Some(v) = s.strip_suffix("rem") {
        v.parse::<f64>().ok()? * font_size
    } else if let Some(v) = s.strip_suffix("em") {
        v.parse::<f64>().ok()? * font_size
    } else {
        s.strip_suffix("px").unwrap_or(s).parse::<f64>().ok()?
    };

    if px > 0.0 { Some(px) } else { None }
}

fn dim_to_px(value: &str, parent: f64) -> u64 {
    let s = value.trim();
    let font_size: f64 = 14.0;

    let px = if let Some(v) = s.strip_suffix('%') {
        v.parse::<f64>().unwrap_or(0.0) / 100.0 * parent
    } else if let Some(v) = s.strip_suffix("rem") {
        v.parse::<f64>().unwrap_or(0.0) * font_size
    } else if let Some(v) = s.strip_suffix("em") {
        v.parse::<f64>().unwrap_or(0.0) * font_size
    } else if let Some(v) = s.strip_suffix("vw") {
        v.parse::<f64>().unwrap_or(0.0) / 100.0 * 1920.0
    } else if let Some(v) = s.strip_suffix("vh") {
        v.parse::<f64>().unwrap_or(0.0) / 100.0 * 1080.0
    } else {
        s.strip_suffix("px")
            .unwrap_or(s)
            .parse::<f64>()
            .unwrap_or(0.0)
    };

    px.max(0.0) as u64
}

fn format_from_mime(mime: &str) -> Option<McatKind> {
    let mime = mime.split(';').next()?.trim();
    match mime {
        "image/gif" => Some(McatKind::Gif),
        "image/svg+xml" => Some(McatKind::Svg),
        "image/png"
        | "image/jpeg"
        | "image/webp"
        | "image/tiff"
        | "image/bmp"
        | "image/x-icon"
        | "image/vnd.microsoft.icon"
        | "image/avif"
        | "image/vnd.radiance"
        | "image/x-exr"
        | "image/qoi"
        | "image/x-portable-anymap"
        | "image/farbfeld"
        | "image/vnd.ms-dds" => Some(McatKind::Image),
        "video/mp4" | "video/webm" | "video/matroska" | "video/quicktime" | "video/avi"
        | "video/x-msvideo" | "video/x-ms-wmv" | "video/x-flv" | "video/mpeg" | "video/ogg"
        | "video/3gpp" | "video/x-m4v" => Some(McatKind::Video),
        "application/pdf" => Some(McatKind::Pdf),
        "text/x-tex" => Some(McatKind::Tex),
        "text/html" => Some(McatKind::Html),
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        | "application/vnd.openxmlformats-officedocument.presentationml.presentation"
        | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        | "application/vnd.ms-excel"
        | "application/vnd.oasis.opendocument.text"
        | "application/vnd.oasis.opendocument.presentation"
        | "application/vnd.oasis.opendocument.spreadsheet"
        | "application/zip"
        | "application/x-tar"
        | "application/gzip"
        | "application/x-xz"
        | "application/json"
        | "application/x-yaml" => Some(McatKind::PreMarkdown),
        _ if mime.starts_with("text/") => Some(McatKind::PreMarkdown),
        _ => None,
    }
}