Skip to content
This repository has been archived by the owner on Jan 17, 2023. It is now read-only.

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
ianb committed Mar 21, 2017
2 parents 62ab422 + e220088 commit 0dde08e
Show file tree
Hide file tree
Showing 16 changed files with 308 additions and 90 deletions.
116 changes: 98 additions & 18 deletions addon/bootstrap.js
@@ -1,38 +1,118 @@
/* globals Components, AddonManager */
/* eslint-disable no-unused-vars */
/* globals AddonManager, Components, Services */

const OLD_ADDON_PREF_NAME = "extensions.jid1-NeEaf3sAHdKHPA@jetpack.deviceIdInfo";
const OLD_ADDON_ID = "jid1-NeEaf3sAHdKHPA@jetpack";
const ADDON_ID = "pageshot@mozilla.org";
const TELEMETRY_PREF = "toolkit.telemetry.enabled";
const PREF_BRANCH = "extensions.pageshot.";
const USER_DISABLE_PREF = "extensions.pageshot.disabled";
const SYSTEM_DISABLE_PREF = "extensions.pageshot.system-disabled";

const prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
Components.utils.import("resource://gre/modules/AddonManager.jsm");
const { interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/Console.jsm");
Cu.import("resource://gre/modules/Services.jsm");
const { EmbeddedExtensionManager } = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm");

function startup(data, reason) {
data.webExtension.startup().then((api) => {
const {browser} = api;
browser.runtime.onMessage.addListener(handleMessage);
const prefs = Services.prefs;
const prefObserver = {
register: function() {
prefs.addObserver(PREF_BRANCH, this, false);
},

unregister: function() {
prefs.removeObserver(PREF_BRANCH, this);
},

observe: function(aSubject, aTopic, aData) {
// aSubject is the nsIPrefBranch we're observing (after appropriate QI)
// aData is the name of the pref that's been changed (relative to aSubject)
if (aData == USER_DISABLE_PREF || aData == SYSTEM_DISABLE_PREF) {
handleStartup();
}
}
};

function startup(data, reason) { // eslint-disable-line no-unused-vars
prefObserver.register();
handleStartup();
}

function shutdown(data, reason) { // eslint-disable-line no-unused-vars
prefObserver.unregister();
}

function install(data, reason) {} // eslint-disable-line no-unused-vars

function uninstall(data, reason) {} // eslint-disable-line no-unused-vars

function getBoolPref(pref) {
return prefs.getPrefType(pref) && prefs.getBoolPref(pref);
}

function shouldDisable() {
return getBoolPref(USER_DISABLE_PREF) || getBoolPref(SYSTEM_DISABLE_PREF);
}

function handleStartup() {
AddonManager.getAddonByID(ADDON_ID).then((addon) => {
if (addon === null) {
console.error("Unable to start WebExtension: wrapper addon not found");
// TODO: Should we send this error to Sentry? #2420
return;
}

const webExtension = EmbeddedExtensionManager.getEmbeddedExtensionFor({
id: ADDON_ID,
resourceURI: addon.getResourceURI().QueryInterface(Ci.nsIFileURL)
});

if (!shouldDisable() && !webExtension.started) {
start(webExtension);
} else if (shouldDisable()) {
stop(webExtension);
}
});
}

function start(webExtension) {
webExtension.startup().then((api) => {
api.browser.runtime.onMessage.addListener(handleMessage);
}).catch((err) => {
// The startup() promise will be rejected if the webExtension was
// already started (a harmless error), or if initializing the
// WebExtension failed and threw (an important error).
console.error(err);
if (err.message !== "This embedded extension has already been started") {
// TODO: Should we send these errors to Sentry? #2420
}
});
}

function shutdown(data, reason) {}
function install(data, reason) {}
function uninstall(data, reason) {}
function stop(webExtension) {
webExtension.shutdown().then(() => {
EmbeddedExtensionManager.untrackEmbeddedExtension(webExtension);
});
}

function handleMessage(msg, sender, sendReply) {
if (msg && msg.funcName === "getTelemetryPref") {
let enableTelemetry = prefs.getPrefType('toolkit.telemetry.enabled') && prefs.getBoolPref("toolkit.telemetry.enabled");
if (!msg) {
return;
}

if (msg.funcName === "getTelemetryPref") {
let enableTelemetry = getBoolPref(TELEMETRY_PREF);
sendReply({type: "success", value: enableTelemetry});
} else if (msg && msg.funcName === "getOldDeviceInfo") {
} else if (msg.funcName === "getOldDeviceInfo") {
let oldDeviceInfo = prefs.prefHasUserValue(OLD_ADDON_PREF_NAME) && prefs.getCharPref(OLD_ADDON_PREF_NAME);
sendReply({type: "success", value: oldDeviceInfo || null});
} else if (msg && msg.funcName === "removeOldAddon") {
} else if (msg.funcName === "removeOldAddon") {
AddonManager.getAddonByID(OLD_ADDON_ID, (addon) => {
// FIXME: remove OLD_ADDON_PREF_NAME, see #2370
prefs.clearUserPref(OLD_ADDON_PREF_NAME);
if (addon) {
addon.uninstall();
}
sendReply({type: "success", value: !! addon});
sendReply({type: "success", value: !!addon});
});
}
}
51 changes: 42 additions & 9 deletions addon/webextension/background/auth.js
@@ -1,5 +1,5 @@
/* globals browser */
/* globals main, makeUuid, deviceInfo, analytics, catcher, defaultSentryDsn */
/* globals main, makeUuid, deviceInfo, analytics, catcher, defaultSentryDsn, communication */

window.auth = (function () {
let exports = {};
Expand Down Expand Up @@ -47,7 +47,7 @@ window.auth = (function () {
console.info("Registered login");
initialized = true;
saveAuthInfo(JSON.parse(req.responseText));
resolve();
resolve(true);
analytics.sendEvent("registered");
} else {
console.warn("Error in response:", req.responseText);
Expand All @@ -62,15 +62,19 @@ window.auth = (function () {
});
}

function login() {
function login(options) {
let { ownershipCheck, noRegister } = options || {};
return new Promise((resolve, reject) => {
let loginUrl = main.getBackend() + "/api/login";
let req = new XMLHttpRequest();
req.open("POST", loginUrl);
req.onload = catcher.watchFunction(() => {
if (req.status == 404) {
// No such user
resolve(register());
if (noRegister) {
resolve(false);
} else {
resolve(register());
}
} else if (req.status >= 300) {
console.warn("Error in response:", req.responseText);
reject(new Error("Could not log in: " + req.status));
Expand All @@ -80,17 +84,29 @@ window.auth = (function () {
reject(error);
} else {
initialized = true;
let jsonResponse = JSON.parse(req.responseText);
console.info("Screenshots logged in");
analytics.sendEvent("login");
saveAuthInfo(JSON.parse(req.responseText));
resolve();
saveAuthInfo(jsonResponse);
if (ownershipCheck) {
resolve({isOwner: jsonResponse.isOwner});
} else {
resolve(true);
}
}
});
req.onerror = catcher.watchFunction(() => {
let exc = new Error("Connection failed");
exc.url = loginUrl;
exc.popupMessage = "CONNECTION_ERROR";
reject(exc);
});
req.setRequestHeader("content-type", "application/x-www-form-urlencoded");
req.send(uriEncode({
deviceId: registrationInfo.deviceId,
secret: registrationInfo.secret,
deviceInfo: JSON.stringify(deviceInfo())
deviceInfo: JSON.stringify(deviceInfo()),
ownershipCheck
}));
});
}
Expand All @@ -115,7 +131,9 @@ window.auth = (function () {
function uriEncode(obj) {
let s = [];
for (let key in obj) {
s.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
if (obj[key] !== undefined) {
s.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
}
}
return s.join("&");
}
Expand Down Expand Up @@ -171,5 +189,20 @@ window.auth = (function () {
});
};

communication.register("getAuthInfo", (sender, ownershipCheck) => {
let info = registrationInfo;
let done = Promise.resolve();
if (info.registered) {
done = login({ownershipCheck}).then((result) => {
if (result && result.isOwner) {
info.isOwner = true;
}
});
}
return done.then(() => {
return info;
});
});

return exports;
})();
3 changes: 2 additions & 1 deletion addon/webextension/background/communication.js
Expand Up @@ -21,14 +21,15 @@ window.communication = (function () {
req.args.unshift(sender);
result = func.apply(null, req.args);
} catch (e) {
console.error(`Error in ${req.funcName}:`, e);
console.error(`Error in ${req.funcName}:`, e, e.stack);
sendResponse({type: "error", name: e+""});
return;
}
if (result && result.then) {
result.then((concreteResult) => {
sendResponse({type: "success", value: concreteResult});
}, (errorResult) => {
console.error(`Promise error in ${req.funcName}:`, errorResult, errorResult && errorResult.stack);
sendResponse({type: "error", name: errorResult+""});
});
return true;
Expand Down
2 changes: 1 addition & 1 deletion addon/webextension/background/senderror.js
Expand Up @@ -48,7 +48,7 @@ window.errorpopup = (function () {
popupMessage = "generic";
}
let title = messages[popupMessage].title;
let message = messages[popupMessage].message || null;
let message = messages[popupMessage].message || '';
let showMessage = messages[popupMessage].showMessage;
if (error.message && showMessage) {
if (message) {
Expand Down
8 changes: 5 additions & 3 deletions addon/webextension/background/takeshot.js
Expand Up @@ -5,7 +5,7 @@ window.takeshot = (function () {
const Shot = shot.AbstractShot;
const { sendEvent } = analytics;

communication.register("takeShot", (sender, options) => {
communication.register("takeShot", catcher.watchFunction((sender, options) => {
let { captureType, captureText, scroll, selectedPos, shotId, shot } = options;
shot = new Shot(main.getBackend(), shotId, shot);
let capturePromise = Promise.resolve();
Expand Down Expand Up @@ -48,7 +48,7 @@ window.takeshot = (function () {
}).then(() => {
return shot.viewUrl;
}));
});
}));

communication.register("screenshotPage", (sender, selectedPos, scroll) => {
return screenshotPage(selectedPos, scroll);
Expand Down Expand Up @@ -106,7 +106,9 @@ window.takeshot = (function () {
}).then((resp) => {
if (! resp.ok) {
sendEvent("upload-failed", `status-${resp.status}`);
throw new Error("Error: response failed");
let exc = new Error(`Response failed with status ${resp.status}`);
exc.popupMessage = "REQUEST_ERROR";
throw exc;
} else {
sendEvent("upload", "success");
}
Expand Down
8 changes: 6 additions & 2 deletions addon/webextension/manifest.json.template
Expand Up @@ -46,8 +46,12 @@
},
"content_scripts": [
{
"matches": ["http://localhost:10080/*"],
"js": ["site-helper.js"],
"matches": ["http://localhost/*"],
"js": [
"catcher.js",
"selector/callBackground.js",
"sitehelper.js"
],
"run_at": "document_start"
}
],
Expand Down
48 changes: 0 additions & 48 deletions addon/webextension/site-helper.js

This file was deleted.

0 comments on commit 0dde08e

Please sign in to comment.