vapi-storage.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*******************************************************************************
  2. ηMatrix - a browser extension to black/white list requests.
  3. Copyright (C) 2014-2019 The uMatrix/uBlock Origin authors
  4. Copyright (C) 2019-2022 Alessio Vanni
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see {http://www.gnu.org/licenses/}.
  15. Home: https://gitlab.com/vannilla/ematrix
  16. uMatrix Home: https://github.com/gorhill/uMatrix
  17. */
  18. 'use strict';
  19. /******************************************************************************/
  20. (function () {
  21. // API matches that of chrome.storage.local:
  22. // https://developer.chrome.com/extensions/storage
  23. vAPI.storage = (function () {
  24. let db = null;
  25. let vacuumTimer = null;
  26. let close = function () {
  27. if (vacuumTimer !== null) {
  28. clearTimeout(vacuumTimer);
  29. vacuumTimer = null;
  30. }
  31. if (db === null) {
  32. return;
  33. }
  34. db.asyncClose();
  35. db = null;
  36. };
  37. let open = function () {
  38. if (db !== null) {
  39. return db;
  40. }
  41. // Create path
  42. let path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  43. path.append('ematrix-data');
  44. if (!path.exists()) {
  45. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  46. }
  47. if (!path.isDirectory()) {
  48. throw Error('Should be a directory...');
  49. }
  50. let path2 = Services.dirsvc.get('ProfD', Ci.nsIFile);
  51. path2.append('extension-data');
  52. path2.append(location.host + '.sqlite');
  53. if (path2.exists()) {
  54. path2.moveTo(path, location.host+'.sqlite');
  55. }
  56. path.append(location.host + '.sqlite');
  57. // Open database
  58. try {
  59. db = Services.storage.openDatabase(path);
  60. if (db.connectionReady === false) {
  61. db.asyncClose();
  62. db = null;
  63. }
  64. } catch (ex) {
  65. // Ignore
  66. }
  67. if (db === null) {
  68. return null;
  69. }
  70. // Database was opened, register cleanup task
  71. vAPI.addCleanUpTask(close);
  72. // Setup database
  73. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS '
  74. +'"settings" ("name" '
  75. +'TEXT PRIMARY KEY NOT NULL, '
  76. +'"value" TEXT);')
  77. .executeAsync();
  78. if (vacuum !== null) {
  79. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  80. }
  81. return db;
  82. };
  83. // Vacuum only once, and only while idle
  84. let vacuum = function () {
  85. vacuumTimer = null;
  86. if (db === null) {
  87. return;
  88. }
  89. let idleSvc =
  90. Cc['@mozilla.org/widget/idleservice;1']
  91. .getService(Ci.nsIIdleService);
  92. if (idleSvc.idleTime < 60000) {
  93. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  94. return;
  95. }
  96. db.createAsyncStatement('VACUUM').executeAsync();
  97. vacuum = null;
  98. };
  99. // Execute a query
  100. let runStatement = function (stmt, callback) {
  101. let result = {};
  102. stmt.executeAsync({
  103. handleResult: function (rows) {
  104. if (!rows || typeof callback !== 'function') {
  105. return;
  106. }
  107. let row;
  108. while ((row = rows.getNextRow())) {
  109. // we assume that there will be two columns, since we're
  110. // using it only for preferences
  111. // eMatrix: the above comment is obsolete
  112. // (it's not used just for preferences
  113. // anymore), but we still expect two columns.
  114. let res = row.getResultByIndex(0);
  115. result[res] = row.getResultByIndex(1);
  116. }
  117. },
  118. handleCompletion: function (reason) {
  119. if (typeof callback === 'function' && reason === 0) {
  120. callback(result);
  121. }
  122. },
  123. handleError: function (error) {
  124. console.error('SQLite error ', error.result, error.message);
  125. // Caller expects an answer regardless of failure.
  126. if (typeof callback === 'function' ) {
  127. callback(null);
  128. }
  129. },
  130. });
  131. };
  132. let bindNames = function (stmt, names) {
  133. if (Array.isArray(names) === false || names.length === 0) {
  134. return;
  135. }
  136. let params = stmt.newBindingParamsArray();
  137. for (let i=names.length-1; i>=0; --i) {
  138. let bp = params.newBindingParams();
  139. bp.bindByName('name', names[i]);
  140. params.addParams(bp);
  141. }
  142. stmt.bindParameters(params);
  143. };
  144. let clear = function (callback) {
  145. if (open() === null) {
  146. if (typeof callback === 'function') {
  147. callback();
  148. }
  149. return;
  150. }
  151. runStatement(db.createAsyncStatement('DELETE FROM "settings";'),
  152. callback);
  153. };
  154. let getBytesInUse = function (keys, callback) {
  155. if (typeof callback !== 'function') {
  156. return;
  157. }
  158. if (open() === null) {
  159. callback(0);
  160. return;
  161. }
  162. let stmt;
  163. if (Array.isArray(keys)) {
  164. stmt = db.createAsyncStatement('SELECT "size" AS "size", '
  165. +'SUM(LENGTH("value")) '
  166. +'FROM "settings" WHERE '
  167. +'"name" = :name');
  168. bindNames(keys);
  169. } else {
  170. stmt = db.createAsyncStatement('SELECT "size" AS "size", '
  171. +'SUM(LENGTH("value")) '
  172. +'FROM "settings"');
  173. }
  174. runStatement(stmt, function (result) {
  175. callback(result.size);
  176. });
  177. };
  178. let read = function (details, callback) {
  179. if (typeof callback !== 'function') {
  180. return;
  181. }
  182. let prepareResult = function (result) {
  183. for (let key in result) {
  184. if (result.hasOwnProperty(key) === false) {
  185. continue;
  186. }
  187. result[key] = JSON.parse(result[key]);
  188. }
  189. if (typeof details === 'object' && details !== null) {
  190. for (let key in details) {
  191. if (result.hasOwnProperty(key) === false) {
  192. result[key] = details[key];
  193. }
  194. }
  195. }
  196. callback(result);
  197. };
  198. if (open() === null) {
  199. prepareResult({});
  200. return;
  201. }
  202. let names = [];
  203. if (details !== null) {
  204. if (Array.isArray(details)) {
  205. names = details;
  206. } else if (typeof details === 'object') {
  207. names = Object.keys(details);
  208. } else {
  209. names = [details.toString()];
  210. }
  211. }
  212. let stmt;
  213. if (names.length === 0) {
  214. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  215. } else {
  216. stmt = db.createAsyncStatement('SELECT * FROM "settings" '
  217. +'WHERE "name" = :name');
  218. bindNames(stmt, names);
  219. }
  220. runStatement(stmt, prepareResult);
  221. };
  222. let remove = function (keys, callback) {
  223. if (open() === null) {
  224. if (typeof callback === 'function') {
  225. callback();
  226. }
  227. return;
  228. }
  229. var stmt = db.createAsyncStatement('DELETE FROM "settings" '
  230. +'WHERE "name" = :name');
  231. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  232. runStatement(stmt, callback);
  233. };
  234. let write = function (details, callback) {
  235. if (open() === null) {
  236. if (typeof callback === 'function') {
  237. callback();
  238. }
  239. return;
  240. }
  241. let stmt = db.createAsyncStatement('INSERT OR REPLACE INTO '
  242. +'"settings" ("name", "value") '
  243. +'VALUES(:name, :value)');
  244. let params = stmt.newBindingParamsArray();
  245. for (let key in details) {
  246. if (details.hasOwnProperty(key) === false) {
  247. continue;
  248. }
  249. let bp = params.newBindingParams();
  250. bp.bindByName('name', key);
  251. bp.bindByName('value', JSON.stringify(details[key]));
  252. params.addParams(bp);
  253. }
  254. if (params.length === 0) {
  255. return;
  256. }
  257. stmt.bindParameters(params);
  258. runStatement(stmt, callback);
  259. };
  260. // Export API
  261. var api = {
  262. QUOTA_BYTES: 100 * 1024 * 1024,
  263. clear: clear,
  264. get: read,
  265. getBytesInUse: getBytesInUse,
  266. remove: remove,
  267. set: write
  268. };
  269. return api;
  270. })();
  271. vAPI.cacheStorage = vAPI.storage;
  272. })();