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