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