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