summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 76a929d078127f0ff30152490845360768601abf (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
use hyper::{Body, Request, Response, Server, service::{make_service_fn, service_fn}};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use webhook::client::WebhookClient;
use std::error::Error;

const IMAGE_URL: &str = "https://www.counter-strike.net/favicon.ico";

#[derive(Debug, Deserialize)]
struct MatchData {
    map: Option<MapData>,
    round: Option<RoundData>,
    player_id: Option<PlayerIdData>,
    player_state: Option<PlayerStateData>,
    player_weapons: Option<PlayerWeaponsData>,
    player_match_stats: Option<PlayerMatchStatsData>,
    allplayers_id: Option<AllPlayersIdData>,
}

#[derive(Debug, Deserialize)]
struct MapData {
    name: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RoundData {
    phase: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PlayerIdData {
    id: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct PlayerStateData {
    health: Option<u32>,
    armor: Option<u32>,
    flashed: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct PlayerWeaponsData {
    primary: Option<String>,
    secondary: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PlayerMatchStatsData {
    kills: Option<u32>,
    deaths: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct AllPlayersIdData {
    players: Vec<PlayerIdData>,
}

#[derive(Serialize)]
struct Message {
    content: String,
}

// Define the state type
type State = Arc<Mutex<HashMap<String, HashMap<String, i64>>>>;

async fn handle_request(req: Request<Body>, state: State) -> Result<Response<Body>, Box<dyn Error + Send + Sync>> {
    if req.method() == hyper::Method::POST {
        let whole_body = hyper::body::to_bytes(req.into_body()).await?;

        // Attempt to parse the JSON
        match serde_json::from_slice::<Value>(&whole_body) {
            Ok(json) => {
                // Print the raw JSON for debugging
                // println!("Received JSON: {}", json);

                // Lock the state for reading and writing
                let mut previous_state = state.lock().unwrap();
                
                // Check if the JSON value is an object
                if let Some(map) = json.as_object() {
                    if let Some(player) = map.get("player") {
                        if let Some(player_obj) = player.as_object() {
                            // Extract weapon information
                            if let Some(weapons) = player_obj.get("weapons") {
                                if let Some(weapons_obj) = weapons.as_object() {
                                    for (weapon_key, weapon_value) in weapons_obj {
                                        if let Some(weapon_obj) = weapon_value.as_object() {
                                            if let Some(name) = weapon_obj.get("name") {
                                                if let Some(name_str) = name.as_str() {
                                                    if let Some(ammo_clip) = weapon_obj.get("ammo_clip") {
                                                        if let Some(ammo_clip_value) = ammo_clip.as_i64() {
                                                            // Update previous state
                                                            let mut weapon_state = previous_state.entry(weapon_key.clone()).or_insert_with(HashMap::new);
                                                            let prev_ammo_clip = weapon_state.entry("ammo_clip".to_string()).or_insert(0);

                                                            // Print debug information
                                                            println!("Weapon: {}, Ammo Clip (prev): {}, Ammo Clip (current): {}", name_str, prev_ammo_clip, ammo_clip_value);

                                                            // Compare ammo_clip with previous state
                                                            if ammo_clip_value < *prev_ammo_clip {
                                                                println!("Weapon {}: {} fired! Ammo Clip: {} -> {}", weapon_key, name_str, prev_ammo_clip, ammo_clip_value);
                                                                
                                                                let url = "https://discord.com/api/webhooks/1277517311347261470/4-UgsyHK3-AcWai9xWsOMHkpnpAHuFc0Izp3fRCb7M0NaHNng9h6tKmS3x_k4X-4tdMS";
                                                                
                                                                // Send the webhook message in an async block
                                                                let client = WebhookClient::new(&url);
                                                                let webhook_info = client.get_information().await?;
                                                                println!("webhook: {:?}", webhook_info);
                                                            
                                                                client.send(|message| message
                                                                    .content("@everyone")
                                                                    .username("Thoo")
                                                                    .avatar_url(IMAGE_URL)
                                                                    .embed(|embed| embed
                                                                        .title("Webhook")
                                                                        .description("Hello, World!")
                                                                        .footer("Footer", Some(String::from(IMAGE_URL)))
                                                                        .image(IMAGE_URL)
                                                                        .thumbnail(IMAGE_URL)
                                                                        .author("Lmao#0001", Some(String::from(IMAGE_URL)), Some(String::from(IMAGE_URL)))
                                                                        .field("name", "value", false))).await?;
                                                            
                                                               }

                                                            // Update previous ammo_clip
                                                            *prev_ammo_clip = ammo_clip_value;
                                                        } else {
                                                            println!("Ammo clip is not an integer for weapon {}", name_str);
                                                        }
                                                    } else {
                                                        println!("Ammo clip field is missing for weapon {}", name_str);
                                                    }
                                                } else {
                                                    println!("Weapon name is not a string");
                                                }
                                            } else {
                                                println!("Weapon object does not contain a name field");
                                            }
                                        } else {
                                            println!("Weapon value is not an object");
                                        }
                                    }
                                } else {
                                    println!("Weapons field is not an object");
                                }
                            } else {
                                println!("Player object does not contain weapons field");
                            }
                        } else {
                            println!("Player field is not an object");
                        }
                    } else {
                        println!("JSON does not contain player field");
                    }
                } else {
                    println!("JSON is not an object");
                }

                Ok(Response::new(Body::from("Received")))
            },
            Err(e) => {
                eprintln!("Failed to parse JSON: {}", e);
                Ok(Response::new(Body::from("Invalid JSON")))
            }
        }
    } else {
        Ok(Response::new(Body::from("Unsupported HTTP method")))
    }
}

#[tokio::main]
async fn main() {
    // Initialize the global state
    let state = Arc::new(Mutex::new(HashMap::new()));

    let make_svc = make_service_fn(move |_conn| {
        let state = state.clone();
        async move { 
            Ok::<_, Box<dyn Error + Send + Sync>>(service_fn(move |req| handle_request(req, state.clone())))
        }
    });

    let addr = ([0, 0, 0, 0], 5000).into(); // Listen on all interfaces on port 5000
    let server = Server::bind(&addr).serve(make_svc);

    println!("Listening on http://{}", addr);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}