'update'
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
5b020e73
BA
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"] }}
9d58ef95 9 select#selectVariant(v-model="newchallenge.vid")
85e5b5c1 10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
5b020e73 11 fieldset
b4d619d1 12 label(for="timeControl") {{ st.tr["Time control"] }}
9d58ef95 13 input#timeControl(type="text" v-model="newchallenge.timeControl"
b4d619d1
BA
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
9d58ef95 16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
6fba6e0c 17 input#selectPlayers(type="text" v-model="newchallenge.to")
b4d619d1 18 fieldset(v-if="st.user.id > 0")
9d58ef95
BA
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95
BA
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
1efe1d79 26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
6855163c
BA
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")
1efe1d79 38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
39 label(for="peopleSection" aria-hidden="true") People
40 div
1efe1d79
BA
41 .button-group
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
6855163c
BA
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)
1efe1d79 52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
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")
625022fd
BA
62</template>
63
64<script>
5b020e73 65import { store } from "@/store";
9d58ef95
BA
66import { checkChallenge } from "@/data/challengeCheck";
67import { ArrayFun } from "@/utils/array";
03608482 68import { ajax } from "@/utils/ajax";
4b0384fa 69import { getRandString, shuffle } from "@/utils/alea";
5b020e73
BA
70import GameList from "@/components/GameList.vue";
71import ChallengeList from "@/components/ChallengeList.vue";
967a2686
BA
72import { GameStorage } from "@/utils/gameStorage";
73import { extractTime } from "@/utils/timeControl";
625022fd 74export default {
cf2343ce 75 name: "my-hall",
5b020e73
BA
76 components: {
77 GameList,
78 ChallengeList,
79 },
fb54f098
BA
80 data: function () {
81 return {
5b020e73 82 st: store.state,
6855163c
BA
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
fb54f098 85 gdisplay: "live",
6855163c 86 games: [],
b4d619d1 87 challenges: [],
6fba6e0c 88 people: [], //(all) online players
9d58ef95 89 newchallenge: {
fb54f098
BA
90 fen: "",
91 vid: 0,
6fba6e0c 92 to: "", //name of challenged player (if any)
6faa92f2 93 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
94 },
95 };
96 },
b4d619d1
BA
97 computed: {
98 uniquePlayers: function() {
6855163c 99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
4d64881e
BA
100 let anonymous = {id:0, name:"@nonymous", count:0};
101 let playerList = [];
6fba6e0c 102 this.people.forEach(p => {
b4d619d1
BA
103 if (p.id > 0)
104 playerList.push(p);
105 else
4d64881e 106 anonymous.count++;
b4d619d1 107 });
4d64881e
BA
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
b4d619d1
BA
110 return playerList;
111 },
112 },
9d58ef95 113 created: function() {
4d64881e 114 // Always add myself to players' list
6fba6e0c 115 this.people.push(this.st.user);
f6f2bef1
BA
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 }
98f48579
BA
125 if (this.st.user.id > 0)
126 {
5d04793e
BA
127 // Ask server for current corr games (all but mines)
128 ajax(
129 "/games",
130 "GET",
131 {uid: this.st.user.id, excluded: true},
132 response => {
133 this.games = this.games.concat(response.games);
134 }
135 );
136 // Also ask for corr challenges (open + sent to me)
98f48579
BA
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 ?
40477190 144 Array.prototype.push.apply(this.challenges, response.challenges);
98f48579
BA
145 }
146 );
147 }
2ada153c 148 // 0.1] Ask server for room composition:
7b01e447 149 const funcPollClients = () => {
81d9ce72 150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 151 };
7b01e447
BA
152 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
153 funcPollClients();
154 else //socket not ready yet (initial loading)
3cb412e9 155 this.st.conn.onopen = funcPollClients;
4d64881e
BA
156 this.st.conn.onmessage = this.socketMessageListener;
157 const socketCloseListener = () => {
cdb34c93 158 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
159 this.st.conn.addEventListener('message', this.socketMessageListener);
160 this.st.conn.addEventListener('close', socketCloseListener);
161 };
162 this.st.conn.onclose = socketCloseListener;
9d58ef95 163 },
fb54f098 164 methods: {
a6bddfc6 165 // Helpers:
6855163c
BA
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 },
2ada153c 172 classifyObject: function(o) { //challenge or game
6855163c 173 // Heuristic: should work for most cases... (TODO)
2ada153c 174 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 175 },
2ada153c 176 showGame: function(g) {
5bd05dba 177 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 178 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 179 let url = "/game/" + g.id;
2ada153c
BA
180 if (g.type == "live")
181 {
d9b86b16
BA
182 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
183 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
184 url += "?rid=" + remotes[rIdx].sid;
2ada153c
BA
185 }
186 this.$router.push(url);
a6bddfc6 187 },
a7808884 188 // TODO: ...filter(...)[0].name, one-line, just remove this function
a6bddfc6
BA
189 getVname: function(vid) {
190 const vIdx = this.st.variants.findIndex(v => v.id == vid);
191 return this.st.variants[vIdx].name;
192 },
193 getSid: function(pname) {
6fba6e0c
BA
194 const pIdx = this.people.findIndex(pl => pl.name == pname);
195 return (pIdx === -1 ? null : this.people[pIdx].sid);
a6bddfc6 196 },
5bd05dba 197 getPname: function(sid) {
6fba6e0c
BA
198 const pIdx = this.people.findIndex(pl => pl.sid == sid);
199 return (pIdx === -1 ? null : this.people[pIdx].name);
5bd05dba 200 },
a6bddfc6
BA
201 sendSomethingTo: function(to, code, obj, warnDisconnected) {
202 const doSend = (code, obj, sid) => {
203 this.st.conn.send(JSON.stringify(Object.assign(
204 {},
205 {code: code},
206 obj,
207 {target: sid}
208 )));
209 };
c9695cb1 210 if (!!to)
a6bddfc6 211 {
c9695cb1
BA
212 // Challenge with targeted players
213 const targetSid = this.getSid(to);
214 if (!targetSid)
215 {
216 if (!!warnDisconnected)
217 alert("Warning: " + pname + " is not connected");
218 }
219 else
220 doSend(code, obj, targetSid);
a6bddfc6
BA
221 }
222 else
223 {
224 // Open challenge: send to all connected players (except us)
6fba6e0c 225 this.people.forEach(p => {
a6bddfc6
BA
226 if (p.sid != this.st.user.sid) //only sid is always set
227 doSend(code, obj, p.sid);
228 });
229 }
230 },
231 // Messaging center:
9d58ef95
BA
232 socketMessageListener: function(msg) {
233 const data = JSON.parse(msg.data);
234 switch (data.code)
235 {
f4f4c03c 236 // 0.2] Receive clients list (just socket IDs)
81d9ce72 237 case "pollclients":
1efe1d79 238 {
5a3da968 239 data.sockIds.forEach(sid => {
6fba6e0c 240 this.people.push({sid:sid, id:0, name:""});
81d9ce72 241 // Ask identity, challenges and game(s)
5a3da968 242 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 243 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
81d9ce72 244 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
5a3da968
BA
245 });
246 break;
1efe1d79 247 }
81d9ce72 248 case "askidentity":
1efe1d79 249 {
6855163c
BA
250 // Request for identification: reply if I'm not anonymous
251 if (this.st.user.id > 0)
252 {
253 this.st.conn.send(JSON.stringify(
254 {code:"identity", user:this.st.user, target:data.from}));
255 }
5a3da968 256 break;
1efe1d79 257 }
dd75774d 258 case "askchallenge":
1efe1d79 259 {
6855163c 260 // Send my current live challenge (if any)
dd75774d 261 const cIdx = this.challenges
6855163c 262 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
263 if (cIdx >= 0)
264 {
265 const c = this.challenges[cIdx];
266 const myChallenge =
267 {
81d9ce72 268 // Minimal challenge informations: (from not required)
2ada153c 269 id: c.id,
81d9ce72
BA
270 to: c.to,
271 fen: c.fen,
272 vid: c.vid,
273 timeControl: c.timeControl
dd75774d
BA
274 };
275 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 276 chall:myChallenge, target:data.from}));
81d9ce72
BA
277 }
278 break;
1efe1d79 279 }
81d9ce72 280 case "askgame":
1efe1d79 281 {
42c15a75
BA
282 // Send my current live game (if any)
283 GameStorage.getCurrent((game) => {
284 if (!!game)
285 {
286 const myGame =
287 {
288 // Minimal game informations:
289 id: game.id,
290 players: game.players.map(p => p.name),
291 vname: game.vname,
292 timeControl: game.timeControl,
293 };
294 this.st.conn.send(JSON.stringify({code:"game",
295 game:myGame, target:data.from}));
296 }
297 });
81d9ce72 298 break;
1efe1d79 299 }
5a3da968 300 case "identity":
1efe1d79 301 {
6fba6e0c
BA
302 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
303 this.people[pIdx].id = data.user.id;
304 this.people[pIdx].name = data.user.name;
5a3da968 305 break;
1efe1d79 306 }
dd75774d 307 case "challenge":
1efe1d79 308 {
dd75774d 309 // Receive challenge from some player (+sid)
6855163c 310 let newChall = data.chall;
2ada153c 311 newChall.type = this.classifyObject(data.chall);
6fba6e0c
BA
312 const pIdx = this.people.findIndex(p => p.sid == data.from);
313 newChall.from = this.people[pIdx]; //may be anonymous
42c15a75
BA
314 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
315 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
6855163c 316 this.challenges.push(newChall);
81d9ce72 317 break;
1efe1d79 318 }
dd75774d 319 case "game":
1efe1d79 320 {
6855163c 321 // Receive game from some player (+sid)
6855163c 322 // NOTE: it may be correspondance (if newgame while we are connected)
d9b86b16
BA
323 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
324 {
325 let newGame = data.game;
326 newGame.type = this.classifyObject(data.game);
327 newGame.rid = data.from;
328 newGame.score = "*";
329 this.games.push(newGame);
330 }
81d9ce72 331 break;
1efe1d79 332 }
9d58ef95 333 case "newgame":
1efe1d79 334 {
5d04793e
BA
335 // New game just started: data contain all information
336 if (data.gameInfo.type == "live")
337 {
338 this.startNewGame(data.gameInfo);
339 // TODO: redirect to game
340 }
341 else
342 {
343 // TODO: notify with game link but do not redirect
344 }
9d58ef95 345 break;
1efe1d79 346 }
bb7dd7db
BA
347 case "refusechallenge":
348 {
485fccd5 349 alert(this.getPname(data.from) + " declined your challenge");
5bd05dba 350 ArrayFun.remove(this.challenges, c => c.id == data.cid);
bb7dd7db
BA
351 break;
352 }
1efe1d79
BA
353 case "deletechallenge":
354 {
1ba761c8 355 // NOTE: the challenge may be already removed
9d58ef95
BA
356 ArrayFun.remove(this.challenges, c => c.id == data.cid);
357 break;
1efe1d79 358 }
b4d619d1 359 case "connect":
1efe1d79 360 {
6fba6e0c 361 this.people.push({name:"", id:0, sid:data.sid});
5a3da968 362 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
f05815d7
BA
363 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
364 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
9d58ef95 365 break;
1efe1d79 366 }
b4d619d1 367 case "disconnect":
1efe1d79 368 {
6fba6e0c 369 ArrayFun.remove(this.people, p => p.sid == data.sid);
a6bddfc6 370 // Also remove all challenges sent by this player:
2ada153c
BA
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
6fba6e0c 375 || !this.people.some(pl => pl.sid == p.sid))), "all");
9d58ef95 376 break;
1efe1d79 377 }
9d58ef95
BA
378 }
379 },
a6bddfc6 380 // Challenge lifecycle:
b4d619d1
BA
381 tryChallenge: function(player) {
382 if (player.id == 0)
383 return; //anonymous players cannot be challenged
a7808884 384 this.newchallenge.to = player.name;
b4d619d1 385 doClick("modalNewgame");
fb54f098 386 },
9d58ef95 387 newChallenge: async function() {
bb7dd7db 388 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
389 const vModule = await import("@/variants/" + vname + ".js");
390 window.V = vModule.VariantRules;
9d58ef95
BA
391 const error = checkChallenge(this.newchallenge);
392 if (!!error)
393 return alert(error);
2ada153c 394 const ctype = this.classifyObject(this.newchallenge);
bb7dd7db 395 // NOTE: "from" information is not required here
a7808884 396 let chall = Object.assign({}, this.newchallenge);
2ada153c 397 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 398 chall.id = cid || "c" + getRandString();
2ada153c 399 // Send challenge to peers (if connected)
c9695cb1 400 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
1efe1d79 401 chall.added = Date.now();
bb7dd7db
BA
402 chall.type = ctype;
403 chall.vname = vname;
404 chall.from = this.st.user;
1efe1d79 405 this.challenges.push(chall);
f6f2bef1 406 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
407 document.getElementById("modalNewgame").checked = false;
408 };
1efe1d79
BA
409 const cIdx = this.challenges.findIndex(
410 c => c.from.sid == this.st.user.sid && c.type == ctype);
411 if (cIdx >= 0)
b4d619d1 412 {
1efe1d79 413 // Delete current challenge (will be replaced now)
bb7dd7db 414 this.sendSomethingTo(this.challenges[cIdx].to,
1efe1d79
BA
415 "deletechallenge", {cid:this.challenges[cIdx].id});
416 if (ctype == "corr")
417 {
418 ajax(
419 "/challenges",
420 "DELETE",
421 {id: this.challenges[cIdx].id}
422 );
423 }
424 this.challenges.splice(cIdx, 1);
425 }
426 if (ctype == "live")
427 {
428 // Live challenges have a random ID
2ada153c 429 finishAddChallenge(null, "warnDisconnected");
03608482 430 }
b4d619d1 431 else
03608482 432 {
b4d619d1 433 // Correspondance game: send challenge to server
03608482 434 ajax(
1efe1d79 435 "/challenges",
03608482 436 "POST",
052d17ea 437 chall,
1efe1d79 438 response => { finishAddChallenge(response.cid); }
03608482 439 );
9d58ef95 440 }
fb54f098 441 },
a6bddfc6 442 clickChallenge: function(c) {
485fccd5
BA
443 const myChallenge = (c.from.sid == this.st.user.sid //live
444 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
445 if (!myChallenge)
a6bddfc6
BA
446 {
447 c.accepted = true;
485fccd5 448 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
449 {
450 // TODO: if special FEN, show diagram after loading variant
451 c.accepted = confirm("Accept challenge?");
452 }
485fccd5 453 if (c.accepted)
36093eba 454 {
485fccd5
BA
455 c.seat = this.st.user;
456 this.launchGame(c);
457 }
458 else
459 {
460 this.st.conn.send(JSON.stringify({
461 code: "refusechallenge",
462 cid: c.id, target: c.from.sid}));
36093eba 463 }
a6bddfc6 464 }
3cb412e9
BA
465 else
466 localStorage.removeItem("challenge");
485fccd5
BA
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 }
a6bddfc6 479 },
485fccd5 480 // NOTE: when launching game, the challenge is already deleted
36093eba 481 launchGame: async function(c) {
a6bddfc6
BA
482 const vname = this.getVname(c.vid);
483 const vModule = await import("@/variants/" + vname + ".js");
484 window.V = vModule.VariantRules;
a7808884
BA
485 // Extract times (in [milli]seconds), set clocks
486 const tc = extractTime(c.timeControl);
4b0384fa
BA
487 // These game informations will be sent to other players
488 const gameInfo =
a6bddfc6 489 {
4b0384fa 490 gameId: getRandString(),
a6bddfc6 491 fen: c.fen || V.GenRandInitFen(),
5d04793e 492 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 493 vid: c.vid,
a7808884
BA
494 timeControl: tc.timeControl,
495 mainTime: tc.mainTime,
496 increment: tc.increment,
5d04793e 497 type: c.type,
a6bddfc6 498 };
6fba6e0c 499 this.st.conn.send(JSON.stringify({code:"newgame",
485fccd5
BA
500 gameInfo:gameInfo, target:c.seat.sid}));
501 if (c.type == "live")
502 this.startNewGame(gameInfo);
503 else //corr: game only on server
504 {
505 ajax(
506 "/games",
507 "POST",
508 {gameInfo: gameInfo}
509 );
510 }
fb54f098 511 },
7b626bdd 512 // NOTE: for live games only (corr games are launched on server)
42c15a75 513 startNewGame: function(gameInfo) {
a7808884
BA
514 const game = Object.assign(gameInfo, {
515 // More game infos: constant
6d01bb17
BA
516 vname: this.getVname(gameInfo.vid),
517 fenStart: gameInfo.fen,
967a2686
BA
518 mode: "live", //function for live games only
519 // Game state: will be updated
967a2686 520 moves: [],
a7808884
BA
521 clocks: [tc.mainTime, tc.mainTime],
522 initime: [Date.now(), 0],
967a2686 523 score: "*",
a7808884 524 });
967a2686 525 GameStorage.add(game);
7b626bdd
BA
526 if (this.st.settings.sound >= 1)
527 new Audio("/sounds/newgame.mp3").play().catch(err => {});
a6088c90 528 // TODO: redirect to game
1efe1d79 529 },
fb54f098 530 },
85e5b5c1 531};
ccd4a2b7 532</script>
85e5b5c1
BA
533
534<style lang="sass">
535// TODO
536</style>