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