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