aniscraper 0.1.2

Rust library designed for efficient web scraping and data extraction. It simplifies the process of fetching, parsing, and extracting data from websites.
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
use regex::Regex;
use scraper::Html;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
    error::AniRustError,
    proxy::Proxy,
    utils::{anirust_error_vec_to_string, bytes_to_hex, decrypt_aes_256_cbc, get_curl},
};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Track {
    pub file: String,
    pub kind: String,
    pub label: Option<String>,
    pub default: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct IntroOutro {
    pub start: u32,
    pub end: u32,
}

impl Default for IntroOutro {
    fn default() -> Self {
        IntroOutro { start: 0, end: 0 }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MegaCloudUnencryptedSrc {
    pub file: String,
    pub src_type: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MegaCloudExtractedData {
    pub intro: IntroOutro,
    pub outro: IntroOutro,
    pub tracks: Vec<Track>,
    pub sources: Vec<Source>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StreamTapeExtractedData {
    pub url: String,
    pub is_m3u8: bool,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Source {
    #[serde(rename = "file")]
    pub url: String,
    #[serde(rename = "type")]
    pub src_type: String,
}

struct MegaCloud {
    pub script: &'static str,
    pub sources: &'static str,
}

const MEGACLOUD: MegaCloud = MegaCloud {
    script: "https://megacloud.tv/js/player/a/prod/e1-player.min.js?v=",
    sources: "https://megacloud.tv/embed-2/ajax/e-1/getSources?id=",
};

struct StreamSb {
    pub host1: &'static str,
    pub host2: &'static str,
}

const STREAMSB: StreamSb = StreamSb {
    host1: "https://watchsb.com/sources50",
    host2: "https://streamsss.net/sources16",
};

#[derive(Debug, PartialEq, Eq)]
pub enum AnimeServer {
    Vidstreaming,
    Megacloud,
    Streamsb,
    Streamtape,
    Vidcloud,
}

impl AnimeServer {
    pub fn from_str(s: &str) -> Self {
        match s {
            "vidsrc" => AnimeServer::Vidstreaming,
            "megacloud" => AnimeServer::Megacloud,
            "streamsb" => AnimeServer::Streamsb,
            "streamtape" => AnimeServer::Streamtape,
            "vidcloud" => AnimeServer::Vidcloud,
            _ => AnimeServer::Vidstreaming,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            AnimeServer::Vidstreaming => "vidsrc",
            AnimeServer::Megacloud => "megacloud",
            AnimeServer::Streamsb => "streamsb",
            AnimeServer::Streamtape => "streamtape",
            AnimeServer::Vidcloud => "vidcloud",
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum EpisodeType {
    Sub,
    Dub,
}

impl EpisodeType {
    pub fn from_str(s: &str) -> Self {
        match s {
            "sub" => EpisodeType::Sub,
            "dub" => EpisodeType::Dub,
            _ => EpisodeType::Sub,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            EpisodeType::Sub => "sub",
            EpisodeType::Dub => "dub",
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ServerExtractedInfo {
    MegaCloud(MegaCloudExtractedData),
    StreamTape(StreamTapeExtractedData),
}

pub struct MegaCloudServer;

impl MegaCloudServer {
    pub async fn extract(
        video_url: &str,
        proxies: &[Proxy],
    ) -> Result<ServerExtractedInfo, AniRustError> {
        let video_id = extract_video_id(video_url);
        let url = format!("{}{}", MEGACLOUD.sources, video_id);
        let json_data = fetch_initial_data(&url, proxies).await?;

        let is_encrypted = json_data["encrypted"].as_bool().unwrap_or(false);
        let intro: IntroOutro = parse_json_field(&json_data, "intro").unwrap_or_default();
        let outro: IntroOutro = parse_json_field(&json_data, "outro").unwrap_or_default();
        let tracks: Vec<Track> = parse_json_field(&json_data, "tracks")?;

        let sources = if is_encrypted {
            let encrypted_string = extract_encrypted_string(&json_data);
            let decrypted_sources = decrypt_sources(&encrypted_string, proxies).await?;
            parse_sources(&decrypted_sources)?
        } else {
            parse_json_field(&json_data, "sources")?
        };

        Ok(ServerExtractedInfo::MegaCloud(MegaCloudExtractedData {
            intro,
            outro,
            tracks,
            sources,
        }))
    }
}

pub struct StreamTapeServer;

impl StreamTapeServer {
    pub async fn extract(
        video_url: &str,
        proxies: &[Proxy],
    ) -> Result<ServerExtractedInfo, AniRustError> {
        let mut error_vec = vec![];
        let mut curl = String::new();

        match get_curl(video_url, proxies).await {
            Ok(curl_string) => {
                curl = curl_string;
            }
            Err(e) => {
                error_vec.push(Some(e));
            }
        }

        if curl.is_empty() {
            let error_string = anirust_error_vec_to_string(error_vec);
            return Err(AniRustError::UnknownError(error_string));
        }

        let document = Html::parse_document(&curl);

        let re = Regex::new(r"robotlink'\).innerHTML = (.*)'").unwrap();
        let html = document.root_element().html();

        if let Some(captures) = re.captures(&html) {
            if let Some(matched) = captures.get(1) {
                let parts: Vec<&str> = matched.as_str().split("+ ('").collect();
                if parts.len() == 2 {
                    let fh = parts[0].replace('\'', "");
                    let mut sh = parts[1].to_string();
                    sh = sh[3..].to_string();

                    let url = format!("https:{}{}", fh, sh);
                    return Ok(ServerExtractedInfo::StreamTape(StreamTapeExtractedData {
                        url: url.clone(),
                        is_m3u8: url.contains(".m3u8"),
                    }));
                }
            }
        }

        Err(AniRustError::FailedToFetchAfterRetries)
    }
}

// BUG: this server has been shut down
// pub struct StreamSBServer;
//
// impl StreamSBServer {
//     pub async fn extract(
//         video_url: &str,
//         is_alt: Option<bool>,
//         proxies: &[Proxy],
//     ) -> Result<(), AniRustError> {
//         let encoded_id = get_encoded_video_id(video_url);
//         let hexed_id = bytes_to_hex(&encoded_id);
//         let res = process_streamsb_url(is_alt, &hexed_id, proxies).await?;
//         Ok(())
//     }
// }

fn extract_variables(text: &str) -> Result<Vec<(u32, u32)>, AniRustError> {
    let regex = Regex::new(r"case\s*0x[0-9a-f]+:\s*\w+\s*=\s*(\w+)\s*,\s*\w+\s*=\s*(\w+);")?;

    let vars: Vec<(u32, u32)> = regex
        .captures_iter(text)
        .filter_map(|cap| {
            if cap[0].contains("partKey") {
                return None;
            }

            let match_key1 = matching_key(&cap[1], text).ok()?;
            let match_key2 = matching_key(&cap[2], text).ok()?;

            match (
                u32::from_str_radix(&match_key1, 16),
                u32::from_str_radix(&match_key2, 16),
            ) {
                (Ok(key1), Ok(key2)) => Some((key1, key2)),
                _ => None,
            }
        })
        .collect();

    Ok(vars)
}

fn matching_key(value: &str, script: &str) -> Result<String, AniRustError> {
    let regex = Regex::new(&format!(r",{}=(((?:0x)?[0-9a-fA-F]+))", value))?;
    if let Some(captures) = regex.captures(script) {
        let match_str = captures
            .get(1)
            .ok_or_else(|| AniRustError::UnknownError("Failed to capture key".to_string()))?
            .as_str();
        Ok(match_str.trim_start_matches("0x").to_string())
    } else {
        Err(AniRustError::UnknownError(
            "Failed to match the key".to_string(),
        ))
    }
}

fn get_secret(encrypted_string: &str, values: &Vec<(u32, u32)>) -> (String, String) {
    let mut secret = String::new();
    let mut encrypted_source_array: Vec<char> = encrypted_string.chars().collect();
    let mut current_index: usize = 0;

    for &(start_offset, length) in values {
        let start = start_offset as usize + current_index;
        let end = start + length as usize;
        for i in start..end {
            if let Some(ch) = encrypted_string.chars().nth(i) {
                secret.push(ch);
                encrypted_source_array[i] = '\0';
            }
        }
        current_index += length as usize;
    }

    let encrypted_source: String = encrypted_source_array
        .into_iter()
        .filter(|&c| c != '\0')
        .collect();

    (secret, encrypted_source)
}

fn decrypt(
    encrypted: &str,
    key_or_secret: &str,
    maybe_iv: Option<Vec<u8>>,
) -> Result<String, Box<dyn std::error::Error>> {
    let (key, nonce, contents) = if let Some(iv) = maybe_iv {
        (
            key_or_secret.as_bytes().to_vec(),
            iv,
            base64::decode(encrypted).unwrap_or_default(),
        )
    } else {
        let cypher = base64::decode(encrypted).unwrap_or_default();
        let salt = &cypher[8..16];
        let password = [key_or_secret.as_bytes(), salt].concat();

        let mut md5_hashes = Vec::new();
        let mut digest = password.clone();
        for _ in 0..3 {
            let hash = md5::compute(&digest);
            md5_hashes.push(hash.0.to_vec());
            digest = [hash.0.to_vec(), password.clone()].concat();
        }

        let key = [&md5_hashes[0][..], &md5_hashes[1][..]].concat();
        let nonce = md5_hashes[2][..].to_vec();
        let contents = cypher[16..].to_vec();

        (key, nonce, contents)
    };

    let decrypted = decrypt_aes_256_cbc(&nonce, &key, &contents);

    Ok(String::from_utf8(decrypted)?)
}

fn extract_video_id(video_url: &str) -> String {
    video_url
        .split('/')
        .last()
        .and_then(|s| s.split('?').next())
        .unwrap_or_default()
        .to_string()
}

async fn fetch_initial_data(url: &str, proxies: &[Proxy]) -> Result<Value, AniRustError> {
    let response = get_curl(url, proxies).await?;
    serde_json::from_str(&response).map_err(|e| AniRustError::UnknownError(e.to_string()))
}

fn parse_json_field<T: serde::de::DeserializeOwned>(
    json: &Value,
    field: &str,
) -> Result<T, AniRustError> {
    serde_json::from_value(json[field].clone())
        .map_err(|e| AniRustError::UnknownError(format!("Failed to parse {}: {}", field, e)))
}

fn extract_encrypted_string(json: &Value) -> String {
    if let Some(data) = json.get("sources") {
        serde_json::from_str::<String>(data.to_string().as_str()).unwrap_or_default()
    } else {
        String::new()
    }
}

async fn decrypt_sources(
    encrypted_string: &str,
    proxies: &[Proxy],
) -> Result<String, AniRustError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|e| AniRustError::UnknownError(e.to_string()))?
        .as_millis();

    let full_url = format!(
        "https://megacloud.tv/js/player/a/prod/e1-player.min.js?v={}",
        now
    );
    let script = get_curl(&full_url, proxies).await?;

    let variables = extract_variables(&script)?;
    if variables.is_empty() {
        return Err(AniRustError::UnknownError(
            "Can't find variables. Perhaps the extractor is outdated.".to_string(),
        ));
    }

    let (secret, encrypted_source) = get_secret(encrypted_string, &variables);
    let decrypted = decrypt(&encrypted_source, &secret, None)?;
    Ok(decrypted)
}

fn parse_sources(decrypted: &str) -> Result<Vec<Source>, AniRustError> {
    serde_json::from_str(decrypted)
        .map_err(|e| AniRustError::UnknownError(format!("Failed to parse sources: {}", e)))
}

fn get_payload(hex: &str) -> String {
    // `5363587530696d33443675687c7c{hex}7c7c433569475830474c497a65767c7c73747265616d7362`;
    let payload = format!("566d337678566f743674494a7c7c{}7c7c346b6767586d6934774855537c7c73747265616d7362/6565417268755339773461447c7c346133383438333436313335376136323337373433383634376337633465366534393338373136643732373736343735373237613763376334363733353737303533366236333463353333363534366137633763373337343732363536313664373336327c7c6b586c3163614468645a47617c7c73747265616d7362", hex);

    payload
}

fn get_encoded_video_id(video_url: &str) -> Vec<u8> {
    let mut id = video_url
        .split("/e/")
        .last()
        .unwrap_or_default()
        .to_string();

    if id.contains("html") {
        id = id.split(".html").next().unwrap_or_default().to_string();
    }

    id.as_bytes().to_vec()
}

async fn process_streamsb_url(
    is_alt: Option<bool>,
    hexed_id: &str,
    proxies: &[Proxy],
) -> Result<String, AniRustError> {
    let host = if matches!(is_alt, Some(true)) {
        &STREAMSB.host2
    } else {
        &STREAMSB.host1
    };

    let url = format!("{}/{}", host, hexed_id);
    let res = get_curl(&url, proxies).await?;

    Ok(res)
}