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