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

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

async fn get_user_data(client: &Client<HttpsConnector<HttpConnector>>, token: &str, user_id: u64) -> anyhow::Result<serde_json::Value> {
    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: serde_json::Value = serde_json::from_str(&json_data)?;
    Ok(json)
}

async fn get_avatar_url(client: &Client<HttpsConnector<HttpConnector>>, token: &str, user_id: u64) -> anyhow::Result<String> {
    let json = get_user_data(client, token, user_id).await?;
    let id = json["id"].as_str().ok_or(anyhow::anyhow!("Missing avatar"))?;
    let discrim = json["discriminator"].as_str().ok_or(anyhow::anyhow!("Missing discriminator"))?;
    println!("Served request for {}: {}#{}", id, json["username"], discrim);
    let avatar_url = match json["avatar"].as_str() {
        None => default_avatar_url(discrim)?,
        Some(avatar_hash) => format!("https://cdn.discordapp.com/avatars/{}/{}.png", 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(discrim: &str) -> anyhow::Result<String> {
    let d = discrim.parse::<u16>()?;
    let bare = d % 5;
    Ok(format!("https://cdn.discordapp.com/embed/avatars/{}.png", bare))
}

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 num_id = match userid.parse::<u64>() {
        Err(_) => return make_err(404, "Not found"),
        Ok(num) => num,
    };
    Ok(Response::builder()
        .status(200)
        .header("content-type", "application/json")
        .body(serde_json::to_string("{\"todo\": true}")?.into())?)
}

async fn respond_with_image(arc: Arc<Ctx>, userid: &str) -> anyhow::Result<Response<Body>> {
    let num_id = match userid.parse::<u64>() {
        Err(_) => return make_err(404, "Not found"),
        Ok(num) => num,
    };
    let avatar_url = match get_avatar_url(&arc.client, &arc.token, num_id).await {
        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(())
}