-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
120 lines (98 loc) · 2.56 KB
/
client.js
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
var WebSocket = require('ws');
var play = require('play');
var request = require('request');
var self = this
var OmegaupEndpoint = "omegaup.com"
var ContestAlias = process.argv[4]
var SocketKeepaliveTimeout = 30000
var ConnectRetryTimeout = 5000
var Username = process.argv[2]
var Pass = process.argv[3]
var UseSSL = true
function startWebSocket(retryFn) {
self.ws = new WebSocket((UseSSL ? 'wss://' : 'ws://') + OmegaupEndpoint + '/api/contest/events/' + ContestAlias, "com.omegaup.events", {
headers: {
'Cookie': self.authCookie
}
});
self.ws.on('open', function open() {
console.log("Connected to websocket w00t!");
play.sound('./sounds/start.wav');
// Set Keepalives
//
self.socket_keepalive = setInterval((function(socket) {
return function() {
console.log("Sending PING..");
socket.send("ping");
};
})(self.ws), SocketKeepaliveTimeout);
});
self.ws.on('message', function(data, flags) {
console.log("OMG A message!");
console.log(data);
var d = JSON.parse(data)
// Play sounds
//
switch (d.message) {
case "/run/update/":
play.sound('./sounds/' + d.run.verdict + '.wav');
break;
case "/clarification/update/":
play.sound('./sounds/clarification.wav');
break;
}
});
self.ws.on('error', function(error) {
console.log("D: error!");
console.log(error);
play.sound('./sounds/gameover.wav');
retryFn();
});
self.ws.on('close', function(error) {
console.log(":( Connection Closed.");
console.log(error);
play.sound('./sounds/gameover.wav');
retryFn();
});
}
function getAuthToken(callback, retryFn) {
// Get auth token
//
console.log("YEY! Starting. Getting omegaUp auth token for " + Username)
request.post((UseSSL ? 'https://' : 'http://') + OmegaupEndpoint + '/api/user/login', {
form: {
usernameOrEmail: Username,
password: Pass
}
},
function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
var b = JSON.parse(body)
self.authCookie = 'ouat=' + b.auth_token
callback()
}
else {
console.log("X_X Epic fail");
console.log(error);
console.log("/house.jpg");
play.sound('./sounds/gameover.wav');
retryFn();
}
}
);
}
function cleanupAndRetry() {
// Cleanup
//
clearInterval(self.socket_keepalive);
self.ws = null;
// Retry
//
console.log(":O Retrying connection.");
setTimeout(
function() {
getAuthToken(startWebSocket, cleanupAndRetry)
}, ConnectRetryTimeout)
}
getAuthToken(startWebSocket, cleanupAndRetry);