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