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