aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: bf20c95befdcb867f53286d2e433f46955196d1b (plain)
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
use std::env;
use std::fmt::format;
use std::net::SocketAddr;
use std::sync::Arc;

use hyper::client::{Client, HttpConnector};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use hyper_tls::HttpsConnector;
use serde::{Deserialize, Serialize};
use serde_json::Value;

macro_rules! unwrap_resp {
    ($x:expr) => {
        match $x {
            Ok(x) => x,
            Err(x) => return Ok(x),
        }
    };
}

#[derive(Deserialize, Debug)]
struct DiscordUserFormat {
    accent_color: Option<i64>,
    username: String,
    discriminator: String,
    id: String,
    public_flags: i64,
    #[serde(default)]
    bot: bool,
    banner: Option<String>,
    avatar: Option<String>,
}

async fn get_user_data(
    client: &Client<HttpsConnector<HttpConnector>>,
    token: &str,
    user_id: u64,
) -> anyhow::Result<DiscordUserFormat> {
    let request = Request::builder()
        .method(Method::GET)
        .uri(format!("https://discord.com/api/v10/users/{}", user_id))
        .header("accept", "application/json")
        .header("authorization", format!("Bot {}", token))
        .body(Body::empty())?;
    let mut x = client.request(request).await?;
    let body = hyper::body::to_bytes(x.body_mut()).await?;
    let json_data = String::from_utf8(Vec::from(body))?;
    let json: DiscordUserFormat = serde_json::from_str(&json_data)?;
    Ok(json)
}

fn get_avatar_url(json: &DiscordUserFormat) -> anyhow::Result<String> {
    println!(
        "Served request for {}: {}#{}",
        json.id, json.username, json.discriminator
    );
    let avatar_url = match &json.avatar {
        None => default_avatar_url(&json.id, &json.discriminator)?,
        Some(avatar_hash) => format!(
            "https://cdn.discordapp.com/avatars/{}/{}.png",
            json.id, avatar_hash
        ),
    };
    Ok(avatar_url)
}

fn make_err(err: u16, text: &str) -> anyhow::Result<Response<Body>> {
    return Ok(Response::builder()
        .status(err)
        .body(format!("{} {}", err, text).into())?);
}

async fn resp(arc: Arc<Ctx>, req: Request<Body>) -> anyhow::Result<Response<Body>> {
    let x = req.uri().path();
    if x == "/" {
        return Ok(Response::builder()
            .status(302)
            .header("Location", "https://git.nea.moe/nea/discordavatarproxy")
            .body(Body::empty())?);
    }
    let request = match x.strip_prefix("/avatar/") {
        None => return make_err(404, "Not found"),
        Some(request) => request,
    };
    if let Some(userid) = request.strip_suffix(".png") {
        return respond_with_image(arc, userid).await;
    }
    if let Some(userid) = request.strip_suffix(".json") {
        return respond_with_json(arc, userid).await;
    }
    return make_err(404, "Invalid format");
}

fn default_avatar_url(user_id: &str, discrim: &str) -> anyhow::Result<String> {
    let d = discrim.parse::<u16>()?;
    let id = user_id.parse::<u64>()?;
    let bare = if d == 0 {
        ((id >> 22) % 6) as u16
    } else {
        d % 5
    };
    Ok(format!(
        "https://cdn.discordapp.com/embed/avatars/{}.png",
        bare
    ))
}

#[derive(Serialize, Debug)]
struct ResponseUserFormat {
    username: String,
    discriminator: String,
    avatar: String,
    banner: Option<String>,
}

async fn respond_with_json(arc: Arc<Ctx>, userid: &str) -> anyhow::Result<Response<Body>> {
    let json = unwrap_resp!(get_discord_data_for(&arc, userid).await?);
    let avatar_url = get_avatar_url(&json)?;
    let response = ResponseUserFormat {
        username: json.username,
        discriminator: json.discriminator,
        avatar: avatar_url,
        banner: json.banner.map(|hash| {
            format!(
                "https://cdn.discordapp.com/banners/{}/{}.png",
                json.id, hash
            )
        }),
    };
    Ok(Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(serde_json::to_string(&response)?.into())?)
}

async fn get_discord_data_for(
    arc: &Arc<Ctx>,
    userid: &str,
) -> anyhow::Result<anyhow::Result<DiscordUserFormat, Response<Body>>> {
    let num_id = match userid.parse::<u64>() {
        Err(_) => return make_err(404, "Not found").map(Err),
        Ok(num) => num,
    };
    Ok(Ok(
        match get_user_data(&arc.client, &arc.token, num_id).await {
            Err(e) => {
                eprintln!("Got error from discord: {:?}", e);
                return make_err(502, "Discord failed to respond").map(Err);
            }
            Ok(user_data) => user_data,
        },
    ))
}

async fn respond_with_image(arc: Arc<Ctx>, userid: &str) -> anyhow::Result<Response<Body>> {
    let json = unwrap_resp!(get_discord_data_for(&arc, userid).await?);
    let avatar_url = match get_avatar_url(&json) {
        Err(_) => return make_err(502, "Discord failed to respond"),
        Ok(avatar_url) => avatar_url,
    };
    let resp = match arc.client.get(avatar_url.parse()?).await {
        Err(_) => {
            return make_err(
                502,
                &format!("Discord failed to supply avatar for url: {}", avatar_url),
            )
        }
        Ok(avatar_data) => avatar_data,
    };
    Ok(Response::builder()
        .status(200)
        .header("content-type", "image/png")
        .body(resp.into_body())?)
}

struct Ctx {
    client: Client<HttpsConnector<HttpConnector>>,
    token: String,
}

async fn wrap_error(arc: Arc<Ctx>, req: Request<Body>) -> anyhow::Result<Response<Body>> {
    return match resp(arc, req).await {
        Err(e) => {
            eprintln!("{:?}", e);
            Ok(Response::builder()
                .status(500)
                .body("500 Internal Error".into())?)
        }
        Ok(o) => Ok(o),
    };
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let token = env::var("TOKEN")?;
    let portstr = env::var("PORT")?;
    let port = portstr.parse::<u16>()?;
    println!("Running with token: {}", token);
    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, Body>(https);
    let arc = Arc::new(Ctx { client, token });
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let service = make_service_fn(|_conn| {
        let carc = Arc::clone(&arc);
        async move { Ok::<_, anyhow::Error>(service_fn(move |req| wrap_error(Arc::clone(&carc), req))) }
    });

    let server = Server::bind(&addr).serve(service);
    server.await?;
    Ok(())
}