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
27 // NOTE: only purpose of sidToPages = know when to delete keys in idToSid
30 wss
.on("connection", (socket
, req
) => {
31 const query
= getJsonFromUrl(req
.url
);
32 const sid
= query
["sid"];
33 const id
= query
["id"];
34 const tmpId
= query
["tmpId"];
35 const page
= query
["page"];
36 const notifyRoom
= (page
, code
, obj
={}, except
) => {
37 if (!clients
[page
]) return;
38 except
= except
|| [];
39 Object
.keys(clients
[page
]).forEach(k
=> {
40 if (except
.includes(k
)) return;
41 Object
.keys(clients
[page
][k
]).forEach(x
=> {
42 if (k
== sid
&& x
== tmpId
) return;
44 clients
[page
][k
][x
].socket
,
45 Object
.assign({ code: code
, from: [sid
, tmpId
] }, obj
)
50 const deleteConnexion
= () => {
51 if (!clients
[page
] || !clients
[page
][sid
] || !clients
[page
][sid
][tmpId
])
52 return; //job already done
53 delete clients
[page
][sid
][tmpId
];
54 if (Object
.keys(clients
[page
][sid
]).length
== 0) {
55 delete clients
[page
][sid
];
56 const pgIndex
= sidToPages
[sid
].findIndex(pg
=> pg
== page
);
57 sidToPages
[sid
].splice(pgIndex
, 1);
58 if (Object
.keys(clients
[page
]).length
== 0)
60 // Am I totally offline?
61 if (sidToPages
[sid
].length
== 0) {
62 delete sidToPages
[sid
];
68 const doDisconnect
= () => {
70 // Nothing to notify when disconnecting from MyGames page:
71 if (page
!= "/mygames") {
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
130 Object
.keys(clients
[page
][k
]).forEach(x
=> {
131 sockIds
[k
][x
] = { focus: clients
[page
][k
][x
].focus
};
135 send(socket
, { code: "pollclients", sockIds: sockIds
});
138 case "pollclientsandgamers": {
141 Object
.keys(clients
["/"]).forEach(k
=> {
142 // Avoid polling myself: no new information to get
145 Object
.keys(clients
[page
][k
]).forEach(x
=> {
148 focus: clients
[page
][k
][x
].focus
153 // NOTE: a "gamer" could also just be an observer
154 Object
.keys(clients
).forEach(p
=> {
155 if (p
.indexOf("/game/") >= 0) {
156 Object
.keys(clients
[p
]).forEach(k
=> {
158 if (!sockIds
[k
]) sockIds
[k
] = {};
159 Object
.keys(clients
[p
][k
]).forEach(x
=> {
162 focus: clients
[p
][k
][x
].focus
169 send(socket
, { code: "pollclientsandgamers", sockIds: sockIds
});
173 // Asking something: from is fully identified,
174 // but the requested resource can be from any tmpId (except current!)
177 case "askchallenges":
179 const pg
= obj
.page
|| page
; //required for askidentity and askgame
180 if (!!clients
[pg
] && !!clients
[pg
][obj
.target
]) {
181 let tmpIds
= Object
.keys(clients
[pg
][obj
.target
]);
182 if (obj
.target
== sid
) {
184 const idx_myTmpid
= tmpIds
.findIndex(x
=> x
== tmpId
);
185 if (idx_myTmpid
>= 0) tmpIds
.splice(idx_myTmpid
, 1);
187 if (tmpIds
.length
> 0) {
188 const ttmpId
= tmpIds
[Math
.floor(Math
.random() * tmpIds
.length
)];
190 clients
[pg
][obj
.target
][ttmpId
].socket
,
191 { code: obj
.code
, from: [sid
,tmpId
,page
] }
198 // Special situation of the previous "case":
199 // Full game can be asked to any observer.
200 case "askfullgame": {
201 if (!!clients
[page
]) {
202 let sids
= Object
.keys(clients
[page
]).filter(k
=> k
!= sid
);
203 if (sids
.length
> 0) {
204 // Pick a SID at random in this set, and ask full game:
205 const rid
= sids
[Math
.floor(Math
.random() * sids
.length
)];
206 // ..to a random tmpId:
207 const tmpIds
= Object
.keys(clients
[page
][rid
]);
208 const rtmpId
= tmpIds
[Math
.floor(Math
.random() * tmpIds
.length
)];
210 clients
[page
][rid
][rtmpId
].socket
,
211 { code: "askfullgame", from: [sid
,tmpId
] }
218 // Some Hall events: target all tmpId's (except mine),
219 case "refusechallenge":
221 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
222 if (obj
.target
!= sid
|| x
!= tmpId
)
224 clients
[page
][obj
.target
][x
].socket
,
225 { code: obj
.code
, data: obj
.data
}
230 // Notify all room: mostly game events
233 case "deletechallenge_s":
240 // "newgame" message can provide a page (corr Game --> Hall)
241 notifyRoom(obj
.page
|| page
, obj
.code
, {data: obj
.data
}, obj
.excluded
);
245 // A rematch game started:
246 notifyRoom(page
, "newgame", {data: obj
.data
});
247 // Explicitely notify Hall if gametype == corr.
248 // Live games will be polled from Hall after gconnect event.
249 if (obj
.data
.cadence
.indexOf('d') >= 0)
250 notifyRoom("/", "newgame", {data: obj
.data
});
254 const dataWithFrom
= { from: [sid
,tmpId
], data: obj
.data
};
255 // Special case re-send newmove only to opponent:
256 if (!!obj
.target
&& !!clients
[page
][obj
.target
]) {
257 Object
.keys(clients
[page
][obj
.target
]).forEach(x
=> {
259 clients
[page
][obj
.target
][x
].socket
,
260 Object
.assign({ code: "newmove" }, dataWithFrom
)
264 // NOTE: data.from is useful only to opponent
265 notifyRoom(page
, "newmove", dataWithFrom
);
271 !!clients
[page
][obj
.target
[0]] &&
272 !!clients
[page
][obj
.target
[0]][obj
.target
[1]]
275 clients
[page
][obj
.target
[0]][obj
.target
[1]].socket
,
282 // Special case: notify all, 'transroom': Game --> Hall
283 notifyRoom("/", "result", { gid: obj
.gid
, score: obj
.score
});
287 const gamePg
= "/game/" + obj
.gid
;
288 if (!!clients
[gamePg
] && !!clients
[gamePg
][obj
.target
]) {
289 Object
.keys(clients
[gamePg
][obj
.target
]).forEach(x
=> {
291 clients
[gamePg
][obj
.target
][x
].socket
,
301 case "notifynewgame":
302 if (!!clients
["/mygames"]) {
303 obj
.targets
.forEach(t
=> {
304 const k
= t
.sid
|| idToSid
[t
.id
];
305 if (!!clients
["/mygames"][k
]) {
306 Object
.keys(clients
["/mygames"][k
]).forEach(x
=> {
308 clients
["/mygames"][k
][x
].socket
,
309 { code: obj
.code
, data: obj
.data
}
319 clients
[page
][sid
][tmpId
].focus
= (obj
.code
== "getfocus");
320 if (page
== "/") notifyRoom("/", obj
.code
, { page: "/" }, [sid
]);
322 // Notify game room + Hall:
323 notifyRoom(page
, obj
.code
, {}, [sid
]);
324 notifyRoom("/", obj
.code
, { page: page
}, [sid
]);
328 // Passing, relaying something: from isn't needed,
329 // but target is fully identified (sid + tmpId)
336 const pg
= obj
.target
[2] || page
; //required for identity and game
337 // NOTE: if in game we ask identity to opponent still in Hall,
338 // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
339 if (!!clients
[pg
] && !!clients
[pg
][obj
.target
[0]]) {
341 clients
[pg
][obj
.target
[0]][obj
.target
[1]].socket
,
342 { code:obj
.code
, data:obj
.data
}
349 const closeListener
= () => {
350 // For browser or tab closing (including page reload):
353 // Update clients object: add new connexion
354 const newElt
= { socket: socket
, focus: true };
356 clients
[page
] = { [sid
]: {[tmpId
]: newElt
} };
357 else if (!clients
[page
][sid
])
358 clients
[page
][sid
] = { [tmpId
]: newElt
};
360 clients
[page
][sid
][tmpId
] = newElt
;
361 // Also update helper correspondances
362 if (!idToSid
[id
]) idToSid
[id
] = sid
;
363 if (!sidToPages
[sid
]) sidToPages
[sid
] = [];
364 const pgIndex
= sidToPages
[sid
].findIndex(pg
=> pg
== page
);
365 if (pgIndex
=== -1) sidToPages
[sid
].push(page
);
366 socket
.on("message", messageListener
);
367 socket
.on("close", closeListener
);