0ade5e58bfa4519a3b60e1989ef538c1b51af18e
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="infoMessage")
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
7 h3#infoMessage.section
8 p(v-html="infoMessage")
9 input#modalNewgame.modal(type="checkbox")
10 div(role="dialog" data-checkbox="modalNewgame"
11 aria-labelledby="titleFenedit")
12 .card.smallpad(@keyup.enter="newChallenge")
13 label#closeNewgame.modal-close(for="modalNewgame")
14 fieldset
15 label(for="selectVariant") {{ st.tr["Variant"] }}
16 select#selectVariant(v-model="newchallenge.vid")
17 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
18 fieldset
19 label(for="timeControl") {{ st.tr["Time control"] }}
20 input#timeControl(type="text" v-model="newchallenge.timeControl"
21 placeholder="3m+2s, 1h+30s, 7d+1d ...")
22 fieldset(v-if="st.user.id > 0")
23 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
24 input#selectPlayers(type="text" v-model="newchallenge.to")
25 fieldset(v-if="st.user.id > 0")
26 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
27 input#inputFen(type="text" v-model="newchallenge.fen")
28 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
29 .row
30 .col-sm-12
31 button#newGame(onClick="doClick('modalNewgame')") New game
32 .row
33 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
34 div
35 .button-group
36 button(@click="(e) => setDisplay('c','live',e)" class="active")
37 | Live Challenges
38 button(@click="(e) => setDisplay('c','corr',e)")
39 | Correspondance challenges
40 ChallengeList(v-show="cdisplay=='live'"
41 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
42 ChallengeList(v-show="cdisplay=='corr'"
43 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
44 #people
45 h3.text-center Who's there?
46 #players
47 p(v-for="p in Object.values(people)" v-if="!!p.name")
48 span {{ p.name }}
49 button.player-action(
50 v-if="p.name != st.user.name"
51 @click="challOrWatch(p,$event)"
52 )
53 | {{ whatPlayerDoes(p) }}
54 p.anonymous @nonymous ({{ anonymousCount }})
55 #chat
56 Chat(:players="[]")
57 .clearer
58 div
59 .button-group
60 button(@click="(e) => setDisplay('g','live',e)" class="active")
61 | Live games
62 button(@click="(e) => setDisplay('g','corr',e)")
63 | Correspondance games
64 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
65 @show-game="showGame")
66 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
67 @show-game="showGame")
68 </template>
69
70 <script>
71 import { store } from "@/store";
72 import { checkChallenge } from "@/data/challengeCheck";
73 import { ArrayFun } from "@/utils/array";
74 import { ajax } from "@/utils/ajax";
75 import { getRandString, shuffle } from "@/utils/alea";
76 import Chat from "@/components/Chat.vue";
77 import GameList from "@/components/GameList.vue";
78 import ChallengeList from "@/components/ChallengeList.vue";
79 import { GameStorage } from "@/utils/gameStorage";
80 export default {
81 name: "my-hall",
82 components: {
83 Chat,
84 GameList,
85 ChallengeList,
86 },
87 data: function () {
88 return {
89 st: store.state,
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
92 gdisplay: "live",
93 games: [],
94 challenges: [],
95 people: {}, //people in main hall
96 infoMessage: "",
97 newchallenge: {
98 fen: "",
99 vid: 0,
100 to: "", //name of challenged player (if any)
101 timeControl: "", //"2m+2s" ...etc
102 },
103 };
104 },
105 watch: {
106 // st.variants changes only once, at loading from [] to [...]
107 "st.variants": function(variantArray) {
108 // Set potential challenges and games variant names:
109 this.challenges.forEach(c => {
110 if (c.vname == "")
111 c.vname = this.getVname(c.vid);
112 });
113 this.games.forEach(g => {
114 if (g.vname == "")
115 g.vname = this.getVname(g.vid);
116 });
117 },
118 },
119 computed: {
120 anonymousCount: function() {
121 let count = 0;
122 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
123 return count;
124 },
125 },
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.$set(this.people, my.sid, {id:my.id, name:my.name});
130 // Retrieve live challenge (not older than 30 minute) if any:
131 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
132 if (!!chall)
133 {
134 // NOTE: a challenge survives 3 minutes, for potential connection issues
135 if ((Date.now() - chall.added)/1000 <= 3*60)
136 {
137 chall.added = Date.now(); //update added time, for next disconnect...
138 this.challenges.push(chall);
139 localStorage.setItem("challenge", JSON.stringify(chall));
140 }
141 else
142 localStorage.removeItem("challenge");
143 }
144 // Ask server for current corr games (all but mines)
145 ajax(
146 "/games",
147 "GET",
148 {uid: this.st.user.id, excluded: true},
149 response => {
150 this.games = this.games.concat(response.games.map(g => {
151 const type = this.classifyObject(g);
152 const vname = this.getVname(g.vid);
153 return Object.assign({}, g, {type: type, vname: vname});
154 }));
155 }
156 );
157 // Also ask for corr challenges (open + sent to me)
158 ajax(
159 "/challenges",
160 "GET",
161 {uid: this.st.user.id},
162 response => {
163 // Gather all senders names, and then retrieve full identity:
164 // (TODO [perf]: some might be online...)
165 const uids = response.challenges.map(c => { return c.uid });
166 ajax("/users",
167 "GET",
168 { ids: uids.join(",") },
169 response2 => {
170 let names = {};
171 response2.users.forEach(u => {names[u.id] = u.name});
172 this.challenges = this.challenges.concat(
173 response.challenges.map(c => {
174 // (just players names in fact)
175 const from = {name: names[c.uid], id: c.uid};
176 const type = this.classifyObject(c);
177 const vname = this.getVname(c.vid);
178 return Object.assign({}, c, {type: type, vname: vname, from: from});
179 })
180 )
181 }
182 );
183 }
184 );
185 // 0.1] Ask server for room composition:
186 const funcPollClients = () => {
187 // Same strategy as in Game.vue: send connection
188 // after we're sure WebSocket is initialized
189 this.st.conn.send(JSON.stringify({code:"connect"}));
190 this.st.conn.send(JSON.stringify({code:"pollclients"}));
191 };
192 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
193 funcPollClients();
194 else //socket not ready yet (initial loading)
195 this.st.conn.onopen = funcPollClients;
196 this.st.conn.onmessage = this.socketMessageListener;
197 const socketCloseListener = () => {
198 store.socketCloseListener(); //reinitialize connexion (in store.js)
199 this.st.conn.addEventListener('message', this.socketMessageListener);
200 this.st.conn.addEventListener('close', socketCloseListener);
201 };
202 this.st.conn.onclose = socketCloseListener;
203 },
204 methods: {
205 // Helpers:
206 filterChallenges: function(type) {
207 return this.challenges.filter(c => c.type == type);
208 },
209 filterGames: function(type) {
210 return this.games.filter(g => g.type == type);
211 },
212 classifyObject: function(o) { //challenge or game
213 // Heuristic: should work for most cases... (TODO)
214 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
215 },
216 showGame: function(g) {
217 // NOTE: we are an observer, since only games I don't play are shown here
218 // ==> Moves sent by connected remote player(s) if live game
219 let url = "/game/" + g.id;
220 if (g.type == "live")
221 url += "?rid=" + g.rid;
222 this.$router.push(url);
223 },
224 setDisplay: function(letter, type, e) {
225 this[letter + "display"] = type;
226 e.target.classList.add("active");
227 if (!!e.target.previousElementSibling)
228 e.target.previousElementSibling.classList.remove("active");
229 else
230 e.target.nextElementSibling.classList.remove("active");
231 },
232 getVname: function(vid) {
233 const variant = this.st.variants.find(v => v.id == vid);
234 // this.st.variants might be uninitialized (variant == null)
235 return (!!variant ? variant.name : "");
236 },
237 whatPlayerDoes: function(p) {
238 if (this.games.some(g => g.type == "live"
239 && g.players.some(pl => pl.sid == p.sid)))
240 {
241 return "Playing";
242 }
243 return "Challenge"; //player is available
244 },
245 sendSomethingTo: function(to, code, obj, warnDisconnected) {
246 const doSend = (code, obj, sid) => {
247 this.st.conn.send(JSON.stringify(Object.assign(
248 {code: code},
249 obj,
250 {target: sid}
251 )));
252 };
253 if (!!to)
254 {
255 // Challenge with targeted players
256 const targetSid =
257 Object.keys(this.people).find(sid => this.people[sid].name == to);
258 if (!targetSid)
259 {
260 if (!!warnDisconnected)
261 alert("Warning: " + to + " is not connected");
262 return false;
263 }
264 else
265 doSend(code, obj, targetSid);
266 }
267 else
268 {
269 // Open challenge: send to all connected players (me excepted)
270 Object.keys(this.people).forEach(sid => {
271 if (sid != this.st.user.sid)
272 doSend(code, obj, sid);
273 });
274 }
275 return true;
276 },
277 // Messaging center:
278 socketMessageListener: function(msg) {
279 const data = JSON.parse(msg.data);
280 switch (data.code)
281 {
282 case "duplicate":
283 alert("Warning: duplicate 'offline' connection");
284 break;
285 // 0.2] Receive clients list (just socket IDs)
286 case "pollclients":
287 {
288 data.sockIds.forEach(sid => {
289 this.$set(this.people, sid, {id:0, name:""});
290 // Ask identity, challenges and game(s)
291 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
292 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
293 });
294 // Also ask current games to all playing peers (TODO: some design issue)
295 this.st.conn.send(JSON.stringify({code:"askgames"}));
296 break;
297 }
298 case "askidentity":
299 {
300 // Request for identification: reply if I'm not anonymous
301 if (this.st.user.id > 0)
302 {
303 this.st.conn.send(JSON.stringify({code:"identity",
304 user: {
305 // NOTE: decompose to avoid revealing email
306 name: this.st.user.name,
307 sid: this.st.user.sid,
308 id: this.st.user.id,
309 },
310 target:data.from}));
311 }
312 break;
313 }
314 case "identity":
315 {
316 this.$set(this.people, data.user.sid,
317 {id: data.user.id, name: data.user.name});
318 break;
319 }
320 case "askchallenge":
321 {
322 // Send my current live challenge (if any)
323 const cIdx = this.challenges.findIndex(c =>
324 c.from.sid == this.st.user.sid && c.type == "live");
325 if (cIdx >= 0)
326 {
327 const c = this.challenges[cIdx];
328 if (!!c.to)
329 {
330 // Only share targeted challenges to the targets:
331 const toSid = Object.keys(this.people).find(k =>
332 this.people[k].name == c.to);
333 if (toSid != data.from)
334 return;
335 }
336 const myChallenge =
337 {
338 // Minimal challenge informations: (from not required)
339 id: c.id,
340 to: c.to,
341 fen: c.fen,
342 vid: c.vid,
343 timeControl: c.timeControl,
344 };
345 this.st.conn.send(JSON.stringify({code:"challenge",
346 chall:myChallenge, target:data.from}));
347 }
348 break;
349 }
350 case "challenge":
351 {
352 // Receive challenge from some player (+sid)
353 let newChall = data.chall;
354 newChall.type = this.classifyObject(data.chall);
355 newChall.from =
356 Object.assign({sid:data.from}, this.people[data.from]);
357 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
358 newChall.vname = this.getVname(newChall.vid);
359 this.challenges.push(newChall);
360 break;
361 }
362 case "game":
363 {
364 // Receive game from some player (+sid)
365 // NOTE: it may be correspondance (if newgame while we are connected)
366 // If duplicate found: select rid (remote ID) at random
367 let game = this.games.find(g => g.id == data.game.id);
368 if (!!game && Math.random() < 0.5)
369 game.rid = data.from;
370 else
371 {
372 let newGame = data.game;
373 newGame.type = this.classifyObject(data.game);
374 newGame.vname = this.getVname(data.game.vid);
375 newGame.rid = data.from;
376 newGame.score = "*";
377 this.games.push(newGame);
378 }
379 break;
380 }
381 case "newgame":
382 {
383 // TODO: next line required ?!
384 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
385 // New game just started: data contain all information
386 if (this.classifyObject(data.gameInfo) == "live")
387 this.startNewGame(data.gameInfo);
388 else
389 {
390 this.infoMessage = "New game started: " +
391 "<a href='#/game/" + data.gameInfo.id + "'>" +
392 "#/game/" + data.gameInfo.id + "</a>";
393 let modalBox = document.getElementById("modalInfo");
394 modalBox.checked = true;
395 setTimeout(() => { modalBox.checked = false; }, 3000);
396 }
397 break;
398 }
399 case "refusechallenge":
400 {
401 ArrayFun.remove(this.challenges, c => c.id == data.cid);
402 localStorage.removeItem("challenge");
403 alert(this.people[data.from].name + " declined your challenge");
404 break;
405 }
406 case "deletechallenge":
407 {
408 // NOTE: the challenge may be already removed
409 ArrayFun.remove(this.challenges, c => c.id == data.cid);
410 localStorage.removeItem("challenge"); //in case of
411 break;
412 }
413 case "connect":
414 {
415 this.$set(this.people, data.from, {name:"", id:0});
416 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
417 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
418 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
419 break;
420 }
421 case "disconnect":
422 {
423 this.$delete(this.people, data.from);
424 // Also remove all challenges sent by this player:
425 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
426 // And all live games where he plays and no other opponent is online
427 ArrayFun.remove(this.games, g =>
428 g.type == "live" && (g.players.every(p => p.sid == data.from
429 || !this.people[p.sid])), "all");
430 break;
431 }
432 }
433 },
434 // Challenge lifecycle:
435 tryChallenge: function(player) {
436 if (player.id == 0)
437 return; //anonymous players cannot be challenged
438 this.newchallenge.to = player.name;
439 doClick("modalNewgame");
440 },
441 challOrWatch: function(p, e) {
442 switch (e.target.innerHTML)
443 {
444 case "Challenge":
445 this.tryChallenge(p);
446 break;
447 case "Playing":
448 // NOTE: this search for game was already done for rendering
449 this.showGame(this.games.find(
450 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
451 break;
452 };
453 },
454 newChallenge: async function() {
455 const vname = this.getVname(this.newchallenge.vid);
456 const vModule = await import("@/variants/" + vname + ".js");
457 window.V = vModule.VariantRules;
458 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
459 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
460 const error = checkChallenge(this.newchallenge);
461 if (!!error)
462 return alert(error);
463 const ctype = this.classifyObject(this.newchallenge);
464 if (ctype == "corr" && this.st.user.id <= 0)
465 return alert("Please log in to play correspondance games");
466 // NOTE: "from" information is not required here
467 let chall = Object.assign({}, this.newchallenge);
468 const finishAddChallenge = (cid,warnDisconnected) => {
469 chall.id = cid || "c" + getRandString();
470 // Send challenge to peers (if connected)
471 const isSent = this.sendSomethingTo(chall.to, "challenge",
472 {chall:chall}, !!warnDisconnected);
473 if (!isSent)
474 return;
475 // Remove old challenge if any (only one at a time):
476 const cIdx = this.challenges.findIndex(c =>
477 c.from.sid == this.st.user.sid && c.type == ctype);
478 if (cIdx >= 0)
479 {
480 // Delete current challenge (will be replaced now)
481 this.sendSomethingTo(this.challenges[cIdx].to,
482 "deletechallenge", {cid:this.challenges[cIdx].id});
483 if (ctype == "corr")
484 {
485 ajax(
486 "/challenges",
487 "DELETE",
488 {id: this.challenges[cIdx].id}
489 );
490 }
491 this.challenges.splice(cIdx, 1);
492 }
493 // Add new challenge:
494 chall.added = Date.now();
495 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
496 chall.type = ctype;
497 chall.vname = vname;
498 chall.from = { //decompose to avoid revealing email
499 sid: this.st.user.sid,
500 id: this.st.user.id,
501 name: this.st.user.name,
502 };
503 this.challenges.push(chall);
504 if (ctype == "live")
505 localStorage.setItem("challenge", JSON.stringify(chall));
506 document.getElementById("modalNewgame").checked = false;
507 };
508 if (ctype == "live")
509 {
510 // Live challenges have a random ID
511 finishAddChallenge(null, "warnDisconnected");
512 }
513 else
514 {
515 // Correspondance game: send challenge to server
516 ajax(
517 "/challenges",
518 "POST",
519 { chall: chall },
520 response => { finishAddChallenge(response.cid); }
521 );
522 }
523 },
524 clickChallenge: function(c) {
525 const myChallenge = (c.from.sid == this.st.user.sid //live
526 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
527 if (!myChallenge)
528 {
529 if (c.type == "corr" && this.st.user.id <= 0)
530 return alert("Please log in to accept corr challenges");
531 c.accepted = true;
532 if (!!c.to) //c.to == this.st.user.name (connected)
533 {
534 // TODO: if special FEN, show diagram after loading variant
535 c.accepted = confirm("Accept challenge?");
536 }
537 if (c.accepted)
538 {
539 c.seat = { //again, avoid c.seat = st.user to not reveal email
540 sid: this.st.user.sid,
541 id: this.st.user.id,
542 name: this.st.user.name,
543 };
544 this.launchGame(c);
545 }
546 else
547 {
548 this.st.conn.send(JSON.stringify({
549 code: "refusechallenge",
550 cid: c.id, target: c.from.sid}));
551 }
552 // TODO: refactor the "sendSomethingTo()" function
553 if (!c.to)
554 this.sendSomethingTo(null, "deletechallenge", {cid:c.id});
555 else
556 {
557 this.st.conn.send(JSON.stringify({
558 code:"deletechallenge", target: c.from.sid, cid: c.id}));
559 }
560 }
561 else //my challenge
562 {
563 if (c.type == "corr")
564 {
565 ajax(
566 "/challenges",
567 "DELETE",
568 {id: c.id}
569 );
570 }
571 else //live
572 localStorage.removeItem("challenge");
573 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
574 }
575 // In all cases, the challenge is consumed:
576 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
577 },
578 // NOTE: when launching game, the challenge is already deleted
579 launchGame: async function(c) {
580 const vModule = await import("@/variants/" + c.vname + ".js");
581 window.V = vModule.VariantRules;
582 // These game informations will be sent to other players
583 const gameInfo =
584 {
585 id: getRandString(),
586 fen: c.fen || V.GenRandInitFen(),
587 players: shuffle([c.from, c.seat]), //white then black
588 vid: c.vid,
589 vname: c.vname, //theoretically vid is enough, but much easier with vname
590 timeControl: c.timeControl,
591 };
592 let oppsid = c.from.sid; //may not be defined if corr + offline opp
593 if (!oppsid)
594 {
595 oppsid = Object.keys(this.people).find(sid =>
596 this.people[sid].id == c.from.id);
597 }
598 const tryNotifyOpponent = () => {
599 if (!!oppsid) //opponent is online
600 {
601 this.st.conn.send(JSON.stringify({code:"newgame",
602 gameInfo:gameInfo, target:oppsid, cid:c.id}));
603 }
604 };
605 if (c.type == "live")
606 {
607 // NOTE: in this case we are sure opponent is online
608 tryNotifyOpponent();
609 this.startNewGame(gameInfo);
610 }
611 else //corr: game only on server
612 {
613 ajax(
614 "/games",
615 "POST",
616 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
617 response => {
618 gameInfo.id = response.gameId;
619 tryNotifyOpponent();
620 this.$router.push("/game/" + response.gameId);
621 }
622 );
623 }
624 // Send game info to everyone except opponent (and me)
625 Object.keys(this.people).forEach(sid => {
626 if (![this.st.user.sid,oppsid].includes(sid))
627 {
628 this.st.conn.send(JSON.stringify({code:"game",
629 game: { //minimal game info:
630 id: gameInfo.id,
631 players: gameInfo.players,
632 vid: gameInfo.vid,
633 timeControl: gameInfo.timeControl,
634 },
635 target: sid}));
636 }
637 });
638 },
639 // NOTE: for live games only (corr games start on the server)
640 startNewGame: function(gameInfo) {
641 const game = Object.assign({}, gameInfo, {
642 // (other) Game infos: constant
643 fenStart: gameInfo.fen,
644 added: Date.now(),
645 // Game state (including FEN): will be updated
646 moves: [],
647 clocks: [-1, -1], //-1 = unstarted
648 initime: [0, 0], //initialized later
649 score: "*",
650 });
651 GameStorage.add(game);
652 if (this.st.settings.sound >= 1)
653 new Audio("/sounds/newgame.mp3").play().catch(err => {});
654 this.$router.push("/game/" + gameInfo.id);
655 },
656 },
657 };
658 </script>
659
660 <style lang="sass" scoped>
661 .active
662 color: #42a983
663 #newGame
664 display: block
665 margin: 10px auto 5px auto
666 #people
667 width: 100%
668 #players
669 width: 50%
670 position: relative
671 float: left
672 #chat
673 width: 50%
674 float: left
675 position: relative
676 @media screen and (max-width: 767px)
677 #players, #chats
678 width: 100%
679 #chat > .card
680 max-width: 100%
681 margin: 0;
682 border: none;
683 #players > p
684 margin-left: 5px
685 .anonymous
686 font-style: italic
687 button.player-action
688 margin-left: 32px
689 </style>