d0cfdd17c975d54cfbb16163dccdee91a251b1f9
[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 Array.prototype.push.apply(this.challenges, 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 // --> do we have players' names ?
182
183 let url = "/" + g.id;
184 if (g.type == "live")
185 {
186 const sids = g.players.map(p => p.sid).join(",");
187 url += "?sids=" + sids;
188 }
189 this.$router.push(url);
190 },
191 getVname: function(vid) {
192 const vIdx = this.st.variants.findIndex(v => v.id == vid);
193 return this.st.variants[vIdx].name;
194 },
195 getSid: function(pname) {
196 const pIdx = this.people.findIndex(pl => pl.name == pname);
197 return (pIdx === -1 ? null : this.people[pIdx].sid);
198 },
199 getPname: function(sid) {
200 const pIdx = this.people.findIndex(pl => pl.sid == sid);
201 return (pIdx === -1 ? null : this.people[pIdx].name);
202 },
203 sendSomethingTo: function(to, code, obj, warnDisconnected) {
204 const doSend = (code, obj, sid) => {
205 this.st.conn.send(JSON.stringify(Object.assign(
206 {},
207 {code: code},
208 obj,
209 {target: sid}
210 )));
211 };
212 if (!!to)
213 {
214 // Challenge with targeted players
215 const targetSid = this.getSid(to);
216 if (!targetSid)
217 {
218 if (!!warnDisconnected)
219 alert("Warning: " + pname + " is not connected");
220 }
221 else
222 doSend(code, obj, targetSid);
223 }
224 else
225 {
226 // Open challenge: send to all connected players (except us)
227 this.people.forEach(p => {
228 if (p.sid != this.st.user.sid) //only sid is always set
229 doSend(code, obj, p.sid);
230 });
231 }
232 },
233 // Messaging center:
234 socketMessageListener: function(msg) {
235 // Save and call current st.conn.onmessage if one was already defined
236 // --> also needed in future Game.vue (also in Chat.vue component)
237 this.oldOnmessage(msg);
238 const data = JSON.parse(msg.data);
239 switch (data.code)
240 {
241 // 0.2] Receive clients list (just socket IDs)
242 case "pollclients":
243 {
244 data.sockIds.forEach(sid => {
245 this.people.push({sid:sid, id:0, name:""});
246 // Ask identity, challenges and game(s)
247 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
248 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
249 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
250 });
251 break;
252 }
253 case "askidentity":
254 {
255 // Request for identification: reply if I'm not anonymous
256 if (this.st.user.id > 0)
257 {
258 this.st.conn.send(JSON.stringify(
259 {code:"identity", user:this.st.user, 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 vname: game.vname,
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); //TODO: just send vname?
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 let newGame = data.game;
329 newGame.type = this.classifyObject(data.game);
330 newGame.rid = data.from;
331 newGame.score = "*";
332 this.games.push(newGame);
333 break;
334 }
335 case "newgame":
336 {
337 // New game just started: data contain all informations
338 this.startNewGame(data.gameInfo);
339 // TODO: if live, redirect to game
340 // if corr, notify with link but do not redirect
341 break;
342 }
343 case "refusechallenge":
344 {
345 alert(this.getPname(data.from) + " declined your challenge");
346 ArrayFun.remove(this.challenges, c => c.id == data.cid);
347 break;
348 }
349 case "deletechallenge":
350 {
351 // NOTE: the challenge may be already removed
352 ArrayFun.remove(this.challenges, c => c.id == data.cid);
353 break;
354 }
355 case "connect":
356 {
357 this.people.push({name:"", id:0, sid:data.sid});
358 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
359 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
360 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
361 break;
362 }
363 case "disconnect":
364 {
365 ArrayFun.remove(this.people, p => p.sid == data.sid);
366 // Also remove all challenges sent by this player:
367 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
368 // And all live games where he plays and no other opponent is online
369 ArrayFun.remove(this.games, g =>
370 g.type == "live" && (g.players.every(p => p.sid == data.sid
371 || !this.people.some(pl => pl.sid == p.sid))), "all");
372 break;
373 }
374 }
375 },
376 // Challenge lifecycle:
377 tryChallenge: function(player) {
378 if (player.id == 0)
379 return; //anonymous players cannot be challenged
380 this.newchallenge.to[0] = player.name;
381 doClick("modalNewgame");
382 },
383 newChallenge: async function() {
384 const vname = this.getVname(this.newchallenge.vid);
385 const vModule = await import("@/variants/" + vname + ".js");
386 window.V = vModule.VariantRules;
387 const error = checkChallenge(this.newchallenge);
388 if (!!error)
389 return alert(error);
390 const ctype = this.classifyObject(this.newchallenge);
391 // NOTE: "from" information is not required here
392 let chall =
393 {
394 fen: this.newchallenge.fen,
395 to: this.newchallenge.to,
396 timeControl: this.newchallenge.timeControl,
397 vid: this.newchallenge.vid,
398 };
399 const finishAddChallenge = (cid,warnDisconnected) => {
400 chall.id = cid || "c" + getRandString();
401 // Send challenge to peers (if connected)
402 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
403 chall.added = Date.now();
404 chall.type = ctype;
405 chall.vname = vname;
406 chall.from = this.st.user;
407 this.challenges.push(chall);
408 localStorage.setItem("challenge", JSON.stringify(chall));
409 document.getElementById("modalNewgame").checked = false;
410 };
411 const cIdx = this.challenges.findIndex(
412 c => c.from.sid == this.st.user.sid && c.type == ctype);
413 if (cIdx >= 0)
414 {
415 // Delete current challenge (will be replaced now)
416 this.sendSomethingTo(this.challenges[cIdx].to,
417 "deletechallenge", {cid:this.challenges[cIdx].id});
418 if (ctype == "corr")
419 {
420 ajax(
421 "/challenges",
422 "DELETE",
423 {id: this.challenges[cIdx].id}
424 );
425 }
426 this.challenges.splice(cIdx, 1);
427 }
428 if (ctype == "live")
429 {
430 // Live challenges have a random ID
431 finishAddChallenge(null, "warnDisconnected");
432 }
433 else
434 {
435 // Correspondance game: send challenge to server
436 ajax(
437 "/challenges",
438 "POST",
439 chall,
440 response => { finishAddChallenge(response.cid); }
441 );
442 }
443 },
444 clickChallenge: function(c) {
445 const myChallenge = (c.from.sid == this.st.user.sid //live
446 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
447 if (!myChallenge)
448 {
449 c.accepted = true;
450 if (!!c.to) //c.to == this.st.user.name (connected)
451 {
452 // TODO: if special FEN, show diagram after loading variant
453 c.accepted = confirm("Accept challenge?");
454 }
455 if (c.accepted)
456 {
457 c.seat = this.st.user;
458 this.launchGame(c);
459 }
460 else
461 {
462 this.st.conn.send(JSON.stringify({
463 code: "refusechallenge",
464 cid: c.id, target: c.from.sid}));
465 }
466 }
467 // In all cases, the challenge is consumed:
468 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
469 // NOTE: deletechallenge event might be redundant (but it's easier this way)
470 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
471 if (c.type == "corr")
472 {
473 ajax(
474 "/challenges",
475 "DELETE",
476 {id: this.challenges[cIdx].id}
477 );
478 }
479 },
480 // NOTE: when launching game, the challenge is already deleted
481 launchGame: async function(c) {
482 const vname = this.getVname(c.vid);
483 const vModule = await import("@/variants/" + vname + ".js");
484 window.V = vModule.VariantRules;
485 let players = [c.from, c.seat];
486 // These game informations will be sent to other players
487 const gameInfo =
488 {
489 gameId: getRandString(),
490 fen: c.fen || V.GenRandInitFen(),
491 // Players' names may be required if game start when a player is offline
492 // Shuffle players order (white then black).
493 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
494 vid: c.vid,
495 timeControl: c.timeControl,
496 };
497 this.st.conn.send(JSON.stringify({code:"newgame",
498 gameInfo:gameInfo, target:c.seat.sid}));
499 if (c.type == "live")
500 this.startNewGame(gameInfo);
501 else //corr: game only on server
502 {
503 ajax(
504 "/games",
505 "POST",
506 {gameInfo: gameInfo}
507 );
508 }
509 },
510 // NOTE: for live games only (corr games are launched on server)
511 startNewGame: function(gameInfo) {
512 // Extract times (in [milli]seconds), set clocks
513 const tc = extractTime(gameInfo.timeControl);
514 let initime = [...Array(gameInfo.players.length)];
515 initime[0] = Date.now();
516 const game =
517 {
518 // Game infos: constant
519 gameId: gameInfo.gameId,
520 vname: this.getVname(gameInfo.vid),
521 fenStart: gameInfo.fen,
522 players: gameInfo.players,
523 timeControl: gameInfo.timeControl,
524 increment: tc.increment,
525 mode: "live", //function for live games only
526 // Game state: will be updated
527 fen: gameInfo.fen,
528 moves: [],
529 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
530 initime: initime,
531 score: "*",
532 };
533 GameStorage.add(game);
534 if (this.st.settings.sound >= 1)
535 new Audio("/sounds/newgame.mp3").play().catch(err => {});
536 // TODO: redirect to game
537 },
538 },
539 };
540 </script>
541
542 <style lang="sass">
543 // TODO
544 </style>
545
546 <!--
547 // TODO:
548 // Remove duplicates if several players of one game send their game info (Hall)
549 // When click on it, assign a random rid among online players (max. 4).
550 -->