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