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
use std::collections::HashMap;
use std::sync::mpsc::{channel, Receiver};
use std::sync::{Arc, Mutex};
use std::thread::{spawn, JoinHandle};
use tungstenite::client::AutoStream;
use tungstenite::http::{HeaderValue, Request};
use tungstenite::{Message, WebSocket};
pub struct Tmi {
ws: Arc<Mutex<WebSocket<AutoStream>>>,
oauth: String,
nick: String,
rooms: Vec<String>,
}
#[derive(Debug)]
pub struct DecodedMessage {
pub metadata: HashMap<String, String>,
pub from: String,
pub command: String,
pub target: Option<String>,
pub params: String,
}
impl Tmi {
pub fn new(oauth: String, nick: String, rooms: Vec<String>) -> Tmi {
let mut request = Request::get("wss://irc-ws.chat.twitch.tv")
.body(())
.unwrap();
request.headers_mut().insert(
"Sec-Websocket-Protocol",
HeaderValue::from_str("tmi".into()).unwrap(),
);
let (ws, _response) =
tungstenite::client::connect(request).expect("Unable to connect to TMI");
let ws = Arc::new(Mutex::new(ws));
let mut tmi = Tmi {
oauth,
nick,
rooms,
ws,
};
tmi.authenticate();
tmi.join_all();
tmi
}
fn authenticate(&mut self) {
self.send(String::from(
"CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership",
))
.unwrap();
self.send(format!("PASS {}", self.oauth)).unwrap();
self.send(format!("NICK {}", self.nick)).unwrap();
}
fn join_all(&mut self) {
if self.rooms.len() == 0 {
return;
}
let iter = self.rooms.clone();
for channel in iter {
self.send(format!("JOIN {}", channel)).unwrap();
}
}
pub fn send(&mut self, message: String) -> Result<(), tungstenite::Error> {
self.ws
.lock()
.unwrap()
.write_message(Message::from(message))
}
pub fn send_to_channel(
&mut self,
message: String,
channel: String,
) -> Result<(), tungstenite::Error> {
self.send(format!("PRIVMSG {} :{}", channel, message))
}
pub fn start(&mut self) -> (JoinHandle<()>, Receiver<DecodedMessage>) {
let (tx, rx) = channel();
let local_ws = self.ws.clone();
let t = spawn(move || loop {
let mut l_ws = local_ws.lock().unwrap();
let message = l_ws.read_message().unwrap().to_string();
let message = message.trim();
let lines = message.split("\r\n");
for line in lines {
if line.starts_with("PING ") {
l_ws.write_message(Message::from(line.replace("PING ", "PONG ")))
.unwrap();
} else {
tx.send(parse_message(line.into())).unwrap();
}
}
});
(t, rx)
}
}
fn parse_message(message: String) -> DecodedMessage {
let mut metadata = HashMap::new();
let mut chunks: Vec<String> = message.split(" ").map(|s| s.to_string()).collect();
if chunks[0].starts_with("@") == true {
for entry in chunks[0].split(";").into_iter() {
let parts: Vec<&str> = entry.split("=").collect();
metadata.insert(parts[0].to_string(), parts[1..].join("=").to_string());
}
chunks.drain(0..1);
}
let from: String = chunks.drain(0..1).next().unwrap()[1..]
.split("@")
.next()
.unwrap()
.split("!")
.next()
.unwrap()
.into();
let command: String = chunks.drain(0..1).next().unwrap().into();
let mut target = None;
let mut params = String::new();
if chunks.len() != 0 {
target = Some(chunks.drain(0..1).next().unwrap().into());
params = chunks.join(" ").into();
if params.starts_with(":") {
params = params[1..].into();
}
}
DecodedMessage {
metadata,
from,
command,
target,
params,
}
}