Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backup/restore settings to/from a file #1533

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/js/background/backgroundLogic.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,93 @@ const backgroundLogic = {
return browser.tabs.remove(tabIds);
},

async backupIdentitiesState() {
const identities = await browser.contextualIdentities.query({});
return Promise.all(
identities.map(async ({ cookieStoreId, color, icon, name }) => {
const userContextId = this.getUserContextIdFromCookieStoreId(cookieStoreId);
const [
{ isIsolated },
sitesByContainer
] = await Promise.all([
identityState.storageArea.get(cookieStoreId),
assignManager.storageArea.getAssignedSites(userContextId)
]);
const sites = Object.values(sitesByContainer).map(({ neverAsk, hostname }) => ({ neverAsk, hostname }));
return ({
color,
icon,
name,
isolated: isIsolated && true, // either `true` or `undefined`
sites
});
})
);
},

async restoreIdentitiesState(identities) {
const backup = await browser.contextualIdentities.query({});
const incomplete = [];
let allSucceed = true;
const identitiesPromise = identities.map(async ({ color, icon, name, isolated, sites }) => {
try {
if (
typeof color !== "string" ||
typeof icon !== "string" ||
typeof name !== "string" ||
(isolated !== true && isolated !== undefined) ||
!Array.isArray((sites))
)
throw new Error("Corrupted container backup");
const identity = await browser.contextualIdentities.create({ color, icon, name });
try {
await identityState.storageArea.get(identity.cookieStoreId); // to create identity state
const userContextId = this.getUserContextIdFromCookieStoreId(identity.cookieStoreId);
for (const { neverAsk, hostname } of sites) {
if (typeof neverAsk !== "boolean" || typeof hostname !== "string" || hostname === "")
throw new Error("Corrupted site association");
const pageUrl = `http://${hostname}`; // protocol doesn't really matter here
await assignManager.storageArea.set(pageUrl, {
neverAsk,
userContextId
});
}
if (isolated)
await identityState.storageArea.set(identity.cookieStoreId, { isIsolated: "locked" });
} catch (err) {
incomplete.push(name); // site association damaged
}
return identity;
} catch (err) {
allSucceed = false;
return null;
}
});

const created = await Promise.all(identitiesPromise);
if (!allSucceed) { // Importation failed, restore previous state
await Promise.all(
created.map(async (identityOrNull) => {
if (identityOrNull) {
await identityState.storageArea.remove(identityOrNull.cookieStoreId);
await browser.contextualIdentities.remove(identityOrNull.cookieStoreId);
}
})
);
throw new Error("Some containers couldn't be created");
}

// Importation succeed, remove old identities
await Promise.all(
backup.map(async (identity) => {
await identityState.storageArea.remove(identity.cookieStoreId);
await browser.contextualIdentities.remove(identity.cookieStoreId);
})
);

return { created: created.length, incomplete };
},

async queryIdentitiesState(windowId) {
const identities = await browser.contextualIdentities.query({});
const identitiesOutput = {};
Expand Down
6 changes: 6 additions & 0 deletions src/js/background/messageHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ const messageHandler = {
windowId: m.windowId
});
break;
case "backupIdentitiesState":
response = backgroundLogic.backupIdentitiesState();
break;
case "restoreIdentitiesState":
response = backgroundLogic.restoreIdentitiesState(m.identities);
break;
case "queryIdentitiesState":
response = backgroundLogic.queryIdentitiesState(m.message.windowId);
break;
Expand Down
57 changes: 56 additions & 1 deletion src/js/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,56 @@ async function enableDisableReplaceTab() {
await browser.storage.local.set({replaceTabEnabled: !!checkbox.checked});
}

async function backupContainers() {
const backupLink = document.getElementById("containers-save-link");
const backupResult = document.getElementById("containers-save-result");
try {
const content = JSON.stringify(
await browser.runtime.sendMessage({
method: "backupIdentitiesState"
})

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty-printing the JSON file would make it a lot easier to read and make diffs, etc.

const content = JSON.stringify(
  await browser.runtime.sendMessage({
    method: "backupIdentitiesState"
  }),
  null,
  2
);

);
backupLink.href = `data:application/json;base64,${btoa(content)}`;
backupLink.download = `containers-backup-${(new Date()).toISOString()}.json`;
backupLink.click();
backupResult.textContent = "";
} catch (err) {
backupResult.textContent = browser.i18n.getMessage("backupFailure", [String(err.message || err)]);
backupResult.style.color = "red";
}
}

async function restoreContainers(event) {
const restoreInput = event.currentTarget;
const restoreResult = document.getElementById("containers-restore-result");
event.preventDefault();
if (restoreInput.files.length) {
const reader = new FileReader();
reader.onloadend = async () => {
try {
const identitiesState = JSON.parse(reader.result);
const { created: restoredCount, incomplete } = await browser.runtime.sendMessage({
method: "restoreIdentitiesState",
identities: identitiesState
});
if (incomplete.length === 0) {
restoreResult.textContent = browser.i18n.getMessage("containersRestored", [String(restoredCount)]);
restoreResult.style.color = "green";
} else {
restoreResult.textContent = browser.i18n.getMessage("containersPartiallyRestored", [String(restoredCount), String(incomplete.join(", "))]);
restoreResult.style.color = "orange";
}
} catch (err) {
console.error("Cannot restore containers list: %s", err.message || err);
restoreResult.textContent = browser.i18n.getMessage("containersRestorationFailed");
restoreResult.style.color = "red";
}
};
reader.readAsText(restoreInput.files.item(0));
}
restoreInput.value = "";
}

async function changeTheme(event) {
const theme = event.currentTarget;
await browser.storage.local.set({currentTheme: theme.value});
Expand Down Expand Up @@ -123,6 +173,7 @@ browser.permissions.onRemoved.addListener(resetPermissionsUi);
document.addEventListener("DOMContentLoaded", setupOptions);
document.querySelector("#syncCheck").addEventListener( "change", enableDisableSync);
document.querySelector("#replaceTabCheck").addEventListener( "change", enableDisableReplaceTab);
document.querySelector("#containersRestoreInput").addEventListener( "change", restoreContainers);
document.querySelector("#changeTheme").addEventListener( "change", changeTheme);

maybeShowPermissionsWarningIcon();
Expand All @@ -132,8 +183,12 @@ for (let i=0; i < NUMBER_OF_KEYBOARD_SHORTCUTS; i++) {
}

document.querySelectorAll("[data-btn-id]").forEach(btn => {
btn.addEventListener("click", () => {
btn.addEventListener("click", e => {
switch (btn.dataset.btnId) {
case "containers-save-button":
e.preventDefault();
backupContainers();
break;
case "reset-onboarding":
resetOnboarding();
break;
Expand Down
18 changes: 18 additions & 0 deletions src/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ <h3 data-i18n-message-id="tabBehavior"></h3>
<p><em data-i18n-message-id="replaceTabDescription"></em></p>
</div>

<h3 data-i18n-message-id="backup"></h3>

<div class="settings-group">
<fieldset>
<legend data-i18n-message-id="restoreLegend"></legend>
<input id="containersRestoreInput" type="file">
<p><em id="containers-restore-result"></em></p>
<p data-i18n-message-id="warningConfigOverride"></p>
</fieldset>
<fieldset>
<legend data-i18n-message-id="saveLegend"></legend>
<a id="containers-save-link" href="#" style="display: none;"></a>
<button data-i18n-message-id="saveButton" data-btn-id="containers-save-button"></button>
<p><em id="containers-save-result"></em></p>
<p data-i18n-message-id="noteWontBackupCookies"></p>
</fieldset>
</div>

<!--
TODO
- Add data-i18n
Expand Down