about summary refs log tree commit diff
path: root/users/tazjin/tgsa/src/main.rs
blob: d23430d7ee2ef30cdcbc0ef451919db3257b33ac (plain) (blame)
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
use anyhow::{anyhow, Context, Result};

#[derive(Debug)]
struct TgLink {
    username: String,
    message_id: usize,
}

impl TgLink {
    fn to_url(&self) -> String {
        format!("https://t.me/{}/{}?embed=1", self.username, self.message_id)
    }

    fn parse(url: &str) -> Option<Self> {
        let url = url.strip_prefix("/")?;
        let parsed = url::Url::parse(url).ok()?;

        if parsed.host()? != url::Host::Domain("t.me") {
            // only t.me links are supported
            return None;
        }

        let parts = parsed.path_segments()?.collect::<Vec<&str>>();
        if parts.len() != 2 {
            // only message links are supported
            return None;
        }

        Some(TgLink {
            username: parts[0].into(),
            message_id: parts[1].parse().ok()?,
        })
    }
}

fn fetch_embed(link: &TgLink) -> Result<String> {
    let response = crimp::Request::get(&link.to_url())
        .send()
        .context("failed to fetch embed data")?
        .as_string()
        .context("failed to decode embed data")?
        .error_for_status(|resp| {
            anyhow!("telegram request failed: {} ({})", resp.body, resp.status)
        })?;

    Ok(response.body)
}

#[derive(Debug)]
struct TgMessage {
    author: String,
    message: Option<String>,
    photos: Vec<String>,
    videos: Vec<String>,
}

fn extract_photo_url(style: &str) -> Option<&str> {
    let url_start = style.find("url('")? + 5;
    let url_end = style.find("')")?;

    Some(&style[url_start..url_end])
}

fn parse_tgmessage(embed: &str) -> Result<TgMessage> {
    use scraper::{Html, Selector};

    let doc = Html::parse_document(embed);

    let author_sel = Selector::parse("a.tgme_widget_message_owner_name").unwrap();
    let author = doc
        .select(&author_sel)
        .next()
        .ok_or_else(|| anyhow!("failed to find message author"))?
        .text()
        .collect::<Vec<&str>>()
        .concat();

    let msg_sel = Selector::parse("div.tgme_widget_message_text.js-message_text").unwrap();
    let message = doc
        .select(&msg_sel)
        .next()
        .map(|m| m.text().collect::<Vec<&str>>().concat());

    let photo_sel = Selector::parse("a.tgme_widget_message_photo_wrap").unwrap();
    let mut photos = vec![];

    for photo in doc.select(&photo_sel) {
        if let Some(style) = photo.value().attr("style") {
            if let Some(url) = extract_photo_url(style) {
                photos.push(url.to_string())
            }
        }
    }

    let video_sel = Selector::parse("i.tgme_widget_message_video_thumb").unwrap();
    let mut videos = vec![];

    for video in doc.select(&video_sel) {
        if let Some(style) = video.value().attr("style") {
            if let Some(url) = extract_photo_url(style) {
                videos.push(url.to_string())
            }
        }
    }

    Ok(TgMessage {
        author,
        message,
        photos,
        videos,
    })
}

fn shorten_link(link: &str) -> Result<String> {
    let mut url = url::Url::parse("https://tinyurl.com/api-create.php")?;
    url.query_pairs_mut().clear().append_pair("url", link);

    let request = url.as_str();

    let response = crimp::Request::get(request)
        .send()
        .context("failed to shorten URL")?
        .as_string()
        .context("failed to decode shortened URL")?
        .error_for_status(|resp| {
            anyhow!("tinyurl request failed: {} ({})", resp.body, resp.status)
        })?;

    Ok(response.body.trim().into())
}

fn to_bbcode(link: &TgLink, msg: &TgMessage) -> Result<String> {
    let mut out = String::new();

    out.push_str(&format!("[quote=\"{}\"]\n", msg.author));

    for video in &msg.videos {
        out.push_str(&format!("[url=\"{}\"]", link.to_url()));
        out.push_str(&format!("[img]{}[/img]", shorten_link(video)?));
        out.push_str("[/url]\n");
        out.push_str("[sub](Click thumbnail to open video)[/sub]\n")
    }

    for photo in &msg.photos {
        out.push_str(&format!("[timg]{}[/timg]\n", shorten_link(photo)?));
    }

    if let Some(message) = &msg.message {
        out.push_str(message);
    }

    out.push_str(&format!(
        "\n\n[sub](via [url=\"{}\"]Telegram[/url])[/sub]",
        link.to_url(),
    ));

    out.push_str("\n[/quote]\n");

    Ok(out)
}

fn handle_tg_link(link: &TgLink) -> Result<String> {
    let embed = fetch_embed(&link)?;
    let msg = parse_tgmessage(&embed)?;
    to_bbcode(&link, &msg).context("failed to make bbcode")
}

fn main() {
    crimp::init();

    rouille::start_server("0.0.0.0:8472", move |request| {
        match TgLink::parse(request.raw_url()) {
            None => rouille::Response::text(
                r#"tgsa
----

this is a stupid program that lets you turn telegram message links
into BBcode suitable for pasting on somethingawful dot com

you can use it by putting a valid telegram message link in the url and
waiting a few seconds (yes it's currently slow, yes it's SA's fault,
yes I could work around but can't be bothered atm)

for example:

  https://tgsa.tazj.in/https://t.me/RWApodcast/113

yes, that looks stupid, but it works

if you see this message and think you did the above correctly, you
didn't. try again. idiot.

pm me on the forums if this makes you mad or something.
"#,
            ),
            Some(link) => {
                let result = handle_tg_link(&link);
                match result {
                    Ok(bbcode) => rouille::Response::text(bbcode),
                    Err(err) => rouille::Response::text(format!(
                        r#"something broke: {}

nobody has been alerted about this and it has probably not been
logged. pm me on the forums if you think it's important enough."#,
                        err
                    )),
                }
            }
        }
    });
}