File indexing completed on 2024-04-28 05:32:50

0001 /*
0002     Copyright (C) 2019 Kai Uwe Broulik <kde@privat.broulik.de>
0003 
0004     This program is free software; you can redistribute it and/or
0005     modify it under the terms of the GNU General Public License as
0006     published by the Free Software Foundation; either version 3 of
0007     the License, or (at your option) any later version.
0008 
0009     This program is distributed in the hope that it will be useful,
0010     but WITHOUT ANY WARRANTY; without even the implied warranty of
0011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0012     GNU General Public License for more details.
0013 
0014     You should have received a copy of the GNU General Public License
0015     along with this program.  If not, see <http://www.gnu.org/licenses/>.
0016  */
0017 
0018 class SettingsUtils {
0019     static storage() {
0020         return (IS_FIREFOX ? chrome.storage.local : chrome.storage.sync);
0021     }
0022 
0023     static get() {
0024         return new Promise((resolve, reject) => {
0025             SettingsUtils.storage().get(null /* get all */, (items) => {
0026                 const error = chrome.runtime.lastError;
0027                 if (error) {
0028                     return reject(error);
0029                 }
0030 
0031                 // Passing a default Object get() only returns defaults for the top level of the object,
0032                 // so we need to merge the level underneath manually.
0033                 const addObjectInto = (obj, add) => {
0034                     if (typeof add !== "object" || Array.isArray(add)) {
0035                         return;
0036                     }
0037 
0038                     Object.keys(add).forEach((key) => {
0039                         if (obj.hasOwnProperty(key)) {
0040                             addObjectInto(obj[key], add[key]);
0041                         } else {
0042                             obj[key] = add[key];
0043                         }
0044                     });
0045                 };
0046 
0047                 addObjectInto(items, DEFAULT_EXTENSION_SETTINGS);
0048                 resolve(items);
0049             });
0050         });
0051     }
0052 
0053     static set(settings) {
0054         return new Promise((resolve, reject) => {
0055             try {
0056                 SettingsUtils.storage().set(settings, () => {
0057                     const error = chrome.runtime.lastError;
0058                     if (error) {
0059                         return reject(error);
0060                     }
0061 
0062                     resolve();
0063                 });
0064             } catch (e) {
0065                 reject(e);
0066             }
0067         });
0068     }
0069 
0070     static onChanged() {
0071         return chrome.storage.onChanged;
0072     }
0073 }