forked from fredrikzkl/FuryRacersCompiled
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.js
129 lines (102 loc) · 2.89 KB
/
hub.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
119
120
121
122
123
124
125
126
127
128
var backend;
var username;
var rumble = false;
function addMessageHandler(callback) {
backend = new WebSocket('ws://' + window.location.hostname + ':3001/ws');
backend.onmessage = function(e) {
var msg = JSON.parse(e.data);
if (msg.action === "identify") {
if (!msg.data) {
var id = localStorage.getItem("id-gsusfcavf");
if (id == null) {
id = Math.random().toString(36).substring(7);
localStorage.setItem("id-gsusfcavf", id)
}
setUsername(id);
sendToBackend("identify", id);
} else if (msg.data === "ok") {
sendToBackend("get username", getId());
callback("identified");
} else {
var id = sessionStorage.getItem("id-gsusfcavf");
if (id == null) {
id = Math.random().toString(36).substring(7);
sessionStorage.setItem("id-gsusfcavf", id)
}
setUsername(id);
sendToBackend("identify", id);
}
} else if (msg.action === "redirect") {
var gameName = msg.data.toLowerCase()
if (document.location.href.indexOf(gameName) < 0) {
document.location.href = "/" + gameName;
}
} else if (msg.action === "set username") {
if (msg.data === "error") {
alert("Username already in use")
}
} else if (msg.action === "get username") {
username = msg.data[1];
}else if(msg.action === "rumble"){
toggleRumble();
}else if(msg.action == "set color"){
setBackgroundColor(msg.data);
}else if(msg.action == "set carModel"){
setCarModel(msg.data);
}
else {
callback(msg);
}
}
}
function toggleRumble() {
if(!rumble){
window.navigator.vibrate(1000);
rumble = true;
}else{
window.navigator.vibrate(0);
rumble = false;
}
}
function sendToGame(action, data) {
send({
"to": "game",
"action": "pass through",
"data": {
"action": action,
"data": data
}
});
}
function sendToBackend(action, data) {
send({
"action": action,
"data": data
});
}
function send(json) {
if (backend) {
backend.send(JSON.stringify(json));
}
}
function getId() {
var id;
if (sessionStorage.getItem("id-gsusfcavf")) {
id = sessionStorage.getItem("id-gsusfcavf");
} else {
id = localStorage.getItem("id-gsusfcavf");
}
return id;
}
function setUsername(newUsername){
username = newUsername;
try {
//writeUsername();
}
catch(err) {
console.log(err.message);
}
}
function getUsername(){
return username;
}