6a57622026cb7c5fc5dbef3c57eb981d9447b3ec
[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 import { extractTime } from "@/utils/timeControl";
74 export default {
75 name: "my-hall",
76 components: {
77 GameList,
78 ChallengeList,
79 },
80 data: function () {
81 return {
82 st: store.state,
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
85 gdisplay: "live",
86 games: [],
87 challenges: [],
88 people: [], //(all) online players
89 newchallenge: {
90 fen: "",
91 vid: 0,
92 to: "", //name of challenged player (if any)
93 timeControl: "", //"2m+2s" ...etc
94 },
95 };
96 },
97 computed: {
98 uniquePlayers: function() {
99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
100 let anonymous = {id:0, name:"@nonymous", count:0};
101 let playerList = [];
102 this.people.forEach(p => {
103 if (p.id > 0)
104 playerList.push(p);
105 else
106 anonymous.count++;
107 });
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
110 return playerList;
111 },
112 },
113 created: function() {
114 // Always add myself to players' list
115 this.people.push(this.st.user);
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 // {excluded: this.st.user.id},
132 // response => {
133 // this.games = this.games.concat(response.games);
134 // }
135 // );
136 // Also ask for corr challenges (open + sent to me)
137 ajax(
138 "/challenges",
139 "GET",
140 {uid: this.st.user.id},
141 response => {
142 console.log(response.challenges);
143 // TODO: post-treatment on challenges ?
144 this.challenges = this.challenges.concat(response.challenges);
145 }
146 );
147 }
148 // 0.1] Ask server for room composition:
149 const socketOpenListener = () => {
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
151 };
152 this.st.conn.onopen = socketOpenListener;
153 // TODO: is this required here?
154 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
155 this.st.conn.onmessage = this.socketMessageListener;
156 const oldOnclose = this.st.conn.onclose;
157 const socketCloseListener = () => {
158 oldOnclose(); //reinitialize connexion (in store.js)
159 this.st.conn.addEventListener('message', this.socketMessageListener);
160 this.st.conn.addEventListener('close', socketCloseListener);
161 };
162 this.st.conn.onclose = socketCloseListener;
163 },
164 methods: {
165 // Helpers:
166 filterChallenges: function(type) {
167 return this.challenges.filter(c => c.type == type);
168 },
169 filterGames: function(type) {
170 return this.games.filter(c => c.type == type);
171 },
172 classifyObject: function(o) { //challenge or game
173 // Heuristic: should work for most cases... (TODO)
174 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
175 },
176 showGame: function(g) {
177 // NOTE: we are an observer, since only games I don't play are shown here
178 // ==> Moves sent by connected remote player(s) if live game
179
180 // TODO: this doesn't work: choose a SID at random
181
182 let url = "/" + g.id;
183 if (g.type == "live")
184 {
185 const sids = g.players.map(p => p.sid).join(",");
186 url += "?sids=" + sids;
187 }
188 this.$router.push(url);
189 },
190 getVname: function(vid) {
191 const vIdx = this.st.variants.findIndex(v => v.id == vid);
192 return this.st.variants[vIdx].name;
193 },
194 getSid: function(pname) {
195 const pIdx = this.people.findIndex(pl => pl.name == pname);
196 return (pIdx === -1 ? null : this.people[pIdx].sid);
197 },
198 getPname: function(sid) {
199 const pIdx = this.people.findIndex(pl => pl.sid == sid);
200 return (pIdx === -1 ? null : this.people[pIdx].name);
201 },
202 sendSomethingTo: function(to, code, obj, warnDisconnected) {
203 const doSend = (code, obj, sid) => {
204 this.st.conn.send(JSON.stringify(Object.assign(
205 {},
206 {code: code},
207 obj,
208 {target: sid}
209 )));
210 };
211 if (!!to)
212 {
213 // Challenge with targeted players
214 const targetSid = this.getSid(to);
215 if (!targetSid)
216 {
217 if (!!warnDisconnected)
218 alert("Warning: " + pname + " is not connected");
219 }
220 else
221 doSend(code, obj, targetSid);
222 }
223 else
224 {
225 // Open challenge: send to all connected players (except us)
226 this.people.forEach(p => {
227 if (p.sid != this.st.user.sid) //only sid is always set
228 doSend(code, obj, p.sid);
229 });
230 }
231 },
232 // Messaging center:
233 socketMessageListener: function(msg) {
234 // Save and call current st.conn.onmessage if one was already defined
235 // --> also needed in future Game.vue (also in Chat.vue component)
236 this.oldOnmessage(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 {code:"identity", user:this.st.user, target:data.from}));
259 }
260 break;
261 }
262 case "askchallenge":
263 {
264 // Send my current live challenge (if any)
265 const cIdx = this.challenges
266 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
267 if (cIdx >= 0)
268 {
269 const c = this.challenges[cIdx];
270 const myChallenge =
271 {
272 // Minimal challenge informations: (from not required)
273 id: c.id,
274 to: c.to,
275 fen: c.fen,
276 vid: c.vid,
277 timeControl: c.timeControl
278 };
279 this.st.conn.send(JSON.stringify({code:"challenge",
280 challenge:myChallenge, target:data.from}));
281 }
282 break;
283 }
284 case "askgame":
285 {
286 // Send my current live games (if any)
287 // TODO: from indexedDB, through GameStorage.
288 // if (!!localStorage["gid"])
289 // {
290 // const myGame =
291 // {
292 // // Minimal game informations: (fen+clock not required)
293 // id: localStorage["gid"],
294 // players: JSON.parse(localStorage["players"]), //array sid+id+name
295 // vname: localStorage["vname"],
296 // timeControl: localStorage["timeControl"],
297 // };
298 // this.st.conn.send(JSON.stringify({code:"game",
299 // game:myGame, target:data.from}));
300 // }
301 break;
302 }
303 case "identity":
304 {
305 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
306 this.people[pIdx].id = data.user.id;
307 this.people[pIdx].name = data.user.name;
308 break;
309 }
310 case "challenge":
311 {
312 // Receive challenge from some player (+sid)
313 let newChall = data.chall;
314 newChall.type = this.classifyObject(data.chall);
315 const pIdx = this.people.findIndex(p => p.sid == data.from);
316 newChall.from = this.people[pIdx]; //may be anonymous
317 newChall.added = Date.now();
318 newChall.vname = this.getVname(newChall.vid);
319 this.challenges.push(newChall);
320 break;
321 }
322 case "game":
323 {
324 // Receive game from some player (+sid)
325 // NOTE: it may be correspondance (if newgame while we are connected)
326 // TODO: ambiguous naming "newGame" ==> rename function ?
327 let newGame = data.game;
328 newGame.type = this.classifyObject(data.game);
329 newGame.vname = newGame.vname;
330 this.games.push(newGame);
331 break;
332 }
333 // * - receive "new game": if live, store locally + redirect to game
334 // * If corr: notify "new game has started", give link, but do not redirect
335 case "newgame":
336 {
337 // Delete corresponding challenge:
338 ArrayFun.remove(this.challenges, c => c.id == data.cid);
339 // New game just started: data contain all informations
340 this.newGame(data.gameInfo);
341 break;
342 }
343 // * - receive "accept/cancel challenge": apply action to challenges list
344 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
345 case "acceptchallenge":
346 {
347 // Someone accept an open (or targeted) challenge
348 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
349 let c = this.challenges[cIdx];
350 const pIdx = this.people.findIndex(p => p.sid == data.from);
351 c.seat = this.people[pIdx];
352 this.launchGame(c);
353 break;
354 }
355 case "refusechallenge":
356 {
357 alert(this.getPname(data.from) + " refused your challenge");
358 ArrayFun.remove(this.challenges, c => c.id == data.cid);
359 break;
360 }
361 case "deletechallenge":
362 {
363 ArrayFun.remove(this.challenges, c => c.id == data.cid);
364 break;
365 }
366 case "connect":
367 {
368 this.people.push({name:"", id:0, sid:data.sid});
369 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
370 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
371 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
372 break;
373 }
374 case "disconnect":
375 {
376 ArrayFun.remove(this.people, p => p.sid == data.sid);
377 // Also remove all challenges sent by this player:
378 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
379 // And all live games where he plays and no other opponent is online
380 ArrayFun.remove(this.games, g =>
381 g.type == "live" && (g.players.every(p => p.sid == data.sid
382 || !this.people.some(pl => pl.sid == p.sid))), "all");
383 break;
384 }
385 }
386 },
387 // Challenge lifecycle:
388 tryChallenge: function(player) {
389 if (player.id == 0)
390 return; //anonymous players cannot be challenged
391 this.newchallenge.to[0] = player.name;
392 doClick("modalNewgame");
393 },
394 newChallenge: async function() {
395 const vname = this.getVname(this.newchallenge.vid);
396 const vModule = await import("@/variants/" + vname + ".js");
397 window.V = vModule.VariantRules;
398 const error = checkChallenge(this.newchallenge);
399 if (!!error)
400 return alert(error);
401 const ctype = this.classifyObject(this.newchallenge);
402 // NOTE: "from" information is not required here
403 let chall =
404 {
405 fen: this.newchallenge.fen,
406 to: this.newchallenge.to,
407 timeControl: this.newchallenge.timeControl,
408 vid: this.newchallenge.vid,
409 };
410 const finishAddChallenge = (cid,warnDisconnected) => {
411 chall.id = cid || "c" + getRandString();
412 // Send challenge to peers (if connected)
413 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
414 chall.added = Date.now();
415 chall.type = ctype;
416 chall.vname = vname;
417 chall.from = this.st.user;
418 this.challenges.push(chall);
419 localStorage.setItem("challenge", JSON.stringify(chall));
420 document.getElementById("modalNewgame").checked = false;
421 };
422 const cIdx = this.challenges.findIndex(
423 c => c.from.sid == this.st.user.sid && c.type == ctype);
424 if (cIdx >= 0)
425 {
426 // Delete current challenge (will be replaced now)
427 this.sendSomethingTo(this.challenges[cIdx].to,
428 "deletechallenge", {cid:this.challenges[cIdx].id});
429 if (ctype == "corr")
430 {
431 ajax(
432 "/challenges",
433 "DELETE",
434 {id: this.challenges[cIdx].id}
435 );
436 }
437 this.challenges.splice(cIdx, 1);
438 }
439 if (ctype == "live")
440 {
441 // Live challenges have a random ID
442 finishAddChallenge(null, "warnDisconnected");
443 }
444 else
445 {
446 // Correspondance game: send challenge to server
447 ajax(
448 "/challenges",
449 "POST",
450 chall,
451 response => { finishAddChallenge(response.cid); }
452 );
453 }
454 },
455 // * - accept challenge (corr or live) --> send info to challenge creator
456 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
457 // * --> send info to challenge creator
458 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
459 // * - prepare and start new game (if challenge is full after acceptation)
460 // * --> include challenge ID (so that opponents can delete the challenge too)
461 clickChallenge: function(c) {
462
463 console.log("click challenge");
464 console.log(c);
465
466 if (c.from.sid == this.st.user.sid
467 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
468 {
469 // It's my challenge: cancel it
470 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
471 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
472 if (c.type == "corr")
473 {
474 ajax(
475 "/challenges",
476 "DELETE",
477 {id: this.challenges[cIdx].id}
478 );
479 }
480 }
481 else //accept (or refuse) a challenge
482 {
483 c.accepted = true;
484 if (!!c.to[0])
485 {
486 // TODO: if special FEN, show diagram after loading variant
487 c.accepted = confirm("Accept challenge?");
488 }
489 this.st.conn.send(JSON.stringify({
490 code: (c.accepted ? "accept" : "refuse") + "challenge",
491 cid: c.id, target: c.from.sid}));
492 if (c.type == "corr" && c.accepted)
493 {
494 ajax(
495 "/challenges",
496 "PUT",
497 {id: this.challenges[cIdx].id}
498 );
499 }
500 if (!c.accepted)
501 {
502 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
503 if (c.type == "corr")
504 {
505 ajax(
506 "/challenges",
507 "DELETE",
508 {id: this.challenges[cIdx].id}
509 );
510 }
511 }
512 }
513 },
514 // NOTE: for live games only (corr games are launched on server)
515 launchGame: async function(c) {
516 // Just assign colors and pass the message
517 const vname = this.getVname(c.vid);
518 const vModule = await import("@/variants/" + vname + ".js");
519 window.V = vModule.VariantRules;
520 let players = [c.from, c.seat];
521 // These game informations will be sent to other players
522 const gameInfo =
523 {
524 gameId: getRandString(),
525 fen: c.fen || V.GenRandInitFen(),
526 // Players' names may be required if game start when a player is offline
527 // Shuffle players order (white then black then other colors).
528 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
529 vid: c.vid,
530 timeControl: c.timeControl,
531 };
532 // NOTE: cid required to remove challenge
533 this.st.conn.send(JSON.stringify({code:"newgame",
534 gameInfo:gameInfo, cid:c.id, target:c.seat.sid}));
535 // Delete corresponding challenge:
536 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
537 this.newGame(gameInfo); //also!
538 },
539 // NOTE: for live games only (corr games are launched on server)
540 newGame: function(gameInfo) {
541 // Extract times (in [milli]seconds), set clocks
542 const tc = extractTime(gameInfo.timeControl);
543 let initime = [...Array(gameInfo.players.length)];
544 initime[0] = Date.now();
545 const game =
546 {
547 // Game infos: constant
548 gameId: gameInfo.gameId,
549 vname: this.getVname(gameInfo.vid),
550 fenStart: gameInfo.fen,
551 players: gameInfo.players,
552 timeControl: gameInfo.timeControl,
553 increment: tc.increment,
554 mode: "live", //function for live games only
555 // Game state: will be updated
556 fen: gameInfo.fen,
557 moves: [],
558 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
559 initime: initime,
560 score: "*",
561 };
562 GameStorage.add(game);
563 if (this.st.settings.sound >= 1)
564 new Audio("/sounds/newgame.mp3").play().catch(err => {});
565 // TODO: redirect to game
566 },
567 },
568 };
569 </script>
570
571 <style lang="sass">
572 // TODO
573 </style>
574
575 <!--
576 // TODO:
577 // Remove duplicates if several players of one game send their game info (Hall)
578 // When click on it, assign a random rid among online players (max. 4).
579 -->