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