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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
pub mod message;
use self::message::Message;
pub use chrono;
use futures::sync::mpsc;
use reqwest::r#async::Client;
use serde_derive::Deserialize;
use std::error::Error as StdError;
use std::fmt::{self, Display, Formatter};
use std::result::Result as StdResult;
use std::str::Utf8Error;
use std::time::{Duration, Instant};
use tokio::prelude::stream::{SplitSink, SplitStream};
use tokio::prelude::*;
use tokio::timer::{self, Delay};
use websocket::r#async;
pub use websocket::url;
use websocket::url::Url;
use websocket::{ClientBuilder, OwnedMessage, WebSocketError};
pub struct Receiver {
stream: SplitStream<r#async::Client<Box<dyn r#async::Stream + Send>>>,
}
impl fmt::Debug for Receiver {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Receiver").finish()
}
}
#[derive(Debug)]
pub struct Sender {
sender: mpsc::Sender<OwnedMessage>,
}
impl Sender {
fn new(sink: SplitSink<r#async::Client<Box<dyn r#async::Stream + Send>>>) -> Sender {
let (sender, receiver) = mpsc::channel(0);
tokio::spawn(
receiver
.fold(sink, |sink, m| {
sink.send(m)
.then(Error::from_ws)
.and_then(|sink| {
Delay::new(Instant::now() + Duration::from_millis(600))
.map(|_| sink)
.map_err(|e| Error(ErrorInner::Timer(e)))
})
.then(|r| Ok(r.unwrap()))
})
.map(|_| ()),
);
Self { sender }
}
pub fn send_global_command(
&mut self,
command: &str,
) -> impl Future<Item = (), Error = Error> + '_ {
self.send(format!("|/{}", command))
}
pub fn send_chat_message(
&mut self,
room_id: RoomId<'_>,
message: &str,
) -> impl Future<Item = (), Error = Error> + '_ {
self.send(format!("{}|{}", room_id.0, message))
}
fn send(&mut self, message: String) -> impl Future<Item = (), Error = Error> + '_ {
(&mut self.sender)
.send(OwnedMessage::Text(message))
.map(|_| ())
.map_err(|e| Error(ErrorInner::Mpsc(e)))
}
}
pub fn connect(name: &str) -> impl Future<Item = (Sender, Receiver), Error = Error> {
fetch_server_url(name).and_then(|url| connect_to_url(&url))
}
pub fn connect_to_url(url: &Url) -> impl Future<Item = (Sender, Receiver), Error = Error> {
ClientBuilder::from_url(url).async_connect(None).then(|r| {
let (sink, stream) = Error::from_ws(r)?.0.split();
Ok((Sender::new(sink), Receiver { stream }))
})
}
pub fn fetch_server_url(name: &str) -> impl Future<Item = Url, Error = Error> {
Client::new()
.get(&format!(
"https://pokemonshowdown.com/servers/{}.json",
name
))
.send()
.and_then(|mut r| r.json())
.then(|result| {
let Server { host, port } = Error::from_reqwest(result)?;
let protocol = if port == 443 { "wss" } else { "ws" };
Url::parse(&format!(
"{}://{}:{}/showdown/websocket",
protocol, host, port
))
.map_err(|e| Error(ErrorInner::Url(e)))
})
}
impl Receiver {
pub fn receive(&mut self) -> impl Future<Item = Message, Error = Error> + '_ {
(&mut self.stream)
.into_future()
.then(|e| Error::from_ws(e.map_err(|e| e.0)))
.and_then(|(message, _)| {
if let Some(OwnedMessage::Text(text)) = message {
Ok(Message { text })
} else {
Err(Error(ErrorInner::UnrecognizedMessage(message)))
}
})
}
}
#[derive(Deserialize)]
struct Server {
host: String,
port: u16,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct RoomId<'a>(pub &'a str);
impl RoomId<'_> {
pub const LOBBY: RoomId<'static> = RoomId("");
}
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub struct Error(ErrorInner);
impl Error {
fn from_ws<T>(r: StdResult<T, WebSocketError>) -> Result<T> {
r.map_err(|e| Error(ErrorInner::WebSocket(e)))
}
fn from_reqwest<T>(r: StdResult<T, reqwest::Error>) -> Result<T> {
r.map_err(|e| Error(ErrorInner::Reqwest(e)))
}
}
#[derive(Debug)]
enum ErrorInner {
WebSocket(WebSocketError),
Reqwest(reqwest::Error),
Url(url::ParseError),
Mpsc(mpsc::SendError<OwnedMessage>),
Utf8(Utf8Error),
Json(serde_json::Error),
Timer(timer::Error),
UnrecognizedMessage(Option<OwnedMessage>),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.0 {
ErrorInner::WebSocket(e) => e.fmt(f),
ErrorInner::Reqwest(e) => e.fmt(f),
ErrorInner::Url(e) => e.fmt(f),
ErrorInner::Mpsc(e) => e.fmt(f),
ErrorInner::Utf8(e) => e.fmt(f),
ErrorInner::Json(e) => e.fmt(f),
ErrorInner::Timer(e) => e.fmt(f),
ErrorInner::UnrecognizedMessage(e) => write!(f, "Unrecognized message: {:?}", e),
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match &self.0 {
ErrorInner::WebSocket(e) => Some(e),
ErrorInner::Reqwest(e) => Some(e),
ErrorInner::Url(e) => Some(e),
ErrorInner::Mpsc(e) => Some(e),
ErrorInner::Utf8(e) => Some(e),
ErrorInner::Json(e) => Some(e),
ErrorInner::Timer(e) => Some(e),
ErrorInner::UnrecognizedMessage(_) => None,
}
}
}