aboutsummaryrefslogtreecommitdiffstats
path: root/js/vapi-storage.js
blob: 7b45ef13a9901ab2ab233415fd91e9c0c013d771 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*******************************************************************************

    ηMatrix - a browser extension to black/white list requests.
    Copyright (C) 2014-2019 The uMatrix/uBlock Origin authors
    Copyright (C) 2019-2020 Alessio Vanni

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see {http://www.gnu.org/licenses/}.

    Home: https://libregit.org/heckyel/ematrix
    uMatrix Home: https://github.com/gorhill/uMatrix
*/

'use strict';

/******************************************************************************/

(function () {
    // API matches that of chrome.storage.local:
    // https://developer.chrome.com/extensions/storage
    vAPI.storage = (function () {
        let db = null;
        let vacuumTimer = null;

        let close = function () {
            if (vacuumTimer !== null) {
                clearTimeout(vacuumTimer);
                vacuumTimer = null;
            }

            if (db === null) {
                return;
            }

            db.asyncClose();
            db = null;
        };

        let open = function () {
            if (db !== null) {
                return db;
            }

            // Create path
            let path = Services.dirsvc.get('ProfD', Ci.nsIFile);
            path.append('ematrix-data');
            if (!path.exists()) {
                path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
            }
            if (!path.isDirectory()) {
                throw Error('Should be a directory...');
            }

            let path2 = Services.dirsvc.get('ProfD', Ci.nsIFile);
            path2.append('extension-data');
            path2.append(location.host + '.sqlite');
            if (path2.exists()) {
                path2.moveTo(path, location.host+'.sqlite');
            }

            path.append(location.host + '.sqlite');

            // Open database
            try {
                db = Services.storage.openDatabase(path);
                if (db.connectionReady === false) {
                    db.asyncClose();
                    db = null;
                }
            } catch (ex) {
                // Ignore
            }

            if (db === null) {
                return null;
            }

            // Database was opened, register cleanup task
            vAPI.addCleanUpTask(close);

            // Setup database
            db.createAsyncStatement('CREATE TABLE IF NOT EXISTS '
                                    +'"settings" ("name" '
                                    +'TEXT PRIMARY KEY NOT NULL, '
                                    +'"value" TEXT);')
                .executeAsync();

            if (vacuum !== null) {
                vacuumTimer = vAPI.setTimeout(vacuum, 60000);
            }

            return db;
        };

        // Vacuum only once, and only while idle
        let vacuum = function () {
            vacuumTimer = null;
            if (db === null) {
                return;
            }
            let idleSvc =
                Cc['@mozilla.org/widget/idleservice;1']
                .getService(Ci.nsIIdleService);

            if (idleSvc.idleTime < 60000) {
                vacuumTimer = vAPI.setTimeout(vacuum, 60000);
                return;
            }

            db.createAsyncStatement('VACUUM').executeAsync();
            vacuum = null;
        };

        // Execute a query
        let runStatement = function (stmt, callback) {
            let result = {};

            stmt.executeAsync({
                handleResult: function (rows) {
                    if (!rows || typeof callback !== 'function') {
                        return;
                    }

                    let row;
                    while ((row = rows.getNextRow())) {
                        // we assume that there will be two columns, since we're
                        // using it only for preferences
                        // eMatrix: the above comment is obsolete
                        // (it's not used just for preferences
                        // anymore), but we still expect two columns.
                        let res = row.getResultByIndex(0);
                        result[res] = row.getResultByIndex(1);
                    }
                },
                handleCompletion: function (reason) {
                    if (typeof callback === 'function' && reason === 0) {
                        callback(result);
                    }
                },
                handleError: function (error) {
                    console.error('SQLite error ', error.result, error.message);

                    // Caller expects an answer regardless of failure.
                    if (typeof callback === 'function' ) {
                        callback(null);
                    }
                },
            });
        };

        let bindNames = function (stmt, names) {
            if (Array.isArray(names) === false || names.length === 0) {
                return;
            }

            let params = stmt.newBindingParamsArray();

            for (let i=names.length-1; i>=0; --i) {
                let bp = params.newBindingParams();
                bp.bindByName('name', names[i]);
                params.addParams(bp);
            }

            stmt.bindParameters(params);
        };

        let clear = function (callback) {
            if (open() === null) {
                if (typeof callback === 'function') {
                    callback();
                }
                return;
            }

            runStatement(db.createAsyncStatement('DELETE FROM "settings";'),
                         callback);
        };

        let getBytesInUse = function (keys, callback) {
            if (typeof callback !== 'function') {
                return;
            }

            if (open() === null) {
                callback(0);
                return;
            }

            let stmt;
            if (Array.isArray(keys)) {
                stmt = db.createAsyncStatement('SELECT "size" AS "size", '
                                               +'SUM(LENGTH("value")) '
                                               +'FROM "settings" WHERE '
                                               +'"name" = :name');
                bindNames(keys);
            } else {
                stmt = db.createAsyncStatement('SELECT "size" AS "size", '
                                               +'SUM(LENGTH("value")) '
                                               +'FROM "settings"');
            }

            runStatement(stmt, function (result) {
                callback(result.size);
            });
        };

        let read = function (details, callback) {
            if (typeof callback !== 'function') {
                return;
            }

            let prepareResult = function (result) {
                for (let key in result) {
                    if (result.hasOwnProperty(key) === false) {
                        continue;
                    }

                    result[key] = JSON.parse(result[key]);
                }

                if (typeof details === 'object' && details !== null) {
                    for (let key in details) {
                        if (result.hasOwnProperty(key) === false) {
                            result[key] = details[key];
                        }
                    }
                }

                callback(result);
            };

            if (open() === null) {
                prepareResult({});
                return;
            }

            let names = [];
            if (details !== null) {
                if (Array.isArray(details)) {
                    names = details;
                } else if (typeof details === 'object') {
                    names = Object.keys(details);
                } else {
                    names = [details.toString()];
                }
            }

            let stmt;
            if (names.length === 0) {
                stmt = db.createAsyncStatement('SELECT * FROM "settings"');
            } else {
                stmt = db.createAsyncStatement('SELECT * FROM "settings" '
                                               +'WHERE "name" = :name');
                bindNames(stmt, names);
            }

            runStatement(stmt, prepareResult);
        };

        let remove = function (keys, callback) {
            if (open() === null) {
                if (typeof callback === 'function') {
                    callback();
                }
                return;
            }

            var stmt = db.createAsyncStatement('DELETE FROM "settings" '
                                               +'WHERE "name" = :name');
            bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
            runStatement(stmt, callback);
        };

        let write = function (details, callback) {
            if (open() === null) {
                if (typeof callback === 'function') {
                    callback();
                }
                return;
            }

            let stmt = db.createAsyncStatement('INSERT OR REPLACE INTO '
                                               +'"settings" ("name", "value") '
                                               +'VALUES(:name, :value)');
            let params = stmt.newBindingParamsArray();

            for (let key in details) {
                if (details.hasOwnProperty(key) === false) {
                    continue;
                }

                let bp = params.newBindingParams();
                bp.bindByName('name', key);
                bp.bindByName('value', JSON.stringify(details[key]));
                params.addParams(bp);
            }

            if (params.length === 0) {
                return;
            }

            stmt.bindParameters(params);
            runStatement(stmt, callback);
        };

        // Export API
        var api = {
            QUOTA_BYTES: 100 * 1024 * 1024,
            clear: clear,
            get: read,
            getBytesInUse: getBytesInUse,
            remove: remove,
            set: write
        };

        return api;
    })();

    vAPI.cacheStorage = vAPI.storage;
})();