Skip to content

Commit

Permalink
Added backup to/restore from file feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Minigugus committed Jan 14, 2022
1 parent cb31410 commit 8b11a60
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 1 deletion.
64 changes: 64 additions & 0 deletions src/js/background/backgroundLogic.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,70 @@ 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 sitesByContainer = await assignManager.storageArea.getAssignedSites(userContextId);
const sites = Object.values(sitesByContainer).map(({ neverAsk, hostname }) => ({ neverAsk, hostname }));
return ({ color, icon, name, sites });
})
);
},

async restoreIdentitiesState(identities) {
const backup = await browser.contextualIdentities.query({});
const incomplete = [];
let allSucceed = true;
const identitiesPromise = identities.map(async ({ color, icon, name, sites }) => {
try {
if (typeof color !== "string" || typeof icon !== "string" || typeof name !== "string" || !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);
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
});
}
} 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");
} else { // 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"
})
);
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 setupOptions() {
const { syncEnabled } = await browser.storage.local.get("syncEnabled");
const { replaceTabEnabled } = await browser.storage.local.get("replaceTabEnabled");
Expand Down Expand Up @@ -114,15 +164,20 @@ 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);
maybeShowPermissionsWarningIcon();
for (let i=0; i < NUMBER_OF_KEYBOARD_SHORTCUTS; i++) {
document.querySelector("#open_container_"+i)
.addEventListener("change", storeShortcutChoice);
}

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>

<h3 data-i18n-message-id="keyboardShortCuts"></h3>
<p><em data-i18n-message-id="editWhichContainer"></em></p>

Expand Down

0 comments on commit 8b11a60

Please sign in to comment.