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