Fix 'challenge' option for anonymous
[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.text-center
14 p
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
18 .diagram(v-html="tchallDiag")
19 .button-group#buttonsTchall
20 button.acceptBtn(@click="decisionChallenge(true)") {{ st.tr["Accept challenge?"] }}
21 button.refuseBtn(@click="decisionChallenge(false)") {{ st.tr["Refuse"] }}
22 input#modalNewgame.modal(
23 type="checkbox"
24 @change="cadenceFocusIfOpened($event)"
25 )
26 div#newgameDiv(
27 role="dialog"
28 data-checkbox="modalNewgame"
29 )
30 .card
31 label#closeNewgame.modal-close(for="modalNewgame")
32 div(@keyup.enter="newChallenge()")
33 fieldset
34 label(for="selectVariant") {{ st.tr["Variant"] }} *
35 select#selectVariant(
36 @change="loadNewchallVariant(trySetNewchallDiag)"
37 v-model="newchallenge.vid"
38 )
39 option(
40 v-for="v in st.variants"
41 :value="v.id"
42 :selected="newchallenge.vid==v.id"
43 )
44 | {{ v.name }}
45 fieldset
46 label(for="cadence") {{ st.tr["Cadence"] }} *
47 div#predefinedCadences
48 button(type="button") 15+5
49 button(type="button") 45+30
50 button(type="button") 3d
51 button(type="button") 7d
52 input#cadence(
53 type="text"
54 v-model="newchallenge.cadence"
55 placeholder="5+0, 1h+30s, 5d ..."
56 )
57 fieldset
58 label(for="selectRandomLevel") {{ st.tr["Randomness"] }}
59 select#selectRandomLevel(v-model="newchallenge.randomness")
60 option(value="0") {{ st.tr["Deterministic"] }}
61 option(value="1") {{ st.tr["Symmetric random"] }}
62 option(value="2") {{ st.tr["Asymmetric random"] }}
63 fieldset(v-if="st.user.id > 0")
64 label(for="selectPlayers") {{ st.tr["Play with?"] }}
65 input#selectPlayers(
66 type="text"
67 v-model="newchallenge.to"
68 )
69 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
70 input#inputFen(
71 placeholder="FEN"
72 @input="trySetNewchallDiag()"
73 type="text"
74 v-model="newchallenge.fen"
75 )
76 .diagram(v-html="newchallenge.diag")
77 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
78 input#modalPeople.modal(
79 type="checkbox"
80 @click="resetSocialColor()"
81 )
82 div#peopleWrap(
83 role="dialog"
84 data-checkbox="modalPeople"
85 )
86 .card
87 label.modal-close(for="modalPeople")
88 #people
89 #players
90 p(
91 v-for="sid in Object.keys(people)"
92 v-if="people[sid].name"
93 )
94 span {{ people[sid].name }}
95 button.player-action(
96 v-if="isGamer(sid) || (st.user.id > 0 && sid!=st.user.sid)"
97 @click="challOrWatch(sid)"
98 )
99 | {{ getActionLabel(sid) }}
100 p.anonymous @nonymous ({{ anonymousCount }})
101 #chat
102 Chat(
103 :newChat="newChat"
104 @mychat="processChat"
105 :pastChats="[]"
106 )
107 .clearer
108 .row
109 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
110 .button-group
111 button#peopleBtn(onClick="window.doClick('modalPeople')")
112 | {{ st.tr["Who's there?"] }}
113 button(onClick="window.doClick('modalNewgame')")
114 | {{ st.tr["New game"] }}
115 .row
116 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
117 div#div2
118 .button-group
119 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
120 | {{ st.tr["Live challenges"] }}
121 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
122 | {{ st.tr["Correspondance challenges"] }}
123 ChallengeList(
124 v-show="cdisplay=='live'"
125 :challenges="filterChallenges('live')"
126 @click-challenge="clickChallenge"
127 )
128 ChallengeList(
129 v-show="cdisplay=='corr'"
130 :challenges="filterChallenges('corr')"
131 @click-challenge="clickChallenge"
132 )
133 div#div3
134 .button-group
135 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
136 | {{ st.tr["Live games"] }}
137 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
138 | {{ st.tr["Correspondance games"] }}
139 GameList(
140 v-show="gdisplay=='live'"
141 :games="filterGames('live')"
142 :showBoth="true"
143 @show-game="showGame"
144 )
145 GameList(
146 v-show="gdisplay=='corr'"
147 :games="filterGames('corr')"
148 :showBoth="true"
149 @show-game="showGame"
150 )
151 </template>
152
153 <script>
154 import { store } from "@/store";
155 import { checkChallenge } from "@/data/challengeCheck";
156 import { ArrayFun } from "@/utils/array";
157 import { ajax } from "@/utils/ajax";
158 import params from "@/parameters";
159 import { getRandString, shuffle } from "@/utils/alea";
160 import { getDiagram } from "@/utils/printDiagram";
161 import Chat from "@/components/Chat.vue";
162 import GameList from "@/components/GameList.vue";
163 import ChallengeList from "@/components/ChallengeList.vue";
164 import { GameStorage } from "@/utils/gameStorage";
165 import { processModalClick } from "@/utils/modalClick";
166 export default {
167 name: "my-hall",
168 components: {
169 Chat,
170 GameList,
171 ChallengeList
172 },
173 data: function() {
174 return {
175 st: store.state,
176 cdisplay: "live", //or corr
177 gdisplay: "live",
178 games: [],
179 challenges: [],
180 people: {},
181 infoMessage: "",
182 newchallenge: {
183 fen: "",
184 vid: parseInt(localStorage.getItem("vid")) || 0,
185 to: "", //name of challenged player (if any)
186 cadence: localStorage.getItem("cadence") || "",
187 randomness: parseInt(localStorage.getItem("randomness")) || 2,
188 // VariantRules object, stored to not interfere with
189 // diagrams of targetted challenges:
190 V: null,
191 vname: "",
192 diag: "" //visualizing FEN
193 },
194 tchallDiag: "",
195 curChallToAccept: {from: {}},
196 newChat: "",
197 conn: null,
198 connexionString: "",
199 // Related to (killing of) self multi-connects:
200 newConnect: {},
201 killed: {}
202 };
203 },
204 watch: {
205 // st.variants changes only once, at loading from [] to [...]
206 "st.variants": function() {
207 // Set potential challenges and games variant names:
208 this.challenges.concat(this.games).forEach(o => {
209 if (o.vname == "") o.vname = this.getVname(o.vid);
210 });
211 if (!this.newchallenge.V && this.newchallenge.vid > 0)
212 this.loadNewchallVariant();
213 }
214 },
215 computed: {
216 anonymousCount: function() {
217 let count = 0;
218 Object.values(this.people).forEach(p => {
219 // Do not cound people who did not send their identity yet:
220 count += (!p.name && p.id === 0) ? 1 : 0;
221 });
222 return count;
223 }
224 },
225 created: function() {
226 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
227 this.loadNewchallVariant();
228 const my = this.st.user;
229 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
230 // Ask server for current corr games (all but mines)
231 ajax(
232 "/games",
233 "GET",
234 { uid: this.st.user.id, excluded: true },
235 response => {
236 this.games = this.games.concat(
237 response.games.map(g => {
238 const type = this.classifyObject(g);
239 const vname = this.getVname(g.vid);
240 return Object.assign({}, g, { type: type, vname: vname });
241 })
242 );
243 }
244 );
245 // Also ask for corr challenges (open + sent by/to me)
246 ajax("/challenges", "GET", { uid: this.st.user.id }, response => {
247 // Gather all senders names, and then retrieve full identity:
248 // (TODO [perf]: some might be online...)
249 let names = {};
250 response.challenges.forEach(c => {
251 if (c.uid != this.st.user.id) names[c.uid] = "";
252 else if (!!c.target && c.target != this.st.user.id)
253 names[c.target] = "";
254 });
255 const addChallenges = () => {
256 names[this.st.user.id] = this.st.user.name; //in case of
257 this.challenges = this.challenges.concat(
258 response.challenges.map(c => {
259 const from = { name: names[c.uid], id: c.uid }; //or just name
260 const type = this.classifyObject(c);
261 const vname = this.getVname(c.vid);
262 return Object.assign(
263 {},
264 {
265 type: type,
266 vname: vname,
267 from: from,
268 to: c.target ? names[c.target] : ""
269 },
270 c
271 );
272 })
273 );
274 };
275 if (Object.keys(names).length > 0) {
276 ajax(
277 "/users",
278 "GET",
279 { ids: Object.keys(names).join(",") },
280 response2 => {
281 response2.users.forEach(u => {
282 names[u.id] = u.name;
283 });
284 addChallenges();
285 }
286 );
287 } else addChallenges();
288 });
289 const connectAndPoll = () => {
290 this.send("connect");
291 this.send("pollclientsandgamers");
292 };
293 // Initialize connection
294 this.connexionString =
295 params.socketUrl +
296 "/?sid=" +
297 this.st.user.sid +
298 "&tmpId=" +
299 getRandString() +
300 "&page=" +
301 encodeURIComponent(this.$route.path);
302 this.conn = new WebSocket(this.connexionString);
303 this.conn.onopen = connectAndPoll;
304 this.conn.onmessage = this.socketMessageListener;
305 this.conn.onclose = this.socketCloseListener;
306 },
307 mounted: function() {
308 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
309 let elt = document.getElementById(eltName);
310 elt.addEventListener("click", processModalClick);
311 });
312 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
313 b.addEventListener("click", () => {
314 this.newchallenge.cadence = b.innerHTML;
315 });
316 });
317 const dispCorr = this.$route.query["disp"];
318 const showCtype =
319 dispCorr || localStorage.getItem("type-challenges") || "live";
320 const showGtype =
321 dispCorr || localStorage.getItem("type-games") || "live";
322 this.setDisplay("c", showCtype);
323 this.setDisplay("g", showGtype);
324 },
325 beforeDestroy: function() {
326 this.send("disconnect");
327 },
328 methods: {
329 // Helpers:
330 cadenceFocusIfOpened: function() {
331 if (event.target.checked)
332 document.getElementById("cadence").focus();
333 },
334 send: function(code, obj) {
335 if (this.conn) {
336 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
337 }
338 },
339 getVname: function(vid) {
340 const variant = this.st.variants.find(v => v.id == vid);
341 // this.st.variants might be uninitialized (variant == null)
342 return variant ? variant.name : "";
343 },
344 filterChallenges: function(type) {
345 return this.challenges.filter(c => c.type == type);
346 },
347 filterGames: function(type) {
348 return this.games.filter(g => g.type == type);
349 },
350 classifyObject: function(o) {
351 //challenge or game
352 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
353 },
354 setDisplay: function(letter, type, e) {
355 this[letter + "display"] = type;
356 localStorage.setItem(
357 "type-" + (letter == "c" ? "challenges" : "games"),
358 type
359 );
360 let elt = e
361 ? e.target
362 : document.getElementById("btn" + letter.toUpperCase() + type);
363 elt.classList.add("active");
364 elt.classList.remove("somethingnew"); //in case of
365 if (elt.previousElementSibling)
366 elt.previousElementSibling.classList.remove("active");
367 else elt.nextElementSibling.classList.remove("active");
368 },
369 isGamer: function(sid) {
370 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
371 },
372 getActionLabel: function(sid) {
373 return this.people[sid].pages.some(p => p == "/game/")
374 ? "Observe"
375 : "Challenge";
376 },
377 challOrWatch: function(sid) {
378 if (this.people[sid].pages.some(p => p == "/")) {
379 // Available, in Hall
380 this.newchallenge.to = this.people[sid].name;
381 document.getElementById("modalPeople").checked = false;
382 window.doClick("modalNewgame");
383 } else {
384 // In some game, maybe playing maybe not: show a random one
385 let gids = [];
386 this.people[sid].pages.forEach(p => {
387 const matchGid = p.match(/[a-zA-Z0-9]+$/);
388 if (matchGid) gids.push(matchGid[0]);
389 });
390 const gid = gids[Math.floor(Math.random() * gids.length)];
391 const game = this.games.find(g => g.id == gid);
392 if (game) this.showGame(game);
393 else this.$router.push("/game/" + gid); //game vs. me
394 }
395 },
396 showGame: function(g) {
397 // NOTE: we are an observer, since only games I don't play are shown here
398 // ==> Moves sent by connected remote player(s) if live game
399 let url = "/game/" + g.id;
400 if (g.type == "live")
401 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
402 this.$router.push(url);
403 },
404 resetSocialColor: function() {
405 // TODO: this is called twice, once on opening an once on closing
406 document.getElementById("peopleBtn").classList.remove("somethingnew");
407 },
408 processChat: function(chat) {
409 this.send("newchat", { data: chat });
410 },
411 // Messaging center:
412 socketMessageListener: function(msg) {
413 if (!this.conn) return;
414 const data = JSON.parse(msg.data);
415 switch (data.code) {
416 case "pollclientsandgamers": {
417 // Since people can be both in Hall and Game,
418 // need to track "askIdentity" requests:
419 let identityAsked = {};
420 data.sockIds.forEach(s => {
421 const page = s.page || "/";
422 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
423 this.send("askidentity", { target: s.sid, page: page });
424 identityAsked[s.sid] = true;
425 }
426 if (!this.people[s.sid])
427 // Do not set name or id: identity unknown yet
428 this.$set(this.people, s.sid, { pages: [page] });
429 else if (this.people[s.sid].pages.indexOf(page) < 0)
430 this.people[s.sid].pages.push(page);
431 if (!s.page)
432 // Peer is in Hall
433 this.send("askchallenge", { target: s.sid });
434 // Peer is in Game
435 else this.send("askgame", { target: s.sid, page: page });
436 });
437 break;
438 }
439 case "connect":
440 case "gconnect": {
441 const page = data.page || "/";
442 // NOTE: player could have been polled earlier, but might have logged in then
443 // So it's a good idea to ask identity if he was anonymous.
444 // But only ask game / challenge if currently disconnected.
445 if (!this.people[data.from]) {
446 this.$set(this.people, data.from, { pages: [page] });
447 if (data.code == "connect")
448 this.send("askchallenge", { target: data.from });
449 else this.send("askgame", { target: data.from, page: page });
450 } else {
451 // Append page if not already in list
452 if (this.people[data.from].pages.indexOf(page) < 0)
453 this.people[data.from].pages.push(page);
454 }
455 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
456 // Identity not known yet
457 this.newConnect[data.from] = true; //for self multi-connects tests
458 this.send("askidentity", { target: data.from, page: page });
459 }
460 break;
461 }
462 case "disconnect":
463 case "gdisconnect": {
464 // If the user reloads the page twice very quickly (experienced with Firefox),
465 // the first reload won't have time to connect but will trigger a "close" event anyway.
466 // ==> Next check is required.
467 if (!this.people[data.from]) return;
468 // Disconnect means no more tmpIds:
469 if (data.code == "disconnect") {
470 // Remove the live challenge sent by this player:
471 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
472 } else {
473 // Remove the matching live game if now unreachable
474 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
475 const gidx = this.games.findIndex(g => g.id == gid);
476 if (gidx >= 0) {
477 const game = this.games[gidx];
478 if (
479 game.type == "live" &&
480 game.rids.length == 1 &&
481 game.rids[0] == data.from
482 ) {
483 this.games.splice(gidx, 1);
484 }
485 }
486 }
487 const page = data.page || "/";
488 ArrayFun.remove(this.people[data.from].pages, p => p == page);
489 if (this.people[data.from].pages.length == 0)
490 this.$delete(this.people, data.from);
491 break;
492 }
493 case "killed":
494 // I logged in elsewhere:
495 this.conn = null;
496 alert(this.st.tr["New connexion detected: tab now offline"]);
497 break;
498 case "askidentity": {
499 // Request for identification (TODO: anonymous shouldn't need to reply)
500 const me = {
501 // Decompose to avoid revealing email
502 name: this.st.user.name,
503 sid: this.st.user.sid,
504 id: this.st.user.id
505 };
506 this.send("identity", { data: me, target: data.from });
507 break;
508 }
509 case "identity": {
510 const user = data.data;
511 this.$set(this.people, user.sid, {
512 id: user.id,
513 name: user.name,
514 pages: this.people[user.sid].pages
515 });
516 if (user.name) {
517 // If I multi-connect, kill current connexion if no mark (I'm older)
518 if (
519 this.newConnect[user.sid] &&
520 user.id > 0 &&
521 user.id == this.st.user.id &&
522 user.sid != this.st.user.sid
523 ) {
524 if (!this.killed[this.st.user.sid]) {
525 this.send("killme", { sid: this.st.user.sid });
526 this.killed[this.st.user.sid] = true;
527 }
528 }
529 }
530 delete this.newConnect[user.sid];
531 break;
532 }
533 case "askchallenge": {
534 // Send my current live challenge (if any)
535 const cIdx = this.challenges.findIndex(
536 c => c.from.sid == this.st.user.sid && c.type == "live"
537 );
538 if (cIdx >= 0) {
539 const c = this.challenges[cIdx];
540 // NOTE: in principle, should only send targeted challenge to the target.
541 // But we may not know yet the identity of the target (just name),
542 // so cannot decide if data.from is the target or not.
543 const myChallenge = {
544 id: c.id,
545 from: this.st.user.sid,
546 to: c.to,
547 randomness: c.randomness,
548 fen: c.fen,
549 vid: c.vid,
550 cadence: c.cadence,
551 added: c.added
552 };
553 this.send("challenge", { data: myChallenge, target: data.from });
554 }
555 break;
556 }
557 case "challenge": //after "askchallenge"
558 case "newchallenge": {
559 // NOTE about next condition: see "askchallenge" case.
560 const chall = data.data;
561 if (
562 !chall.to ||
563 (this.people[chall.from].id > 0 &&
564 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
565 ) {
566 let newChall = Object.assign({}, chall);
567 newChall.type = this.classifyObject(chall);
568 newChall.randomness = chall.randomness;
569 newChall.added = Date.now();
570 let fromValues = Object.assign({}, this.people[chall.from]);
571 delete fromValues["pages"]; //irrelevant in this context
572 newChall.from = Object.assign({ sid: chall.from }, fromValues);
573 newChall.vname = this.getVname(newChall.vid);
574 this.challenges.push(newChall);
575 if (
576 (newChall.type == "live" && this.cdisplay == "corr") ||
577 (newChall.type == "corr" && this.cdisplay == "live")
578 ) {
579 document
580 .getElementById("btnC" + newChall.type)
581 .classList.add("somethingnew");
582 }
583 }
584 break;
585 }
586 case "refusechallenge": {
587 const cid = data.data;
588 ArrayFun.remove(this.challenges, c => c.id == cid);
589 alert(this.st.tr["Challenge declined"]);
590 break;
591 }
592 case "deletechallenge": {
593 // NOTE: the challenge may be already removed
594 const cid = data.data;
595 ArrayFun.remove(this.challenges, c => c.id == cid);
596 break;
597 }
598 case "game": //individual request
599 case "newgame": {
600 // NOTE: it may be live or correspondance
601 const game = data.data;
602 // Ignore games where I play (corr games)
603 if (game.players.every(p =>
604 p.sid != this.st.user.sid || p.id != this.st.user.id))
605 {
606 let locGame = this.games.find(g => g.id == game.id);
607 if (!locGame) {
608 let newGame = game;
609 newGame.type = this.classifyObject(game);
610 newGame.vname = this.getVname(game.vid);
611 if (!game.score)
612 //if new game from Hall
613 newGame.score = "*";
614 newGame.rids = [game.rid];
615 delete newGame["rid"];
616 this.games.push(newGame);
617 if (
618 (newGame.type == "live" && this.gdisplay == "corr") ||
619 (newGame.type == "corr" && this.gdisplay == "live")
620 ) {
621 document
622 .getElementById("btnG" + newGame.type)
623 .classList.add("somethingnew");
624 }
625 } else {
626 // Append rid (if not already in list)
627 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
628 }
629 }
630 break;
631 }
632 case "result": {
633 let g = this.games.find(g => g.id == data.gid);
634 if (g) g.score = data.score;
635 break;
636 }
637 case "startgame": {
638 // New game just started: data contain all information
639 const gameInfo = data.data;
640 if (this.classifyObject(gameInfo) == "live")
641 this.startNewGame(gameInfo);
642 else {
643 this.infoMessage =
644 this.st.tr["New correspondance game:"] +
645 " <a href='#/game/" +
646 gameInfo.id +
647 "'>" +
648 "#/game/" +
649 gameInfo.id +
650 "</a>";
651 let modalBox = document.getElementById("modalInfo");
652 modalBox.checked = true;
653 }
654 break;
655 }
656 case "newchat":
657 this.newChat = data.data;
658 if (!document.getElementById("modalPeople").checked)
659 document.getElementById("peopleBtn").classList.add("somethingnew");
660 break;
661 }
662 },
663 socketCloseListener: function() {
664 if (!this.conn) return;
665 this.conn = new WebSocket(this.connexionString);
666 this.conn.addEventListener("message", this.socketMessageListener);
667 this.conn.addEventListener("close", this.socketCloseListener);
668 },
669 // Challenge lifecycle:
670 loadNewchallVariant: async function(cb) {
671 const vname = this.getVname(this.newchallenge.vid);
672 const vModule = await import("@/variants/" + vname + ".js");
673 this.newchallenge.V = vModule.VariantRules;
674 this.newchallenge.vname = vname;
675 if (cb)
676 cb();
677 },
678 trySetNewchallDiag: function() {
679 if (!this.newchallenge.fen) {
680 this.newchallenge.diag = "";
681 return;
682 }
683 // If vid > 0 then the variant is loaded (function above):
684 window.V = this.newchallenge.V;
685 if (
686 this.newchallenge.vid > 0 &&
687 this.newchallenge.fen &&
688 V.IsGoodFen(this.newchallenge.fen)
689 ) {
690 const parsedFen = V.ParseFen(this.newchallenge.fen);
691 this.newchallenge.diag = getDiagram({
692 position: parsedFen.position,
693 orientation: V.GetOppCol(parsedFen.turn)
694 });
695 }
696 },
697 newChallenge: async function() {
698 if (this.newchallenge.cadence.match(/^[0-9]+$/))
699 this.newchallenge.cadence += "+0"; //assume minutes, no increment
700 const ctype = this.classifyObject(this.newchallenge);
701 // TODO: cadence still unchecked so ctype could be wrong...
702 let error = "";
703 if (!this.newchallenge.vid)
704 error = this.st.tr["Please select a variant"];
705 else if (ctype == "corr" && this.st.user.id <= 0)
706 error = this.st.tr["Please log in to play correspondance games"];
707 else if (this.newchallenge.to) {
708 if (this.newchallenge.to == this.st.user.name)
709 error = this.st.tr["Self-challenge is forbidden"];
710 else if (
711 ctype == "live" &&
712 Object.values(this.people).every(p => p.name != this.newchallenge.to)
713 )
714 error = this.newchallenge.to + " " + this.st.tr["is not online"];
715 }
716 if (error) {
717 alert(error);
718 return;
719 }
720 window.V = this.newchallenge.V;
721 error = checkChallenge(this.newchallenge);
722 if (error) {
723 alert(error);
724 return;
725 }
726 // NOTE: "from" information is not required here
727 let chall = Object.assign({}, this.newchallenge);
728 delete chall["V"];
729 delete chall["diag"];
730 const finishAddChallenge = cid => {
731 chall.id = cid || "c" + getRandString();
732 // Remove old challenge if any (only one at a time of a given type):
733 const cIdx = this.challenges.findIndex(
734 c =>
735 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
736 c.type == ctype
737 );
738 if (cIdx >= 0) {
739 // Delete current challenge (will be replaced now)
740 this.send("deletechallenge", { data: this.challenges[cIdx].id });
741 if (ctype == "corr") {
742 ajax("/challenges", "DELETE", { id: this.challenges[cIdx].id });
743 }
744 this.challenges.splice(cIdx, 1);
745 }
746 this.send("newchallenge", {
747 data: Object.assign({ from: this.st.user.sid }, chall)
748 });
749 // Add new challenge:
750 chall.from = {
751 // Decompose to avoid revealing email
752 sid: this.st.user.sid,
753 id: this.st.user.id,
754 name: this.st.user.name
755 };
756 chall.added = Date.now();
757 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
758 chall.type = ctype;
759 chall.vname = this.newchallenge.vname;
760 this.challenges.push(chall);
761 // Remember cadence + vid for quicker further challenges:
762 localStorage.setItem("cadence", chall.cadence);
763 localStorage.setItem("vid", chall.vid);
764 localStorage.setItem("randomness", chall.randomness);
765 document.getElementById("modalNewgame").checked = false;
766 // Show the challenge if not on current display
767 if (
768 (ctype == "live" && this.cdisplay == "corr") ||
769 (ctype == "corr" && this.cdisplay == "live")
770 ) {
771 this.setDisplay('c', ctype);
772 }
773 };
774 if (ctype == "live") {
775 // Live challenges have a random ID
776 finishAddChallenge(null);
777 } else {
778 // Correspondance game: send challenge to server
779 ajax("/challenges", "POST", { chall: chall }, response => {
780 finishAddChallenge(response.cid);
781 });
782 }
783 },
784 // Callback function after a diagram was showed to accept
785 // or refuse targetted challenge:
786 decisionChallenge: function(accepted) {
787 this.curChallToAccept.accepted = accepted;
788 this.finishProcessingChallenge(this.curChallToAccept);
789 document.getElementById("modalAccept").checked = false;
790 },
791 finishProcessingChallenge: function(c) {
792 if (c.accepted) {
793 c.seat = {
794 // Again, avoid c.seat = st.user to not reveal email
795 sid: this.st.user.sid,
796 id: this.st.user.id,
797 name: this.st.user.name
798 };
799 this.launchGame(c);
800 } else {
801 this.send("refusechallenge", { data: c.id, target: c.from.sid });
802 }
803 this.send("deletechallenge", { data: c.id });
804 },
805 clickChallenge: async function(c) {
806 const myChallenge =
807 c.from.sid == this.st.user.sid || //live
808 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
809 if (!myChallenge) {
810 if (c.type == "corr" && this.st.user.id <= 0) {
811 alert(this.st.tr["Please log in to accept corr challenges"]);
812 return;
813 }
814 c.accepted = true;
815 const vModule = await import("@/variants/" + c.vname + ".js");
816 window.V = vModule.VariantRules;
817 if (c.to) {
818 // c.to == this.st.user.name (connected)
819 if (c.fen) {
820 const parsedFen = V.ParseFen(c.fen);
821 c.mycolor = V.GetOppCol(parsedFen.turn);
822 this.tchallDiag = getDiagram({
823 position: parsedFen.position,
824 orientation: c.mycolor
825 });
826 this.curChallToAccept = c;
827 document.getElementById("modalAccept").checked = true;
828 }
829 else {
830 if (!confirm(this.st.tr["Accept challenge?"]))
831 c.accepted = false;
832 this.finishProcessingChallenge(c);
833 }
834 }
835 else
836 this.finishProcessingChallenge(c);
837 }
838 else {
839 // My challenge
840 if (c.type == "corr") {
841 ajax("/challenges", "DELETE", { id: c.id });
842 }
843 this.send("deletechallenge", { data: c.id });
844 }
845 // In all cases, the challenge is consumed:
846 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
847 },
848 // NOTE: when launching game, the challenge is already being deleted
849 launchGame: function(c) {
850 // These game informations will be shared
851 let gameInfo = {
852 id: getRandString(),
853 fen: c.fen || V.GenRandInitFen(c.randomness),
854 // White player index 0, black player index 1:
855 players: c.mycolor
856 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
857 : shuffle([c.from, c.seat]),
858 vid: c.vid,
859 cadence: c.cadence
860 };
861 let oppsid = c.from.sid; //may not be defined if corr + offline opp
862 if (!oppsid) {
863 oppsid = Object.keys(this.people).find(
864 sid => this.people[sid].id == c.from.id
865 );
866 }
867 const notifyNewgame = () => {
868 if (oppsid)
869 //opponent is online
870 this.send("startgame", { data: gameInfo, target: oppsid });
871 // Send game info (only if live) to everyone except me in this tab
872 this.send("newgame", { data: gameInfo });
873 };
874 if (c.type == "live") {
875 notifyNewgame();
876 this.startNewGame(gameInfo);
877 } //corr: game only on server
878 else {
879 ajax(
880 "/games",
881 "POST",
882 { gameInfo: gameInfo, cid: c.id }, //cid useful to delete challenge
883 response => {
884 gameInfo.id = response.gameId;
885 notifyNewgame();
886 this.$router.push("/game/" + response.gameId);
887 }
888 );
889 }
890 },
891 // NOTE: for live games only (corr games start on the server)
892 startNewGame: function(gameInfo) {
893 const game = Object.assign({}, gameInfo, {
894 // (other) Game infos: constant
895 fenStart: gameInfo.fen,
896 vname: this.getVname(gameInfo.vid),
897 created: Date.now(),
898 // Game state (including FEN): will be updated
899 moves: [],
900 clocks: [-1, -1], //-1 = unstarted
901 initime: [0, 0], //initialized later
902 score: "*"
903 });
904 GameStorage.add(game, (err) => {
905 // If an error occurred, game is not added: abort
906 if (!err) {
907 if (this.st.settings.sound)
908 new Audio("/sounds/newgame.flac").play().catch(() => {});
909 this.$router.push("/game/" + gameInfo.id);
910 }
911 });
912 }
913 }
914 };
915 </script>
916
917 <style lang="sass" scoped>
918 .active
919 color: #42a983
920
921 #infoDiv > .card
922 padding: 15px 0
923 max-width: 430px
924
925 #newgameDiv > .card, #acceptDiv > .card
926 max-width: 767px
927 max-height: 100%
928
929 div#peopleWrap > .card
930 max-height: 100%
931
932 @media screen and (min-width: 1281px)
933 div#peopleWrap > .card
934 max-width: 66.67%
935
936 @media screen and (max-width: 1280px)
937 div#peopleWrap > .card
938 max-width: 83.33%
939
940 @media screen and (max-width: 767px)
941 div#peopleWrap > .card
942 max-width: 100%
943
944 #players
945 width: 50%
946 position: relative
947 float: left
948
949 #chat
950 width: 50%
951 float: left
952 position: relative
953
954 @media screen and (max-width: 767px)
955 #players, #chats
956 width: 100%
957
958 #chat > .card
959 max-width: 100%
960 margin: 0;
961 border: none;
962
963 #players > p
964 margin-left: 5px
965
966 .anonymous
967 font-style: italic
968
969 button.player-action
970 margin-left: 32px
971
972 .somethingnew
973 background-color: #c5fefe !important
974
975 .tabbtn
976 background-color: #f9faee
977
978 button.acceptBtn
979 background-color: lightgreen
980 button.refuseBtn
981 background-color: red
982
983 #buttonsTchall
984 margin-top: 10px
985
986 .variantName
987 font-weight: bold
988
989 .diagram
990 margin: 0 auto
991 max-width: 400px
992
993 #inputFen
994 width: 100%
995
996 #div2, #div3
997 margin-top: 15px
998 @media screen and (max-width: 767px)
999 #div2, #div3
1000 margin-top: 0
1001 </style>