summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 7cb0aff0da629a672a439bf3a2f33b290be2acb7 (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
use std::io::Read;
use std::path::PathBuf;
use std::str::FromStr;

use futures::{
    compat::Future01CompatExt,
    future::{FutureExt, TryFutureExt},
};

use futures01::{future::Future, stream::Stream, sync::mpsc};
use structopt::clap::AppSettings;
use structopt::StructOpt;

use tsclientlib::{
    events::Event, ChannelId, ConnectOptions, Connection, ConnectionLock, DisconnectOptions,
    Event::ConEvents, Identity, MessageTarget,
};

use log::error;

mod state;
use state::State;

#[derive(StructOpt, Debug)]
#[structopt(raw(global_settings = "&[AppSettings::ColoredHelp]"))]
struct Args {
    #[structopt(
        short = "a",
        long = "address",
        default_value = "localhost",
        help = "The address of the server to connect to"
    )]
    address: String,
    #[structopt(
        short = "i",
        long = "id",
        help = "Identity file - good luck creating one",
        parse(from_os_str)
    )]
    id_path: Option<PathBuf>,
    #[structopt(
        short = "v",
        long = "verbose",
        help = "Print the content of all packets",
        parse(from_occurrences)
    )]
    verbose: u8,
    // 0. Print nothing
    // 1. Print command string
    // 2. Print packets
    // 3. Print udp packets
}

fn main() {
    tokio::run(async_main().unit_error().boxed().compat());
}

async fn async_main() {
    // Parse command line options
    let args = Args::from_args();

    let id = if let Some(path) = args.id_path {
        let mut file = std::fs::File::open(path).expect("Failed to open id file");
        let mut content = String::new();
        file.read_to_string(&mut content)
            .expect("Failed to read id file");

        toml::from_str(&content).expect("Failed to parse id file")
    } else {
        Identity::create().expect("Failed to create id")
    };

    let con_config = ConnectOptions::new(args.address)
        .version(tsclientlib::Version::Linux_3_3_2)
        .name(String::from("PokeBot"))
        .identity(id)
        .log_commands(args.verbose >= 1)
        .log_packets(args.verbose >= 2)
        .log_udp_packets(args.verbose >= 3);

    //let (disconnect_send, disconnect_recv) = mpsc::unbounded();
    let conn = Connection::new(con_config).compat().await.unwrap();

    let mut state = State::new(conn.clone());
    {
        let packet = conn.lock().server.set_subscribed(true);
        conn.send_packet(packet).compat().await;
    }
    //con.add_on_disconnect(Box::new( || {
    //disconnect_send.unbounded_send(()).unwrap()
    //}));
    let inner_state = state.clone();
    conn.add_event_listener(
        String::from("listener"),
        Box::new(move |e| {
            if let ConEvents(conn, events) = e {
                for event in *events {
                    handle_event(&inner_state, &conn, event);
                }
            }
        }),
    );

    loop {
        state.poll().await;
    }
    let ctrl_c = tokio_signal::ctrl_c().flatten_stream();

    //let dc_fut = disconnect_recv.into_future().compat().fuse();
    //let ctrlc_fut = ctrl_c.into_future().compat().fuse();
    //ctrlc_fut.await.map_err(|(e, _)| e).unwrap();

    conn.disconnect(DisconnectOptions::new())
        .compat()
        .await
        .unwrap();

    // TODO Should not be required
    std::process::exit(0);
}

fn handle_event<'a>(state: &State, conn: &ConnectionLock<'a>, event: &Event) {
    match event {
        Event::Message {
            from: target,
            invoker: sender,
            message: msg,
        } => {
            if let MessageTarget::Poke(who) = target {
                let channel = conn
                    .clients
                    .get(&who)
                    .expect("can find poke sender")
                    .channel;
                tokio::spawn(
                    conn.to_mut()
                        .get_client(&conn.own_client)
                        .expect("can get myself")
                        .set_channel(channel)
                        .map_err(|e| error!("Failed to switch channel: {}", e)),
                );
            } else if sender.id != conn.own_client {
                if msg.starts_with("!") {
                    let tokens = msg[1..].split_whitespace().collect::<Vec<_>>();
                    match tokens.get(0).map(|t| *t) {
                        Some("test") => {
                            tokio::spawn(
                                conn.to_mut()
                                    .send_message(*target, "works :)")
                                    .map_err(|_| ()),
                            );
                        }
                        Some("add") => {
                            let mut invalid = false;
                            if let Some(url) = &tokens.get(1) {
                                if url.len() > 11 {
                                    tokio::spawn(
                                        conn.to_mut().set_name("PokeBot - Loading").map_err(|_| ()),
                                    );
                                    let trimmed = url[5..url.len() - 6].to_owned();
                                    state.add_audio(trimmed);
                                } else {
                                    invalid = true;
                                }
                            } else {
                                invalid = true;
                            }
                            if invalid {
                                tokio::spawn(
                                    conn.to_mut()
                                        .send_message(MessageTarget::Channel, "Invalid Url")
                                        .map_err(|_| ()),
                                );
                            }
                        }
                        Some("volume") => {
                            if let Ok(volume) = f64::from_str(tokens[1]) {
                                state.volume(volume / 100.0);
                            }
                        }
                        Some("play") => {
                            state.play();
                        }
                        Some("pause") => {
                            state.pause();
                        }
                        Some("stop") => {
                            state.stop();
                        }
                        _ => (),
                    };
                }
            }
        }
        _ => (),
    }
}