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
mod handler;
pub use self::handler::{
DefaultHandler,
Handler,
};
use crate::{
async_trait,
KahootError,
KahootResult,
LoginResponse,
Message,
USER_AGENT_STR,
};
use cometd::{
json,
packet::Packet,
CometError,
};
use log::{
trace,
warn,
};
use std::sync::{
Arc,
Mutex,
};
pub const DEFAULT_DEVICE_WIDTH: u64 = 1920;
pub const DEFAULT_DEVICE_HEIGHT: u64 = 1080;
pub const DEFAULT_LAG: u64 = 0;
pub const CONTROLLER_CHANNEL: &str = "/service/controller";
pub const PLAYER_CHANNEL: &str = "/service/player";
pub const STATUS_CHANNEL: &str = "/service/status";
pub(crate) struct KahootHandler<T> {
pub(crate) code: Arc<str>,
pub(crate) name: Arc<str>,
pub(crate) handler: Arc<T>,
pub(crate) exit_error: Arc<Mutex<Option<KahootError>>>,
}
impl<T> KahootHandler<T> {
pub(crate) fn new(code: &str, name: &str, handler: T) -> Self {
Self {
code: Arc::from(code),
name: Arc::from(name),
handler: Arc::new(handler),
exit_error: Arc::new(Mutex::new(None)),
}
}
pub(crate) fn kahoot_ctx(&self, ctx: &cometd::client::Context) -> Context {
Context::new(ctx.clone(), self.code.clone(), self.name.clone())
}
}
#[derive(Clone)]
pub struct Context {
pub ctx: cometd::client::Context,
pub code: Arc<str>,
pub name: Arc<str>,
}
impl Context {
pub fn new(ctx: cometd::client::Context, code: Arc<str>, name: Arc<str>) -> Self {
Context { ctx, code, name }
}
pub fn get_device_data_str(&self) -> KahootResult<String> {
let content = json!({
"device": {
"userAgent": USER_AGENT_STR,
"screen": {
"width": DEFAULT_DEVICE_WIDTH,
"height": DEFAULT_DEVICE_HEIGHT,
}
}
});
Ok(serde_json::to_string(&content)?)
}
pub async fn login(&self, name: &str) -> KahootResult<()> {
trace!("logging in as '{}'", name);
let client_id = self
.ctx
.get_client_id()
.ok_or(KahootError::Comet(CometError::MissingClientId))?;
let packet = Packet::new()
.channel(CONTROLLER_CHANNEL.into())
.client_id(client_id)
.data(json!({
"type": "login",
"gameid": &*self.code,
"host": "kahoot.it",
"name": name,
"content": self.get_device_data_str()?,
}));
self.ctx.send_packet(packet).await?;
self.ctx.subscribe(CONTROLLER_CHANNEL).await?;
self.ctx.subscribe(PLAYER_CHANNEL).await?;
self.ctx.subscribe(STATUS_CHANNEL).await?;
Ok(())
}
pub async fn submit_answer(&self, choice: usize) -> KahootResult<()> {
let client_id = self
.ctx
.get_client_id()
.ok_or(KahootError::Comet(CometError::MissingClientId))?;
let content = json!({
"choice": choice,
"meta": {
"lag": DEFAULT_LAG,
"device": self.get_device_data_str()?,
}
});
let packet = Packet::new()
.channel(CONTROLLER_CHANNEL.into())
.client_id(client_id)
.data(json!({
"content": serde_json::to_string(&content)?,
"gameid": &*self.code,
"host": "kahoot.it",
"id": 45,
"type": "message",
}));
self.ctx.send_packet(packet).await?;
Ok(())
}
pub fn get_username(&self) -> Arc<str> {
self.name.clone()
}
pub async fn shutdown(&self) -> KahootResult<()> {
self.ctx.shutdown().await?;
Ok(())
}
}
#[async_trait]
impl<T: Handler + 'static> cometd::client::Handler for KahootHandler<T> {
async fn on_reconnect(&self, ctx: cometd::client::Context) {
let ctx = self.kahoot_ctx(&ctx);
let handler = self.handler.clone();
let name = self.name.clone();
tokio::spawn(async move {
tokio::time::delay_for(std::time::Duration::from_millis(1000)).await;
match ctx.login(&name).await {
Ok(_) => {}
Err(e) => handler.on_error(ctx, e).await,
}
});
}
async fn on_message(&self, ctx: cometd::client::Context, packet: Packet) {
match packet.channel.as_str() {
CONTROLLER_CHANNEL => {
let data = match packet.data.as_ref() {
Some(d) => d,
None => &serde_json::Value::Null,
};
if let Some(login_response) = LoginResponse::from_value(data) {
if login_response.error.as_ref().is_some() {
*self.exit_error.lock().unwrap() =
Some(KahootError::InvalidLogin(login_response));
ctx.shutdown().await.expect("Shutdown");
} else {
let handler = self.handler.clone();
let ctx = self.kahoot_ctx(&ctx);
tokio::spawn(async move { handler.on_login(ctx).await });
}
} else {
warn!("Controller Packet: {:#?}", packet);
}
}
STATUS_CHANNEL => {
warn!("Status Packet: {:#?}", packet);
}
PLAYER_CHANNEL => {
let data = match packet.data {
Some(d) => d,
None => serde_json::Value::Null,
};
match Message::from_value(data) {
Message::UsernameAccepted { msg, .. } => {
let handler = self.handler.clone();
let ctx = self.kahoot_ctx(&ctx);
tokio::spawn(async move { handler.on_username_accepted(ctx, msg).await });
}
Message::GetReady { msg } => {
let handler = self.handler.clone();
let ctx = self.kahoot_ctx(&ctx);
tokio::spawn(async move { handler.on_get_ready(ctx, msg).await });
}
Message::StartQuestion { msg } => {
let ctx = self.kahoot_ctx(&ctx);
let handler = self.handler.clone();
tokio::spawn(async move {
handler.on_start_question(ctx, msg).await;
});
}
msg => {
warn!("Unknown Message: {:#?}", msg);
}
}
}
_ => {
warn!("Unknown Packet: {:#?}", packet);
}
}
}
async fn on_error(&self, ctx: cometd::client::Context, error: CometError) {
let handler = self.handler.clone();
let ctx = self.kahoot_ctx(&ctx);
tokio::spawn(async move {
let _result = handler.on_error(ctx, error.into()).await;
});
}
}
pub struct Client<T> {
client: cometd::Client<KahootHandler<T>>,
}
impl<T: Handler + Send + 'static> Client<T> {
pub async fn connect_with_handler(
code: String,
name: String,
handler: T,
) -> KahootResult<Client<T>> {
trace!(
"connecting with custom handler with code='{}' and name='{}'",
code,
name
);
let token = crate::challenge::Client::new().get_token(&code).await?;
trace!("solved challenge, got token='{}'", token);
let url = format!("wss://kahoot.it/cometd/{}/{}", &code, token);
let handler = KahootHandler::new(&code, &name, handler);
let client = cometd::Client::connect_with_handler(&url, handler).await?;
let client = Client { client };
Ok(client)
}
pub async fn run(&mut self) -> KahootResult<()> {
trace!("running kahoot client");
self.client.run().await?;
if let Some(e) = self.client.handler.exit_error.lock().unwrap().take() {
return Err(e);
}
Ok(())
}
pub fn handler(&self) -> Arc<T> {
self.client.handler.handler.clone()
}
}