ferristream 0.0.21

A TUI app for streaming torrents on-the-fly
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
use reqwest::Client;
use serde::Deserialize;
use thiserror::Error;
use tracing::{debug, info};

#[derive(Error, Debug)]
pub enum OpenSubtitlesError {
    #[error("request failed: {0}")]
    RequestError(#[from] reqwest::Error),
    #[error("no subtitles found")]
    NotFound,
    #[error("API error: {0}")]
    ApiError(String),
}

#[derive(Debug, Deserialize)]
struct SearchResponse {
    data: Vec<SubtitleResult>,
}

#[derive(Debug, Deserialize)]
struct SubtitleResult {
    attributes: SubtitleAttributes,
}

#[derive(Debug, Deserialize)]
struct SubtitleAttributes {
    language: String,
    files: Vec<SubtitleFileInfo>,
}

#[derive(Debug, Deserialize)]
struct SubtitleFileInfo {
    file_id: u64,
    file_name: String,
}

#[derive(Debug, Deserialize)]
struct DownloadResponse {
    link: String,
}

const BASE_URL: &str = "https://api.opensubtitles.com";

pub struct OpenSubtitlesClient {
    client: Client,
    api_key: String,
    base_url: String,
}

#[derive(Debug, Clone)]
pub struct SubtitleDownload {
    pub language: String,
    pub file_name: String,
    pub download_url: String,
}

impl OpenSubtitlesClient {
    pub fn new(api_key: &str) -> Self {
        Self::new_with_base_url(api_key, BASE_URL)
    }

    #[cfg(test)]
    pub(crate) fn new_with_base_url(api_key: &str, base_url: &str) -> Self {
        let user_agent = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));

        let client = Client::builder()
            .user_agent(user_agent)
            .build()
            .expect("Failed to build HTTP client");

        Self {
            client,
            api_key: api_key.to_string(),
            base_url: base_url.to_string(),
        }
    }

    #[cfg(not(test))]
    fn new_with_base_url(api_key: &str, base_url: &str) -> Self {
        let user_agent = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));

        let client = Client::builder()
            .user_agent(user_agent)
            .build()
            .expect("Failed to build HTTP client");

        Self {
            client,
            api_key: api_key.to_string(),
            base_url: base_url.to_string(),
        }
    }

    /// Search for subtitles by IMDB ID
    pub async fn search_by_imdb(
        &self,
        imdb_id: &str,
        language: &str,
    ) -> Result<Vec<SubtitleDownload>, OpenSubtitlesError> {
        // Clean IMDB ID (remove 'tt' prefix if present)
        let imdb_clean = imdb_id.trim_start_matches("tt");

        let url = format!(
            "{}/api/v1/subtitles?imdb_id={}&languages={}",
            self.base_url, imdb_clean, language
        );

        debug!(imdb = imdb_clean, language, "searching OpenSubtitles");

        let response = self
            .client
            .get(&url)
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(OpenSubtitlesError::ApiError(format!(
                "HTTP {}: {}",
                status, body
            )));
        }

        let search: SearchResponse = response.json().await?;

        if search.data.is_empty() {
            return Err(OpenSubtitlesError::NotFound);
        }

        info!(count = search.data.len(), "found subtitles");

        // Get download links for each subtitle
        let mut results = Vec::new();
        for sub in search.data.into_iter().take(3) {
            // Limit to top 3
            if let Some(file) = sub.attributes.files.first() {
                match self.get_download_link(file.file_id).await {
                    Ok(link) => {
                        results.push(SubtitleDownload {
                            language: sub.attributes.language.clone(),
                            file_name: file.file_name.clone(),
                            download_url: link,
                        });
                    }
                    Err(e) => {
                        debug!(error = %e, "failed to get download link");
                    }
                }
            }
        }

        if results.is_empty() {
            return Err(OpenSubtitlesError::NotFound);
        }

        Ok(results)
    }

    /// Search for subtitles by TMDB ID
    pub async fn search_by_tmdb(
        &self,
        tmdb_id: u64,
        language: &str,
    ) -> Result<Vec<SubtitleDownload>, OpenSubtitlesError> {
        let url = format!(
            "{}/api/v1/subtitles?tmdb_id={}&languages={}",
            self.base_url, tmdb_id, language
        );

        debug!(tmdb_id, language, "searching OpenSubtitles by TMDB");

        let response = self
            .client
            .get(&url)
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(OpenSubtitlesError::ApiError(format!(
                "HTTP {}: {}",
                status, body
            )));
        }

        let search: SearchResponse = response.json().await?;

        if search.data.is_empty() {
            return Err(OpenSubtitlesError::NotFound);
        }

        info!(count = search.data.len(), "found subtitles");

        let mut results = Vec::new();
        for sub in search.data.into_iter().take(3) {
            if let Some(file) = sub.attributes.files.first() {
                match self.get_download_link(file.file_id).await {
                    Ok(link) => {
                        results.push(SubtitleDownload {
                            language: sub.attributes.language.clone(),
                            file_name: file.file_name.clone(),
                            download_url: link,
                        });
                    }
                    Err(e) => {
                        debug!(error = %e, "failed to get download link");
                    }
                }
            }
        }

        if results.is_empty() {
            return Err(OpenSubtitlesError::NotFound);
        }

        Ok(results)
    }

    async fn get_download_link(&self, file_id: u64) -> Result<String, OpenSubtitlesError> {
        let url = format!("{}/api/v1/download", self.base_url);

        let response = self
            .client
            .post(url)
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({ "file_id": file_id }))
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(OpenSubtitlesError::ApiError(format!(
                "HTTP {}: {}",
                status, body
            )));
        }

        let download: DownloadResponse = response.json().await?;
        Ok(download.link)
    }
}

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

    #[test]
    fn test_imdb_id_cleaning() {
        // Test that IMDB IDs have 'tt' prefix removed
        let client = OpenSubtitlesClient::new("test-key");
        // We can't easily test the async function directly, but we can verify the cleaning logic
        // by examining what would happen with different inputs
        assert_eq!("1234567".trim_start_matches("tt"), "1234567");
        assert_eq!("tt1234567".trim_start_matches("tt"), "1234567");
        assert_eq!("tt0133093".trim_start_matches("tt"), "0133093"); // The Matrix
    }

    #[test]
    fn test_user_agent_format() {
        let client = OpenSubtitlesClient::new("test-key");
        // User agent should be in format "ferristream/VERSION"
        let expected_prefix = "ferristream/";
        // We can't directly access the user agent, but we verify the format is built correctly
        assert!(env!("CARGO_PKG_NAME") == "ferristream");
        assert!(!env!("CARGO_PKG_VERSION").is_empty());
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;
    use wiremock::matchers::{body_json, header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_search_by_imdb_success() {
        let mock_server = MockServer::start().await;

        let search_response = serde_json::json!({
            "data": [
                {
                    "attributes": {
                        "language": "en",
                        "files": [
                            {
                                "file_id": 123,
                                "file_name": "movie.en.srt"
                            }
                        ]
                    }
                }
            ]
        });

        let download_response = serde_json::json!({
            "link": "https://example.com/download/subtitle.srt"
        });

        // Mock search endpoint
        Mock::given(method("GET"))
            .and(path("/api/v1/subtitles"))
            .and(query_param("imdb_id", "0133093"))
            .and(query_param("languages", "en"))
            .and(header("Api-Key", "test-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&search_response))
            .mount(&mock_server)
            .await;

        // Mock download endpoint
        Mock::given(method("POST"))
            .and(path("/api/v1/download"))
            .and(header("Api-Key", "test-key"))
            .and(body_json(serde_json::json!({"file_id": 123})))
            .respond_with(ResponseTemplate::new(200).set_body_json(&download_response))
            .mount(&mock_server)
            .await;

        // Create client with mock server URL
        let client = OpenSubtitlesClient::new_with_base_url("test-key", &mock_server.uri());

        // Test the actual API call
        let subtitles = client.search_by_imdb("tt0133093", "en").await.unwrap();

        assert_eq!(subtitles.len(), 1);
        assert_eq!(subtitles[0].language, "en");
        assert_eq!(subtitles[0].file_name, "movie.en.srt");
        assert_eq!(
            subtitles[0].download_url,
            "https://example.com/download/subtitle.srt"
        );
    }

    #[tokio::test]
    async fn test_search_by_imdb_with_tt_prefix() {
        // Test that "tt" prefix is properly removed
        let imdb_with_prefix = "tt0133093";
        let imdb_without_prefix = imdb_with_prefix.trim_start_matches("tt");
        assert_eq!(imdb_without_prefix, "0133093");
    }

    #[tokio::test]
    async fn test_search_response_deserialization() {
        let json = r#"{
            "data": [
                {
                    "attributes": {
                        "language": "en",
                        "files": [
                            {
                                "file_id": 456,
                                "file_name": "test.srt"
                            }
                        ]
                    }
                }
            ]
        }"#;

        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.data.len(), 1);
        assert_eq!(response.data[0].attributes.language, "en");
        assert_eq!(response.data[0].attributes.files[0].file_id, 456);
        assert_eq!(response.data[0].attributes.files[0].file_name, "test.srt");
    }

    #[tokio::test]
    async fn test_search_response_empty() {
        let json = r#"{"data": []}"#;
        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert!(response.data.is_empty());
    }

    #[tokio::test]
    async fn test_download_response_deserialization() {
        let json = r#"{"link": "https://example.com/subtitle.srt"}"#;
        let response: DownloadResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.link, "https://example.com/subtitle.srt");
    }

    #[tokio::test]
    async fn test_subtitle_result_multiple_files() {
        let json = r#"{
            "data": [
                {
                    "attributes": {
                        "language": "es",
                        "files": [
                            {
                                "file_id": 100,
                                "file_name": "first.srt"
                            },
                            {
                                "file_id": 101,
                                "file_name": "second.srt"
                            }
                        ]
                    }
                }
            ]
        }"#;

        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.data[0].attributes.files.len(), 2);
        // Implementation uses .first() so only first file is used
        assert_eq!(response.data[0].attributes.files[0].file_name, "first.srt");
    }

    #[tokio::test]
    async fn test_search_by_imdb_not_found() {
        let mock_server = MockServer::start().await;

        let empty_response = serde_json::json!({
            "data": []
        });

        Mock::given(method("GET"))
            .and(path("/api/v1/subtitles"))
            .and(query_param("imdb_id", "9999999"))
            .and(query_param("languages", "en"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&empty_response))
            .mount(&mock_server)
            .await;

        let client = OpenSubtitlesClient::new_with_base_url("test-key", &mock_server.uri());
        let result = client.search_by_imdb("tt9999999", "en").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), OpenSubtitlesError::NotFound));
    }

    #[tokio::test]
    async fn test_search_by_imdb_api_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/api/v1/subtitles"))
            .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized"))
            .mount(&mock_server)
            .await;

        let client = OpenSubtitlesClient::new_with_base_url("bad-key", &mock_server.uri());
        let result = client.search_by_imdb("tt0133093", "en").await;

        assert!(result.is_err());
        match result.unwrap_err() {
            OpenSubtitlesError::ApiError(msg) => {
                assert!(msg.contains("401"));
            }
            _ => panic!("Expected ApiError"),
        }
    }

    #[tokio::test]
    async fn test_search_by_tmdb_success() {
        let mock_server = MockServer::start().await;

        let search_response = serde_json::json!({
            "data": [
                {
                    "attributes": {
                        "language": "es",
                        "files": [
                            {
                                "file_id": 456,
                                "file_name": "pelicula.es.srt"
                            }
                        ]
                    }
                }
            ]
        });

        let download_response = serde_json::json!({
            "link": "https://example.com/download/spanish.srt"
        });

        Mock::given(method("GET"))
            .and(path("/api/v1/subtitles"))
            .and(query_param("tmdb_id", "603"))
            .and(query_param("languages", "es"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&search_response))
            .mount(&mock_server)
            .await;

        Mock::given(method("POST"))
            .and(path("/api/v1/download"))
            .and(body_json(serde_json::json!({"file_id": 456})))
            .respond_with(ResponseTemplate::new(200).set_body_json(&download_response))
            .mount(&mock_server)
            .await;

        let client = OpenSubtitlesClient::new_with_base_url("test-key", &mock_server.uri());
        let subtitles = client.search_by_tmdb(603, "es").await.unwrap();

        assert_eq!(subtitles.len(), 1);
        assert_eq!(subtitles[0].language, "es");
        assert_eq!(subtitles[0].file_name, "pelicula.es.srt");
        assert_eq!(
            subtitles[0].download_url,
            "https://example.com/download/spanish.srt"
        );
    }

    #[tokio::test]
    async fn test_multiple_subtitles_limited_to_3() {
        let mock_server = MockServer::start().await;

        let search_response = serde_json::json!({
            "data": [
                {
                    "attributes": {
                        "language": "en",
                        "files": [{"file_id": 1, "file_name": "sub1.srt"}]
                    }
                },
                {
                    "attributes": {
                        "language": "en",
                        "files": [{"file_id": 2, "file_name": "sub2.srt"}]
                    }
                },
                {
                    "attributes": {
                        "language": "en",
                        "files": [{"file_id": 3, "file_name": "sub3.srt"}]
                    }
                },
                {
                    "attributes": {
                        "language": "en",
                        "files": [{"file_id": 4, "file_name": "sub4.srt"}]
                    }
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/api/v1/subtitles"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&search_response))
            .mount(&mock_server)
            .await;

        // Mock download endpoints for first 3
        for i in 1..=3 {
            Mock::given(method("POST"))
                .and(path("/api/v1/download"))
                .and(body_json(serde_json::json!({"file_id": i})))
                .respond_with(ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"link": format!("https://example.com/sub{}.srt", i)}),
                ))
                .mount(&mock_server)
                .await;
        }

        let client = OpenSubtitlesClient::new_with_base_url("test-key", &mock_server.uri());
        let subtitles = client.search_by_imdb("tt0133093", "en").await.unwrap();

        // Should only return top 3
        assert_eq!(subtitles.len(), 3);
    }
}