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