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