Fix clocks while playing live game
[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 computed: {
97 uniquePlayers: function() {
98 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
99 let anonymous = {id:0, name:"@nonymous", count:0};
100 let playerList = [];
101 this.people.forEach(p => {
102 if (p.id > 0)
103 playerList.push(p);
104 else
105 anonymous.count++;
106 });
107 if (anonymous.count > 0)
108 playerList.push(anonymous);
109 return playerList;
110 },
111 },
112 created: function() {
113 // Always add myself to players' list
114 const my = this.st.user;
115 this.people.push({sid:my.sid, id:my.id, name:my.name});
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
118 if (!!chall)
119 {
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
122 else
123 localStorage.removeItem("challenge");
124 }
125 if (this.st.user.id > 0)
126 {
127 // Ask server for current corr games (all but mines)
128 ajax(
129 "/games",
130 "GET",
131 {uid: this.st.user.id, excluded: true},
132 response => {
133 this.games = this.games.concat(response.games.map(g => {
134 const type = this.classifyObject(g);
135 const vname = this.getVname(g.vid);
136 return Object.assign({}, g, {type: type, vname: vname});
137 }));
138 }
139 );
140 // Also ask for corr challenges (open + sent to me)
141 ajax(
142 "/challenges",
143 "GET",
144 {uid: this.st.user.id},
145 response => {
146 console.log(response.challenges);
147 // TODO: post-treatment on challenges ?
148 Array.prototype.push.apply(this.challenges, response.challenges);
149 }
150 );
151 }
152 // 0.1] Ask server for room composition:
153 const funcPollClients = () => {
154 this.st.conn.send(JSON.stringify({code:"pollclients"}));
155 };
156 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
157 funcPollClients();
158 else //socket not ready yet (initial loading)
159 this.st.conn.onopen = funcPollClients;
160 this.st.conn.onmessage = this.socketMessageListener;
161 const socketCloseListener = () => {
162 store.socketCloseListener(); //reinitialize connexion (in store.js)
163 this.st.conn.addEventListener('message', this.socketMessageListener);
164 this.st.conn.addEventListener('close', socketCloseListener);
165 };
166 this.st.conn.onclose = socketCloseListener;
167 },
168 methods: {
169 // Helpers:
170 filterChallenges: function(type) {
171 return this.challenges.filter(c => c.type == type);
172 },
173 filterGames: function(type) {
174 return this.games.filter(g => g.type == type);
175 },
176 classifyObject: function(o) { //challenge or game
177 // Heuristic: should work for most cases... (TODO)
178 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
179 },
180 showGame: function(g) {
181 // NOTE: we are an observer, since only games I don't play are shown here
182 // ==> Moves sent by connected remote player(s) if live game
183 let url = "/game/" + g.id;
184 if (g.type == "live")
185 {
186 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
187 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
188 url += "?rid=" + remotes[rIdx].sid;
189 }
190 this.$router.push(url);
191 },
192 // TODO: ...filter(...)[0].name, one-line, just remove this function
193 getVname: function(vid) {
194 const vIdx = this.st.variants.findIndex(v => v.id == vid);
195 return this.st.variants[vIdx].name;
196 },
197 getSid: function(pname) {
198 const pIdx = this.people.findIndex(pl => pl.name == pname);
199 return (pIdx === -1 ? null : this.people[pIdx].sid);
200 },
201 getPname: function(sid) {
202 const pIdx = this.people.findIndex(pl => pl.sid == sid);
203 return (pIdx === -1 ? null : this.people[pIdx].name);
204 },
205 sendSomethingTo: function(to, code, obj, warnDisconnected) {
206 const doSend = (code, obj, sid) => {
207 this.st.conn.send(JSON.stringify(Object.assign(
208 {},
209 {code: code},
210 obj,
211 {target: sid}
212 )));
213 };
214 if (!!to)
215 {
216 // Challenge with targeted players
217 const targetSid = this.getSid(to);
218 if (!targetSid)
219 {
220 if (!!warnDisconnected)
221 alert("Warning: " + pname + " is not connected");
222 }
223 else
224 doSend(code, obj, targetSid);
225 }
226 else
227 {
228 // Open challenge: send to all connected players (except us)
229 this.people.forEach(p => {
230 if (p.sid != this.st.user.sid) //only sid is always set
231 doSend(code, obj, p.sid);
232 });
233 }
234 },
235 // Messaging center:
236 socketMessageListener: function(msg) {
237 const data = JSON.parse(msg.data);
238 switch (data.code)
239 {
240 // 0.2] Receive clients list (just socket IDs)
241 case "pollclients":
242 {
243 data.sockIds.forEach(sid => {
244 this.people.push({sid:sid, id:0, name:""});
245 // Ask identity, challenges and game(s)
246 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
247 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
248 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
249 });
250 break;
251 }
252 case "askidentity":
253 {
254 // Request for identification: reply if I'm not anonymous
255 if (this.st.user.id > 0)
256 {
257 this.st.conn.send(JSON.stringify(
258 // people[0] instead of st.user to avoid sending email
259 {code:"identity", user:this.people[0], target:data.from}));
260 }
261 break;
262 }
263 case "askchallenge":
264 {
265 // Send my current live challenge (if any)
266 const cIdx = this.challenges
267 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
268 if (cIdx >= 0)
269 {
270 const c = this.challenges[cIdx];
271 const myChallenge =
272 {
273 // Minimal challenge informations: (from not required)
274 id: c.id,
275 to: c.to,
276 fen: c.fen,
277 vid: c.vid,
278 timeControl: c.timeControl
279 };
280 this.st.conn.send(JSON.stringify({code:"challenge",
281 chall:myChallenge, target:data.from}));
282 }
283 break;
284 }
285 case "askgame":
286 {
287 // Send my current live game (if any)
288 GameStorage.getCurrent((game) => {
289 if (!!game)
290 {
291 const myGame =
292 {
293 // Minimal game informations:
294 id: game.id,
295 players: game.players.map(p => p.name),
296 vid: game.vid,
297 timeControl: game.timeControl,
298 };
299 this.st.conn.send(JSON.stringify({code:"game",
300 game:myGame, target:data.from}));
301 }
302 });
303 break;
304 }
305 case "identity":
306 {
307 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
308 this.people[pIdx].id = data.user.id;
309 this.people[pIdx].name = data.user.name;
310 break;
311 }
312 case "challenge":
313 {
314 // Receive challenge from some player (+sid)
315 let newChall = data.chall;
316 newChall.type = this.classifyObject(data.chall);
317 const pIdx = this.people.findIndex(p => p.sid == data.from);
318 newChall.from = this.people[pIdx]; //may be anonymous
319 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
320 newChall.vname = this.getVname(newChall.vid);
321 this.challenges.push(newChall);
322 break;
323 }
324 case "game":
325 {
326 // Receive game from some player (+sid)
327 // NOTE: it may be correspondance (if newgame while we are connected)
328 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
329 {
330 let newGame = data.game;
331 newGame.type = this.classifyObject(data.game);
332 newGame.vname = this.getVname(data.game.vid);
333 newGame.rid = data.from;
334 newGame.score = "*";
335 this.games.push(newGame);
336 }
337 break;
338 }
339 case "newgame":
340 {
341 // TODO: next line required ?!
342 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
343 // New game just started: data contain all information
344 if (this.classifyObject(data.gameInfo) == "live")
345 this.startNewGame(data.gameInfo);
346 else
347 {
348 // TODO: notify with game link but do not redirect
349 }
350 break;
351 }
352 case "refusechallenge":
353 {
354 alert(this.getPname(data.from) + " declined your challenge");
355 ArrayFun.remove(this.challenges, c => c.id == data.cid);
356 break;
357 }
358 case "deletechallenge":
359 {
360 // NOTE: the challenge may be already removed
361 ArrayFun.remove(this.challenges, c => c.id == data.cid);
362 localStorage.removeItem("challenge"); //in case of
363 break;
364 }
365 case "connect":
366 {
367 this.people.push({name:"", id:0, sid:data.sid});
368 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
369 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
370 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
371 break;
372 }
373 case "disconnect":
374 {
375 ArrayFun.remove(this.people, p => p.sid == data.sid);
376 // Also remove all challenges sent by this player:
377 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
378 // And all live games where he plays and no other opponent is online
379 ArrayFun.remove(this.games, g =>
380 g.type == "live" && (g.players.every(p => p.sid == data.sid
381 || !this.people.some(pl => pl.sid == p.sid))), "all");
382 break;
383 }
384 }
385 },
386 // Challenge lifecycle:
387 tryChallenge: function(player) {
388 if (player.id == 0)
389 return; //anonymous players cannot be challenged
390 this.newchallenge.to = player.name;
391 doClick("modalNewgame");
392 },
393 newChallenge: async function() {
394 const vname = this.getVname(this.newchallenge.vid);
395 const vModule = await import("@/variants/" + vname + ".js");
396 window.V = vModule.VariantRules;
397 const error = checkChallenge(this.newchallenge);
398 if (!!error)
399 return alert(error);
400 const ctype = this.classifyObject(this.newchallenge);
401 // NOTE: "from" information is not required here
402 let chall = Object.assign({}, this.newchallenge);
403 const finishAddChallenge = (cid,warnDisconnected) => {
404 chall.id = cid || "c" + getRandString();
405 // Send challenge to peers (if connected)
406 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
407 chall.added = Date.now();
408 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
409 chall.type = ctype;
410 chall.vname = vname;
411 chall.from = this.people[0]; //avoid sending email
412 this.challenges.push(chall);
413 localStorage.setItem("challenge", JSON.stringify(chall));
414 document.getElementById("modalNewgame").checked = false;
415 };
416 const cIdx = this.challenges.findIndex(
417 c => c.from.sid == this.st.user.sid && c.type == ctype);
418 if (cIdx >= 0)
419 {
420 // Delete current challenge (will be replaced now)
421 this.sendSomethingTo(this.challenges[cIdx].to,
422 "deletechallenge", {cid:this.challenges[cIdx].id});
423 if (ctype == "corr")
424 {
425 ajax(
426 "/challenges",
427 "DELETE",
428 {id: this.challenges[cIdx].id}
429 );
430 }
431 this.challenges.splice(cIdx, 1);
432 }
433 if (ctype == "live")
434 {
435 // Live challenges have a random ID
436 finishAddChallenge(null, "warnDisconnected");
437 }
438 else
439 {
440 // Correspondance game: send challenge to server
441 ajax(
442 "/challenges",
443 "POST",
444 chall,
445 response => { finishAddChallenge(response.cid); }
446 );
447 }
448 },
449 clickChallenge: function(c) {
450 // In all cases, the challenge is consumed:
451 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
452 // NOTE: deletechallenge event might be redundant (but it's easier this way)
453 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
454 const myChallenge = (c.from.sid == this.st.user.sid //live
455 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
456 if (!myChallenge)
457 {
458 c.accepted = true;
459 if (!!c.to) //c.to == this.st.user.name (connected)
460 {
461 // TODO: if special FEN, show diagram after loading variant
462 c.accepted = confirm("Accept challenge?");
463 }
464 if (c.accepted)
465 {
466 c.seat = this.people[0]; //avoid sending email
467 this.launchGame(c);
468 }
469 else
470 {
471 this.st.conn.send(JSON.stringify({
472 code: "refusechallenge",
473 cid: c.id, target: c.from.sid}));
474 }
475 }
476 else
477 localStorage.removeItem("challenge");
478 if (c.type == "corr")
479 {
480 ajax(
481 "/challenges",
482 "DELETE",
483 {id: c.id}
484 );
485 }
486 },
487 // NOTE: when launching game, the challenge is already deleted
488 launchGame: async function(c) {
489 const vModule = await import("@/variants/" + c.vname + ".js");
490 window.V = vModule.VariantRules;
491 // These game informations will be sent to other players
492 const gameInfo =
493 {
494 gameId: getRandString(),
495 fen: c.fen || V.GenRandInitFen(),
496 players: shuffle([c.from, c.seat]), //white then black
497 vid: c.vid,
498 timeControl: c.timeControl,
499 };
500 this.st.conn.send(JSON.stringify({code:"newgame",
501 gameInfo:gameInfo, target:c.from.sid, cid:c.id}));
502 if (c.type == "live")
503 this.startNewGame(gameInfo);
504 else //corr: game only on server
505 {
506 ajax(
507 "/games",
508 "POST",
509 {gameInfo: gameInfo}
510 );
511 // TODO: redirection here
512 }
513 },
514 // NOTE: for live games only (corr games start on the server)
515 startNewGame: function(gameInfo) {
516 const game = Object.assign({}, gameInfo, {
517 // (other) Game infos: constant
518 fenStart: gameInfo.fen,
519 // Game state (including FEN): will be updated
520 moves: [],
521 clocks: [-1, -1], //-1 = unstarted
522 initime: [0, 0], //initialized later
523 score: "*",
524 });
525 GameStorage.add(game);
526 if (this.st.settings.sound >= 1)
527 new Audio("/sounds/newgame.mp3").play().catch(err => {});
528 this.$router.push("/game/" + gameInfo.gameId);
529 },
530 },
531 };
532 </script>
533
534 <style lang="sass">
535 // TODO
536 </style>