ad330aec802c2454a4d4377dac8ad5961b4c0015
[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 reopenTimeout: 0,
82 reconnectTimeout: 0
83 };
84 },
85 watch: {
86 $route: function(to, from) {
87 if (to.path != "/mygames") this.cleanBeforeDestroy();
88 },
89 // st.variants changes only once, at loading from [] to [...]
90 "st.variants": function() {
91 // Set potential games variant names + display:
92 this.liveGames.concat(this.corrGames).concat(this.importGames)
93 .forEach(o => {
94 if (!o.vname) this.setVname(o);
95 });
96 }
97 },
98 created: function() {
99 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
100 this.connexionString =
101 params.socketUrl +
102 "/?sid=" + this.st.user.sid +
103 "&id=" + this.st.user.id +
104 "&tmpId=" + getRandString() +
105 "&page=" +
106 encodeURIComponent(this.$route.path);
107 this.openConnection();
108 },
109 mounted: function() {
110 const adjustAndSetDisplay = () => {
111 // showType is the last type viewed by the user (default)
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 };
131 GameStorage.getRunning(localGames => {
132 localGames.forEach(g => g.type = "live");
133 this.decorate(localGames);
134 this.liveGames = localGames;
135 if (this.st.user.id > 0) {
136 // Ask running corr games first
137 ajax(
138 "/runninggames",
139 "GET",
140 {
141 credentials: true,
142 success: (res) => {
143 // These games are garanteed to not be deleted
144 this.corrGames = res.games;
145 this.corrGames.forEach(g => {
146 g.type = "corr";
147 g.score = "*";
148 g.options = JSON.parse(g.options);
149 });
150 this.decorate(this.corrGames);
151 // Now ask completed games (partial list)
152 this.loadMore(
153 "live",
154 () => this.loadMore("corr", () => {
155 this.loadMore("import", adjustAndSetDisplay);
156 })
157 );
158 }
159 }
160 );
161 }
162 else {
163 this.loadMore("live", () => {
164 this.loadMore("import", adjustAndSetDisplay);
165 });
166 }
167 });
168 },
169 beforeDestroy: function() {
170 this.cleanBeforeDestroy();
171 },
172 methods: {
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 },
190 cleanBeforeDestroy: function() {
191 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
192 clearTimeout(this.reopenTimeout);
193 this.conn.send(JSON.stringify({code: "disconnect"}));
194 this.conn = null;
195 },
196 setDisplay: function(type, e) {
197 this.display = type;
198 localStorage.setItem("type-myGames", type);
199 let elt = (!!e ? e.target : document.getElementById(type + "Games"));
200 elt.classList.add("active");
201 elt.classList.remove("somethingnew"); //in case of
202 for (let t of ["live","corr","import"]) {
203 if (t != type)
204 document.getElementById(t + "Games").classList.remove("active");
205 }
206 },
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 },
215 addGameImport(game) {
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 }
223 // NOTE: since a random new ID is generated for imported games,
224 // this error will not occur.
225 else alert(this.st.tr["The game was already imported"]);
226 }
227 this.$router.push("/game/" + game.id);
228 });
229 },
230 tryShowNewsIndicator: function(type) {
231 if (
232 (type == "live" && this.display != "live") ||
233 (type == "corr" && this.display != "corr")
234 ) {
235 document
236 .getElementById(type + "Games")
237 .classList.add("somethingnew");
238 }
239 },
240 // Called at loading to augment games with myColor + myTurn infos
241 decorate: function(games) {
242 games.forEach(g => {
243 g.myColor =
244 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
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:
249 if (g.score == "*") {
250 const rem = g.movesCount % 2;
251 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
252 g.myTurn = true;
253 }
254 this.setVname(g);
255 });
256 },
257 socketMessageListener: function(msg) {
258 if (!this.conn) return;
259 const data = JSON.parse(msg.data);
260 // NOTE: no imported games here
261 let gamesArrays = {
262 "corr": this.corrGames,
263 "live": this.liveGames
264 };
265 switch (data.code) {
266 case "notifyturn":
267 case "notifyscore": {
268 const info = data.data;
269 const type = (!!parseInt(info.gid, 10) ? "corr" : "live");
270 let game = gamesArrays[type].find(g => g.id == info.gid);
271 // "notifything" --> "thing":
272 const thing = data.code.substr(6);
273 game[thing] = info[thing];
274 if (thing == "turn") {
275 game.myTurn = !game.myTurn;
276 if (game.myTurn) this.tryShowNewsIndicator(type);
277 }
278 else game.myTurn = false;
279 // TODO: forcing refresh like that is ugly and wrong.
280 // How to do it cleanly?
281 this.$refs[type + "games"].$forceUpdate();
282 break;
283 }
284 case "notifynewgame": {
285 let gameInfo = data.data;
286 this.setVname(gameInfo);
287 // TODO: remove patch on next line (options || "{}")
288 gameInfo.options = JSON.parse(gameInfo.options || "{}");
289 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
290 let game = Object.assign(
291 {
292 type: type,
293 score: "*",
294 created: Date.now()
295 },
296 gameInfo
297 );
298 game.myTurn =
299 (type == "corr" && game.players[0].id == this.st.user.id) ||
300 (type == "live" && game.players[0].sid == this.st.user.sid);
301 gamesArrays[type].push(game);
302 if (game.myTurn) this.tryShowNewsIndicator(type);
303 // TODO: cleaner refresh
304 this.$refs[type + "games"].$forceUpdate();
305 break;
306 }
307 }
308 },
309 showGame: function(game) {
310 if (game.type != "corr" || !game.myTurn) {
311 this.$router.push("/game/" + game.id);
312 return;
313 }
314 // It's my turn in this game. Are there others?
315 let nextIds = "";
316 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
317 g.id != game.id && !!g.myTurn);
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);
325 },
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;
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 }
346 }
347 // NOTE: no imported games here
348 else if (!game.deletedByWhite || !game.deletedByBlack) {
349 // Set score if game isn't deleted on server:
350 ajax(
351 "/games",
352 "PUT",
353 {
354 data: {
355 gid: game.id,
356 newObj: {
357 score: "?",
358 scoreMsg: getScoreMessage("?")
359 }
360 }
361 }
362 );
363 }
364 },
365 loadMore: function(type, cb) {
366 if (type == "corr" && this.st.user.id > 0) {
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;
378 moreGames.forEach(g => {
379 g.type = "corr";
380 g.options = JSON.parse(g.options);
381 });
382 this.decorate(moreGames);
383 this.corrGames = this.corrGames.concat(moreGames);
384 }
385 else this.hasMore["corr"] = false;
386 if (!!cb) cb();
387 }
388 }
389 );
390 }
391 else if (type == "live") {
392 GameStorage.getNext(this.cursor["live"], localGames => {
393 const L = localGames.length;
394 if (L > 0) {
395 // Add "-1" because IDBKeyRange.upperBound includes boundary
396 this.cursor["live"] = localGames[L - 1].created - 1;
397 localGames.forEach(g => {
398 g.type = "live";
399 // TODO: remove patch on next line (options || "{}")
400 g.options = JSON.parse(g.options || "{}");
401 });
402 this.decorate(localGames);
403 this.liveGames = this.liveGames.concat(localGames);
404 }
405 else this.hasMore["live"] = false;
406 if (!!cb) cb();
407 });
408 }
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;
415 importGames.forEach(g => {
416 g.type = "import";
417 // TODO: remove following patch (options || "{}")
418 g.options = JSON.parse(g.options || "{}");
419 this.setVname(g);
420 });
421 this.importGames = this.importGames.concat(importGames);
422 }
423 else this.hasMore["import"] = false;
424 if (!!cb) cb();
425 });
426 }
427 }
428 }
429 };
430 </script>
431
432 <style lang="sass" scoped>
433 .active
434 color: #388e3c
435
436 .tabbtn
437 background-color: #f9faee
438
439 button#loadMoreBtn
440 display: block
441 margin: 0 auto
442
443 .somethingnew
444 background-color: #90C4EC !important
445 </style>
446
447 <!-- Not scoped because acting on GameList -->
448 <style lang="sass">
449 table.game-list
450 max-height: 100%
451 </style>