2014-06-18 21:19:56 +00:00
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
|
|
|
|
|
|
|
const {Cu, CC} = require("chrome");
|
2015-03-21 09:51:00 +00:00
|
|
|
const promise = require("promise");
|
2014-06-18 21:19:56 +00:00
|
|
|
const {Services} = Cu.import("resource://gre/modules/Services.jsm");
|
|
|
|
|
|
|
|
const XMLHttpRequest = CC("@mozilla.org/xmlextras/xmlhttprequest;1");
|
|
|
|
|
2015-03-21 09:51:00 +00:00
|
|
|
// Downloads and caches a JSON file from a URL given by the pref.
|
|
|
|
exports.getJSON = function (prefName, bypassCache) {
|
2014-06-18 21:19:56 +00:00
|
|
|
if (!bypassCache) {
|
|
|
|
try {
|
2015-03-21 09:51:00 +00:00
|
|
|
let str = Services.prefs.getCharPref(prefName + "_cache");
|
2014-06-18 21:19:56 +00:00
|
|
|
let json = JSON.parse(str);
|
|
|
|
return promise.resolve(json);
|
|
|
|
} catch(e) {/* no pref or invalid json. Let's continue */}
|
|
|
|
}
|
|
|
|
|
|
|
|
let deferred = promise.defer();
|
|
|
|
let xhr = new XMLHttpRequest();
|
|
|
|
|
|
|
|
xhr.onload = () => {
|
|
|
|
let json;
|
|
|
|
try {
|
|
|
|
json = JSON.parse(xhr.responseText);
|
|
|
|
} catch(e) {
|
2015-03-21 09:51:00 +00:00
|
|
|
return deferred.reject("Invalid JSON");
|
2014-06-18 21:19:56 +00:00
|
|
|
}
|
2015-03-21 09:51:00 +00:00
|
|
|
Services.prefs.setCharPref(prefName + "_cache", xhr.responseText);
|
2014-06-18 21:19:56 +00:00
|
|
|
deferred.resolve(json);
|
|
|
|
}
|
|
|
|
|
|
|
|
xhr.onerror = (e) => {
|
|
|
|
deferred.reject("Network error");
|
|
|
|
}
|
|
|
|
|
2015-03-21 09:51:00 +00:00
|
|
|
xhr.open("get", Services.prefs.getCharPref(prefName));
|
2014-06-18 21:19:56 +00:00
|
|
|
xhr.send();
|
|
|
|
|
|
|
|
return deferred.promise;
|
|
|
|
}
|