TODO: fix draw logic
[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 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
36 label(for="challengeSection" aria-hidden="true") Challenges
37 div
38 .button-group
39 button(@click="cdisplay='live'") Live Challenges
40 button(@click="cdisplay='corr'") 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 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
46 label(for="peopleSection" aria-hidden="true") People
47 div
48 .button-group
49 button(@click="pdisplay='players'") Players
50 button(@click="pdisplay='chat'") 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 input#gameSection(type="radio" aria-hidden="true" name="accordion")
61 label(for="gameSection" aria-hidden="true") Games
62 div
63 .button-group
64 button(@click="gdisplay='live'") Live games
65 button(@click="gdisplay='corr'") 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 getVname: function(vid) {
232 const variant = this.st.variants.find(v => v.id == vid);
233 // this.st.variants might be uninitialized (variant == null)
234 return (!!variant ? variant.name : "");
235 },
236 whatPlayerDoes: function(p) {
237 if (this.games.some(g => g.type == "live"
238 && g.players.some(pl => pl.sid == p.sid)))
239 {
240 return "Playing";
241 }
242 return "Challenge"; //player is available
243 },
244 sendSomethingTo: function(to, code, obj, warnDisconnected) {
245 const doSend = (code, obj, sid) => {
246 this.st.conn.send(JSON.stringify(Object.assign(
247 {},
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: " + pname + " is not connected");
262 }
263 else
264 doSend(code, obj, targetSid);
265 }
266 else
267 {
268 // Open challenge: send to all connected players (except us)
269 Object.keys(this.people).forEach(sid => {
270 if (sid != this.st.user.sid)
271 doSend(code, obj, sid);
272 });
273 }
274 },
275 // Messaging center:
276 socketMessageListener: function(msg) {
277 const data = JSON.parse(msg.data);
278 switch (data.code)
279 {
280 case "duplicate":
281 alert("Warning: duplicate 'offline' connection");
282 break;
283 // 0.2] Receive clients list (just socket IDs)
284 case "pollclients":
285 {
286 data.sockIds.forEach(sid => {
287 this.$set(this.people, sid, {id:0, name:""});
288 // Ask identity, challenges and game(s)
289 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
290 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
291 });
292 // Also ask current games to all playing peers (TODO: some design issue)
293 this.st.conn.send(JSON.stringify({code:"askgames"}));
294 break;
295 }
296 case "askidentity":
297 {
298 // Request for identification: reply if I'm not anonymous
299 if (this.st.user.id > 0)
300 {
301 this.st.conn.send(JSON.stringify({code:"identity",
302 user: {
303 // NOTE: decompose to avoid revealing email
304 name: this.st.user.name,
305 sid: this.st.user.sid,
306 id: this.st.user.id,
307 },
308 target:data.from}));
309 }
310 break;
311 }
312 case "identity":
313 {
314 this.$set(this.people, data.user.sid,
315 {id: data.user.id, name: data.user.name});
316 break;
317 }
318 case "askchallenge":
319 {
320 // Send my current live challenge (if any)
321 const cIdx = this.challenges
322 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
323 if (cIdx >= 0)
324 {
325 const c = this.challenges[cIdx];
326 const myChallenge =
327 {
328 // Minimal challenge informations: (from not required)
329 id: c.id,
330 to: c.to,
331 fen: c.fen,
332 vid: c.vid,
333 timeControl: c.timeControl
334 };
335 this.st.conn.send(JSON.stringify({code:"challenge",
336 chall:myChallenge, target:data.from}));
337 }
338 break;
339 }
340 case "challenge":
341 {
342 // Receive challenge from some player (+sid)
343 let newChall = data.chall;
344 newChall.type = this.classifyObject(data.chall);
345 newChall.from =
346 Object.assign({sid:data.from}, this.people[data.from]);
347 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
348 newChall.vname = this.getVname(newChall.vid);
349 this.challenges.push(newChall);
350 break;
351 }
352 case "game":
353 {
354 // Receive game from some player (+sid)
355 // NOTE: it may be correspondance (if newgame while we are connected)
356 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
357 {
358 let newGame = data.game;
359 newGame.type = this.classifyObject(data.game);
360 newGame.vname = this.getVname(data.game.vid);
361 newGame.rid = data.from;
362 newGame.score = "*";
363 this.games.push(newGame);
364 }
365 break;
366 }
367 case "newgame":
368 {
369 // TODO: next line required ?!
370 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
371 // New game just started: data contain all information
372 if (this.classifyObject(data.gameInfo) == "live")
373 this.startNewGame(data.gameInfo);
374 else
375 {
376 this.infoMessage = "New game started: " +
377 "<a href='#/game/" + data.gameInfo.id + "'>" +
378 "#/game/" + data.gameInfo.id + "</a>";
379 let modalBox = document.getElementById("modalInfo");
380 modalBox.checked = true;
381 setTimeout(() => { modalBox.checked = false; }, 3000);
382 }
383 break;
384 }
385 case "refusechallenge":
386 {
387 alert(this.people[data.from].name + " declined your challenge");
388 ArrayFun.remove(this.challenges, c => c.id == data.cid);
389 break;
390 }
391 case "deletechallenge":
392 {
393 // NOTE: the challenge may be already removed
394 ArrayFun.remove(this.challenges, c => c.id == data.cid);
395 localStorage.removeItem("challenge"); //in case of
396 break;
397 }
398 case "connect":
399 {
400 this.$set(this.people, data.from, {name:"", id:0});
401 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
402 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
403 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
404 break;
405 }
406 case "disconnect":
407 {
408 this.$delete(this.people, data.from);
409 // Also remove all challenges sent by this player:
410 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
411 // And all live games where he plays and no other opponent is online
412 ArrayFun.remove(this.games, g =>
413 g.type == "live" && (g.players.every(p => p.sid == data.from
414 || !this.people[p.sid])), "all");
415 break;
416 }
417 }
418 },
419 // Challenge lifecycle:
420 tryChallenge: function(player) {
421 if (player.id == 0)
422 return; //anonymous players cannot be challenged
423 this.newchallenge.to = player.name;
424 doClick("modalNewgame");
425 },
426 challOrWatch: function(p, e) {
427 switch (e.target.innerHTML)
428 {
429 case "Challenge":
430 this.tryChallenge(p);
431 break;
432 case "Playing":
433 // NOTE: this search for game was already done for rendering
434 this.showGame(this.games.find(
435 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
436 break;
437 };
438 },
439 newChallenge: async function() {
440 const vname = this.getVname(this.newchallenge.vid);
441 const vModule = await import("@/variants/" + vname + ".js");
442 window.V = vModule.VariantRules;
443 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
444 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
445 const error = checkChallenge(this.newchallenge);
446 if (!!error)
447 return alert(error);
448 const ctype = this.classifyObject(this.newchallenge);
449 if (ctype == "corr" && this.st.user.id <= 0)
450 return alert("Please log in to play correspondance games");
451 // NOTE: "from" information is not required here
452 let chall = Object.assign({}, this.newchallenge);
453 const finishAddChallenge = (cid,warnDisconnected) => {
454 chall.id = cid || "c" + getRandString();
455 // Send challenge to peers (if connected)
456 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
457 chall.added = Date.now();
458 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
459 chall.type = ctype;
460 chall.vname = vname;
461 chall.from = { //decompose to avoid revealing email
462 sid: this.st.user.sid,
463 id: this.st.user.id,
464 name: this.st.user.name,
465 };
466 this.challenges.push(chall);
467 if (ctype == "live")
468 localStorage.setItem("challenge", JSON.stringify(chall));
469 document.getElementById("modalNewgame").checked = false;
470 };
471 const cIdx = this.challenges.findIndex(
472 c => c.from.sid == this.st.user.sid && c.type == ctype);
473 if (cIdx >= 0)
474 {
475 // Delete current challenge (will be replaced now)
476 this.sendSomethingTo(this.challenges[cIdx].to,
477 "deletechallenge", {cid:this.challenges[cIdx].id});
478 if (ctype == "corr")
479 {
480 ajax(
481 "/challenges",
482 "DELETE",
483 {id: this.challenges[cIdx].id}
484 );
485 }
486 this.challenges.splice(cIdx, 1);
487 }
488 if (ctype == "live")
489 {
490 // Live challenges have a random ID
491 finishAddChallenge(null, "warnDisconnected");
492 }
493 else
494 {
495 // Correspondance game: send challenge to server
496 ajax(
497 "/challenges",
498 "POST",
499 { chall: chall },
500 response => { finishAddChallenge(response.cid); }
501 );
502 }
503 },
504 clickChallenge: function(c) {
505 const myChallenge = (c.from.sid == this.st.user.sid //live
506 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
507 if (!myChallenge)
508 {
509 if (c.type == "corr" && this.st.user.id <= 0)
510 return alert("Please log in to accept corr challenges");
511 c.accepted = true;
512 if (!!c.to) //c.to == this.st.user.name (connected)
513 {
514 // TODO: if special FEN, show diagram after loading variant
515 c.accepted = confirm("Accept challenge?");
516 }
517 if (c.accepted)
518 {
519 c.seat = { //again, avoid c.seat = st.user to not reveal email
520 sid: this.st.user.sid,
521 id: this.st.user.id,
522 name: this.st.user.name,
523 };
524 this.launchGame(c);
525 }
526 else
527 {
528 this.st.conn.send(JSON.stringify({
529 code: "refusechallenge",
530 cid: c.id, target: c.from.sid}));
531 }
532 }
533 else //my challenge
534 {
535 if (c.type == "corr")
536 {
537 ajax(
538 "/challenges",
539 "DELETE",
540 {id: c.id}
541 );
542 }
543 else //live
544 localStorage.removeItem("challenge");
545 }
546 // In (almost) all cases, the challenge is consumed:
547 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
548 // NOTE: deletechallenge event might be redundant (but it's easier this way)
549 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
550 },
551 // NOTE: when launching game, the challenge is already deleted
552 launchGame: async function(c) {
553 const vModule = await import("@/variants/" + c.vname + ".js");
554 window.V = vModule.VariantRules;
555 // These game informations will be sent to other players
556 const gameInfo =
557 {
558 id: getRandString(),
559 fen: c.fen || V.GenRandInitFen(),
560 players: shuffle([c.from, c.seat]), //white then black
561 vid: c.vid,
562 vname: c.vname, //theoretically vid is enough, but much easier with vname
563 timeControl: c.timeControl,
564 };
565 let target = c.from.sid; //may not be defined if corr + offline opp
566 if (!target)
567 {
568 target = Object.keys(this.people).find(sid =>
569 this.people[sid].id == c.from.id);
570 }
571 const tryNotifyOpponent = () => {
572 if (!!target) //opponent is online
573 {
574 this.st.conn.send(JSON.stringify({code:"newgame",
575 gameInfo:gameInfo, target:target, cid:c.id}));
576 }
577 };
578 if (c.type == "live")
579 {
580 tryNotifyOpponent();
581 this.startNewGame(gameInfo);
582 }
583 else //corr: game only on server
584 {
585 ajax(
586 "/games",
587 "POST",
588 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
589 response => {
590 gameInfo.id = response.gameId;
591 tryNotifyOpponent();
592 this.$router.push("/game/" + response.gameId);
593 }
594 );
595 }
596 // Send game info to everyone except opponent (and me)
597 this.st.conn.send(JSON.stringify({code:"game",
598 game: { //minimal game info:
599 id: gameInfo.id,
600 players: gameInfo.players.map(p => p.name),
601 vid: gameInfo.vid,
602 timeControl: gameInfo.timeControl,
603 },
604 oppsid: target}));
605 },
606 // NOTE: for live games only (corr games start on the server)
607 startNewGame: function(gameInfo) {
608 const game = Object.assign({}, gameInfo, {
609 // (other) Game infos: constant
610 fenStart: gameInfo.fen,
611 added: Date.now(),
612 // Game state (including FEN): will be updated
613 moves: [],
614 clocks: [-1, -1], //-1 = unstarted
615 initime: [0, 0], //initialized later
616 score: "*",
617 });
618 GameStorage.add(game);
619 if (this.st.settings.sound >= 1)
620 new Audio("/sounds/newgame.mp3").play().catch(err => {});
621 this.$router.push("/game/" + gameInfo.id);
622 },
623 },
624 };
625 </script>
626
627 <style lang="sass" scoped>
628 #newGame
629 display: block
630 margin: 10px auto 5px auto
631 #chat > .card
632 max-width: 100%
633 margin: 0;
634 border: none;
635 #players > p
636 margin-left: 40%
637 @media screen and (max-width: 767px)
638 #players > p
639 margin-left: 5px
640 .anonymous
641 font-style: italic
642 button.player-action
643 margin-left: 32px
644 </style>