Better board size auto-adjust. Still far from perfect
[vchess.git] / client / src / utils / gameStorage.js
CommitLineData
967a2686
BA
1// Game object: {
2// // Static informations:
11667c79 3// id: string
967a2686
BA
4// vname: string,
5// fenStart: string,
6// players: array of sid+id+name,
71468011 7// cadence: string,
967a2686 8// increment: integer (seconds),
910d631b 9// type: string ("live" or "corr")
967a2686
BA
10// // Game (dynamic) state:
11// fen: string,
12// moves: array of Move objects,
13// clocks: array of integers,
809ba2aa 14// initime: array of integers (when clock start running),
967a2686
BA
15// score: string (several options; '*' == running),
16// }
17
602d6bef 18import { store } from "@/store";
fd7aea36 19
6808d7a1 20function dbOperation(callback) {
967a2686 21 let db = null;
76373619 22 let DBOpenRequest = window.indexedDB.open("vchess", 5);
967a2686
BA
23
24 DBOpenRequest.onerror = function(event) {
2c5d7b20
BA
25 alert(store.state.tr[
26 "Database error: stop private browsing, or update your browser"]);
934f7f70 27 callback("error", null);
967a2686
BA
28 };
29
6808d7a1 30 DBOpenRequest.onsuccess = function() {
967a2686 31 db = DBOpenRequest.result;
934f7f70 32 callback(null, db);
967a2686
BA
33 db.close();
34 };
35
36 DBOpenRequest.onupgradeneeded = function(event) {
37 let db = event.target.result;
bee36510
BA
38 let upgradeTransaction = event.target.transaction;
39 let objectStore = undefined;
40 if (!db.objectStoreNames.contains("games"))
41 objectStore = db.createObjectStore("games", { keyPath: "id" });
42 else
43 objectStore = upgradeTransaction.objectStore("games");
44 if (!objectStore.indexNames.contains("score"))
45 // To sarch games by score (useful for running games)
46 objectStore.createIndex("score", "score", { unique: false });
47 if (!objectStore.indexNames.contains("created"))
48 // To search by date intervals. Two games cannot start at the same time
49 objectStore.createIndex("created", "created", { unique: true });
6808d7a1 50 };
967a2686
BA
51}
52
6808d7a1 53export const GameStorage = {
937c24ab 54
967a2686 55 // Optional callback to get error status
6808d7a1 56 add: function(game, callback) {
5f918a27 57 dbOperation((err, db) => {
c292ebb2 58 if (!!err) {
8477e53d
BA
59 callback("error");
60 return;
967a2686 61 }
8477e53d
BA
62 let transaction = db.transaction("games", "readwrite");
63 transaction.oncomplete = function() {
934f7f70
BA
64 // Everything's fine
65 callback();
8477e53d 66 };
c292ebb2 67 transaction.onerror = function(err) {
934f7f70
BA
68 // Duplicate key error (most likely)
69 callback(err);
c292ebb2 70 };
934f7f70 71 transaction.objectStore("games").add(game);
967a2686
BA
72 });
73 },
74
dcd68c41 75 // obj: chat, move, fen, clocks, score[Msg], initime, ...
6808d7a1 76 update: function(gameId, obj) {
5f918a27 77 dbOperation((err, db) => {
aae89b49
BA
78 let objectStore = db
79 .transaction("games", "readwrite")
80 .objectStore("games");
81 objectStore.get(gameId).onsuccess = function(event) {
82 // Ignoring error silently: shouldn't happen now. TODO?
cc25444a 83 if (!!event.target.result) {
aae89b49
BA
84 let game = event.target.result;
85 // Hidden tabs are delayed, to prevent multi-updates:
86 if (obj.moveIdx < game.moves.length) return;
87 Object.keys(obj).forEach(k => {
88 if (k == "move") game.moves.push(obj[k]);
1a021529 89 else if (k == "chat") game.chats.push(obj[k]);
1ef65040 90 else if (k == "chatRead") game.chatRead = Date.now();
1a021529 91 else if (k == "delchat") game.chats = [];
d4605a02
BA
92 else if (k == "playerName")
93 game.players[obj[k].idx].name = obj[k].name;
aae89b49
BA
94 else game[k] = obj[k];
95 });
96 objectStore.put(game); //save updated data
3d55deea 97 }
aae89b49
BA
98 };
99 });
967a2686
BA
100 },
101
934f7f70
BA
102 // Retrieve (all) running local games
103 getRunning: function(callback) {
5f918a27 104 dbOperation((err, db) => {
934f7f70
BA
105 let objectStore = db
106 .transaction("games", "readonly")
107 .objectStore("games");
108 let index = objectStore.index("score");
109 const range = IDBKeyRange.only("*");
fd7aea36 110 let games = [];
934f7f70 111 index.openCursor(range).onsuccess = function(event) {
fd7aea36 112 let cursor = event.target.result;
934f7f70
BA
113 if (!cursor) callback(games);
114 else {
115 // If there is still another cursor to go, keep running this code
db1f1f9a 116 let g = cursor.value;
6b7b2cf7
BA
117 // Do not retrieve moves or clocks (unused in list mode)
118 g.movesCount = g.moves.length;
119 delete g.moves;
120 delete g.clocks;
121 delete g.initime;
db1f1f9a 122 games.push(g);
fd7aea36 123 cursor.continue();
934f7f70
BA
124 }
125 };
126 });
127 },
128
129 // Retrieve completed local games
130 getNext: function(upperDt, callback) {
5f918a27 131 dbOperation((err, db) => {
934f7f70
BA
132 let objectStore = db
133 .transaction("games", "readonly")
134 .objectStore("games");
135 let index = objectStore.index("created");
136 const range = IDBKeyRange.upperBound(upperDt);
137 let games = [];
138 index.openCursor(range).onsuccess = function(event) {
139 let cursor = event.target.result;
140 if (!cursor) {
141 // Most recent games first:
142 games = games.sort((g1, g2) => g2.created - g1.created);
143 // TODO: 20 games showed per request is arbitrary
144 callback(games.slice(0, 20));
145 }
146 else {
147 // If there is still another cursor to go, keep running this code
148 let g = cursor.value;
149 if (g.score != "*") {
150 // Do not retrieve moves or clocks (unused in list mode)
151 g.movesCount = g.moves.length;
152 delete g.moves;
153 delete g.clocks;
154 delete g.initime;
155 games.push(g);
156 }
157 cursor.continue();
158 }
6808d7a1 159 };
fd7aea36
BA
160 });
161 },
162
5f918a27 163 // Retrieve any game from its identifier.
fd7aea36 164 // NOTE: need callback because result is obtained asynchronously
6808d7a1 165 get: function(gameId, callback) {
5f918a27 166 dbOperation((err, db) => {
aae89b49
BA
167 let objectStore = db.transaction("games").objectStore("games");
168 objectStore.get(gameId).onsuccess = function(event) {
f54f4c26
BA
169 // event.target.result is null if game not found
170 callback(event.target.result);
aae89b49
BA
171 };
172 });
967a2686
BA
173 },
174
175 // Delete a game in indexedDB
6808d7a1 176 remove: function(gameId, callback) {
5f918a27 177 dbOperation((err, db) => {
8477e53d 178 if (!err) {
934f7f70 179 let transaction = db.transaction("games", "readwrite");
967a2686 180 transaction.oncomplete = function() {
3b0f26c1 181 callback(); //everything's fine
6808d7a1 182 };
8477e53d 183 transaction.objectStore("games").delete(gameId);
967a2686 184 }
967a2686 185 });
6808d7a1 186 }
937c24ab 187
967a2686 188};