halldyll-media 0.1.0

Media extraction (images, videos, links) for halldyll scraper
Documentation
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
//! Audio extraction for halldyll-media
//!
//! Extracts audio from HTML with support for:
//! - HTML5 audio elements
//! - Embedded players (Spotify, SoundCloud, etc.)
//! - Podcast feeds
//! - Audio sources

use lazy_static::lazy_static;
use regex::Regex;
use scraper::{Html, Selector, ElementRef};
use std::collections::HashSet;
use url::Url;

use crate::types::{
    AudioMedia, AudioPlatform, AudioSource, MediaResult,
};

lazy_static! {
    /// Spotify track/album/playlist ID pattern
    static ref SPOTIFY_ID: Regex = Regex::new(
        r"open\.spotify\.com/(?:track|album|playlist|episode)/([a-zA-Z0-9]+)"
    ).unwrap();
    
    /// SoundCloud URL pattern
    static ref SOUNDCLOUD_URL: Regex = Regex::new(
        r"soundcloud\.com/([^/]+/[^?]+)"
    ).unwrap();
}

// ============================================================================
// EXTRACTION FUNCTIONS
// ============================================================================

/// Extract all audio from HTML document
pub fn extract_audio(document: &Html, base_url: Option<&Url>) -> Vec<AudioMedia> {
    let mut audio_items = Vec::new();
    let mut seen_urls: HashSet<String> = HashSet::new();
    
    // Extract HTML5 audio elements
    if let Ok(sel) = Selector::parse("audio") {
        for el in document.select(&sel) {
            if let Some(audio) = extract_audio_element(&el, base_url) {
                let key = audio.absolute_url.as_ref().unwrap_or(&audio.src).clone();
                if seen_urls.insert(key) {
                    audio_items.push(audio);
                }
            }
        }
    }
    
    // Extract embedded audio from iframes
    if let Ok(sel) = Selector::parse("iframe[src]") {
        for el in document.select(&sel) {
            if let Some(src) = el.value().attr("src") {
                if is_audio_embed(src) {
                    if let Some(audio) = extract_embedded_audio(&el, base_url) {
                        let key = audio.absolute_url.as_ref().unwrap_or(&audio.src).clone();
                        if seen_urls.insert(key) {
                            audio_items.push(audio);
                        }
                    }
                }
            }
        }
    }
    
    // Extract from links to audio files
    if let Ok(sel) = Selector::parse("a[href]") {
        for el in document.select(&sel) {
            if let Some(href) = el.value().attr("href") {
                if is_audio_file(href) {
                    if let Some(audio) = create_audio_from_link(&el, base_url) {
                        let key = audio.absolute_url.as_ref().unwrap_or(&audio.src).clone();
                        if seen_urls.insert(key) {
                            audio_items.push(audio);
                        }
                    }
                }
            }
        }
    }
    
    audio_items
}

/// Extract HTML5 audio element
fn extract_audio_element(el: &ElementRef, base_url: Option<&Url>) -> Option<AudioMedia> {
    let src = el.value().attr("src")
        .or_else(|| {
            if let Ok(sel) = Selector::parse("source") {
                el.select(&sel).next()
                    .and_then(|s| s.value().attr("src"))
            } else {
                None
            }
        })?;
    
    let absolute_url = resolve_url(src, base_url);
    
    let mut audio = AudioMedia {
        src: src.to_string(),
        absolute_url,
        platform: AudioPlatform::Html5,
        ..Default::default()
    };
    
    // Parse attributes
    audio.autoplay = el.value().attr("autoplay").is_some();
    audio.loop_audio = el.value().attr("loop").is_some();
    audio.muted = el.value().attr("muted").is_some();
    audio.controls = el.value().attr("controls").is_some();
    
    // Get MIME type
    audio.mime_type = el.value().attr("type").map(|s| s.to_string())
        .or_else(|| guess_audio_mime(&audio.src));
    
    // Extract sources
    audio.sources = extract_audio_sources(el, base_url);
    
    // Get title from various sources
    audio.title = el.value().attr("title").map(|s| s.to_string())
        .or_else(|| el.value().attr("aria-label").map(|s| s.to_string()));
    
    Some(audio)
}

/// Extract audio sources from audio element
fn extract_audio_sources(audio: &ElementRef, base_url: Option<&Url>) -> Vec<AudioSource> {
    let mut sources = Vec::new();
    
    if let Ok(sel) = Selector::parse("source") {
        for source in audio.select(&sel) {
            if let Some(src) = source.value().attr("src") {
                sources.push(AudioSource {
                    src: resolve_url(src, base_url).unwrap_or_else(|| src.to_string()),
                    mime_type: source.value().attr("type").map(|s| s.to_string()),
                });
            }
        }
    }
    
    sources
}

/// Extract embedded audio from iframe
fn extract_embedded_audio(el: &ElementRef, base_url: Option<&Url>) -> Option<AudioMedia> {
    let src = el.value().attr("src")?;
    let platform = AudioPlatform::from_url(src);
    
    let mut audio = AudioMedia {
        src: src.to_string(),
        absolute_url: resolve_url(src, base_url),
        platform,
        embed_url: Some(src.to_string()),
        ..Default::default()
    };
    
    // Get title
    audio.title = el.value().attr("title").map(|s| s.to_string());
    
    Some(audio)
}

/// Create audio from link
fn create_audio_from_link(el: &ElementRef, base_url: Option<&Url>) -> Option<AudioMedia> {
    let href = el.value().attr("href")?;
    
    let audio = AudioMedia {
        src: href.to_string(),
        absolute_url: resolve_url(href, base_url),
        platform: AudioPlatform::Html5,
        title: Some(el.text().collect::<String>().trim().to_string()),
        mime_type: guess_audio_mime(href),
        ..Default::default()
    };
    
    Some(audio)
}

/// Check if URL is an audio embed
fn is_audio_embed(url: &str) -> bool {
    let url_lower = url.to_lowercase();
    let audio_hosts = [
        "open.spotify.com",
        "soundcloud.com",
        "w.soundcloud.com",
        "podcasts.apple.com",
        "anchor.fm",
        "podbean.com",
        "buzzsprout.com",
        "spreaker.com",
        "castbox.fm",
    ];
    
    audio_hosts.iter().any(|host| url_lower.contains(host))
}

/// Check if URL is an audio file
fn is_audio_file(url: &str) -> bool {
    let url_lower = url.to_lowercase();
    let audio_extensions = [".mp3", ".wav", ".ogg", ".oga", ".flac", ".aac", ".m4a", ".opus", ".wma"];
    
    audio_extensions.iter().any(|ext| url_lower.ends_with(ext))
}

/// Guess audio MIME type from URL
fn guess_audio_mime(url: &str) -> Option<String> {
    let url_lower = url.to_lowercase();
    
    if url_lower.contains(".mp3") {
        Some("audio/mpeg".to_string())
    } else if url_lower.contains(".wav") {
        Some("audio/wav".to_string())
    } else if url_lower.contains(".ogg") || url_lower.contains(".oga") {
        Some("audio/ogg".to_string())
    } else if url_lower.contains(".flac") {
        Some("audio/flac".to_string())
    } else if url_lower.contains(".aac") {
        Some("audio/aac".to_string())
    } else if url_lower.contains(".m4a") {
        Some("audio/mp4".to_string())
    } else if url_lower.contains(".opus") {
        Some("audio/opus".to_string())
    } else {
        None
    }
}

/// Resolve relative URL
fn resolve_url(href: &str, base_url: Option<&Url>) -> Option<String> {
    if href.starts_with("http://") || href.starts_with("https://") {
        return Some(href.to_string());
    }
    
    if href.starts_with("//") {
        return Some(format!("https:{}", href));
    }
    
    base_url.and_then(|base| base.join(href).ok().map(|u| u.to_string()))
}

// ============================================================================
// CONVENIENCE FUNCTIONS
// ============================================================================

/// Extract audio from HTML string
pub fn extract_audio_from_html(html: &str, base_url: Option<&str>) -> MediaResult<Vec<AudioMedia>> {
    let document = Html::parse_document(html);
    let base = base_url.and_then(|u| Url::parse(u).ok());
    Ok(extract_audio(&document, base.as_ref()))
}

/// Get all audio URLs from HTML
pub fn get_audio_urls(html: &str, base_url: Option<&str>) -> Vec<String> {
    extract_audio_from_html(html, base_url)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|a| a.absolute_url)
        .collect()
}

/// Check if HTML has audio
pub fn has_audio(document: &Html) -> bool {
    if let Ok(sel) = Selector::parse("audio, iframe[src*='spotify'], iframe[src*='soundcloud']") {
        document.select(&sel).next().is_some()
    } else {
        false
    }
}

/// Get Spotify embed URL
pub fn spotify_embed_url(track_id: &str) -> String {
    format!("https://open.spotify.com/embed/track/{}", track_id)
}

/// Get SoundCloud embed URL (requires API)
pub fn soundcloud_embed_url(url: &str) -> String {
    format!("https://w.soundcloud.com/player/?url={}&auto_play=false", 
            urlencoding::encode(url))
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_html(html: &str) -> Html {
        Html::parse_document(html)
    }

    #[test]
    fn test_extract_html5_audio() {
        let html = r#"
            <audio src="/audio/podcast.mp3" controls>
                <source src="/audio/podcast.ogg" type="audio/ogg">
            </audio>
        "#;
        let doc = parse_html(html);
        let base = Url::parse("https://example.com").unwrap();
        let audio = extract_audio(&doc, Some(&base));
        
        assert_eq!(audio.len(), 1);
        assert_eq!(audio[0].platform, AudioPlatform::Html5);
        assert!(audio[0].controls);
        assert!(!audio[0].sources.is_empty());
    }

    #[test]
    fn test_extract_spotify_embed() {
        let html = r#"
            <iframe src="https://open.spotify.com/embed/track/4iV5W9uYEdYUVa79Axb7Rh" 
                    width="300" height="380" title="Spotify Track">
            </iframe>
        "#;
        let doc = parse_html(html);
        let audio = extract_audio(&doc, None);
        
        assert_eq!(audio.len(), 1);
        assert_eq!(audio[0].platform, AudioPlatform::Spotify);
    }

    #[test]
    fn test_extract_soundcloud_embed() {
        let html = r#"
            <iframe src="https://w.soundcloud.com/player/?url=https://soundcloud.com/artist/track">
            </iframe>
        "#;
        let doc = parse_html(html);
        let audio = extract_audio(&doc, None);
        
        assert_eq!(audio.len(), 1);
        assert_eq!(audio[0].platform, AudioPlatform::SoundCloud);
    }

    #[test]
    fn test_extract_audio_link() {
        let html = r#"<a href="/downloads/song.mp3">Download Song</a>"#;
        let doc = parse_html(html);
        let base = Url::parse("https://example.com").unwrap();
        let audio = extract_audio(&doc, Some(&base));
        
        assert_eq!(audio.len(), 1);
        assert_eq!(audio[0].title, Some("Download Song".to_string()));
    }

    #[test]
    fn test_audio_attributes() {
        let html = r#"<audio src="test.mp3" autoplay loop muted></audio>"#;
        let doc = parse_html(html);
        let audio = extract_audio(&doc, None);
        
        assert!(audio[0].autoplay);
        assert!(audio[0].loop_audio);
        assert!(audio[0].muted);
    }

    #[test]
    fn test_audio_sources() {
        let html = r#"
            <audio>
                <source src="audio.mp3" type="audio/mpeg">
                <source src="audio.ogg" type="audio/ogg">
            </audio>
        "#;
        let doc = parse_html(html);
        let audio = extract_audio(&doc, None);
        
        assert_eq!(audio[0].sources.len(), 2);
    }

    #[test]
    fn test_has_audio() {
        let with_audio = "<audio src='test.mp3'></audio>";
        let with_spotify = "<iframe src='https://open.spotify.com/embed/track/abc'></iframe>";
        let without = "<p>No audio</p>";
        
        assert!(has_audio(&parse_html(with_audio)));
        assert!(has_audio(&parse_html(with_spotify)));
        assert!(!has_audio(&parse_html(without)));
    }

    #[test]
    fn test_is_audio_file() {
        assert!(is_audio_file("/audio/song.mp3"));
        assert!(is_audio_file("/audio/track.wav"));
        assert!(is_audio_file("/audio/podcast.ogg"));
        assert!(!is_audio_file("/page.html"));
    }

    #[test]
    fn test_guess_audio_mime() {
        assert_eq!(guess_audio_mime("song.mp3"), Some("audio/mpeg".to_string()));
        assert_eq!(guess_audio_mime("track.wav"), Some("audio/wav".to_string()));
        assert_eq!(guess_audio_mime("audio.ogg"), Some("audio/ogg".to_string()));
        assert_eq!(guess_audio_mime("audio.flac"), Some("audio/flac".to_string()));
    }

    #[test]
    fn test_spotify_embed_url() {
        let url = spotify_embed_url("4iV5W9uYEdYUVa79Axb7Rh");
        assert_eq!(url, "https://open.spotify.com/embed/track/4iV5W9uYEdYUVa79Axb7Rh");
    }
}