Skip to content

Commit

Permalink
build background scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
gildas-lormeau committed Sep 25, 2021
1 parent 1fff69c commit 7ad42b0
Show file tree
Hide file tree
Showing 22 changed files with 428 additions and 276 deletions.
1 change: 1 addition & 0 deletions dist/extension-background.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions dist/single-file-background.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions extension/core/bg/autosave-util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2010-2020 Gildas Lormeau
* contact : gildas.lormeau <at> gmail.com
*
* This file is part of SingleFile.
*
* The code in this file is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* (GNU AGPL) as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* The code in this file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* As additional permission under GNU AGPL version 3 section 7, you may
* distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
* AGPL normally required by section 4, provided you include this license
* notice and a URL through which recipients can access the Corresponding
* Source.
*/

/* global browser */

import * as config from "./config.js";
import * as tabsData from "./tabs-data.js";

export {
autoSaveIsEnabled,
refreshAutoSaveTabs
};

async function autoSaveIsEnabled(tab) {
if (tab) {
const [allTabsData, rule] = await Promise.all([tabsData.get(), config.getRule(tab.url)]);
return Boolean(allTabsData.autoSaveAll ||
(allTabsData.autoSaveUnpinned && !tab.pinned) ||
(allTabsData[tab.id] && allTabsData[tab.id].autoSave)) &&
(!rule || rule.autoSaveProfile != config.DISABLED_PROFILE_NAME);
}
}

async function refreshAutoSaveTabs() {
const tabs = (await browser.tabs.query({}));
return Promise.all(tabs.map(async tab => {
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(tab.url, true), autoSaveIsEnabled(tab)]);
try {
await browser.tabs.sendMessage(tab.id, { method: "content.init", autoSaveEnabled, options });
} catch (error) {
// ignored
}
}));
}
36 changes: 6 additions & 30 deletions extension/core/bg/autosave.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
* Source.
*/

/* global infobar, URL, XMLHttpRequest, singlefile */
/* global browser, infobar, URL, XMLHttpRequest, singlefile */

import * as config from "./config.js";
import * as business from "./business.js";
import * as downloads from "./downloads.js";
import * as tabsData from "./tabs-data.js";
import * as tabs from "./tabs.js";
import * as ui from "./../../ui/bg/index.js";
import { getPageData } from "./../../index.js";
import { autoSaveIsEnabled } from "./autosave-util.js";

const pendingMessages = {};
const replacedTabIds = {};
Expand All @@ -38,8 +38,6 @@ export {
onMessage,
onMessageExternal,
onInit,
isEnabled,
refreshTabs,
onTabUpdated,
onTabRemoved,
onTabDiscarded,
Expand All @@ -48,7 +46,7 @@ export {

async function onMessage(message, sender) {
if (message.method.endsWith(".init")) {
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(sender.tab.url, true), isEnabled(sender.tab)]);
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(sender.tab.url, true), autoSaveIsEnabled(sender.tab)]);
return { options, autoSaveEnabled, tabId: sender.tab.id, tabIndex: sender.tab.index };
}
if (message.method.endsWith(".save")) {
Expand Down Expand Up @@ -123,39 +121,17 @@ async function onMessageExternal(message, currentTab) {
ui.refreshTab(currentTab);
}
if (message.method == "isAutoSaveEnabled") {
return isEnabled(currentTab);
return autoSaveIsEnabled(currentTab);
}
}

async function onInit(tab) {
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(tab.url, true), isEnabled(tab)]);
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(tab.url, true), autoSaveIsEnabled(tab)]);
if (options && ((options.autoSaveLoad || options.autoSaveLoadOrUnload) && autoSaveEnabled)) {
business.saveTabs([tab], { autoSave: true });
}
}

async function isEnabled(tab) {
if (tab) {
const [allTabsData, rule] = await Promise.all([tabsData.get(), config.getRule(tab.url)]);
return Boolean(allTabsData.autoSaveAll ||
(allTabsData.autoSaveUnpinned && !tab.pinned) ||
(allTabsData[tab.id] && allTabsData[tab.id].autoSave)) &&
(!rule || rule.autoSaveProfile != config.DISABLED_PROFILE_NAME);
}
}

async function refreshTabs() {
const allTabs = (await tabs.get({}));
return Promise.all(allTabs.map(async tab => {
const [options, autoSaveEnabled] = await Promise.all([config.getOptions(tab.url, true), isEnabled(tab)]);
try {
await tabs.sendMessage(tab.id, { method: "content.init", autoSaveEnabled, options });
} catch (error) {
// ignored
}
}));
}

async function saveContent(message, tab) {
const tabId = tab.id;
const options = await config.getOptions(tab.url, true);
Expand Down Expand Up @@ -216,7 +192,7 @@ async function saveContent(message, tab) {
if (message.taskId) {
business.onSaveEnd(message.taskId);
} else if (options.autoClose) {
tabs.remove(replacedTabIds[tabId] || tabId);
browser.tabs.remove(replacedTabIds[tabId] || tabId);
delete replacedTabIds[tabId];
}
if (pageData && pageData.url) {
Expand Down
9 changes: 3 additions & 6 deletions extension/core/bg/background.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@

<body>
<script src="/dist/chrome-browser-polyfill.js"></script>
<script src="/dist/single-file-background.js"></script>
<script src="/dist/extension-background.js"></script>
<script src="/dist/protobuf.js"></script>
<script src="/dist/single-file.js"></script>
<script src="/dist/infobar.js"></script>
<script src="/extension/core/common/page-proto.js"></script>
<script type="module" src="/extension/core/bg/messages.js"></script>
<script type="module" src="/extension/ui/bg/ui-commands.js"></script>
<script type="module" src="/extension/lib/single-file/fetch/bg/fetch.js"></script>
<script type="module" src="/extension/lib/single-file/frame-tree/bg/frame-tree.js"></script>
<script type="module" src="/extension/lib/single-file/lazy/bg/lazy-timeout.js"></script>
<script src="/extension/core/common/page-proto.js"></script>
</body>

</html>
9 changes: 4 additions & 5 deletions extension/core/bg/bookmarks.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

import * as config from "./config.js";
import * as business from "./business.js";
import * as tabs from "./tabs.js";

Promise.resolve().then(enable);

Expand Down Expand Up @@ -83,7 +82,7 @@ async function update(id, changes) {
}

async function onCreated(bookmarkId, bookmarkInfo) {
const activeTabs = await tabs.get({ lastFocusedWindow: true, active: true });
const activeTabs = await browser.tabs.query({ lastFocusedWindow: true, active: true });
const options = await config.getOptions(bookmarkInfo.url);
if (options.saveCreatedBookmarks) {
const bookmarkFolders = await getParentFolders(bookmarkInfo.parentId);
Expand All @@ -98,9 +97,9 @@ async function onCreated(bookmarkId, bookmarkInfo) {
if (activeTabs.length && activeTabs[0].url == bookmarkInfo.url) {
business.saveTabs(activeTabs, { bookmarkId, bookmarkFolders });
} else {
const allTabs = await tabs.get({});
if (allTabs.length) {
const tab = allTabs.find(tab => tab.url == bookmarkInfo.url);
const tabs = await browser.tabs.query({});
if (tabs.length) {
const tab = tabs.find(tab => tab.url == bookmarkInfo.url);
if (tab) {
business.saveTabs([tab], { bookmarkId, bookmarkFolders });
} else {
Expand Down
39 changes: 31 additions & 8 deletions extension/core/bg/business.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
* Source.
*/

/* global browser */

import * as config from "./config.js";
import * as autosave from "./autosave.js";
import { autoSaveIsEnabled } from "./autosave-util.js";
import * as requests from "./requests.js";
import * as tabs from "./tabs.js";
import * as ui from "./../../ui/bg/index.js";
import { injectScript } from "./../../index.js";

Expand All @@ -45,6 +46,7 @@ const extensionScriptFiles = [

const tasks = [];
let currentTaskId = 0, maxParallelWorkers;
ui.setBusiness({ isSavingTab, saveTabs, saveUrls, cancelTab, saveSelectedLinks });

export {
isSavingTab,
Expand All @@ -66,7 +68,7 @@ async function saveSelectedLinks(tab) {
const tabOptions = { extensionScriptFiles, tabId: tab.id, tabIndex: tab.index };
const scriptsInjected = await injectScript(tab.id, tabOptions);
if (scriptsInjected) {
const response = await tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
const response = await browser.tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
if (response.urls && response.urls.length) {
await saveUrls(response.urls);
}
Expand Down Expand Up @@ -108,7 +110,7 @@ async function saveTabs(tabs, options = {}) {
await requests.enableReferrerOnError();
}
if (options.autoSave) {
if (autosave.isEnabled(tab)) {
if (autoSaveIsEnabled(tab)) {
const taskInfo = addTask({
status: TASK_PROCESSING_STATE,
tab,
Expand Down Expand Up @@ -175,7 +177,7 @@ async function runTask(taskInfo) {
if (!taskInfo.tab.id) {
let scriptsInjected;
try {
const tab = await tabs.createAndWait({ url: taskInfo.tab.url, active: false });
const tab = await createTabAndWaitUntilComplete({ url: taskInfo.tab.url, active: false });
taskInfo.tab.id = taskInfo.options.tabId = tab.id;
taskInfo.tab.index = taskInfo.options.tabIndex = tab.index;
ui.onStart(taskInfo.tab.id, INJECT_SCRIPTS_STEP);
Expand All @@ -192,7 +194,7 @@ async function runTask(taskInfo) {
}
taskInfo.options.taskId = taskId;
try {
await tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
await browser.tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
} catch (error) {
if (error && (!error.message || !isIgnoredError(error))) {
console.log(error.message ? error.message : error); // eslint-disable-line no-console
Expand Down Expand Up @@ -220,12 +222,33 @@ function onSaveEnd(taskId) {
const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
if (taskInfo) {
if (taskInfo.options.autoClose && !taskInfo.cancelled) {
tabs.remove(taskInfo.tab.id);
browser.tabs.remove(taskInfo.tab.id);
}
taskInfo.done();
}
}

async function createTabAndWaitUntilComplete(createProperties) {
const tab = await browser.tabs.create(createProperties);
return new Promise((resolve, reject) => {
browser.tabs.onUpdated.addListener(onTabUpdated);
browser.tabs.onRemoved.addListener(onTabRemoved);
function onTabUpdated(tabId, changeInfo) {
if (tabId == tab.id && changeInfo.status == "complete") {
resolve(tab);
browser.tabs.onUpdated.removeListener(onTabUpdated);
browser.tabs.onRemoved.removeListener(onTabRemoved);
}
}
function onTabRemoved(tabId) {
if (tabId == tab.id) {
reject(tabId);
browser.tabs.onRemoved.removeListener(onTabRemoved);
}
}
});
}

function setCancelCallback(taskId, cancelCallback) {
const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
if (taskInfo) {
Expand Down Expand Up @@ -256,7 +279,7 @@ function getTaskInfo(taskId) {
function cancel(taskInfo) {
const tabId = taskInfo.tab.id;
taskInfo.cancelled = true;
tabs.sendMessage(tabId, {
browser.tabs.sendMessage(tabId, {
method: "content.cancelSave",
options: {
loadDeferredImages: taskInfo.options.loadDeferredImages,
Expand Down
4 changes: 2 additions & 2 deletions extension/core/bg/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

/* global browser, navigator, URL, Blob */

import * as downloads from "./downloads.js";
import { download } from "./download-util.js";
import * as tabsData from "./tabs-data.js";

const CURRENT_PROFILE_NAME = "-";
Expand Down Expand Up @@ -457,7 +457,7 @@ async function exportConfig() {
saveAs: true
};
try {
await downloads.download(downloadInfo, "_");
await download(downloadInfo, "_");
} finally {
URL.revokeObjectURL(url);
}
Expand Down
4 changes: 2 additions & 2 deletions extension/core/bg/devtools.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
* Source.
*/

import * as tabs from "./tabs.js";
/* global browser */

export {
onMessage
Expand All @@ -30,7 +30,7 @@ export {
async function onMessage(message) {
if (message.method.endsWith(".resourceCommitted")) {
if (message.tabId && message.url && (message.type == "stylesheet" || message.type == "script")) {
await tabs.sendMessage(message.tabId, message);
await browser.tabs.sendMessage(message.tabId, message);
}
}
}
Loading

0 comments on commit 7ad42b0

Please sign in to comment.