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