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