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