Add patch for preset challenges too
[vchess.git] / client / src / views / MyGames.vue
CommitLineData
afd3240d
BA
1<template lang="pug">
2main
3 .row
4 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
5 .button-group
910d631b
BA
6 button.tabbtn#liveGames(@click="setDisplay('live',$event)")
7 | {{ st.tr["Live games"] }}
8 button.tabbtn#corrGames(@click="setDisplay('corr',$event)")
6e0f2842 9 | {{ st.tr["Correspondence games"] }}
5f918a27
BA
10 button.tabbtn#importGames(@click="setDisplay('import',$event)")
11 | {{ st.tr["Imported games"] }}
910d631b 12 GameList(
585d0955 13 ref="livegames"
910d631b
BA
14 v-show="display=='live'"
15 :games="liveGames"
16 @show-game="showGame"
3b0f26c1 17 @abortgame="abortGame"
910d631b 18 )
934f7f70
BA
19 GameList(
20 v-show="display=='corr'"
21 ref="corrgames"
22 :games="corrGames"
23 @show-game="showGame"
24 @abortgame="abortGame"
25 )
73f8753f
BA
26 UploadGame(
27 v-show="display=='import'"
28 @game-uploaded="addGameImport"
29 )
5f918a27
BA
30 GameList(
31 v-show="display=='import'"
32 ref="importgames"
33 :games="importGames"
5b18515f 34 :show-both="true"
5f918a27
BA
35 @show-game="showGame"
36 )
934f7f70
BA
37 button#loadMoreBtn(
38 v-show="hasMore[display]"
39 @click="loadMore(display)"
40 )
41 | {{ st.tr["Load more"] }}
afd3240d
BA
42</template>
43
44<script>
afd3240d
BA
45import { store } from "@/store";
46import { GameStorage } from "@/utils/gameStorage";
5f918a27 47import { ImportgameStorage } from "@/utils/importgameStorage";
afd3240d 48import { ajax } from "@/utils/ajax";
aae89b49 49import { getScoreMessage } from "@/utils/scoring";
23ecf008
BA
50import params from "@/parameters";
51import { getRandString } from "@/utils/alea";
afd3240d 52import GameList from "@/components/GameList.vue";
91777c2c 53import UploadGame from "@/components/UploadGame.vue";
afd3240d 54export default {
89021f18 55 name: "my-my-games",
afd3240d 56 components: {
5f918a27
BA
57 GameList,
58 UploadGame
afd3240d
BA
59 },
60 data: function() {
61 return {
62 st: store.state,
dac39588 63 display: "live",
2f258c37 64 liveGames: [],
db1f1f9a 65 corrGames: [],
5f918a27 66 importGames: [],
934f7f70
BA
67 // timestamp of last showed (oldest) game:
68 cursor: {
69 live: Number.MAX_SAFE_INTEGER,
5f918a27 70 "import": Number.MAX_SAFE_INTEGER,
934f7f70
BA
71 corr: Number.MAX_SAFE_INTEGER
72 },
0234201f 73 // hasMore == TRUE: a priori there could be more games to load
5f918a27
BA
74 hasMore: {
75 live: true,
76 "import": true,
77 corr: (store.state.user.id > 0)
78 },
db1f1f9a 79 conn: null,
882ec6fe
BA
80 connexionString: "",
81 socketCloseListener: 0
afd3240d
BA
82 };
83 },
1112f1fd
BA
84 watch: {
85 $route: function(to, from) {
86 if (to.path != "/mygames") this.cleanBeforeDestroy();
eaa5ad3e
BA
87 },
88 // st.variants changes only once, at loading from [] to [...]
89 "st.variants": function() {
90 // Set potential games variant names + display:
3aa0c778 91 this.liveGames.concat(this.corrGames).concat(this.importGames)
eaa5ad3e
BA
92 .forEach(o => {
93 if (!o.vname) this.setVname(o);
94 });
1112f1fd
BA
95 }
96 },
afd3240d 97 created: function() {
1112f1fd 98 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
db1f1f9a
BA
99 // Initialize connection
100 this.connexionString =
101 params.socketUrl +
7e476ce4
BA
102 "/?sid=" + this.st.user.sid +
103 "&id=" + this.st.user.id +
104 "&tmpId=" + getRandString() +
db1f1f9a
BA
105 "&page=" +
106 encodeURIComponent(this.$route.path);
107 this.conn = new WebSocket(this.connexionString);
108 this.conn.onmessage = this.socketMessageListener;
882ec6fe
BA
109 this.socketCloseListener = setInterval(
110 () => {
111 if (this.conn.readyState == 3) {
112 // Connexion is closed: re-open
113 this.conn.removeEventListener("message", this.socketMessageListener);
114 this.conn = new WebSocket(this.connexionString);
115 this.conn.addEventListener("message", this.socketMessageListener);
116 }
117 },
118 1000
119 );
afd3240d 120 },
2f258c37 121 mounted: function() {
585d0955 122 const adjustAndSetDisplay = () => {
0705a80c 123 // showType is the last type viewed by the user (default)
585d0955
BA
124 let showType = localStorage.getItem("type-myGames") || "live";
125 // Live games, my turn: highest priority:
126 if (this.liveGames.some(g => !!g.myTurn)) showType = "live";
127 // Then corr games, my turn:
128 else if (this.corrGames.some(g => !!g.myTurn)) showType = "corr";
129 else {
130 // If a listing is empty, try showing the other (if non-empty)
131 const types = ["corr", "live"];
132 for (let i of [0,1]) {
133 if (
134 this[types[i] + "Games"].length > 0 &&
135 this[types[1-i] + "Games"].length == 0
136 ) {
137 showType = types[i];
138 }
139 }
140 }
141 this.setDisplay(showType);
142 };
934f7f70 143 GameStorage.getRunning(localGames => {
585d0955
BA
144 localGames.forEach(g => g.type = "live");
145 this.decorate(localGames);
146 this.liveGames = localGames;
147 if (this.st.user.id > 0) {
0234201f 148 // Ask running corr games first
585d0955 149 ajax(
0234201f 150 "/runninggames",
585d0955
BA
151 "GET",
152 {
f14572c4 153 credentials: true,
585d0955 154 success: (res) => {
0234201f
BA
155 // These games are garanteed to not be deleted
156 this.corrGames = res.games;
f14572c4
BA
157 this.corrGames.forEach(g => {
158 g.type = "corr";
159 g.score = "*";
902378e6 160 g.options = JSON.parse(g.options);
f14572c4 161 });
0234201f
BA
162 this.decorate(this.corrGames);
163 // Now ask completed games (partial list)
934f7f70
BA
164 this.loadMore(
165 "live",
1ef65040
BA
166 () => this.loadMore("corr", () => {
167 this.loadMore("import", adjustAndSetDisplay);
168 })
0234201f 169 );
585d0955
BA
170 }
171 }
172 );
1ef65040
BA
173 }
174 else {
175 this.loadMore("live", () => {
176 this.loadMore("import", adjustAndSetDisplay);
177 });
178 }
585d0955 179 });
2f258c37 180 },
23ecf008 181 beforeDestroy: function() {
1112f1fd 182 this.cleanBeforeDestroy();
23ecf008 183 },
afd3240d 184 methods: {
1112f1fd 185 cleanBeforeDestroy: function() {
882ec6fe 186 clearInterval(this.socketCloseListener);
1112f1fd 187 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
68e3aa8c 188 this.conn.removeEventListener("message", this.socketMessageListener);
1112f1fd 189 this.conn.send(JSON.stringify({code: "disconnect"}));
68e3aa8c 190 this.conn = null;
1112f1fd 191 },
2f258c37
BA
192 setDisplay: function(type, e) {
193 this.display = type;
194 localStorage.setItem("type-myGames", type);
0705a80c 195 let elt = (!!e ? e.target : document.getElementById(type + "Games"));
2f258c37 196 elt.classList.add("active");
23ecf008 197 elt.classList.remove("somethingnew"); //in case of
73f8753f
BA
198 for (let t of ["live","corr","import"]) {
199 if (t != type)
200 document.getElementById(t + "Games").classList.remove("active");
201 }
2f258c37 202 },
eaa5ad3e
BA
203 // TODO: duplicated from Hall.vue:
204 setVname: function(obj) {
205 const variant = this.st.variants.find(v => v.id == obj.vid);
206 if (!!variant) {
207 obj.vname = variant.name;
208 obj.vdisp = variant.display;
209 }
210 },
5f918a27 211 addGameImport(game) {
1ef65040
BA
212 game.type = "import";
213 ImportgameStorage.add(game, (err) => {
214 if (!!err) {
215 if (err.message.indexOf("Key already exists") < 0) {
216 alert(this.st.tr["An error occurred. Try again!"]);
217 return;
218 }
fef153df
BA
219 // NOTE: since a random new ID is generated for imported games,
220 // this error will not occur.
1ef65040
BA
221 else alert(this.st.tr["The game was already imported"]);
222 }
223 this.$router.push("/game/" + game.id);
224 });
5f918a27 225 },
cafe0166
BA
226 tryShowNewsIndicator: function(type) {
227 if (
73f8753f
BA
228 (type == "live" && this.display != "live") ||
229 (type == "corr" && this.display != "corr")
cafe0166
BA
230 ) {
231 document
232 .getElementById(type + "Games")
233 .classList.add("somethingnew");
234 }
235 },
28b32b4f 236 // Called at loading to augment games with myColor + myTurn infos
e727fe31
BA
237 decorate: function(games) {
238 games.forEach(g => {
6b7b2cf7 239 g.myColor =
0234201f 240 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
6b7b2cf7
BA
241 (g.type == "live" && g.players[0].sid == this.st.user.sid)
242 ? 'w'
243 : 'b';
244 // If game is over, myTurn doesn't exist:
e727fe31 245 if (g.score == "*") {
e727fe31 246 const rem = g.movesCount % 2;
6b7b2cf7 247 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
e727fe31 248 g.myTurn = true;
e727fe31 249 }
eaa5ad3e 250 this.setVname(g);
e727fe31
BA
251 });
252 },
cafe0166 253 socketMessageListener: function(msg) {
68e3aa8c 254 if (!this.conn) return;
cafe0166 255 const data = JSON.parse(msg.data);
5f918a27 256 // NOTE: no imported games here
e727fe31
BA
257 let gamesArrays = {
258 "corr": this.corrGames,
259 "live": this.liveGames
260 };
cafe0166 261 switch (data.code) {
cafe0166
BA
262 case "notifyturn":
263 case "notifyscore": {
264 const info = data.data;
e50a8025 265 const type = (!!parseInt(info.gid, 10) ? "corr" : "live");
e727fe31 266 let game = gamesArrays[type].find(g => g.id == info.gid);
cafe0166
BA
267 // "notifything" --> "thing":
268 const thing = data.code.substr(6);
e727fe31 269 game[thing] = info[thing];
585d0955
BA
270 if (thing == "turn") {
271 game.myTurn = !game.myTurn;
272 if (game.myTurn) this.tryShowNewsIndicator(type);
0705a80c
BA
273 }
274 else game.myTurn = false;
585d0955
BA
275 // TODO: forcing refresh like that is ugly and wrong.
276 // How to do it cleanly?
277 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
278 break;
279 }
280 case "notifynewgame": {
eaa5ad3e
BA
281 let gameInfo = data.data;
282 this.setVname(gameInfo);
902378e6
BA
283 // TODO: remove patch on next line (options || "{}")
284 gameInfo.options = JSON.parse(gameInfo.options || "{}");
e727fe31
BA
285 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
286 let game = Object.assign(
cafe0166 287 {
cafe0166 288 type: type,
2a8a94c9 289 score: "*",
e727fe31 290 created: Date.now()
cafe0166
BA
291 },
292 gameInfo
293 );
28b32b4f 294 game.myTurn =
0234201f 295 (type == "corr" && game.players[0].id == this.st.user.id) ||
28b32b4f 296 (type == "live" && game.players[0].sid == this.st.user.sid);
e727fe31 297 gamesArrays[type].push(game);
585d0955
BA
298 if (game.myTurn) this.tryShowNewsIndicator(type);
299 // TODO: cleaner refresh
300 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
301 break;
302 }
303 }
304 },
feaf1bf7 305 showGame: function(game) {
5f918a27 306 if (game.type != "corr" || !game.myTurn) {
feaf1bf7 307 this.$router.push("/game/" + game.id);
620a88ed
BA
308 return;
309 }
feaf1bf7
BA
310 // It's my turn in this game. Are there others?
311 let nextIds = "";
e727fe31
BA
312 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
313 g.id != game.id && !!g.myTurn);
feaf1bf7
BA
314 if (otherCorrGamesMyTurn.length > 0) {
315 nextIds += "/?next=[";
316 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
317 // Remove last comma and close array:
318 nextIds = nextIds.slice(0, -1) + "]";
319 }
320 this.$router.push("/game/" + game.id + nextIds);
db1f1f9a 321 },
aae89b49
BA
322 abortGame: function(game) {
323 // Special "trans-pages" case: from MyGames to Game
324 // TODO: also for corr games? (It's less important)
325 if (game.type == "live") {
326 const oppsid =
327 game.players[0].sid == this.st.user.sid
328 ? game.players[1].sid
329 : game.players[0].sid;
68e3aa8c
BA
330 if (!!this.conn) {
331 this.conn.send(
332 JSON.stringify(
333 {
334 code: "mabort",
335 gid: game.id,
336 // NOTE: target might not be online
337 target: oppsid
338 }
339 )
340 );
341 }
aae89b49 342 }
5f918a27 343 // NOTE: no imported games here
aae89b49
BA
344 else if (!game.deletedByWhite || !game.deletedByBlack) {
345 // Set score if game isn't deleted on server:
346 ajax(
347 "/games",
348 "PUT",
349 {
e57c4de4
BA
350 data: {
351 gid: game.id,
352 newObj: {
353 score: "?",
354 scoreMsg: getScoreMessage("?")
355 }
aae89b49
BA
356 }
357 }
358 );
359 }
0234201f 360 },
934f7f70 361 loadMore: function(type, cb) {
7ebc0408 362 if (type == "corr" && this.st.user.id > 0) {
934f7f70
BA
363 ajax(
364 "/completedgames",
365 "GET",
366 {
367 credentials: true,
368 data: { cursor: this.cursor["corr"] },
369 success: (res) => {
370 const L = res.games.length;
371 if (L > 0) {
372 this.cursor["corr"] = res.games[L - 1].created;
373 let moreGames = res.games;
902378e6
BA
374 moreGames.forEach(g => {
375 g.type = "corr";
376 g.options = JSON.parse(g.options);
377 });
934f7f70
BA
378 this.decorate(moreGames);
379 this.corrGames = this.corrGames.concat(moreGames);
0705a80c
BA
380 }
381 else this.hasMore["corr"] = false;
934f7f70
BA
382 if (!!cb) cb();
383 }
0234201f 384 }
934f7f70 385 );
5f918a27
BA
386 }
387 else if (type == "live") {
934f7f70
BA
388 GameStorage.getNext(this.cursor["live"], localGames => {
389 const L = localGames.length;
390 if (L > 0) {
2c5d7b20 391 // Add "-1" because IDBKeyRange.upperBound includes boundary
934f7f70 392 this.cursor["live"] = localGames[L - 1].created - 1;
4f07d54f
BA
393 localGames.forEach(g => {
394 g.type = "live";
902378e6
BA
395 // TODO: remove patch on next line (options || "{}")
396 g.options = JSON.parse(g.options || "{}");
4f07d54f 397 });
934f7f70
BA
398 this.decorate(localGames);
399 this.liveGames = this.liveGames.concat(localGames);
0705a80c
BA
400 }
401 else this.hasMore["live"] = false;
934f7f70
BA
402 if (!!cb) cb();
403 });
404 }
5f918a27
BA
405 else if (type == "import") {
406 ImportgameStorage.getNext(this.cursor["import"], importGames => {
407 const L = importGames.length;
408 if (L > 0) {
409 // Add "-1" because IDBKeyRange.upperBound includes boundary
410 this.cursor["import"] = importGames[L - 1].created - 1;
eaa5ad3e
BA
411 importGames.forEach(g => {
412 g.type = "import";
7d48e539
BA
413 // TODO: remove following patch (options || "{}")
414 g.options = JSON.parse(g.options || "{}");
eaa5ad3e
BA
415 this.setVname(g);
416 });
5f918a27 417 this.importGames = this.importGames.concat(importGames);
0705a80c
BA
418 }
419 else this.hasMore["import"] = false;
5f918a27
BA
420 if (!!cb) cb();
421 });
422 }
6808d7a1
BA
423 }
424 }
afd3240d
BA
425};
426</script>
2f258c37 427
26d8a01a 428<style lang="sass" scoped>
2f258c37 429.active
5fbc0680 430 color: #388e3c
5fe7e71c
BA
431
432.tabbtn
433 background-color: #f9faee
e2590fa8 434
0234201f 435button#loadMoreBtn
f14572c4
BA
436 display: block
437 margin: 0 auto
0234201f 438
23ecf008 439.somethingnew
107dc1bd 440 background-color: #90C4EC !important
2f258c37 441</style>
4b8cf8ef
BA
442
443<!-- Not scoped because acting on GameList -->
444<style lang="sass">
445table.game-list
446 max-height: 100%
447</style>