Attempt to fix countdown for live games. Some issues with GameStorage.add now
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
5 .card.smallpad
6 label#closeNewgame.modal-close(for="modalNewgame")
7 fieldset
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9 select#selectVariant(v-model="newchallenge.vid")
10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
11 fieldset
12 label(for="timeControl") {{ st.tr["Time control"] }}
13 input#timeControl(type="text" v-model="newchallenge.timeControl"
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
17 input#selectPlayers(type="text" v-model="newchallenge.to")
18 fieldset(v-if="st.user.id > 0")
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
22 .row
23 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
24 button(onClick="doClick('modalNewgame')") New game
25 .row
26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
27 .collapse
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
30 div
31 .button-group
32 button(@click="cdisplay='live'") Live Challenges
33 button(@click="cdisplay='corr'") Correspondance challenges
34 ChallengeList(v-show="cdisplay=='live'"
35 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
36 ChallengeList(v-show="cdisplay=='corr'"
37 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
39 label(for="peopleSection" aria-hidden="true") People
40 div
41 .button-group
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
44 #players(v-show="pdisplay=='players'")
45 h3 Online players
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
48 )
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
51 h3 Chat (TODO)
52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
53 label(for="gameSection" aria-hidden="true") Games
54 div
55 .button-group
56 button(@click="gdisplay='live'") Live games
57 button(@click="gdisplay='corr'") Correspondance games
58 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
59 @show-game="showGame")
60 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
61 @show-game="showGame")
62 </template>
63
64 <script>
65 import { store } from "@/store";
66 import { checkChallenge } from "@/data/challengeCheck";
67 import { ArrayFun } from "@/utils/array";
68 import { ajax } from "@/utils/ajax";
69 import { getRandString, shuffle } from "@/utils/alea";
70 import GameList from "@/components/GameList.vue";
71 import ChallengeList from "@/components/ChallengeList.vue";
72 import { GameStorage } from "@/utils/gameStorage";
73 export default {
74 name: "my-hall",
75 components: {
76 GameList,
77 ChallengeList,
78 },
79 data: function () {
80 return {
81 st: store.state,
82 cdisplay: "live", //or corr
83 pdisplay: "players", //or chat
84 gdisplay: "live",
85 games: [],
86 challenges: [],
87 people: [], //(all) online players
88 newchallenge: {
89 fen: "",
90 vid: 0,
91 to: "", //name of challenged player (if any)
92 timeControl: "", //"2m+2s" ...etc
93 },
94 };
95 },
96 watch: {
97 // st.variants changes only once, at loading from [] to [...]
98 "st.variants": function(variantArray) {
99 // Set potential challenges and games variant names:
100 this.challenges.forEach(c => {
101 if (c.vname == "")
102 c.vname = this.getVname(c.vid);
103 });
104 this.games.forEach(g => {
105 if (g.vname == "")
106 g.vname = this.getVname(g.vid)
107 });
108 },
109 },
110 computed: {
111 uniquePlayers: function() {
112 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
113 let anonymous = {id:0, name:"@nonymous", count:0};
114 let playerList = [];
115 this.people.forEach(p => {
116 if (p.id > 0)
117 playerList.push(p);
118 else
119 anonymous.count++;
120 });
121 if (anonymous.count > 0)
122 playerList.push(anonymous);
123 return playerList;
124 },
125 },
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.people.push({sid:my.sid, id:my.id, name:my.name});
130 // Retrieve live challenge (not older than 30 minute) if any:
131 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
132 if (!!chall)
133 {
134 if ((Date.now() - chall.added)/1000 <= 30*60)
135 this.challenges.push(chall);
136 else
137 localStorage.removeItem("challenge");
138 }
139 if (this.st.user.id > 0)
140 {
141 // Ask server for current corr games (all but mines)
142 ajax(
143 "/games",
144 "GET",
145 {uid: this.st.user.id, excluded: true},
146 response => {
147 this.games = this.games.concat(response.games.map(g => {
148 const type = this.classifyObject(g);
149 const vname = this.getVname(g.vid);
150 return Object.assign({}, g, {type: type, vname: vname});
151 }));
152 }
153 );
154 // Also ask for corr challenges (open + sent to me)
155 ajax(
156 "/challenges",
157 "GET",
158 {uid: this.st.user.id},
159 response => {
160 // Gather all senders names, and then retrieve full identity:
161 // (TODO [perf]: some might be online...)
162 const uids = response.challenges.map(c => { return c.uid });
163 ajax("/users",
164 "GET",
165 { ids: uids.join(",") },
166 response2 => {
167 let names = {};
168 response2.users.forEach(u => {names[u.id] = u.name});
169 this.challenges = this.challenges.concat(
170 response.challenges.map(c => {
171 // (just players names in fact)
172 const from = {name: names[c.uid], id: c.uid};
173 const type = this.classifyObject(c);
174 const vname = this.getVname(c.vid);
175 return Object.assign({}, c, {type: type, vname: vname, from: from});
176 })
177 )
178 }
179 );
180 }
181 );
182 }
183 // 0.1] Ask server for room composition:
184 const funcPollClients = () => {
185 this.st.conn.send(JSON.stringify({code:"pollclients"}));
186 };
187 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
188 funcPollClients();
189 else //socket not ready yet (initial loading)
190 this.st.conn.onopen = funcPollClients;
191 this.st.conn.onmessage = this.socketMessageListener;
192 const socketCloseListener = () => {
193 store.socketCloseListener(); //reinitialize connexion (in store.js)
194 this.st.conn.addEventListener('message', this.socketMessageListener);
195 this.st.conn.addEventListener('close', socketCloseListener);
196 };
197 this.st.conn.onclose = socketCloseListener;
198 },
199 methods: {
200 // Helpers:
201 filterChallenges: function(type) {
202 return this.challenges.filter(c => c.type == type);
203 },
204 filterGames: function(type) {
205 return this.games.filter(g => g.type == type);
206 },
207 classifyObject: function(o) { //challenge or game
208 // Heuristic: should work for most cases... (TODO)
209 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
210 },
211 showGame: function(g) {
212 // NOTE: we are an observer, since only games I don't play are shown here
213 // ==> Moves sent by connected remote player(s) if live game
214 let url = "/game/" + g.id;
215 if (g.type == "live")
216 {
217 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
218 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
219 url += "?rid=" + remotes[rIdx].sid;
220 }
221 this.$router.push(url);
222 },
223 // TODO: ...filter(...)[0].name, one-line, just remove this function
224 getVname: function(vid) {
225 const vIdx = this.st.variants.findIndex(v => v.id == vid);
226 return vIdx >= 0 ? this.st.variants[vIdx].name : "";
227 },
228 getSid: function(pname) {
229 const pIdx = this.people.findIndex(pl => pl.name == pname);
230 return (pIdx === -1 ? null : this.people[pIdx].sid);
231 },
232 getPname: function(sid) {
233 const pIdx = this.people.findIndex(pl => pl.sid == sid);
234 return (pIdx === -1 ? null : this.people[pIdx].name);
235 },
236 sendSomethingTo: function(to, code, obj, warnDisconnected) {
237 const doSend = (code, obj, sid) => {
238 this.st.conn.send(JSON.stringify(Object.assign(
239 {},
240 {code: code},
241 obj,
242 {target: sid}
243 )));
244 };
245 if (!!to)
246 {
247 // Challenge with targeted players
248 const targetSid = this.getSid(to);
249 if (!targetSid)
250 {
251 if (!!warnDisconnected)
252 alert("Warning: " + pname + " is not connected");
253 }
254 else
255 doSend(code, obj, targetSid);
256 }
257 else
258 {
259 // Open challenge: send to all connected players (except us)
260 this.people.forEach(p => {
261 if (p.sid != this.st.user.sid) //only sid is always set
262 doSend(code, obj, p.sid);
263 });
264 }
265 },
266 // Messaging center:
267 socketMessageListener: function(msg) {
268 const data = JSON.parse(msg.data);
269 switch (data.code)
270 {
271 // 0.2] Receive clients list (just socket IDs)
272 case "pollclients":
273 {
274 data.sockIds.forEach(sid => {
275 this.people.push({sid:sid, id:0, name:""});
276 // Ask identity, challenges and game(s)
277 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
278 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
279 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
280 });
281 break;
282 }
283 case "askidentity":
284 {
285 // Request for identification: reply if I'm not anonymous
286 if (this.st.user.id > 0)
287 {
288 this.st.conn.send(JSON.stringify(
289 // people[0] instead of st.user to avoid sending email
290 {code:"identity", user:this.people[0], target:data.from}));
291 }
292 break;
293 }
294 case "askchallenge":
295 {
296 // Send my current live challenge (if any)
297 const cIdx = this.challenges
298 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
299 if (cIdx >= 0)
300 {
301 const c = this.challenges[cIdx];
302 const myChallenge =
303 {
304 // Minimal challenge informations: (from not required)
305 id: c.id,
306 to: c.to,
307 fen: c.fen,
308 vid: c.vid,
309 timeControl: c.timeControl
310 };
311 this.st.conn.send(JSON.stringify({code:"challenge",
312 chall:myChallenge, target:data.from}));
313 }
314 break;
315 }
316 case "askgame":
317 {
318 // Send my current live game (if any)
319 GameStorage.getCurrent((game) => {
320 if (!!game)
321 {
322 const myGame =
323 {
324 // Minimal game informations:
325 id: game.id,
326 players: game.players.map(p => p.name),
327 vid: game.vid,
328 timeControl: game.timeControl,
329 };
330 this.st.conn.send(JSON.stringify({code:"game",
331 game:myGame, target:data.from}));
332 }
333 });
334 break;
335 }
336 case "identity":
337 {
338 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
339 this.people[pIdx].id = data.user.id;
340 this.people[pIdx].name = data.user.name;
341 break;
342 }
343 case "challenge":
344 {
345 // Receive challenge from some player (+sid)
346 let newChall = data.chall;
347 newChall.type = this.classifyObject(data.chall);
348 const pIdx = this.people.findIndex(p => p.sid == data.from);
349 newChall.from = this.people[pIdx]; //may be anonymous
350 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
351 newChall.vname = this.getVname(newChall.vid);
352 this.challenges.push(newChall);
353 break;
354 }
355 case "game":
356 {
357 // Receive game from some player (+sid)
358 // NOTE: it may be correspondance (if newgame while we are connected)
359 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
360 {
361 let newGame = data.game;
362 newGame.type = this.classifyObject(data.game);
363 newGame.vname = this.getVname(data.game.vid);
364 newGame.rid = data.from;
365 newGame.score = "*";
366 this.games.push(newGame);
367 }
368 break;
369 }
370 case "newgame":
371 {
372 // TODO: next line required ?!
373 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
374 // New game just started: data contain all information
375 if (this.classifyObject(data.gameInfo) == "live")
376 this.startNewGame(data.gameInfo);
377 else
378 {
379 // TODO: notify with game link but do not redirect
380 }
381 break;
382 }
383 case "refusechallenge":
384 {
385 alert(this.getPname(data.from) + " declined your challenge");
386 ArrayFun.remove(this.challenges, c => c.id == data.cid);
387 break;
388 }
389 case "deletechallenge":
390 {
391 // NOTE: the challenge may be already removed
392 ArrayFun.remove(this.challenges, c => c.id == data.cid);
393 localStorage.removeItem("challenge"); //in case of
394 break;
395 }
396 case "connect":
397 {
398 this.people.push({name:"", id:0, sid:data.sid});
399 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
400 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
401 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
402 break;
403 }
404 case "disconnect":
405 {
406 ArrayFun.remove(this.people, p => p.sid == data.sid);
407 // Also remove all challenges sent by this player:
408 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
409 // And all live games where he plays and no other opponent is online
410 ArrayFun.remove(this.games, g =>
411 g.type == "live" && (g.players.every(p => p.sid == data.sid
412 || !this.people.some(pl => pl.sid == p.sid))), "all");
413 break;
414 }
415 }
416 },
417 // Challenge lifecycle:
418 tryChallenge: function(player) {
419 if (player.id == 0)
420 return; //anonymous players cannot be challenged
421 this.newchallenge.to = player.name;
422 doClick("modalNewgame");
423 },
424 newChallenge: async function() {
425 const vname = this.getVname(this.newchallenge.vid);
426 const vModule = await import("@/variants/" + vname + ".js");
427 window.V = vModule.VariantRules;
428 const error = checkChallenge(this.newchallenge);
429 if (!!error)
430 return alert(error);
431 const ctype = this.classifyObject(this.newchallenge);
432 if (ctype == "corr" && this.st.user.id <= 0)
433 return alert("Please log in to play correspondance games");
434 // NOTE: "from" information is not required here
435 let chall = Object.assign({}, this.newchallenge);
436 const finishAddChallenge = (cid,warnDisconnected) => {
437 chall.id = cid || "c" + getRandString();
438 // Send challenge to peers (if connected)
439 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
440 chall.added = Date.now();
441 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
442 chall.type = ctype;
443 chall.vname = vname;
444 chall.from = this.people[0]; //avoid sending email
445 this.challenges.push(chall);
446 localStorage.setItem("challenge", JSON.stringify(chall));
447 document.getElementById("modalNewgame").checked = false;
448 };
449 const cIdx = this.challenges.findIndex(
450 c => c.from.sid == this.st.user.sid && c.type == ctype);
451 if (cIdx >= 0)
452 {
453 // Delete current challenge (will be replaced now)
454 this.sendSomethingTo(this.challenges[cIdx].to,
455 "deletechallenge", {cid:this.challenges[cIdx].id});
456 if (ctype == "corr")
457 {
458 ajax(
459 "/challenges",
460 "DELETE",
461 {id: this.challenges[cIdx].id}
462 );
463 }
464 this.challenges.splice(cIdx, 1);
465 }
466 if (ctype == "live")
467 {
468 // Live challenges have a random ID
469 finishAddChallenge(null, "warnDisconnected");
470 }
471 else
472 {
473 // Correspondance game: send challenge to server
474 ajax(
475 "/challenges",
476 "POST",
477 { chall: chall },
478 response => { finishAddChallenge(response.cid); }
479 );
480 }
481 },
482 clickChallenge: function(c) {
483 // In all cases, the challenge is consumed:
484 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
485 // NOTE: deletechallenge event might be redundant (but it's easier this way)
486 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
487 const myChallenge = (c.from.sid == this.st.user.sid //live
488 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
489 if (!myChallenge)
490 {
491 c.accepted = true;
492 if (!!c.to) //c.to == this.st.user.name (connected)
493 {
494 // TODO: if special FEN, show diagram after loading variant
495 c.accepted = confirm("Accept challenge?");
496 }
497 if (c.accepted)
498 {
499 c.seat = this.people[0]; //== this.st.user, avoid revealing email
500 this.launchGame(c);
501 }
502 else
503 {
504 this.st.conn.send(JSON.stringify({
505 code: "refusechallenge",
506 cid: c.id, target: c.from.sid}));
507 }
508 }
509 else //my challenge
510 {
511 localStorage.removeItem("challenge");
512 if (c.type == "corr")
513 {
514 ajax(
515 "/challenges",
516 "DELETE",
517 {id: c.id}
518 );
519 }
520 }
521 },
522 // NOTE: when launching game, the challenge is already deleted
523 launchGame: async function(c) {
524 const vModule = await import("@/variants/" + c.vname + ".js");
525 window.V = vModule.VariantRules;
526 // These game informations will be sent to other players
527 const gameInfo =
528 {
529 gameId: getRandString(),
530 fen: c.fen || V.GenRandInitFen(),
531 players: shuffle([c.from, c.seat]), //white then black
532 vid: c.vid,
533 timeControl: c.timeControl,
534 };
535 let target = c.from.sid; //may not be defined if corr + offline opp
536 if (!target)
537 {
538 const opponent = this.people.find(p => p.id == c.from.id);
539 if (!!opponent)
540 target = opponent.sid
541 }
542 if (!!target) //opponent is online
543 {
544 this.st.conn.send(JSON.stringify({code:"newgame",
545 gameInfo:gameInfo, target:target, cid:c.id}));
546 }
547 if (c.type == "live")
548 this.startNewGame(gameInfo);
549 else //corr: game only on server
550 {
551 ajax(
552 "/games",
553 "POST",
554 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
555 response => { this.$router.push("/game/" + response.gameId); }
556 );
557 }
558 },
559 // NOTE: for live games only (corr games start on the server)
560 startNewGame: function(gameInfo) {
561 const game = Object.assign({}, gameInfo, {
562 // (other) Game infos: constant
563 fenStart: gameInfo.fen,
564 created: Date.now(),
565 // Game state (including FEN): will be updated
566 moves: [],
567 clocks: [-1, -1], //-1 = unstarted
568 initime: [0, 0], //initialized later
569 score: "*",
570 });
571 GameStorage.add(game);
572 if (this.st.settings.sound >= 1)
573 new Audio("/sounds/newgame.mp3").play().catch(err => {});
574 this.$router.push("/game/" + gameInfo.gameId);
575 },
576 },
577 };
578 </script>
579
580 <style lang="sass">
581 // TODO
582 </style>