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