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