spectur 0.4.2

The browser-extension-to-download-manager communication layer and stream resolver. Currently used by tur-rs.
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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use std::collections::HashMap;

#[derive(Debug, Clone, serde::Deserialize)]
pub struct StreamPayload {
    #[serde(rename = "requestId")]
    pub request_id: String,
    pub url: String,
    pub method: String,
    #[serde(rename = "requestHeaders")]
    pub request_headers: HashMap<String, String>,
    #[serde(rename = "responseHeaders")]
    pub response_headers: HashMap<String, String>,
    #[serde(rename = "serverIp")]
    pub server_ip: String,
    #[serde(rename = "pageUrl")]
    pub page_url: String,
    #[serde(rename = "pageTitle")]
    pub page_title: String,
    pub timestamp: u64,
    #[serde(rename = "manifestContent")]
    pub manifest_content: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct WsMessage {
    #[serde(rename = "type")]
    pub msg_type: Option<String>,
    #[serde(rename = "requestId")]
    pub request_id: Option<String>,
    pub url: Option<String>,
    pub method: Option<String>,
    #[serde(rename = "requestHeaders")]
    pub request_headers: Option<HashMap<String, String>>,
    #[serde(rename = "responseHeaders")]
    pub response_headers: Option<HashMap<String, String>>,
    #[serde(rename = "serverIp")]
    pub server_ip: Option<String>,
    #[serde(rename = "pageUrl")]
    pub page_url: Option<String>,
    #[serde(rename = "pageTitle")]
    pub page_title: Option<String>,
    pub timestamp: Option<u64>,
    #[serde(rename = "manifestContent")]
    pub manifest_content: Option<String>,
    pub key: Option<Vec<u8>>,
    pub href: Option<String>,
    #[serde(rename = "streamingData")]
    pub streaming_data: Option<serde_json::Value>,
}

impl WsMessage {
    pub fn is_stream_payload(&self) -> bool {
        self.msg_type.is_none() && self.url.is_some()
    }

    pub fn is_key_intercepted(&self) -> bool {
        self.msg_type.as_deref() == Some("keyIntercepted")
    }

    pub fn is_youtube_formats(&self) -> bool {
        self.msg_type.as_deref() == Some("youtubeFormats")
    }

    pub fn to_stream_payload(&self) -> Option<StreamPayload> {
        Some(StreamPayload {
            request_id: self.request_id.clone()?,
            url: self.url.clone()?,
            method: self.method.clone().unwrap_or_default(),
            request_headers: self.request_headers.clone().unwrap_or_default(),
            response_headers: self.response_headers.clone().unwrap_or_default(),
            server_ip: self.server_ip.clone().unwrap_or_default(),
            page_url: self.page_url.clone().unwrap_or_default(),
            page_title: self.page_title.clone().unwrap_or_default(),
            timestamp: self.timestamp.unwrap_or(0),
            manifest_content: self.manifest_content.clone(),
        })
    }

    pub fn to_key_payload(&self) -> Option<KeyPayload> {
        Some(KeyPayload {
            key: self.key.clone()?,
            href: self.href.clone().unwrap_or_default(),
            page_url: self.page_url.clone().unwrap_or_default(),
            page_title: self.page_title.clone().unwrap_or_default(),
            timestamp: self.timestamp.unwrap_or(0),
        })
    }
}

#[derive(Debug, Clone)]
pub struct KeyPayload {
    pub key: Vec<u8>,
    pub href: String,
    pub page_url: String,
    pub page_title: String,
    pub timestamp: u64,
}

#[derive(Debug, Clone)]
pub struct AppState {
    pub next_stream_id: u64,
    pub intercepted_keys: Vec<KeyPayload>,
    pub selected_yt_format_index: usize,
    pub selected_tab_index: usize,
    pub selected_stream_index: usize,
    pub selected_resolution_index: usize,
    pub selected_download_index: usize,
    pub tabs: Vec<TabSession>,
    pub downloads: Vec<DownloadTask>,
    pub tui_logs: Vec<String>,
    pub focused_panel: Panel,
}

#[derive(Debug, Clone)]
pub struct TabSession {
    pub page_url: String,
    pub page_title: String,
    pub streams: Vec<CapturedStream>,
    pub show_noise: bool,
    pub yt_formats: Vec<YtFormat>,
}

impl TabSession {
    pub fn filtered_streams(&self) -> Vec<&CapturedStream> {
        self.streams.iter()
            .filter(|s| self.show_noise || !s.is_noise())
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ProbeState {
    Probing,
    Done(StreamMetadata),
    Failed(String),
}

#[derive(Debug, Clone)]
pub struct CapturedStream {
    pub stream_id: u64,
    pub url: String,
    pub method: String,
    pub request_headers: HashMap<String, String>,
    pub server_ip: String,
    pub format: StreamFormat,
    pub probe_state: ProbeState,
    pub manifest_content: Option<String>,
}

impl CapturedStream {
    pub fn is_noise(&self) -> bool {
        if self.format == StreamFormat::Ts {
            return true;
        }
        let url_lower = self.url.to_lowercase();
        if url_lower.contains(".m4s") 
            || url_lower.contains("/segment") 
            || url_lower.contains("/fragment") 
            || url_lower.contains("/chunk") 
            || url_lower.contains("/init-") 
            || url_lower.contains("seg-") 
            || url_lower.contains("/range/") 
            || url_lower.contains("/bytes/") 
        {
            return true;
        }
        false
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum StreamFormat {
    Hls,
    Dash,
    Mp4,
    Ts,
    Youtube,
    Unknown,
}

#[derive(Debug, Clone, PartialEq)]
pub struct StreamMetadata {
    pub duration_seconds: f32,
    pub total_segments: usize,
    pub resolutions: Vec<ResolutionInfo>,
    pub audio_tracks: Vec<String>,
    pub keys: Vec<KeyInfo>,
    pub drm: Vec<DrmInfo>,
    pub segment_base_url: Option<String>,
    pub size_bytes: Option<u64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ResolutionInfo {
    pub label: String,
    pub bandwidth: u64,
    pub codecs: Option<String>,
    pub frame_rate: Option<String>,
    pub mime_type: Option<String>,
    pub url: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct KeyInfo {
    pub method: String,
    pub uri: Option<String>,
    pub iv: Option<String>,
    pub keyformat: Option<String>,
    pub key_hex: Option<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct YtFormat {
    pub itag: i64,
    pub mime_type: String,
    pub bitrate: Option<i64>,
    pub width: Option<i64>,
    pub height: Option<i64>,
    pub fps: Option<i64>,
    pub quality_label: Option<String>,
    pub content_length: Option<String>,
    pub approx_duration_ms: Option<String>,
    pub audio_channels: Option<i64>,
    pub audio_sample_rate: Option<String>,
}

impl YtFormat {
    pub fn is_video(&self) -> bool {
        self.width.is_some() && self.height.is_some()
    }

    pub fn is_audio_only(&self) -> bool {
        self.mime_type.starts_with("audio/")
    }

    pub fn resolution_label(&self) -> String {
        if let (Some(w), Some(h)) = (self.width, self.height) {
            if let Some(ref ql) = self.quality_label {
                format!("{}x{} ({})", w, h, ql)
            } else {
                format!("{}x{}", w, h)
            }
        } else if let Some(ref ql) = self.quality_label {
            ql.clone()
        } else if self.is_audio_only() {
            format!("Audio (itag {})", self.itag)
        } else {
            format!("itag {}", self.itag)
        }
    }

    pub fn short_label(&self) -> String {
        if let Some(ref ql) = self.quality_label {
            ql.clone()
        } else if self.is_audio_only() {
            "Audio".into()
        } else {
            format!("itag {}", self.itag)
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct DrmInfo {
    pub system: String,
    pub scheme_id_uri: String,
    pub pssh_data: Option<String>,
    pub default_kid: Option<String>,
    pub license_url: Option<String>,
}

#[derive(Debug, Clone)]
pub struct DownloadTask {
    pub id: usize,
    pub stream_url: String,
    pub output_path: String,
    pub progress: u8,
    pub speed_mbps: f32,
    pub log_lines: Vec<String>,
    pub status: DownloadStatus,
}

#[derive(Debug, Clone)]
pub enum DownloadStatus {
    Queued,
    Running,
    Finished,
    Failed(String),
}

#[derive(Debug, Clone, PartialEq)]
pub enum Panel {
    Streams,
    Metadata,
    Downloads,
}

impl AppState {
    pub fn new() -> Self {
        Self {
            next_stream_id: 1,
            selected_tab_index: 0,
            selected_stream_index: 0,
            selected_resolution_index: 0,
            selected_yt_format_index: 0,
            selected_download_index: 0,
            tabs: Vec::new(),
            downloads: Vec::new(),
            tui_logs: Vec::new(),
            intercepted_keys: Vec::new(),
            focused_panel: Panel::Streams,
        }
    }

    pub fn add_stream(&mut self, payload: StreamPayload) -> (usize, u64, bool) {
        let format = detect_format(&payload.url, &payload.response_headers);
        let dedup = path_dedup(&payload.url);

        let tab_pos = self
            .tabs
            .iter()
            .position(|t| t.page_url == payload.page_url);

        if let Some(idx) = tab_pos {
            let tab = &mut self.tabs[idx];
            if let Some(existing) = tab.streams.iter_mut().find(|s| {
                if s.url == payload.url {
                    return true;
                }
                if format != StreamFormat::Mp4 && s.format == format && path_dedup(&s.url) == dedup {
                    return true;
                }
                false
            }) {
                let stream_id = existing.stream_id;
                let should_analyze = if payload.manifest_content.is_some() {
                    match &existing.probe_state {
                        ProbeState::Done(_) => false,
                        _ => {
                            existing.manifest_content = payload.manifest_content.clone();
                            existing.probe_state = ProbeState::Probing;
                            true
                        }
                    }
                } else {
                    false
                };
                existing.url = payload.url;
                existing.request_headers = payload.request_headers;
                (idx, stream_id, !should_analyze)
            } else {
                let stream_id = self.next_stream_id;
                self.next_stream_id += 1;
                let captured = CapturedStream {
                    stream_id,
                    url: payload.url.clone(),
                    method: payload.method,
                    request_headers: payload.request_headers.clone(),
                    server_ip: payload.server_ip,
                    format,
                    probe_state: ProbeState::Probing,
                    manifest_content: payload.manifest_content.clone(),
                };
                tab.streams.push(captured);
                (idx, stream_id, false)
            }
        } else {
            let stream_id = self.next_stream_id;
            self.next_stream_id += 1;
            let captured = CapturedStream {
                stream_id,
                url: payload.url.clone(),
                method: payload.method,
                request_headers: payload.request_headers.clone(),
                server_ip: payload.server_ip,
                format,
                probe_state: ProbeState::Probing,
                manifest_content: payload.manifest_content.clone(),
            };
            let idx = self.tabs.len();
            self.tabs.push(TabSession {
                page_url: payload.page_url,
                page_title: if payload.page_title.is_empty() {
                    "Unknown Page".into()
                } else {
                    payload.page_title
                },
                streams: vec![captured],
                show_noise: false,
                yt_formats: Vec::new(),
            });
            (idx, stream_id, false)
        }
    }

    pub fn selected_stream(&self) -> Option<&CapturedStream> {
        if self.tabs.is_empty() {
            return None;
        }
        let tab = &self.tabs[self.selected_tab_index];
        let fs = tab.filtered_streams();
        if fs.is_empty() {
            return None;
        }
        if self.selected_stream_index >= fs.len() {
            return None;
        }
        Some(fs[self.selected_stream_index])
    }

    pub fn next_tab(&mut self) {
        if self.tabs.len() > 1 {
            self.selected_tab_index = (self.selected_tab_index + 1) % self.tabs.len();
            self.selected_stream_index = 0;
            self.selected_resolution_index = 0;
        }
    }

    pub fn prev_tab(&mut self) {
        if !self.tabs.is_empty() {
            self.selected_tab_index = self
                .selected_tab_index
                .checked_sub(1)
                .unwrap_or(self.tabs.len() - 1);
            self.selected_stream_index = 0;
            self.selected_resolution_index = 0;
        }
    }

    pub fn next_stream(&mut self) {
        if !self.tabs.is_empty() {
            let tab = &self.tabs[self.selected_tab_index];
            let fs_len = tab.filtered_streams().len();
            if fs_len > 1 {
                self.selected_stream_index =
                    (self.selected_stream_index + 1) % fs_len;
                self.selected_resolution_index = 0;
            }
        }
    }

    pub fn prev_stream(&mut self) {
        if !self.tabs.is_empty() {
            let tab = &self.tabs[self.selected_tab_index];
            let fs_len = tab.filtered_streams().len();
            if fs_len > 0 {
                self.selected_stream_index = self
                    .selected_stream_index
                    .checked_sub(1)
                    .unwrap_or(fs_len - 1);
                self.selected_resolution_index = 0;
            }
        }
    }

    pub fn next_resolution(&mut self) {
        if let Some(stream) = self.selected_stream() {
            if let ProbeState::Done(meta) = &stream.probe_state {
                if !meta.resolutions.is_empty() {
                    self.selected_resolution_index =
                        (self.selected_resolution_index + 1) % meta.resolutions.len();
                }
            }
        }
    }

    pub fn prev_resolution(&mut self) {
        if let Some(stream) = self.selected_stream() {
            if let ProbeState::Done(meta) = &stream.probe_state {
                if !meta.resolutions.is_empty() {
                    self.selected_resolution_index = self
                        .selected_resolution_index
                        .checked_sub(1)
                        .unwrap_or(meta.resolutions.len() - 1);
                }
            }
        }
    }

    pub fn set_stream_probe_done(&mut self, stream_id: u64, metadata: StreamMetadata, format: StreamFormat) {
        for tab in &mut self.tabs {
            if let Some(stream) = tab.streams.iter_mut().find(|s| s.stream_id == stream_id) {
                stream.probe_state = ProbeState::Done(metadata);
                stream.format = format;
                return;
            }
        }
    }

    pub fn set_stream_probe_failed(&mut self, stream_id: u64, error: String) {
        for tab in &mut self.tabs {
            if let Some(stream) = tab.streams.iter_mut().find(|s| s.stream_id == stream_id) {
                stream.probe_state = ProbeState::Failed(error);
                return;
            }
        }
    }
}

fn detect_format(url: &str, response_headers: &HashMap<String, String>) -> StreamFormat {
    if let Ok(parsed) = url::Url::parse(url) {
        let path = parsed.path().to_lowercase();
        if path.contains(".m3u8") {
            return StreamFormat::Hls;
        }
        if path.contains(".mpd") {
            return StreamFormat::Dash;
        }
        if path.contains(".mp4") {
            return StreamFormat::Mp4;
        }
        if path.contains(".ts") {
            return StreamFormat::Ts;
        }
    }
    for (k, v) in response_headers {
        if k.to_lowercase() == "content-type" {
            let v_lower = v.to_lowercase();
            if v_lower.contains("mpegurl") {
                return StreamFormat::Hls;
            }
            if v_lower.contains("dash+xml") {
                return StreamFormat::Dash;
            }
            if v_lower.contains("video/mp4") {
                return StreamFormat::Mp4;
            }
            if v_lower.contains("video/mp2t") {
                return StreamFormat::Ts;
            }
        }
    }
    StreamFormat::Unknown
}

/*
pub fn translate_generic_json_manifest(url: &str) -> String {
    if let Ok(mut parsed) = url::Url::parse(url) {
        let path = parsed.path().to_lowercase();
        let is_json_manifest = path.contains("master.json") || path.contains("playlist.json");
        if is_json_manifest {
            let mut new_path = parsed.path().to_string();
            if new_path.contains("master.json") {
                new_path = new_path.replace("master.json", "master.mpd");
            } else if new_path.contains("playlist.json") {
                new_path = new_path.replace("playlist.json", "playlist.mpd");
            }
            parsed.set_path(&new_path);

            let mut params = Vec::new();
            let mut has_ranges = false;
            for (k, v) in parsed.query_pairs() {
                if k == "base64_init" {
                    continue; // Strip base64_init parameter to avoid inline blobs
                }
                if k == "query_string_ranges" {
                    has_ranges = true;
                }
                params.push((k.into_owned(), v.into_owned()));
            }
            if !has_ranges {
                params.push(("query_string_ranges".to_string(), "1".to_string()));
            }

            let mut query_str = String::new();
            for (i, (k, v)) in params.iter().enumerate() {
                if i > 0 { query_str.push('&'); }
                query_str.push_str(&format!("{}={}", k, v));
            }
            parsed.set_query(Some(&query_str));
            return parsed.to_string();
        }
    }
    url.to_string()
}
*/

fn path_dedup(url: &str) -> String {
    if let Ok(parsed) = url::Url::parse(url) {
        let path = parsed.path();
        if let Some(last_slash) = path.rfind('/') {
            let base = &path[..last_slash + 1];
            return format!("{}|{}", parsed.host_str().unwrap_or(""), base);
        }
    }
    url.to_string()
}