Experimental multi-tabs support (TODO: prevent multi-connect)
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo" 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#newgameDiv(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="cadence") {{ st.tr["Cadence"] }} *
22 div#predefinedCadences
23 button 3+2
24 button 5+3
25 button 15+5
26 input#cadence(type="text" v-model="newchallenge.cadence"
27 placeholder="5+0, 1h+30s, 7d+1d ...")
28 fieldset(v-if="st.user.id > 0")
29 label(for="selectPlayers") {{ st.tr["Play with?"] }}
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") FEN
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')") {{ st.tr["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 | {{ st.tr["Live challenges"] }}
44 button(@click="(e) => setDisplay('c','corr',e)")
45 | {{ st.tr["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 {{ st.tr["Who's there?"] }}
52 #players
53 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
55 // Check: anonymous players cannot send individual challenges or be challenged individually
56 button.player-action(
57 v-if="sid != st.user.sid && !!st.user.name && people[sid].id > 0"
58 @click="challOrWatch(sid)"
59 )
60 | {{ getActionLabel(sid) }}
61 p.anonymous @nonymous ({{ anonymousCount }})
62 #chat
63 Chat(:newChat="newChat" @mychat="processChat")
64 .clearer
65 div
66 .button-group
67 button(@click="(e) => setDisplay('g','live',e)" class="active")
68 | {{ st.tr["Live games"] }}
69 button(@click="(e) => setDisplay('g','corr',e)")
70 | {{ st.tr["Correspondance games"] }}
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 @show-game="showGame")
75 </template>
76
77 <script>
78 import { store } from "@/store";
79 import { checkChallenge } from "@/data/challengeCheck";
80 import { ArrayFun } from "@/utils/array";
81 import { ajax } from "@/utils/ajax";
82 import params from "@/parameters";
83 import { getRandString, shuffle } from "@/utils/alea";
84 import Chat from "@/components/Chat.vue";
85 import GameList from "@/components/GameList.vue";
86 import ChallengeList from "@/components/ChallengeList.vue";
87 import { GameStorage } from "@/utils/gameStorage";
88 import { processModalClick } from "@/utils/modalClick";
89 export default {
90 name: "my-hall",
91 components: {
92 Chat,
93 GameList,
94 ChallengeList,
95 },
96 data: function () {
97 return {
98 st: store.state,
99 cdisplay: "live", //or corr
100 gdisplay: "live",
101 games: [],
102 challenges: [],
103 people: {},
104 infoMessage: "",
105 newchallenge: {
106 fen: "",
107 vid: localStorage.getItem("vid") || "",
108 to: "", //name of challenged player (if any)
109 cadence: localStorage.getItem("cadence") || "",
110 },
111 newChat: "",
112 conn: null,
113 };
114 },
115 watch: {
116 // st.variants changes only once, at loading from [] to [...]
117 "st.variants": function(variantArray) {
118 // Set potential challenges and games variant names:
119 this.challenges.concat(this.games).forEach(o => {
120 if (o.vname == "")
121 o.vname = this.getVname(o.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 const my = this.st.user;
134 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
135 // Ask server for current corr games (all but mines)
136 ajax(
137 "/games",
138 "GET",
139 {uid: this.st.user.id, excluded: true},
140 response => {
141 this.games = this.games.concat(response.games.map(g => {
142 const type = this.classifyObject(g);
143 const vname = this.getVname(g.vid);
144 return Object.assign({}, g, {type: type, vname: vname});
145 }));
146 }
147 );
148 // Also ask for corr challenges (open + sent by/to me)
149 ajax(
150 "/challenges",
151 "GET",
152 {uid: this.st.user.id},
153 response => {
154 // Gather all senders names, and then retrieve full identity:
155 // (TODO [perf]: some might be online...)
156 let names = {};
157 response.challenges.forEach(c => {
158 if (c.uid != this.st.user.id)
159 names[c.uid] = ""; //unknwon for now
160 else if (!!c.target && c.target != this.st.user.id)
161 names[c.target] = "";
162 });
163 const addChallenges = (newChalls) => {
164 names[this.st.user.id] = this.st.user.name; //in case of
165 this.challenges = this.challenges.concat(
166 response.challenges.map(c => {
167 const from = {name: names[c.uid], id: c.uid}; //or just name
168 const type = this.classifyObject(c);
169 const vname = this.getVname(c.vid);
170 return Object.assign({},
171 {
172 type: type,
173 vname: vname,
174 from: from,
175 to: (!!c.target ? names[c.target] : ""),
176 },
177 c);
178 })
179 );
180 };
181 if (names !== {})
182 {
183 ajax("/users",
184 "GET",
185 { ids: Object.keys(names).join(",") },
186 response2 => {
187 response2.users.forEach(u => {names[u.id] = u.name});
188 addChallenges();
189 }
190 );
191 }
192 else
193 addChallenges();
194 }
195 );
196 const connectAndPoll = () => {
197 this.send("connect");
198 this.send("pollclientsandgamers");
199 };
200 // Initialize connection
201 const connexionString = params.socketUrl +
202 "/?sid=" + this.st.user.sid +
203 "&tmpId=" + getRandString() +
204 "&page=" + encodeURIComponent(this.$route.path);
205 this.conn = new WebSocket(connexionString);
206 this.conn.onopen = connectAndPoll;
207 this.conn.onmessage = this.socketMessageListener;
208 const socketCloseListener = () => {
209 this.conn = new WebSocket(connexionString);
210 this.conn.addEventListener('message', this.socketMessageListener);
211 this.conn.addEventListener('close', socketCloseListener);
212 };
213 this.conn.onclose = socketCloseListener;
214 },
215 mounted: function() {
216 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
217 .forEach(elt => elt.addEventListener("click", processModalClick));
218 document.querySelectorAll("#predefinedCadences > button").forEach(
219 (b) => { b.addEventListener("click",
220 () => { this.newchallenge.cadence = b.innerHTML; }
221 )}
222 );
223 },
224 beforeDestroy: function() {
225 this.send("disconnect");
226 },
227 methods: {
228 // Helpers:
229 send: function(code, obj) {
230 this.conn.send(JSON.stringify(
231 Object.assign(
232 {code: code},
233 obj,
234 )
235 ));
236 },
237 getVname: function(vid) {
238 const variant = this.st.variants.find(v => v.id == vid);
239 // this.st.variants might be uninitialized (variant == null)
240 return (!!variant ? variant.name : "");
241 },
242 filterChallenges: function(type) {
243 return this.challenges.filter(c => c.type == type);
244 },
245 filterGames: function(type) {
246 return this.games.filter(g => g.type == type);
247 },
248 classifyObject: function(o) { //challenge or game
249 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
250 },
251 setDisplay: function(letter, type, e) {
252 this[letter + "display"] = type;
253 e.target.classList.add("active");
254 if (!!e.target.previousElementSibling)
255 e.target.previousElementSibling.classList.remove("active");
256 else
257 e.target.nextElementSibling.classList.remove("active");
258 },
259 getActionLabel: function(sid) {
260 return this.people[sid].pages.some(p => p == "/")
261 ? "Challenge"
262 : "Observe";
263 },
264 challOrWatch: function(sid) {
265 if (this.people[sid].pages.some(p => p == "/"))
266 {
267 // Available, in Hall
268 this.newchallenge.to = this.people[sid].name;
269 doClick("modalNewgame");
270 }
271 else
272 {
273 // In some game, maybe playing maybe not
274 const gid = this.people[sid].page.match(/[a-zA-Z0-9]+$/)[0];
275 this.showGame(this.games.find(g => g.id == gid)), sid;
276 }
277 },
278 showGame: function(g, obsId) {
279 // NOTE: we are an observer, since only games I don't play are shown here
280 // ==> Moves sent by connected remote player(s) if live game
281 let url = "/game/" + g.id;
282 if (g.type == "live")
283 {
284 let rids = [];
285 for (let i of [0,1])
286 {
287 if (this.people[g.players[i].sid].pages.indexOf(url) >= 0)
288 rids.push(g.players[i].sid);
289 }
290 if (!!obsId)
291 rids.push(obsId); //observer can provide game too
292 const ridIdx = Math.floor(Math.random() * rids.length);
293 url += "?rid=" + rids[ridIdx];
294 }
295 this.$router.push(url);
296 },
297 processChat: function(chat) {
298 this.send("newchat", {data:chat});
299 },
300 // Messaging center:
301 socketMessageListener: function(msg) {
302 const data = JSON.parse(msg.data);
303 switch (data.code)
304 {
305 case "pollclientsandgamers":
306 {
307 let identityAsked = {};
308 data.sockIds.forEach(s => {
309 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
310 {
311 identityAsked[s.sid] = true;
312 this.send("askidentity", {target:s.sid});
313 }
314 if (!this.people[s.sid])
315 this.$set(this.people, s.sid, {id:0, name:"", pages:[s.page || "/"]});
316 else if (!!s.page && this.people[s.sid].pages.indexOf(s.page) < 0)
317 this.people[s.sid].pages.push(s.page);
318 if (!s.page)
319 this.send("askchallenge", {target:s.sid});
320 else
321 this.send("askgame", {target:s.sid});
322 });
323 break;
324 }
325 case "connect":
326 case "gconnect":
327 // NOTE: player could have been polled earlier, but might have logged in then
328 // So it's a good idea to ask identity if he was anonymous.
329 // But only ask game / challenge if currently disconnected.
330 if (!this.people[data.from])
331 {
332 this.$set(this.people, data.from, {name:"", id:0, pages:[data.page]});
333 if (data.code == "connect")
334 this.send("askchallenge", {target:data.from});
335 else
336 this.send("askgame", {target:data.from});
337 }
338 else
339 {
340 // append page if not already in list
341 if (this.people[data.from].pages.indexOf(data.page) < 0)
342 this.people[data.from].pages.push(data.page);
343 }
344 if (this.people[data.from].id == 0)
345 this.send("askidentity", {target:data.from});
346 break;
347 case "disconnect":
348 case "gdisconnect":
349 // Disconnect means no more tmpIds:
350 if (data.code == "disconnect")
351 {
352 this.$delete(this.people, data.from);
353 // Also remove all challenges sent by this player:
354 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
355 }
356 else
357 {
358 const pidx = this.people[data.from].pages.indexOf(data.page);
359 this.people[data.from].pages.splice(pageIdx, 1);
360 if (this.people[data.from].pages.length == 0)
361 {
362 this.$delete(this.people, data.from);
363 // And all live games where he plays and no other opponent is online
364 ArrayFun.remove(this.games, g =>
365 g.type == "live" && (g.players.every(p => p.sid == data.from
366 || !this.people[p.sid])), "all");
367 }
368 }
369 break;
370 case "askidentity":
371 // Request for identification: reply if I'm not anonymous
372 if (this.st.user.id > 0)
373 {
374 const me = {
375 // NOTE: decompose to avoid revealing email
376 name: this.st.user.name,
377 sid: this.st.user.sid,
378 id: this.st.user.id,
379 };
380 this.send("identity", {data:me, target:data.from});
381 }
382 break;
383 case "identity":
384 {
385 const user = data.data;
386 this.$set(this.people, user.sid,
387 {
388 id: user.id,
389 name: user.name,
390 pages: this.people[user.sid].pages,
391 });
392
393 // // TODO: smarter, if multi-connect, send to all instances... (several sid's)
394 // // Or better: just prevent multi-connect.
395 // // Fix anomaly: if registered player multi-connect, should be left only one
396 // const anomalies = Object.keys(this.people).filter(sid => this.people[sid].id == user.id);
397 // if (anomalies.length == 2)
398 // this.$delete(this.people, anomalies[0]);
399 // // --> this isn't good, some sid's are just forgetted
400
401 break;
402 }
403 case "askchallenge":
404 {
405 // Send my current live challenge (if any)
406 const cIdx = this.challenges.findIndex(c =>
407 c.from.sid == this.st.user.sid && c.type == "live");
408 if (cIdx >= 0)
409 {
410 const c = this.challenges[cIdx];
411 // NOTE: in principle, should only send targeted challenge to the target.
412 // But we may not know yet the identity of the target (just name),
413 // so cannot decide if data.from is the target or not.
414 const myChallenge =
415 {
416 id: c.id,
417 from: this.st.user.sid,
418 to: c.to,
419 fen: c.fen,
420 vid: c.vid,
421 cadence: c.cadence,
422 added: c.added,
423 };
424 this.send("challenge", {data:myChallenge, target:data.from});
425 }
426 break;
427 }
428 case "challenge": //after "askchallenge"
429 case "newchallenge":
430 {
431 // NOTE about next condition: see "askchallenge" case.
432 const chall = data.data;
433 if (!chall.to || (this.people[chall.from].id > 0 &&
434 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
435 {
436 let newChall = Object.assign({}, chall);
437 newChall.type = this.classifyObject(chall);
438 newChall.added = Date.now();
439 let fromValues = Object.assign({}, this.people[chall.from]);
440 delete fromValues["pages"]; //irrelevant in this context
441 newChall.from = Object.assign({sid:chall.from}, fromValues);
442 newChall.vname = this.getVname(newChall.vid);
443 this.challenges.push(newChall);
444 }
445 break;
446 }
447 case "refusechallenge":
448 {
449 const cid = data.data;
450 ArrayFun.remove(this.challenges, c => c.id == cid);
451 alert(this.st.tr["Challenge declined"]);
452 break;
453 }
454 case "deletechallenge":
455 {
456 // NOTE: the challenge may be already removed
457 const cid = data.data;
458 ArrayFun.remove(this.challenges, c => c.id == cid);
459 break;
460 }
461 case "game": //individual request
462 case "newgame":
463 {
464 // NOTE: it may be live or correspondance
465 const game = data.data;
466 if (this.games.findIndex(g => g.id == game.id) < 0)
467 {
468 let newGame = game;
469 newGame.type = this.classifyObject(game);
470 newGame.vname = this.getVname(game.vid);
471 if (!game.score) //if new game from Hall
472 newGame.score = "*";
473 this.games.push(newGame);
474 }
475 break;
476 }
477 case "startgame":
478 {
479 // New game just started: data contain all information
480 const gameInfo = data.data;
481 if (this.classifyObject(gameInfo) == "live")
482 this.startNewGame(gameInfo);
483 else
484 {
485 this.infoMessage = this.st.tr["New correspondance game:"] +
486 " <a href='#/game/" + gameInfo.id + "'>" +
487 "#/game/" + gameInfo.id + "</a>";
488 let modalBox = document.getElementById("modalInfo");
489 modalBox.checked = true;
490 setTimeout(() => { modalBox.checked = false; }, 3000);
491 }
492 break;
493 }
494 case "newchat":
495 this.newChat = data.data;
496 break;
497 }
498 },
499 // Challenge lifecycle:
500 newChallenge: async function() {
501 if (this.newchallenge.vid == "")
502 return alert(this.st.tr["Please select a variant"]);
503 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
504 return alert(this.st.tr["Self-challenge is forbidden"]);
505 const vname = this.getVname(this.newchallenge.vid);
506 const vModule = await import("@/variants/" + vname + ".js");
507 window.V = vModule.VariantRules;
508 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
509 this.newchallenge.cadence += "+0"; //assume minutes, no increment
510 const error = checkChallenge(this.newchallenge);
511 if (!!error)
512 return alert(error);
513 const ctype = this.classifyObject(this.newchallenge);
514 if (ctype == "corr" && this.st.user.id <= 0)
515 return alert(this.st.tr["Please log in to play correspondance games"]);
516 // NOTE: "from" information is not required here
517 let chall = Object.assign({}, this.newchallenge);
518 const finishAddChallenge = (cid) => {
519 chall.id = cid || "c" + getRandString();
520 // Remove old challenge if any (only one at a time of a given type):
521 const cIdx = this.challenges.findIndex(c =>
522 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
523 if (cIdx >= 0)
524 {
525 // Delete current challenge (will be replaced now)
526 this.send("deletechallenge", {data:this.challenges[cIdx].id});
527 if (ctype == "corr")
528 {
529 ajax(
530 "/challenges",
531 "DELETE",
532 {id: this.challenges[cIdx].id}
533 );
534 }
535 this.challenges.splice(cIdx, 1);
536 }
537 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
538 // Add new challenge:
539 chall.from = { //decompose to avoid revealing email
540 sid: this.st.user.sid,
541 id: this.st.user.id,
542 name: this.st.user.name,
543 };
544 chall.added = Date.now();
545 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
546 chall.type = ctype;
547 chall.vname = vname;
548 this.challenges.push(chall);
549 // Remember cadence + vid for quicker further challenges:
550 localStorage.setItem("cadence", chall.cadence);
551 localStorage.setItem("vid", chall.vid);
552 document.getElementById("modalNewgame").checked = false;
553 };
554 if (ctype == "live")
555 {
556 // Live challenges have a random ID
557 finishAddChallenge(null);
558 }
559 else
560 {
561 // Correspondance game: send challenge to server
562 ajax(
563 "/challenges",
564 "POST",
565 { chall: chall },
566 response => { finishAddChallenge(response.cid); }
567 );
568 }
569 },
570 clickChallenge: function(c) {
571 const myChallenge = (c.from.sid == this.st.user.sid //live
572 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
573 if (!myChallenge)
574 {
575 if (c.type == "corr" && this.st.user.id <= 0)
576 return alert(this.st.tr["Please log in to accept corr challenges"]);
577 c.accepted = true;
578 if (!!c.to) //c.to == this.st.user.name (connected)
579 {
580 // TODO: if special FEN, show diagram after loading variant
581 c.accepted = confirm("Accept challenge?");
582 }
583 if (c.accepted)
584 {
585 c.seat = { //again, avoid c.seat = st.user to not reveal email
586 sid: this.st.user.sid,
587 id: this.st.user.id,
588 name: this.st.user.name,
589 };
590 this.launchGame(c);
591 }
592 else
593 {
594 this.send("refusechallenge", {data:c.id, target:c.from.sid});
595 }
596 this.send("deletechallenge", {data:c.id});
597 }
598 else //my challenge
599 {
600 if (c.type == "corr")
601 {
602 ajax(
603 "/challenges",
604 "DELETE",
605 {id: c.id}
606 );
607 }
608 this.send("deletechallenge", {data:c.id});
609 }
610 // In all cases, the challenge is consumed:
611 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
612 },
613 // NOTE: when launching game, the challenge is already being deleted
614 launchGame: async function(c) {
615 const vModule = await import("@/variants/" + c.vname + ".js");
616 window.V = vModule.VariantRules;
617 // These game informations will be shared
618 let gameInfo =
619 {
620 id: getRandString(),
621 fen: c.fen || V.GenRandInitFen(),
622 players: shuffle([c.from, c.seat]), //white then black
623 vid: c.vid,
624 cadence: c.cadence,
625 };
626 let oppsid = c.from.sid; //may not be defined if corr + offline opp
627 if (!oppsid)
628 {
629 oppsid = Object.keys(this.people).find(sid =>
630 this.people[sid].id == c.from.id);
631 }
632 const notifyNewgame = () => {
633 if (!!oppsid) //opponent is online
634 this.send("startgame", {data:gameInfo, target:oppsid});
635 // Send game info (only if live) to everyone except me in this tab
636 this.send("newgame", {data:gameInfo});
637 };
638 if (c.type == "live")
639 {
640 notifyNewgame();
641 this.startNewGame(gameInfo);
642 }
643 else //corr: game only on server
644 {
645 ajax(
646 "/games",
647 "POST",
648 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
649 response => {
650 gameInfo.id = response.gameId;
651 notifyNewgame();
652 this.$router.push("/game/" + response.gameId);
653 }
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 vname: this.getVname(gameInfo.vid),
663 created: Date.now(),
664 // Game state (including FEN): will be updated
665 moves: [],
666 clocks: [-1, -1], //-1 = unstarted
667 initime: [0, 0], //initialized later
668 score: "*",
669 });
670 GameStorage.add(game);
671 if (this.st.settings.sound >= 1)
672 new Audio("/sounds/newgame.mp3").play().catch(err => {});
673 this.$router.push("/game/" + gameInfo.id);
674 },
675 },
676 };
677 </script>
678
679 <style lang="sass" scoped>
680 .active
681 color: #42a983
682 #newGame
683 display: block
684 margin: 10px auto 5px auto
685 #people
686 width: 100%
687 #players
688 width: 50%
689 position: relative
690 float: left
691 #chat
692 width: 50%
693 float: left
694 position: relative
695 @media screen and (max-width: 767px)
696 #players, #chats
697 width: 100%
698 #chat > .card
699 max-width: 100%
700 margin: 0;
701 border: none;
702 #players > p
703 margin-left: 5px
704 .anonymous
705 font-style: italic
706 button.player-action
707 margin-left: 32px
708 </style>