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
use std::path::Path;

use grammers_client::{
    types::{Downloadable, Media, Message},
    Client,
};
use log::{debug, error, info};
use mime::Mime;
// pub mod audio;
pub mod fabric;
pub mod message_handler;
pub mod test_handler;
pub mod update_handler;
pub mod whisper;
pub mod you_hander;

pub fn get_message_video(message: &&Message) -> Option<grammers_client::types::Media> {
    match message.media() {
        Some(media) => match media {
            Media::Document(_) => {
                if crate::handlers::get_file_extension(&media).eq(".mp4") {
                    Some(media)
                } else {
                    None
                }
            }
            _ => None, // Filter out any other media types
        },
        None => None,
    }
}

pub fn has_video(message: &&Message) -> bool {
    match message.media() {
        Some(media) => match media {
            grammers_client::types::Media::Document(_) => {
                if crate::handlers::get_file_extension(&media).eq(".mp4") {
                    true
                } else {
                    false
                }
            }
            _ => false, // Filter out any other media types
        },
        None => false,
    }
}

pub fn get_file_size(media: &Media) -> i64 {
    match media {
        Media::Photo(photo) => photo.size(),
        Media::Sticker(sticker) => sticker.document.size(),
        Media::Document(document) => document.size(),
        Media::Contact(_) => 0 as i64,
        _ => 0 as i64,
    }
}

pub fn get_file_extension(media: &Media) -> String {
    match media {
        Media::Photo(_) => ".jpg".to_string(),
        Media::Sticker(sticker) => get_mime_extension(sticker.document.mime_type()),
        Media::Document(document) => get_mime_extension(document.mime_type()),
        Media::Contact(_) => ".vcf".to_string(),
        _ => String::new(),
    }
}

pub fn get_mime_extension(mime_type: Option<&str>) -> String {
    mime_type
        .map(|m| {
            let mime: Mime = m.parse().unwrap();
            format!(".{}", mime.subtype())
        })
        .unwrap_or_default()
}

pub async fn download_media(
    tg: &Client,
    media: grammers_client::types::Media,
    message_id: i32,
) -> String {
    let dest = format!(
        "./data/cache/message-{}{}",
        &message_id.to_string(),
        crate::handlers::get_file_extension(&media)
    );

    let destination_path = Path::new(&dest);
    match destination_path.exists() {
        true => {
            debug!("Media exists {}", dest);
        }
        false => {
            match tg
                .download_media(
                    &Downloadable::Media(media.clone()),
                    &Path::new(dest.as_str()),
                )
                .await
            {
                Ok(_) => {
                    let expected_size: u64 = crate::handlers::get_file_size(&media) as u64;
                    let mut file_size: u64 = 0;
                    while file_size < expected_size {
                        file_size = tokio::fs::metadata(&dest).await.unwrap().len();
                        info!(
                            "Waiting for file to download... {} / {} bytes",
                            file_size, expected_size
                        );
                        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    }
                    info!(
                        "Downloaded {:?} of media to {}",
                        media.to_raw_input_location().unwrap(),
                        dest
                    );
                }
                Err(_) => {
                    error!("Failed to download media");
                }
            };
        }
    }

    dest
}