Fix missing name when launching a game from Hall (TODO: understand why it fails somet...
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(
5 role="dialog"
6 data-checkbox="modalInfo"
7 )
8 .card.text-center
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
13 .card
14 p.text-center
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
18 .diagram(
19 v-if="!!curChallToAccept.fen"
20 v-html="tchallDiag"
21 )
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
27 input#modalNewgame.modal(
28 type="checkbox"
29 @change="cadenceFocusIfOpened($event)"
30 )
31 div#newgameDiv(
32 role="dialog"
33 data-checkbox="modalNewgame"
34 )
35 .card
36 label#closeNewgame.modal-close(for="modalNewgame")
37 div(@keyup.enter="issueNewChallenge()")
38 fieldset
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
40 select#selectVariant(
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
43 )
44 option(
45 v-for="v in st.variants"
46 :value="v.id"
47 :selected="newchallenge.vid==v.id"
48 )
49 | {{ v.name }}
50 fieldset
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
53 button(type="button") 15+5
54 button(type="button") 45+30
55 button(type="button") 3d
56 button(type="button") 7d
57 input#cadence(
58 type="text"
59 v-model="newchallenge.cadence"
60 placeholder="5+0, 1h+30s, 5d ..."
61 )
62 fieldset
63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
68 fieldset
69 label(for="memorizeChall") {{ st.tr["Memorize"] }}
70 input#memorizeChall(
71 type="checkbox"
72 v-model="newchallenge.memorize"
73 )
74 fieldset(v-if="st.user.id > 0")
75 label(for="selectPlayers") {{ st.tr["Play with"] }}
76 select#selectPlayersInList(
77 v-model="newchallenge.to"
78 @change="changeChallTarget()"
79 )
80 option(value="")
81 option(
82 v-for="p in Object.values(people)"
83 v-if="!!p.name"
84 :value="p.name"
85 )
86 | {{ p.name }}
87 input#selectPlayers(
88 type="text"
89 v-model="newchallenge.to"
90 )
91 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
92 input#inputFen(
93 placeholder="FEN"
94 @input="trySetNewchallDiag()"
95 type="text"
96 v-model="newchallenge.fen"
97 )
98 .diagram(v-html="newchallenge.diag")
99 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
100 input#modalPeople.modal(
101 type="checkbox"
102 @click="toggleSocialColor()"
103 )
104 div#peopleWrap(
105 role="dialog"
106 data-checkbox="modalPeople"
107 )
108 .card
109 label.modal-close(for="modalPeople")
110 #people
111 #players
112 p(
113 v-for="sid in Object.keys(people)"
114 v-if="!!people[sid].name"
115 )
116 span {{ people[sid].name }}
117 button.player-action(
118 v-if="isGamer(sid)"
119 @click="watchGame(sid)"
120 )
121 | {{ st.tr["Observe"] }}
122 button.player-action(
123 v-else-if="isFocusedOnHall(sid)"
124 @click="challenge(sid)"
125 )
126 | {{ st.tr["Challenge"] }}
127 p.anonymous @nonymous ({{ anonymousCount() }})
128 #chat
129 Chat(
130 ref="chatcomp"
131 @mychat="processChat"
132 :pastChats="[]"
133 )
134 .clearer
135 .row
136 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
137 .button-group
138 button#peopleBtn(onClick="window.doClick('modalPeople')")
139 | {{ st.tr["Who's there?"] }}
140 button(@click="showNewchallengeForm()")
141 | {{ st.tr["New game"] }}
142 .row(v-if="presetChalls.length > 0")
143 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
144 h4.text-center {{ st.tr["Preset challenges"] }}
145 table
146 thead
147 tr
148 th {{ st.tr["Variant"] }}
149 th {{ st.tr["Cadence"] }}
150 th {{ st.tr["Random?"] }}
151 th
152 tbody
153 tr(
154 v-for="pc in presetChalls"
155 @click="newChallFromPreset(pc)"
156 )
157 td {{ pc.vname }}
158 td {{ pc.cadence }}
159 td(:class="getRandomnessClass(pc)")
160 td.remove-preset(@click="removePresetChall($event, pc)")
161 img(src="/images/icons/delete.svg")
162 .row
163 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
164 div#div2
165 .button-group
166 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
167 | {{ st.tr["Live challenges"] }}
168 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
169 | {{ st.tr["Correspondance challenges"] }}
170 ChallengeList(
171 v-show="cdisplay=='live'"
172 :challenges="filterChallenges('live')"
173 @click-challenge="clickChallenge"
174 )
175 ChallengeList(
176 v-show="cdisplay=='corr'"
177 :challenges="filterChallenges('corr')"
178 @click-challenge="clickChallenge"
179 )
180 div#div3
181 .button-group
182 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
183 | {{ st.tr["Live games"] }}
184 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
185 | {{ st.tr["Correspondance games"] }}
186 GameList(
187 v-show="gdisplay=='live'"
188 :games="filterGames('live')"
189 :showBoth="true"
190 @show-game="showGame"
191 )
192 div(v-show="gdisplay=='corr'")
193 GameList(
194 :games="filterGames('corr')"
195 :showBoth="true"
196 @show-game="showGame"
197 )
198 button#loadMoreBtn(
199 v-if="hasMore"
200 @click="loadMoreCorr()"
201 )
202 | {{ st.tr["Load more"] }}
203 </template>
204
205 <script>
206 import { store } from "@/store";
207 import { checkChallenge } from "@/data/challengeCheck";
208 import { notify } from "@/utils/notifications";
209 import { ArrayFun } from "@/utils/array";
210 import { ajax } from "@/utils/ajax";
211 import params from "@/parameters";
212 import { getRandString, shuffle, randInt } from "@/utils/alea";
213 import { getDiagram } from "@/utils/printDiagram";
214 import Chat from "@/components/Chat.vue";
215 import GameList from "@/components/GameList.vue";
216 import ChallengeList from "@/components/ChallengeList.vue";
217 import { GameStorage } from "@/utils/gameStorage";
218 import { processModalClick } from "@/utils/modalClick";
219 export default {
220 name: "my-hall",
221 components: {
222 Chat,
223 GameList,
224 ChallengeList
225 },
226 data: function() {
227 return {
228 st: store.state,
229 cdisplay: "live", //or corr
230 gdisplay: "live",
231 // timestamp of last showed (oldest) corr game:
232 cursor: Number.MAX_SAFE_INTEGER,
233 // hasMore == TRUE: a priori there could be more games to load
234 hasMore: true,
235 games: [],
236 challenges: [],
237 people: {},
238 infoMessage: "",
239 newchallenge: {
240 fen: "",
241 vid: parseInt(localStorage.getItem("vid")) || 0,
242 to: "", //name of challenged player (if any)
243 cadence: localStorage.getItem("cadence") || "",
244 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
245 // VariantRules object, stored to not interfere with
246 // diagrams of targetted challenges:
247 V: null,
248 vname: "",
249 diag: "", //visualizing FEN
250 memorize: false //put settings in localStorage
251 },
252 focus: true,
253 tchallDiag: "",
254 curChallToAccept: {from: {}},
255 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
256 conn: null,
257 connexionString: "",
258 socketCloseListener: 0,
259 // Related to (killing of) self multi-connects:
260 newConnect: {}
261 };
262 },
263 watch: {
264 // st.variants changes only once, at loading from [] to [...]
265 "st.variants": function() {
266 // Set potential challenges and games variant names:
267 this.challenges.concat(this.games).forEach(o => {
268 if (!o.vname) o.vname = this.getVname(o.vid);
269 });
270 if (!this.newchallenge.V && this.newchallenge.vid > 0)
271 this.loadNewchallVariant();
272 },
273 $route: function(to, from) {
274 if (to.path != "/") this.cleanBeforeDestroy();
275 }
276 },
277 created: function() {
278 document.addEventListener('visibilitychange', this.visibilityChange);
279 window.addEventListener('focus', this.onFocus);
280 window.addEventListener('blur', this.onBlur);
281 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
282 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
283 this.loadNewchallVariant();
284 const my = this.st.user;
285 const tmpId = getRandString();
286 this.$set(
287 this.people,
288 my.sid,
289 {
290 id: my.id,
291 name: my.name,
292 tmpIds: {
293 tmpId: { page: "/", focus: true }
294 }
295 }
296 );
297 const connectAndPoll = () => {
298 this.send("connect");
299 this.send("pollclientsandgamers");
300 };
301 // Initialize connection
302 this.connexionString =
303 params.socketUrl +
304 "/?sid=" + this.st.user.sid +
305 "&id=" + this.st.user.id +
306 "&tmpId=" + tmpId +
307 "&page=" +
308 // Hall: path is "/" (TODO: could be hard-coded as well)
309 encodeURIComponent(this.$route.path);
310 this.conn = new WebSocket(this.connexionString);
311 this.conn.onopen = connectAndPoll;
312 this.conn.addEventListener("message", this.socketMessageListener);
313 this.socketCloseListener = setInterval(
314 () => {
315 if (this.conn.readyState == 3) {
316 this.conn.removeEventListener("message", this.socketMessageListener);
317 this.conn = new WebSocket(this.connexionString);
318 this.conn.addEventListener("message", this.socketMessageListener);
319 }
320 },
321 1000
322 );
323 },
324 mounted: function() {
325 document.getElementById("peopleWrap")
326 .addEventListener("click", (e) => {
327 processModalClick(e, () => {
328 this.toggleSocialColor("close")
329 });
330 });
331 ["infoDiv", "newgameDiv"].forEach(eltName => {
332 document.getElementById(eltName)
333 .addEventListener("click", processModalClick);
334 });
335 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
336 b.addEventListener("click", () => {
337 this.newchallenge.cadence = b.innerHTML;
338 });
339 });
340 const dispCorr = this.$route.query["disp"];
341 const showCtype =
342 dispCorr || localStorage.getItem("type-challenges") || "live";
343 const showGtype =
344 dispCorr || localStorage.getItem("type-games") || "live";
345 this.setDisplay('c', showCtype);
346 this.setDisplay('g', showGtype);
347 // Ask server for current corr games (all but mines)
348 this.loadMoreCorr();
349 // Also ask for corr challenges (open + sent by/to me)
350 // List them all, because they are not supposed to be that many (TODO?)
351 ajax(
352 "/challenges",
353 "GET",
354 {
355 data: { uid: this.st.user.id },
356 success: (response) => {
357 if (
358 response.challenges.length > 0 &&
359 this.challenges.length == 0 &&
360 this.cdisplay == "live"
361 ) {
362 document
363 .getElementById("btnCcorr")
364 .classList.add("somethingnew");
365 }
366 // Gather all senders names, and then retrieve full identity:
367 // (TODO [perf]: some might be online...)
368 let names = {};
369 response.challenges.forEach(c => {
370 if (c.uid != this.st.user.id) names[c.uid] = "";
371 else if (!!c.target && c.target != this.st.user.id)
372 names[c.target] = "";
373 });
374 const addChallenges = () => {
375 names[this.st.user.id] = this.st.user.name; //in case of
376 this.challenges = this.challenges.concat(
377 response.challenges.map(c => {
378 const from = { name: names[c.uid], id: c.uid }; //or just name
379 const type = this.classifyObject(c);
380 const vname = this.getVname(c.vid);
381 return Object.assign(
382 {},
383 {
384 type: type,
385 vname: vname,
386 from: from,
387 to: c.target ? names[c.target] : ""
388 },
389 c
390 );
391 })
392 );
393 };
394 if (Object.keys(names).length > 0) {
395 ajax(
396 "/users",
397 "GET",
398 {
399 data: { ids: Object.keys(names).join(",") },
400 success: (response2) => {
401 response2.users.forEach(u => {
402 names[u.id] = u.name;
403 });
404 addChallenges();
405 }
406 }
407 );
408 } else addChallenges();
409 }
410 }
411 );
412 },
413 beforeDestroy: function() {
414 this.cleanBeforeDestroy();
415 },
416 methods: {
417 cleanBeforeDestroy: function() {
418 clearInterval(this.socketCloseListener);
419 document.removeEventListener('visibilitychange', this.visibilityChange);
420 window.removeEventListener('focus', this.onFocus);
421 window.removeEventListener('blur', this.onBlur);
422 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
423 this.conn.removeEventListener("message", this.socketMessageListener);
424 this.send("disconnect");
425 this.conn = null;
426 },
427 getRandomnessClass: function(pc) {
428 return {
429 ["random-" + pc.randomness]: true
430 };
431 },
432 anonymousCount: function() {
433 let count = 0;
434 Object.values(this.people).forEach(p => {
435 // Do not cound people who did not send their identity yet:
436 count += (!p.name && p.id === 0) ? 1 : 0;
437 });
438 return count;
439 },
440 visibilityChange: function() {
441 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
442 this.focus = (document.visibilityState == "visible");
443 this.send(this.focus ? "getfocus" : "losefocus");
444 },
445 onFocus: function() {
446 this.focus = true;
447 this.send("getfocus");
448 },
449 onBlur: function() {
450 this.focus = false;
451 this.send("losefocus");
452 },
453 partialResetNewchallenge: function() {
454 // Reset potential target and custom FEN:
455 this.newchallenge.to = "";
456 this.newchallenge.fen = "";
457 this.newchallenge.diag = "";
458 this.newchallenge.memorize = false;
459 },
460 showNewchallengeForm: function() {
461 this.partialResetNewchallenge();
462 window.doClick("modalNewgame");
463 },
464 addPresetChall: function(chall) {
465 // Add only if not already existing:
466 if (this.presetChalls.some(c =>
467 c.vid == chall.vid &&
468 c.cadence == chall.cadence &&
469 c.randomness == chall.randomness
470 )) {
471 return;
472 }
473 const L = this.presetChalls.length;
474 this.presetChalls.push({
475 index: L,
476 vid: chall.vid,
477 vname: chall.vname, //redundant, but easier
478 cadence: chall.cadence,
479 randomness: chall.randomness
480 });
481 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
482 },
483 removePresetChall: function(e, pchall) {
484 e.stopPropagation();
485 const pchallIdx =
486 this.presetChalls.findIndex(pc => pc.index == pchall.index);
487 this.presetChalls.splice(pchallIdx, 1);
488 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
489 },
490 tchallButtonsMargin: function() {
491 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
492 return {};
493 },
494 changeChallTarget: function() {
495 if (!this.newchallenge.to) {
496 // Reset potential FEN + diagram
497 this.newchallenge.fen = "";
498 this.newchallenge.diag = "";
499 }
500 },
501 cadenceFocusIfOpened: function() {
502 if (event.target.checked)
503 document.getElementById("cadence").focus();
504 },
505 send: function(code, obj) {
506 if (!!this.conn && this.conn.readyState == 1) {
507 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
508 }
509 },
510 getVname: function(vid) {
511 const variant = this.st.variants.find(v => v.id == vid);
512 // this.st.variants might be uninitialized (variant == null)
513 return variant ? variant.name : "";
514 },
515 filterChallenges: function(type) {
516 return this.challenges.filter(c => c.type == type);
517 },
518 filterGames: function(type) {
519 return this.games.filter(g => g.type == type);
520 },
521 // o: challenge or game
522 classifyObject: function(o) {
523 // Consider imports as live games (TODO)
524 if (!!o.id && !!o.id.toString().match(/^i/)) return "live";
525 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
526 },
527 setDisplay: function(letter, type, e) {
528 this[letter + "display"] = type;
529 localStorage.setItem(
530 "type-" + (letter == "c" ? "challenges" : "games"),
531 type
532 );
533 let elt = e
534 ? e.target
535 : document.getElementById("btn" + letter.toUpperCase() + type);
536 elt.classList.add("active");
537 elt.classList.remove("somethingnew"); //in case of
538 if (!!elt.previousElementSibling)
539 elt.previousElementSibling.classList.remove("active");
540 else elt.nextElementSibling.classList.remove("active");
541 },
542 isGamer: function(sid) {
543 return Object.values(this.people[sid].tmpIds)
544 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
545 },
546 isFocusedOnHall: function(sid) {
547 return (
548 // This is meant to challenge people, thus the next 2 conditions:
549 this.st.user.id > 0 &&
550 sid != this.st.user.sid &&
551 Object.values(this.people[sid].tmpIds)
552 .some(v => v.focus && v.page == "/")
553 );
554 },
555 challenge: function(sid) {
556 this.partialResetNewchallenge();
557 // Available, in Hall
558 this.newchallenge.to = this.people[sid].name;
559 // TODO: also store target sid to not re-search for it
560 document.getElementById("modalPeople").checked = false;
561 window.doClick("modalNewgame");
562 },
563 watchGame: function(sid) {
564 // In some game, maybe playing maybe not: show a random one
565 let gids = [];
566 Object.values(this.people[sid].tmpIds).forEach(v => {
567 if (v.focus) {
568 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
569 if (!!matchGid) gids.push(matchGid[0]);
570 }
571 });
572 const gid = gids[Math.floor(Math.random() * gids.length)];
573 const game = this.games.find(g => g.id == gid);
574 if (!!game) this.showGame(game);
575 else this.$router.push("/game/" + gid); //game vs. me
576 },
577 showGame: function(g) {
578 // NOTE: we are an observer, since only games I don't play are shown here
579 // ==> Moves sent by connected remote player(s) if live game
580 this.$router.push("/game/" + g.id);
581 },
582 toggleSocialColor: function(action) {
583 if (!action && document.getElementById("modalPeople").checked)
584 document.getElementById("inputChat").focus();
585 else
586 document.getElementById("peopleBtn").classList.remove("somethingnew");
587 },
588 processChat: function(chat) {
589 this.send("newchat", { data: chat });
590 },
591 getOppsid: function(c) {
592 let oppsid = c.from.sid; //may not be defined if corr + offline opp
593 if (!oppsid) {
594 oppsid = Object.keys(this.people).find(
595 sid => this.people[sid].id == c.from.id
596 );
597 }
598 return oppsid;
599 },
600 // Messaging center:
601 socketMessageListener: function(msg) {
602 if (!this.conn) return;
603 const data = JSON.parse(msg.data);
604 switch (data.code) {
605 case "pollclientsandgamers": {
606 // TODO: shuffling and random filtering on server,
607 // if the room is really crowded.
608 Object.keys(data.sockIds).forEach(sid => {
609 if (sid != this.st.user.sid) {
610 // Pick a target tmpId (+page) at random:
611 const pt = Object.values(data.sockIds[sid]);
612 const randPage = pt[randInt(pt.length)].page;
613 this.send(
614 "askidentity",
615 {
616 target: sid,
617 page: randPage
618 }
619 );
620 }
621 if (!this.people[sid])
622 // Do not set name or id: identity unknown yet
623 this.people[sid] = { tmpIds: data.sockIds[sid] };
624 else
625 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
626 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
627 // Peer is in Hall
628 this.send("askchallenges", { target: sid });
629 Object.values(data.sockIds[sid]).forEach(v => {
630 if (
631 v.page.indexOf("/game/") >= 0 &&
632 !v.page.match(/\/[0-9]+$/)
633 ) {
634 // Peer is in Game: ask only if live game
635 this.send("askgame", { target: sid, page: v.page });
636 }
637 });
638 });
639 break;
640 }
641 case "connect":
642 case "gconnect": {
643 const page = data.page || "/";
644 if (data.code == "connect") {
645 // Ask challenges only on first connexion:
646 if (!this.people[data.from[0]])
647 this.send("askchallenges", { target: data.from[0] });
648 }
649 // Ask game only if live:
650 else if (!page.match(/\/[0-9]+$/))
651 this.send("askgame", { target: data.from[0], page: page });
652 if (!this.people[data.from[0]]) {
653 this.$set(
654 this.people,
655 data.from[0],
656 {
657 tmpIds: {
658 [data.from[1]]: { page: page, focus: true }
659 }
660 }
661 );
662 // For self multi-connects tests:
663 this.newConnect[data.from[0]] = true;
664 this.send("askidentity", { target: data.from[0], page: page });
665 } else {
666 this.people[data.from[0]].tmpIds[data.from[1]] =
667 { page: page, focus: true };
668 this.$forceUpdate(); //TODO: shouldn't be required
669 }
670 break;
671 }
672 case "disconnect":
673 case "gdisconnect": {
674 // If the user reloads the page twice very quickly
675 // (experienced with Firefox), the first reload won't have time to
676 // connect but will trigger a "close" event anyway.
677 // ==> Next check is required.
678 if (!this.people[data.from[0]]) return;
679 delete this.people[data.from[0]].tmpIds[data.from[1]];
680 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
681 this.$delete(this.people, data.from[0]);
682 else this.$forceUpdate(); //TODO: shouldn't be required
683 if (data.code == "disconnect") {
684 // Remove the live challenges sent by this player:
685 ArrayFun.remove(
686 this.challenges,
687 c => c.type == "live" && c.from.sid == data.from[0],
688 "all"
689 );
690 } else {
691 // Remove the matching live game if now unreachable
692 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
693 // Corr games are always reachable:
694 if (!gid.match(/^[0-9]+$/)) {
695 // Live games are reachable if someone is on the game page
696 if (Object.values(this.people).every(p =>
697 Object.values(p.tmpIds).every(v => v.page != data.page))
698 ) {
699 ArrayFun.remove(this.games, g => g.id == gid);
700 }
701 }
702 }
703 break;
704 }
705 case "getfocus": {
706 let player = this.people[data.from[0]];
707 // If user reload a page, focus may arrive earlier than connect
708 if (!!player) {
709 player.tmpIds[data.from[1]].focus = true;
710 this.$forceUpdate(); //TODO: shouldn't be required
711 }
712 break;
713 }
714 case "losefocus": {
715 let player = this.people[data.from[0]];
716 if (!!player) {
717 player.tmpIds[data.from[1]].focus = false;
718 this.$forceUpdate(); //TODO: shouldn't be required
719 }
720 break;
721 }
722 case "askidentity": {
723 // Request for identification
724 const me = {
725 // Decompose to avoid revealing email
726 name: this.st.user.name,
727 sid: this.st.user.sid,
728 id: this.st.user.id
729 };
730 this.send("identity", { data: me, target: data.from });
731 break;
732 }
733 case "identity": {
734 const user = data.data;
735 let player = this.people[user.sid];
736 // player.tmpIds is already set
737 player.id = user.id;
738 player.name = user.name;
739 // TODO: this.$set(people, ...) fails. So forceUpdate.
740 // But this shouldn't be like that!
741 this.$forceUpdate();
742 // If I multi-connect, kill current connexion if no mark (I'm older)
743 if (this.newConnect[user.sid]) {
744 delete this.newConnect[user.sid];
745 if (
746 user.id > 0 &&
747 user.id == this.st.user.id &&
748 user.sid != this.st.user.sid
749 ) {
750 // I logged in elsewhere:
751 this.cleanBeforeDestroy();
752 alert(this.st.tr["New connexion detected: tab now offline"]);
753 }
754 }
755 break;
756 }
757 case "askchallenges": {
758 // Send my current live challenges (if any)
759 const myChallenges = this.challenges
760 .filter(c =>
761 c.from.sid == this.st.user.sid && c.type == "live"
762 )
763 .map(c => {
764 // NOTE: in principle, should only send targeted challenge to the
765 // target. But we may not know yet the identity of the target
766 // (just name), so can't decide if data.from is the target.
767 return {
768 id: c.id,
769 from: this.st.user.sid,
770 to: c.to,
771 randomness: c.randomness,
772 fen: c.fen,
773 vid: c.vid,
774 cadence: c.cadence,
775 added: c.added
776 };
777 });
778 if (myChallenges.length > 0)
779 this.send("challenges", { data: myChallenges, target: data.from });
780 break;
781 }
782 case "challenges": //after "askchallenges"
783 data.data.forEach(this.addChallenge);
784 break;
785 case "newchallenge":
786 this.addChallenge(data.data);
787 break;
788 case "refusechallenge": {
789 const cid = data.data;
790 ArrayFun.remove(this.challenges, c => c.id == cid);
791 alert(this.st.tr["Challenge declined"]);
792 break;
793 }
794 case "deletechallenge_s": {
795 // NOTE: the challenge(s) may be already removed
796 const cref = data.data;
797 if (!!cref.cid)
798 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
799 else if (!!cref.sids) {
800 cref.sids.forEach(s => {
801 ArrayFun.remove(
802 this.challenges,
803 c => c.type == "live" && c.from.sid == s,
804 "all"
805 );
806 });
807 }
808 break;
809 }
810 case "game": // Individual request
811 case "newgame": {
812 const game = data.data;
813 // Ignore games where I play (will go in MyGames page),
814 // and also games that I already received.
815 if (
816 game.players.every(p =>
817 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
818 this.games.findIndex(g => g.id == game.id) == -1
819 ) {
820 let newGame = game;
821 newGame.type = this.classifyObject(game);
822 newGame.vname = this.getVname(game.vid);
823 if (!game.score)
824 // New game from Hall
825 newGame.score = "*";
826 this.games.push(newGame);
827 if (
828 (newGame.type == "live" && this.gdisplay == "corr") ||
829 (newGame.type == "corr" && this.gdisplay == "live")
830 ) {
831 document
832 .getElementById("btnG" + newGame.type)
833 .classList.add("somethingnew");
834 }
835 }
836 break;
837 }
838 case "result": {
839 let g = this.games.find(g => g.id == data.gid);
840 if (!!g) g.score = data.score;
841 break;
842 }
843 case "startgame": {
844 // New game just started, I'm involved
845 const gameInfo = data.data;
846 if (this.classifyObject(gameInfo) == "live")
847 this.startNewGame(gameInfo);
848 else {
849 this.infoMessage =
850 this.st.tr["New correspondance game:"] + " " +
851 "<a href='#/game/" + gameInfo.id + "'>" +
852 "#/game/" + gameInfo.id + "</a>";
853 document.getElementById("modalInfo").checked = true;
854 }
855 break;
856 }
857 case "newchat":
858 this.$refs["chatcomp"].newChat(data.data);
859 if (!document.getElementById("modalPeople").checked)
860 document.getElementById("peopleBtn").classList.add("somethingnew");
861 break;
862 }
863 },
864 loadMoreCorr: function() {
865 ajax(
866 "/observedgames",
867 "GET",
868 {
869 data: {
870 uid: this.st.user.id,
871 cursor: this.cursor
872 },
873 success: (res) => {
874 const L = res.games.length;
875 if (L > 0) {
876 if (
877 this.cursor == Number.MAX_SAFE_INTEGER &&
878 this.games.length == 0 &&
879 this.gdisplay == "live"
880 ) {
881 // First loading: show indicators
882 document
883 .getElementById("btnGcorr")
884 .classList.add("somethingnew");
885 }
886 this.cursor = res.games[L - 1].created;
887 let moreGames = res.games.map(g => {
888 const vname = this.getVname(g.vid);
889 return Object.assign(
890 {},
891 g,
892 {
893 type: "corr",
894 vname: vname
895 }
896 );
897 });
898 this.games = this.games.concat(moreGames);
899 } else this.hasMore = false;
900 }
901 }
902 );
903 },
904 // Challenge lifecycle:
905 addChallenge: function(chall) {
906 // NOTE about next condition: see "askchallenges" case.
907 if (
908 !chall.to ||
909 (this.people[chall.from].id > 0 &&
910 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
911 ) {
912 let newChall = Object.assign({}, chall);
913 newChall.type = this.classifyObject(chall);
914 newChall.randomness = chall.randomness;
915 newChall.added = Date.now();
916 let fromValues = Object.assign({}, this.people[chall.from]);
917 delete fromValues["pages"]; //irrelevant in this context
918 newChall.from = Object.assign({ sid: chall.from }, fromValues);
919 newChall.vname = this.getVname(newChall.vid);
920 this.challenges.push(newChall);
921 if (
922 (newChall.type == "live" && this.cdisplay == "corr") ||
923 (newChall.type == "corr" && this.cdisplay == "live")
924 ) {
925 document
926 .getElementById("btnC" + newChall.type)
927 .classList.add("somethingnew");
928 }
929 if (!!chall.to) {
930 notify(
931 "New challenge",
932 // fromValues.name should exist since the player is online, but
933 // let's consider there is some chance that the challenge arrives
934 // right after we connected and before receiving the poll result:
935 { body: "from " + (fromValues.name || "unknown yet...") }
936 );
937 }
938 }
939 },
940 loadNewchallVariant: async function(cb) {
941 const vname = this.getVname(this.newchallenge.vid);
942 await import("@/variants/" + vname + ".js")
943 .then((vModule) => {
944 window.V = vModule[vname + "Rules"];
945 this.newchallenge.V = window.V;
946 this.newchallenge.vname = vname;
947 if (!!cb) cb();
948 });
949 },
950 trySetNewchallDiag: function() {
951 if (!this.newchallenge.fen) {
952 this.newchallenge.diag = "";
953 return;
954 }
955 // If vid > 0 then the variant is loaded (function above):
956 window.V = this.newchallenge.V;
957 if (
958 this.newchallenge.vid > 0 &&
959 !!this.newchallenge.fen &&
960 V.IsGoodFen(this.newchallenge.fen)
961 ) {
962 const parsedFen = V.ParseFen(this.newchallenge.fen);
963 this.newchallenge.diag = getDiagram({
964 position: parsedFen.position,
965 orientation: parsedFen.turn
966 });
967 } else this.newchallenge.diag = "";
968 },
969 newChallFromPreset(pchall) {
970 this.partialResetNewchallenge();
971 this.newchallenge.vid = pchall.vid;
972 this.newchallenge.cadence = pchall.cadence;
973 this.newchallenge.randomness = pchall.randomness;
974 this.loadNewchallVariant(this.issueNewChallenge);
975 },
976 issueNewChallenge: async function() {
977 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
978 this.newchallenge.cadence += "+0"; //assume minutes, no increment
979 const ctype = this.classifyObject(this.newchallenge);
980 // TODO: cadence still unchecked so ctype could be wrong...
981 let error = "";
982 if (!this.newchallenge.vid)
983 error = this.st.tr["Please select a variant"];
984 else if (ctype == "corr" && this.st.user.id <= 0)
985 error = this.st.tr["Please log in to play correspondance games"];
986 else if (!!this.newchallenge.to) {
987 if (this.newchallenge.to == this.st.user.name)
988 error = this.st.tr["Self-challenge is forbidden"];
989 else if (
990 ctype == "live" &&
991 Object.values(this.people).every(p => p.name != this.newchallenge.to)
992 ) {
993 error = this.newchallenge.to + " " + this.st.tr["is not online"];
994 }
995 }
996 if (error) {
997 alert(error);
998 return;
999 }
1000 window.V = this.newchallenge.V;
1001 error = checkChallenge(this.newchallenge);
1002 if (error) {
1003 alert(error);
1004 return;
1005 }
1006 // NOTE: "from" information is not required here
1007 let chall = Object.assign({}, this.newchallenge);
1008 // Add only if not already issued (not counting target or FEN):
1009 if (this.challenges.some(c =>
1010 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
1011 c.vid == chall.vid &&
1012 c.cadence == chall.cadence &&
1013 c.randomness == chall.randomness
1014 )) {
1015 alert(this.st.tr["Challenge already exists"]);
1016 return;
1017 }
1018 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1019 delete chall["V"];
1020 delete chall["diag"];
1021 const finishAddChallenge = cid => {
1022 chall.id = cid || "c" + getRandString();
1023 const MAX_ALLOWED_CHALLS = 3;
1024 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1025 let countMyChalls = 0;
1026 let challToDelIdx = 0;
1027 let oldestAdded = Number.MAX_SAFE_INTEGER;
1028 for (let i=0; i<this.challenges.length; i++) {
1029 const c = this.challenges[i];
1030 if (
1031 c.type == ctype &&
1032 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
1033 ) {
1034 countMyChalls++;
1035 if (c.added < oldestAdded) {
1036 challToDelIdx = i;
1037 oldestAdded = c.added;
1038 }
1039 }
1040 }
1041 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1042 this.send(
1043 "deletechallenge_s",
1044 { data: { cid: this.challenges[challToDelIdx].id } }
1045 );
1046 if (ctype == "corr") {
1047 ajax(
1048 "/challenges",
1049 "DELETE",
1050 { data: { id: this.challenges[challToDelIdx].id } }
1051 );
1052 }
1053 this.challenges.splice(challToDelIdx, 1);
1054 }
1055 this.send("newchallenge", {
1056 data: Object.assign({ from: this.st.user.sid }, chall)
1057 });
1058 // Add new challenge:
1059 chall.from = {
1060 sid: this.st.user.sid,
1061 id: this.st.user.id,
1062 name: this.st.user.name
1063 };
1064 chall.added = Date.now();
1065 // NOTE: vname and type are redundant (deduced from cadence + vid)
1066 chall.type = ctype;
1067 chall.vname = this.newchallenge.vname;
1068 this.challenges.push(chall);
1069 // Remember cadence + vid for quicker further challenges:
1070 localStorage.setItem("cadence", chall.cadence);
1071 localStorage.setItem("vid", chall.vid);
1072 localStorage.setItem("challRandomness", chall.randomness);
1073 document.getElementById("modalNewgame").checked = false;
1074 // Show the challenge if not on current display
1075 if (
1076 (ctype == "live" && this.cdisplay == "corr") ||
1077 (ctype == "corr" && this.cdisplay == "live")
1078 ) {
1079 this.setDisplay('c', ctype);
1080 }
1081 };
1082 if (ctype == "live") {
1083 // Live challenges have a random ID
1084 finishAddChallenge(null);
1085 } else {
1086 // Correspondance game: send challenge to server
1087 ajax(
1088 "/challenges",
1089 "POST",
1090 {
1091 data: { chall: chall },
1092 success: (response) => {
1093 finishAddChallenge(response.id);
1094 }
1095 }
1096 );
1097 }
1098 },
1099 // Callback function after a diagram was showed to accept
1100 // or refuse targetted challenge:
1101 decisionChallenge: function(accepted) {
1102 this.curChallToAccept.accepted = accepted;
1103 this.finishProcessingChallenge(this.curChallToAccept);
1104 document.getElementById("modalAccept").checked = false;
1105 },
1106 finishProcessingChallenge: function(c) {
1107 if (c.accepted) {
1108 c.seat = {
1109 sid: this.st.user.sid,
1110 id: this.st.user.id,
1111 name: this.st.user.name
1112 };
1113 this.launchGame(c);
1114 if (c.type == "live") {
1115 // Remove all live challenges of both players
1116 this.send(
1117 "deletechallenge_s",
1118 { data: { sids: [c.from.sid, c.seat.sid] } }
1119 );
1120 }
1121 else
1122 // Corr challenge: just remove the challenge
1123 this.send("deletechallenge_s", { data: { cid: c.id } });
1124 } else {
1125 const oppsid = this.getOppsid(c);
1126 if (!!oppsid)
1127 this.send("refusechallenge", { data: c.id, target: oppsid });
1128 if (c.type == "corr") {
1129 ajax(
1130 "/challenges",
1131 "DELETE",
1132 { data: { id: c.id } }
1133 );
1134 }
1135 this.send("deletechallenge_s", { data: { cid: c.id } });
1136 }
1137 },
1138 // TODO: if several players click same challenge at the same time: problem
1139 clickChallenge: async function(c) {
1140 const myChallenge =
1141 c.from.sid == this.st.user.sid || //live
1142 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1143 if (!myChallenge) {
1144 if (c.type == "corr" && this.st.user.id <= 0) {
1145 alert(this.st.tr["Please log in to accept corr challenges"]);
1146 return;
1147 }
1148 c.accepted = true;
1149 await import("@/variants/" + c.vname + ".js")
1150 .then((vModule) => {
1151 window.V = vModule[c.vname + "Rules"];
1152 if (!!c.to) {
1153 // c.to == this.st.user.name (connected)
1154 if (!!c.fen) {
1155 const parsedFen = V.ParseFen(c.fen);
1156 c.mycolor = V.GetOppCol(parsedFen.turn);
1157 this.tchallDiag = getDiagram({
1158 position: parsedFen.position,
1159 orientation: c.mycolor
1160 });
1161 }
1162 this.curChallToAccept = c;
1163 document.getElementById("modalAccept").checked = true;
1164 }
1165 else this.finishProcessingChallenge(c);
1166 });
1167 }
1168 else {
1169 // My challenge
1170 if (c.type == "corr") {
1171 ajax(
1172 "/challenges",
1173 "DELETE",
1174 { data: { id: c.id } }
1175 );
1176 }
1177 this.send("deletechallenge_s", { data: { cid: c.id } });
1178 }
1179 // In all cases, the challenge is consumed:
1180 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1181 },
1182 // NOTE: when launching game, the challenge is already being deleted
1183 launchGame: function(c) {
1184 // White player index 0, black player index 1:
1185 let players =
1186 !!c.mycolor
1187 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1188 : shuffle([c.from, c.seat]);
1189 players.forEach(p => {
1190 if (!!p["tmpIds"]) delete p["tmpIds"];
1191 });
1192 // These game informations will be shared
1193 let gameInfo = {
1194 id: getRandString(),
1195 fen: c.fen || V.GenRandInitFen(c.randomness),
1196 randomness: c.randomness, //for rematch
1197 players: players,
1198 vid: c.vid,
1199 cadence: c.cadence
1200 };
1201 const notifyNewgame = () => {
1202 const oppsid = this.getOppsid(c);
1203 if (!!oppsid)
1204 // Opponent is online
1205 this.send("startgame", { data: gameInfo, target: oppsid });
1206 // If new corr game, notify Hall (except opponent and me)
1207 if (c.type == "corr") {
1208 this.send(
1209 "newgame",
1210 {
1211 data: gameInfo,
1212 excluded: [this.st.user.sid, oppsid]
1213 }
1214 );
1215 }
1216 // Notify MyGames page:
1217 this.send(
1218 "notifynewgame",
1219 {
1220 data: gameInfo,
1221 targets: gameInfo.players
1222 }
1223 );
1224 // NOTE: no need to send the game to the room, since I'll connect
1225 // on game just after, the main Hall will be notified.
1226 };
1227 if (c.type == "live") {
1228 notifyNewgame();
1229 this.startNewGame(gameInfo);
1230 } else {
1231 // corr: game only on server
1232 ajax(
1233 "/games",
1234 "POST",
1235 {
1236 // cid is useful to delete the challenge:
1237 data: {
1238 gameInfo: gameInfo,
1239 cid: c.id
1240 },
1241 success: (response) => {
1242 gameInfo.id = response.id;
1243 notifyNewgame();
1244 this.$router.push("/game/" + response.id);
1245 }
1246 }
1247 );
1248 }
1249 },
1250 // NOTE: for live games only (corr games start on the server)
1251 startNewGame: function(gameInfo) {
1252 const game = Object.assign(
1253 {},
1254 gameInfo,
1255 {
1256 // (other) Game infos: constant
1257 fenStart: gameInfo.fen,
1258 vname: this.getVname(gameInfo.vid),
1259 created: Date.now(),
1260 // Game state (including FEN): will be updated
1261 moves: [],
1262 clocks: [-1, -1], //-1 = unstarted
1263 chats: [],
1264 score: "*"
1265 }
1266 );
1267 setTimeout(
1268 () => {
1269 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1270 GameStorage.add(game, (err) => {
1271 // If an error occurred, game is not added: a tab already
1272 // added the game. Maybe a focused one, maybe not.
1273 // We know for sure that it emitted the gong start sound.
1274 // ==> Do not play it again.
1275 if (!err && this.st.settings.sound)
1276 new Audio("/sounds/newgame.flac").play().catch(() => {});
1277 if (!this.focus) {
1278 notify(
1279 "New live game",
1280 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1281 );
1282 }
1283 this.$router.push("/game/" + gameInfo.id);
1284 });
1285 },
1286 this.focus ? 500 + 1000 * Math.random() : 0
1287 );
1288 }
1289 }
1290 };
1291 </script>
1292
1293 <style lang="sass" scoped>
1294 .active
1295 color: #42a983
1296
1297 #infoDiv > .card
1298 padding: 15px 0
1299 max-width: 430px
1300
1301 #newgameDiv > .card, #acceptDiv > .card
1302 max-width: 767px
1303 max-height: 100%
1304
1305 div#peopleWrap > .card
1306 max-height: 100%
1307
1308 @media screen and (min-width: 1281px)
1309 div#peopleWrap > .card
1310 max-width: 66.67%
1311
1312 @media screen and (max-width: 1280px)
1313 div#peopleWrap > .card
1314 max-width: 83.33%
1315
1316 @media screen and (max-width: 767px)
1317 div#peopleWrap > .card
1318 max-width: 100%
1319
1320 #players
1321 width: 50%
1322 position: relative
1323 float: left
1324
1325 #chat
1326 width: 50%
1327 float: left
1328 position: relative
1329
1330 @media screen and (max-width: 767px)
1331 #players, #chats
1332 width: 100%
1333
1334 #chat > .card
1335 max-width: 100%
1336 margin: 0;
1337 border: none;
1338
1339 #players > p
1340 margin-left: 5px
1341
1342 .anonymous
1343 font-style: italic
1344
1345 button.player-action
1346 margin-left: 32px
1347
1348 .somethingnew
1349 background-color: #c5fefe !important
1350
1351 .tabbtn
1352 background-color: #f9faee
1353
1354 button.acceptBtn
1355 background-color: lightgreen
1356 button.refuseBtn
1357 background-color: red
1358
1359 #buttonsTchall
1360 // margin-top set dynamically (depends if diagram showed or not)
1361 & > button > span
1362 width: 100%
1363 text-align: center
1364
1365 .variantName
1366 font-weight: bold
1367
1368 .diagram
1369 margin: 0 auto
1370 max-width: 400px
1371 // width: 100% required for Firefox
1372 width: 100%
1373
1374 #inputFen
1375 width: 100%
1376
1377 #div2, #div3
1378 margin-top: 15px
1379 @media screen and (max-width: 767px)
1380 #div2, #div3
1381 margin-top: 0
1382
1383 tr > td
1384 &.random-0
1385 background-color: #FF5733
1386 &.random-1
1387 background-color: #2B63B4
1388 &.random-2
1389 background-color: #33B42B
1390
1391 @media screen and (max-width: 767px)
1392 h4
1393 margin: 5px 0
1394
1395 button#loadMoreBtn
1396 display: block
1397 margin: 0 auto
1398
1399 td.remove-preset
1400 background-color: lightgrey
1401 text-align: center
1402 & > img
1403 height: 1em
1404 </style>