1 const url
= require('url');
3 // Node version in Ubuntu 16.04 does not know about URL class
4 // NOTE: url is already transformed, without ?xxx=yyy... parts
5 function getJsonFromUrl(url
) {
6 const query
= url
.substr(2); //starts with "/?"
8 query
.split("&").forEach((part
) => {
9 const item
= part
.split("=");
10 result
[item
[0]] = decodeURIComponent(item
[1]);
15 // Helper to safe-send some message through a (web-)socket:
16 function send(socket
, message
) {
17 if (!!socket
&& socket
.readyState
== 1)
18 socket
.send(JSON
.stringify(message
));
21 module
.exports = function(wss
) {
22 // Associative array page --> sid --> tmpId --> socket
23 // "page" is either "/" for hall or "/game/some_gid" for Game,
24 // or "/mygames" for Mygames page (simpler: no 'people' array).
25 // tmpId is required if a same user (browser) has different tabs
29 wss
.on("connection", (socket
, req
) => {
30 const query
= getJsonFromUrl(req
.url
);
31 const sid
= query
["sid"];
32 const id
= query
["id"];
33 const tmpId
= query
["tmpId"];
34 const page
= query
["page"];
35 const notifyRoom
= (page
, code
, obj
={}, except
) => {
36 if (!clients
[page
]) return;
37 except
= except
|| [];
38 Object
.keys(clients
[page
]).forEach(k
=> {
39 if (except
.includes(k
)) return;
40 Object
.keys(clients
[page
][k
]).forEach(x
=> {
41 if (k
== sid
&& x
== tmpId
) return;
43 clients
[page
][k
][x
].socket
,
44 Object
.assign({ code: code
, from: sid
}, obj
)
49 const deleteConnexion
= () => {
50 if (!clients
[page
] || !clients
[page
][sid
] || !clients
[page
][sid
][tmpId
])
51 return; //job already done
52 delete clients
[page
][sid
][tmpId
];
53 if (Object
.keys(clients
[page
][sid
]).length
== 0) {
54 delete clients
[page
][sid
];
55 const pgIndex
= sidToPages
[sid
].findIndex(pg
=> pg
== page
);
56 sidToPages
[sid
].splice(pgIndex
, 1);
57 if (Object
.keys(clients
[page
]).length
== 0)
59 // Am I totally offline?
60 if (sidToPages
[sid
].length
== 0) {
61 delete sidToPages
[sid
];
67 const doDisconnect
= () => {
69 // Nothing to notify when disconnecting from MyGames page:
70 if (page
!= "/mygames" && (!clients
[page
] || !clients
[page
][sid
])) {
71 // I effectively disconnected from this page:
72 notifyRoom(page
, "disconnect");
73 if (page
.indexOf("/game/") >= 0)
74 notifyRoom("/", "gdisconnect", { page:page
});
77 const messageListener
= (objtxt
) => {
78 let obj
= JSON
.parse(objtxt
);
80 // Wait for "connect" message to notify connection to the room,
81 // because if game loading is slow the message listener might
82 // not be ready too early.
84 notifyRoom(page
, "connect");
85 if (page
.indexOf("/game/") >= 0)
86 notifyRoom("/", "gconnect", { page:page
});
94 // Self multi-connect: manual removal + disconnect
95 const doKill
= (pg
) => {
96 Object
.keys(clients
[pg
][obj
.sid
]).forEach(x
=> {
97 send(clients
[pg
][obj
.sid
][x
].socket
, { code: "killed" });
99 delete clients
[pg
][obj
.sid
];
101 const disconnectFromOtherConnexion
= (pg
,code
,o
={}) => {
102 Object
.keys(clients
[pg
]).forEach(k
=> {
104 Object
.keys(clients
[pg
][k
]).forEach(x
=> {
106 clients
[pg
][k
][x
].socket
,
107 Object
.assign({ code: code
, from: obj
.sid
}, o
)
113 Object
.keys(clients
).forEach(pg
=> {
114 if (clients
[pg
][obj
.sid
]) {
116 disconnectFromOtherConnexion(pg
, "disconnect");
117 if (pg
.indexOf("/game/") >= 0 && clients
["/"])
118 disconnectFromOtherConnexion("/", "gdisconnect", { page: pg
});
123 case "pollclients": {
126 Object
.keys(clients
[page
]).forEach(k
=> {
127 // Avoid polling myself: no new information to get
128 if (k
!= sid
) sockIds
.push(k
);
130 send(socket
, { code: "pollclients", sockIds: sockIds
});
133 case "pollclientsandgamers": {
136 Object
.keys(clients
["/"]).forEach(k
=> {
137 // Avoid polling myself: no new information to get
138 if (k
!= sid
) sockIds
.push({sid:k
});
140 // NOTE: a "gamer" could also just be an observer
141 Object
.keys(clients
).forEach(p
=> {
142 if (p
.indexOf("/game/") >= 0) {
143 Object
.keys(clients
[p
]).forEach(k
=> {
144 // 'page' indicator is needed for gamers
145 if (k
!= sid
) sockIds
.push({ sid:k
, page:p
});
149 send(socket
, { code: "pollclientsandgamers", sockIds: sockIds
});
153 // Asking something: from is fully identified,
154 // but the requested resource can be from any tmpId (except current!)
157 case "askchallenges":
159 const pg
= obj
.page
|| page
; //required for askidentity and askgame
160 if (!!clients
[pg
] && !!clients
[pg
][obj
.target
]) {
161 let tmpIds
= Object
.keys(clients
[pg
][obj
.target
]);
162 if (obj
.target
== sid
) {
164 const idx_myTmpid
= tmpIds
.findIndex(x
=> x
== tmpId
);
165 if (idx_myTmpid
>= 0) tmpIds
.splice(idx_myTmpid
, 1);
167 if (tmpIds
.length
> 0) {
168 const ttmpId
= tmpIds
[Math
.floor(Math
.random() * tmpIds
.length
)];
170 clients
[pg
][obj
.target
][ttmpId
].socket
,
171 { code: obj
.code
, from: [sid
,tmpId
,page
] }
178 // Special situation of the previous "case":
179 // Full game can be asked to any observer.
180 case "askfullgame": {
181 if (!!clients
[page
]) {
182 let sids
= Object
.keys(clients
[page
]).filter(k
=> k
!= sid
);
183 if (sids
.length
> 0) {
184 // Pick a SID at random in this set, and ask full game:
185 const rid
= sids
[Math
.floor(Math
.random() * sids
.length
)];
186 // ..to a random tmpId:
187 const tmpIds
= Object
.keys(clients
[page
][rid
]);
188 const rtmpId
= tmpIds
[Math
.floor(Math
.random() * tmpIds
.length
)];
190 clients
[page
][rid
][rtmpId
].socket
,
191 { code: "askfullgame", from: [sid
,tmpId
] }
198 // Some Hall events: target all tmpId's (except mine),
199 case "refusechallenge":
201 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
202 if (obj
.target
!= sid
|| x
!= tmpId
)
204 clients
[page
][obj
.target
][x
].socket
,
205 { code: obj
.code
, data: obj
.data
}
210 // Notify all room: mostly game events
213 case "deletechallenge_s":
220 notifyRoom(page
, obj
.code
, {data: obj
.data
}, obj
.excluded
);
224 // A rematch game started:
225 notifyRoom(page
, "newgame", {data: obj
.data
});
226 // Explicitely notify Hall if gametype == corr.
227 // Live games will be polled from Hall after gconnect event.
228 if (obj
.data
.cadence
.indexOf('d') >= 0)
229 notifyRoom("/", "newgame", {data: obj
.data
});
233 const dataWithFrom
= { from: [sid
,tmpId
], data: obj
.data
};
234 // Special case re-send newmove only to opponent:
235 if (!!obj
.target
&& !!clients
[page
][obj
.target
]) {
236 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
238 clients
[page
][obj
.target
][x
].socket
,
239 Object
.assign({ code: "newmove" }, dataWithFrom
)
243 // NOTE: data.from is useful only to opponent
244 notifyRoom(page
, "newmove", dataWithFrom
);
250 !!clients
[page
][obj
.target
[0]] &&
251 !!clients
[page
][obj
.target
[0]][obj
.target
[1]]
254 clients
[page
][obj
.target
[0]][obj
.target
[1]].socket
,
261 // Special case: notify all, 'transroom': Game --> Hall
262 notifyRoom("/", "result", { gid: obj
.gid
, score: obj
.score
});
266 const gamePg
= "/game/" + obj
.gid
;
267 if (!!clients
[gamePg
] && !!clients
[gamePg
][obj
.target
]) {
268 Object
.keys(clients
[gamePg
][obj
.target
]).forEach(x
=> {
270 clients
[gamePg
][obj
.target
][x
].socket
,
280 case "notifynewgame":
281 if (!!clients
["/mygames"]) {
282 obj
.targets
.forEach(t
=> {
283 const k
= t
.sid
|| idToSid
[t
.id
];
284 if (!!clients
["/mygames"][k
]) {
285 Object
.keys(clients
["/mygames"][k
]).forEach(x
=> {
287 clients
["/mygames"][k
][x
].socket
,
288 { code: obj
.code
, data: obj
.data
}
298 if (page
== "/") notifyRoom("/", obj
.code
, { page: "/" }, [sid
]);
300 // Notify game room + Hall:
301 notifyRoom(page
, obj
.code
, {}, [sid
]);
302 notifyRoom("/", obj
.code
, { page: page
}, [sid
]);
306 // Passing, relaying something: from isn't needed,
307 // but target is fully identified (sid + tmpId)
314 const pg
= obj
.target
[2] || page
; //required for identity and game
315 // NOTE: if in game we ask identity to opponent still in Hall,
316 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
317 if (!!clients
[pg
] && !!clients
[pg
][obj
.target
[0]]) {
319 clients
[pg
][obj
.target
[0]][obj
.target
[1]].socket
,
320 { code:obj
.code
, data:obj
.data
}
327 const closeListener
= () => {
328 // For browser or tab closing (including page reload):
331 // Update clients object: add new connexion
332 const newElt
= { socket: socket
, focus: true };
334 clients
[page
] = { [sid
]: {[tmpId
]: newElt
} };
335 else if (!clients
[page
][sid
])
336 clients
[page
][sid
] = { [tmpId
]: newElt
};
338 clients
[page
][sid
][tmpId
] = newElt
;
339 // Also update helper correspondances
340 if (!idToSid
[id
]) idToSid
[id
] = sid
;
341 if (!sidToPages
[sid
]) sidToPages
[sid
] = [];
342 const pgIndex
= sidToPages
[sid
].findIndex(pg
=> pg
== page
);
343 if (pgIndex
=== -1) sidToPages
[sid
].push(page
);
344 socket
.on("message", messageListener
);
345 socket
.on("close", closeListener
);