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