Fix polling bug. Still multiple challenge sending issue
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
5 .card.smallpad
6 label#closeNewgame.modal-close(for="modalNewgame")
7 fieldset
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9 select#selectVariant(v-model="newchallenge.vid")
10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
11 fieldset
12 label(for="timeControl") {{ st.tr["Time control"] }}
13 input#timeControl(type="text" v-model="newchallenge.timeControl"
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
17 input#selectPlayers(type="text" v-model="newchallenge.to")
18 fieldset(v-if="st.user.id > 0")
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
22 .row
23 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
24 button(onClick="doClick('modalNewgame')") New game
25 .row
26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
27 .collapse
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
30 div
31 .button-group
32 button(@click="cdisplay='live'") Live Challenges
33 button(@click="cdisplay='corr'") Correspondance challenges
34 ChallengeList(v-show="cdisplay=='live'"
35 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
36 ChallengeList(v-show="cdisplay=='corr'"
37 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
39 label(for="peopleSection" aria-hidden="true") People
40 div
41 .button-group
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
44 #players(v-show="pdisplay=='players'")
45 h3 Online players
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
48 )
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
51 h3 Chat (TODO)
52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
53 label(for="gameSection" aria-hidden="true") Games
54 div
55 .button-group
56 button(@click="gdisplay='live'") Live games
57 button(@click="gdisplay='corr'") Correspondance games
58 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
59 @show-game="showGame")
60 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
61 @show-game="showGame")
62 </template>
63
64 <script>
65 import { store } from "@/store";
66 import { checkChallenge } from "@/data/challengeCheck";
67 import { ArrayFun } from "@/utils/array";
68 import { ajax } from "@/utils/ajax";
69 import { getRandString, shuffle } from "@/utils/alea";
70 import GameList from "@/components/GameList.vue";
71 import ChallengeList from "@/components/ChallengeList.vue";
72 import { GameStorage } from "@/utils/gameStorage";
73 import { extractTime } from "@/utils/timeControl";
74 export default {
75 name: "my-hall",
76 components: {
77 GameList,
78 ChallengeList,
79 },
80 data: function () {
81 return {
82 st: store.state,
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
85 gdisplay: "live",
86 games: [],
87 challenges: [],
88 people: [], //(all) online players
89 newchallenge: {
90 fen: "",
91 vid: 0,
92 to: "", //name of challenged player (if any)
93 timeControl: "", //"2m+2s" ...etc
94 },
95 };
96 },
97 computed: {
98 uniquePlayers: function() {
99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
100 let anonymous = {id:0, name:"@nonymous", count:0};
101 let playerList = [];
102 this.people.forEach(p => {
103 if (p.id > 0)
104 playerList.push(p);
105 else
106 anonymous.count++;
107 });
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
110 return playerList;
111 },
112 },
113 created: function() {
114 // Always add myself to players' list
115 this.people.push(this.st.user);
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
118 if (!!chall)
119 {
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
122 else
123 localStorage.removeItem("challenge");
124 }
125 if (this.st.user.id > 0)
126 {
127 // Ask server for current corr games (all but mines)
128 // ajax(
129 // "/games",
130 // "GET",
131 // {excluded: this.st.user.id},
132 // response => {
133 // this.games = this.games.concat(response.games);
134 // }
135 // );
136 // Also ask for corr challenges (open + sent to me)
137 ajax(
138 "/challenges",
139 "GET",
140 {uid: this.st.user.id},
141 response => {
142 console.log(response.challenges);
143 // TODO: post-treatment on challenges ?
144 Array.prototype.push.apply(this.challenges, response.challenges);
145 }
146 );
147 }
148 // 0.1] Ask server for room composition:
149 const funcPollClients = () => {
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
151 };
152 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
153 funcPollClients();
154 else //socket not ready yet (initial loading)
155 {
156 const socketOpenListener = funcPollClients;
157 this.st.conn.onopen = socketOpenListener;
158 }
159 // TODO: is this required here?
160 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
161 this.st.conn.onmessage = this.socketMessageListener;
162 const oldOnclose = this.st.conn.onclose;
163 const socketCloseListener = () => {
164 oldOnclose(); //reinitialize connexion (in store.js)
165 this.st.conn.addEventListener('message', this.socketMessageListener);
166 this.st.conn.addEventListener('close', socketCloseListener);
167 };
168 this.st.conn.onclose = socketCloseListener;
169 },
170 methods: {
171 // Helpers:
172 filterChallenges: function(type) {
173 return this.challenges.filter(c => c.type == type);
174 },
175 filterGames: function(type) {
176 return this.games.filter(c => c.type == type);
177 },
178 classifyObject: function(o) { //challenge or game
179 // Heuristic: should work for most cases... (TODO)
180 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
181 },
182 showGame: function(g) {
183 // NOTE: we are an observer, since only games I don't play are shown here
184 // ==> Moves sent by connected remote player(s) if live game
185 let url = "/game/" + g.id;
186 if (g.type == "live")
187 {
188 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
189 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
190 url += "?rid=" + remotes[rIdx].sid;
191 }
192 this.$router.push(url);
193 },
194 getVname: function(vid) {
195 const vIdx = this.st.variants.findIndex(v => v.id == vid);
196 return this.st.variants[vIdx].name;
197 },
198 getSid: function(pname) {
199 const pIdx = this.people.findIndex(pl => pl.name == pname);
200 return (pIdx === -1 ? null : this.people[pIdx].sid);
201 },
202 getPname: function(sid) {
203 const pIdx = this.people.findIndex(pl => pl.sid == sid);
204 return (pIdx === -1 ? null : this.people[pIdx].name);
205 },
206 sendSomethingTo: function(to, code, obj, warnDisconnected) {
207 const doSend = (code, obj, sid) => {
208 this.st.conn.send(JSON.stringify(Object.assign(
209 {},
210 {code: code},
211 obj,
212 {target: sid}
213 )));
214 };
215 if (!!to)
216 {
217 // Challenge with targeted players
218 const targetSid = this.getSid(to);
219 if (!targetSid)
220 {
221 if (!!warnDisconnected)
222 alert("Warning: " + pname + " is not connected");
223 }
224 else
225 doSend(code, obj, targetSid);
226 }
227 else
228 {
229 // Open challenge: send to all connected players (except us)
230 this.people.forEach(p => {
231 if (p.sid != this.st.user.sid) //only sid is always set
232 doSend(code, obj, p.sid);
233 });
234 }
235 },
236 // Messaging center:
237 socketMessageListener: function(msg) {
238 // Save and call current st.conn.onmessage if one was already defined
239 // --> also needed in future Game.vue (also in Chat.vue component)
240 this.oldOnmessage(msg);
241 const data = JSON.parse(msg.data);
242 switch (data.code)
243 {
244 // 0.2] Receive clients list (just socket IDs)
245 case "pollclients":
246 {
247 data.sockIds.forEach(sid => {
248 this.people.push({sid:sid, id:0, name:""});
249 // Ask identity, challenges and game(s)
250 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
251 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
252 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
253 });
254 break;
255 }
256 case "askidentity":
257 {
258 // Request for identification: reply if I'm not anonymous
259 if (this.st.user.id > 0)
260 {
261 this.st.conn.send(JSON.stringify(
262 {code:"identity", user:this.st.user, target:data.from}));
263 }
264 break;
265 }
266 case "askchallenge":
267 {
268 // Send my current live challenge (if any)
269 const cIdx = this.challenges
270 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
271 if (cIdx >= 0)
272 {
273 const c = this.challenges[cIdx];
274 const myChallenge =
275 {
276 // Minimal challenge informations: (from not required)
277 id: c.id,
278 to: c.to,
279 fen: c.fen,
280 vid: c.vid,
281 timeControl: c.timeControl
282 };
283
284 // TODO: understand multiple (increasing) "send challenge" events.... (when potential opponent navigate Hall --> variants --> Hall)
285 console.log("send challenge to " + data.from);
286
287 this.st.conn.send(JSON.stringify({code:"challenge",
288 chall:myChallenge, target:data.from}));
289 }
290 break;
291 }
292 case "askgame":
293 {
294 // Send my current live game (if any)
295 GameStorage.getCurrent((game) => {
296 if (!!game)
297 {
298 const myGame =
299 {
300 // Minimal game informations:
301 id: game.id,
302 players: game.players.map(p => p.name),
303 vname: game.vname,
304 timeControl: game.timeControl,
305 };
306 this.st.conn.send(JSON.stringify({code:"game",
307 game:myGame, target:data.from}));
308 }
309 });
310 break;
311 }
312 case "identity":
313 {
314 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
315 this.people[pIdx].id = data.user.id;
316 this.people[pIdx].name = data.user.name;
317 break;
318 }
319 case "challenge":
320 {
321
322 console.log(data.chall);
323
324 // Receive challenge from some player (+sid)
325 let newChall = data.chall;
326 newChall.type = this.classifyObject(data.chall);
327 const pIdx = this.people.findIndex(p => p.sid == data.from);
328 newChall.from = this.people[pIdx]; //may be anonymous
329 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
330 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
331 this.challenges.push(newChall);
332 break;
333 }
334 case "game":
335 {
336 // Receive game from some player (+sid)
337 // NOTE: it may be correspondance (if newgame while we are connected)
338 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
339 {
340 let newGame = data.game;
341 newGame.type = this.classifyObject(data.game);
342 newGame.rid = data.from;
343 newGame.score = "*";
344 this.games.push(newGame);
345 }
346 break;
347 }
348 case "newgame":
349 {
350 // New game just started: data contain all informations
351 this.startNewGame(data.gameInfo);
352 // TODO: if live, redirect to game
353 // if corr, notify with link but do not redirect
354 break;
355 }
356 case "refusechallenge":
357 {
358 alert(this.getPname(data.from) + " declined your challenge");
359 ArrayFun.remove(this.challenges, c => c.id == data.cid);
360 break;
361 }
362 case "deletechallenge":
363 {
364 // NOTE: the challenge may be already removed
365 ArrayFun.remove(this.challenges, c => c.id == data.cid);
366 break;
367 }
368 case "connect":
369 {
370 this.people.push({name:"", id:0, sid:data.sid});
371 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
372 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
373 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
374 break;
375 }
376 case "disconnect":
377 {
378 ArrayFun.remove(this.people, p => p.sid == data.sid);
379 // Also remove all challenges sent by this player:
380 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
381 // And all live games where he plays and no other opponent is online
382 ArrayFun.remove(this.games, g =>
383 g.type == "live" && (g.players.every(p => p.sid == data.sid
384 || !this.people.some(pl => pl.sid == p.sid))), "all");
385 break;
386 }
387 }
388 },
389 // Challenge lifecycle:
390 tryChallenge: function(player) {
391 if (player.id == 0)
392 return; //anonymous players cannot be challenged
393 this.newchallenge.to[0] = player.name;
394 doClick("modalNewgame");
395 },
396 newChallenge: async function() {
397 const vname = this.getVname(this.newchallenge.vid);
398 const vModule = await import("@/variants/" + vname + ".js");
399 window.V = vModule.VariantRules;
400 const error = checkChallenge(this.newchallenge);
401 if (!!error)
402 return alert(error);
403 const ctype = this.classifyObject(this.newchallenge);
404 // NOTE: "from" information is not required here
405 let chall =
406 {
407 fen: this.newchallenge.fen,
408 to: this.newchallenge.to,
409 timeControl: this.newchallenge.timeControl,
410 vid: this.newchallenge.vid,
411 };
412 const finishAddChallenge = (cid,warnDisconnected) => {
413 chall.id = cid || "c" + getRandString();
414 // Send challenge to peers (if connected)
415 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
416 chall.added = Date.now();
417 chall.type = ctype;
418 chall.vname = vname;
419 chall.from = this.st.user;
420 this.challenges.push(chall);
421 localStorage.setItem("challenge", JSON.stringify(chall));
422 document.getElementById("modalNewgame").checked = false;
423 };
424 const cIdx = this.challenges.findIndex(
425 c => c.from.sid == this.st.user.sid && c.type == ctype);
426 if (cIdx >= 0)
427 {
428 // Delete current challenge (will be replaced now)
429 this.sendSomethingTo(this.challenges[cIdx].to,
430 "deletechallenge", {cid:this.challenges[cIdx].id});
431 if (ctype == "corr")
432 {
433 ajax(
434 "/challenges",
435 "DELETE",
436 {id: this.challenges[cIdx].id}
437 );
438 }
439 this.challenges.splice(cIdx, 1);
440 }
441 if (ctype == "live")
442 {
443 // Live challenges have a random ID
444 finishAddChallenge(null, "warnDisconnected");
445 }
446 else
447 {
448 // Correspondance game: send challenge to server
449 ajax(
450 "/challenges",
451 "POST",
452 chall,
453 response => { finishAddChallenge(response.cid); }
454 );
455 }
456 },
457 clickChallenge: function(c) {
458 const myChallenge = (c.from.sid == this.st.user.sid //live
459 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
460 if (!myChallenge)
461 {
462 c.accepted = true;
463 if (!!c.to) //c.to == this.st.user.name (connected)
464 {
465 // TODO: if special FEN, show diagram after loading variant
466 c.accepted = confirm("Accept challenge?");
467 }
468 if (c.accepted)
469 {
470 c.seat = this.st.user;
471 this.launchGame(c);
472 }
473 else
474 {
475 this.st.conn.send(JSON.stringify({
476 code: "refusechallenge",
477 cid: c.id, target: c.from.sid}));
478 }
479 }
480 // In all cases, the challenge is consumed:
481 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
482 // NOTE: deletechallenge event might be redundant (but it's easier this way)
483 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
484 if (c.type == "corr")
485 {
486 ajax(
487 "/challenges",
488 "DELETE",
489 {id: this.challenges[cIdx].id}
490 );
491 }
492 },
493 // NOTE: when launching game, the challenge is already deleted
494 launchGame: async function(c) {
495 const vname = this.getVname(c.vid);
496 const vModule = await import("@/variants/" + vname + ".js");
497 window.V = vModule.VariantRules;
498 let players = [c.from, c.seat];
499 // These game informations will be sent to other players
500 const gameInfo =
501 {
502 gameId: getRandString(),
503 fen: c.fen || V.GenRandInitFen(),
504 // Players' names may be required if game start when a player is offline
505 // Shuffle players order (white then black).
506 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
507 vid: c.vid,
508 timeControl: c.timeControl,
509 };
510 this.st.conn.send(JSON.stringify({code:"newgame",
511 gameInfo:gameInfo, target:c.seat.sid}));
512 if (c.type == "live")
513 this.startNewGame(gameInfo);
514 else //corr: game only on server
515 {
516 ajax(
517 "/games",
518 "POST",
519 {gameInfo: gameInfo}
520 );
521 }
522 },
523 // NOTE: for live games only (corr games are launched on server)
524 startNewGame: function(gameInfo) {
525 // Extract times (in [milli]seconds), set clocks
526 const tc = extractTime(gameInfo.timeControl);
527 let initime = [...Array(gameInfo.players.length)];
528 initime[0] = Date.now();
529 const game =
530 {
531 // Game infos: constant
532 gameId: gameInfo.gameId,
533 vname: this.getVname(gameInfo.vid),
534 fenStart: gameInfo.fen,
535 players: gameInfo.players,
536 timeControl: gameInfo.timeControl,
537 increment: tc.increment,
538 mode: "live", //function for live games only
539 // Game state: will be updated
540 fen: gameInfo.fen,
541 moves: [],
542 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
543 initime: initime,
544 score: "*",
545 };
546 GameStorage.add(game);
547 if (this.st.settings.sound >= 1)
548 new Audio("/sounds/newgame.mp3").play().catch(err => {});
549 // TODO: redirect to game
550 },
551 },
552 };
553 </script>
554
555 <style lang="sass">
556 // TODO
557 </style>