109c8251c04e90e2a99534e0064b6a771373380e
[vchess.git] / client / src / utils / gameStorage.js
1 // Game object: {
2 // // Static informations:
3 // id: string
4 // vname: string,
5 // fenStart: string,
6 // players: array of sid+id+name,
7 // cadence: string,
8 // increment: integer (seconds),
9 // type: string ("live" or "corr")
10 // // Game (dynamic) state:
11 // fen: string,
12 // moves: array of Move objects,
13 // clocks: array of integers,
14 // initime: array of integers (when clock start running),
15 // score: string (several options; '*' == running),
16 // }
17
18 import { store } from "@/store";
19
20 function dbOperation(callback) {
21 let db = null;
22 let DBOpenRequest = window.indexedDB.open("vchess", 5);
23
24 DBOpenRequest.onerror = function(event) {
25 alert(store.state.tr[
26 "Database error: stop private browsing, or update your browser"]);
27 callback("error", null);
28 };
29
30 DBOpenRequest.onsuccess = function() {
31 db = DBOpenRequest.result;
32 callback(null, db);
33 db.close();
34 };
35
36 DBOpenRequest.onupgradeneeded = function(event) {
37 let db = event.target.result;
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 });
50 };
51 }
52
53 export const GameStorage = {
54 // Optional callback to get error status
55 add: function(game, callback) {
56 dbOperation((err, db) => {
57 if (!!err) {
58 callback("error");
59 return;
60 }
61 let transaction = db.transaction("games", "readwrite");
62 transaction.oncomplete = function() {
63 // Everything's fine
64 callback();
65 };
66 transaction.onerror = function(err) {
67 // Duplicate key error (most likely)
68 callback(err);
69 };
70 transaction.objectStore("games").add(game);
71 });
72 },
73
74 // obj: chat, move, fen, clocks, score[Msg], initime, ...
75 update: function(gameId, obj) {
76 // live
77 dbOperation((err, db) => {
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?
83 if (event.target.result) {
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]);
89 else if (k == "chat") game.chats.push(obj[k]);
90 else if (k == "delchat") game.chats = [];
91 else game[k] = obj[k];
92 });
93 objectStore.put(game); //save updated data
94 }
95 };
96 });
97 },
98
99 // Retrieve (all) running local games
100 getRunning: function(callback) {
101 dbOperation((err, db) => {
102 let objectStore = db
103 .transaction("games", "readonly")
104 .objectStore("games");
105 let index = objectStore.index("score");
106 const range = IDBKeyRange.only("*");
107 let games = [];
108 index.openCursor(range).onsuccess = function(event) {
109 let cursor = event.target.result;
110 if (!cursor) callback(games);
111 else {
112 // If there is still another cursor to go, keep running this code
113 let g = cursor.value;
114 // Do not retrieve moves or clocks (unused in list mode)
115 g.movesCount = g.moves.length;
116 delete g.moves;
117 delete g.clocks;
118 delete g.initime;
119 games.push(g);
120 cursor.continue();
121 }
122 };
123 });
124 },
125
126 // Retrieve completed local games
127 getNext: function(upperDt, callback) {
128 dbOperation((err, db) => {
129 let objectStore = db
130 .transaction("games", "readonly")
131 .objectStore("games");
132 let index = objectStore.index("created");
133 const range = IDBKeyRange.upperBound(upperDt);
134 let games = [];
135 index.openCursor(range).onsuccess = function(event) {
136 let cursor = event.target.result;
137 if (!cursor) {
138 // Most recent games first:
139 games = games.sort((g1, g2) => g2.created - g1.created);
140 // TODO: 20 games showed per request is arbitrary
141 callback(games.slice(0, 20));
142 }
143 else {
144 // If there is still another cursor to go, keep running this code
145 let g = cursor.value;
146 if (g.score != "*") {
147 // Do not retrieve moves or clocks (unused in list mode)
148 g.movesCount = g.moves.length;
149 delete g.moves;
150 delete g.clocks;
151 delete g.initime;
152 games.push(g);
153 }
154 cursor.continue();
155 }
156 };
157 });
158 },
159
160 // Retrieve any game from its identifier.
161 // NOTE: need callback because result is obtained asynchronously
162 get: function(gameId, callback) {
163 dbOperation((err, db) => {
164 let objectStore = db.transaction("games").objectStore("games");
165 objectStore.get(gameId).onsuccess = function(event) {
166 // event.target.result is null if game not found
167 callback(event.target.result);
168 };
169 });
170 },
171
172 // Delete a game in indexedDB
173 remove: function(gameId, callback) {
174 dbOperation((err, db) => {
175 if (!err) {
176 let transaction = db.transaction("games", "readwrite");
177 transaction.oncomplete = function() {
178 callback(); //everything's fine
179 };
180 transaction.objectStore("games").delete(gameId);
181 }
182 });
183 }
184 };