Skip to content

Commit

Permalink
Merge pull request #43 from AdeelH/async
Browse files Browse the repository at this point in the history
Convert JS promises to `async`/`await`
  • Loading branch information
AdeelH authored May 1, 2022
2 parents 7335c00 + dbd9093 commit 2c4b692
Show file tree
Hide file tree
Showing 4 changed files with 169 additions and 160 deletions.
120 changes: 62 additions & 58 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,14 @@ let recentlyQueried = new Set([]);
updateListenerFlags();
})();

function updateListenerFlags() {
getOptions(bgOptions).then(opts => {
bgOpts = opts;
tabUpdatedListenerActive = bgOpts.autorun.updated
tabActivatedListenerActive = bgOpts.autorun.activated;
});
async function updateListenerFlags() {
const opts = await getOptions(bgOptions);
bgOpts = opts;
tabUpdatedListenerActive = bgOpts.autorun.updated;
tabActivatedListenerActive = bgOpts.autorun.activated;
}

function tabUpdatedListener(tabId, info, tab) {
async function tabUpdatedListener(tabId, info, tab) {
updateListenerFlags();
if (!tabUpdatedListenerActive) {
return;
Expand All @@ -48,128 +47,133 @@ function tabUpdatedListener(tabId, info, tab) {
}
recentlyQueried.add(tab.url);
setTimeout(() => recentlyQueried.delete(tab.url), 1e3);
return removeBadge(tabId).then(() => autoFind(tabId, tab.url));
await removeBadge(tabId);
return autoSearch(tabId, tab.url);
}

function tabActivatedListener(activeInfo) {
async function tabActivatedListener(activeInfo) {
updateListenerFlags();
if (!tabActivatedListenerActive) {
return;
}
let tabId = activeInfo.tabId;
return getTabById(tabId).then(tab => autoFind(tabId, tab.url));
const tabId = activeInfo.tabId;
const tab = await getTabById(tabId);
return autoSearch(tabId, tab.url);
}


function autoFind(tabId, url) {
async function autoSearch(tabId, url) {
if (!isAllowed(removeQueryString(url))) {
return;
}
let isYt = isYoutubeUrl(url) && bgOpts.search.ytHandling;
let exactMatch = bgOpts.search.exactMatch && !isYt;
let urlToSearch = processUrl(url, bgOpts.search.ignoreQs, isYt);

const isYt = isYoutubeUrl(url) && bgOpts.search.ytHandling;
const exactMatch = bgOpts.search.exactMatch && !isYt;
const urlToSearch = processUrl(url, bgOpts.search.ignoreQs, isYt);
let posts;
if (exactMatch) {
searchExact(tabId, urlToSearch);
posts = await searchExact(tabId, urlToSearch);
} else {
searchNonExact(tabId, urlToSearch);
posts = await searchNonExact(tabId, urlToSearch);
}
return setResultsBadge(tabId, posts);
}

const BG_RETRY_INTERVAL = 5e3;
const MAX_RETRIES = 5;
function searchExact(tabId, url, retryCount = 0) {
async function searchExact(tabId, url, retryCount = 0) {
if (retryCount >= MAX_RETRIES) {
return;
}
findOnReddit(url, true, true)
.then(posts => {
if (bgOpts.autorun.retryExact && posts.length === 0) {
searchNonExact(tabId, url);
} else {
setResultsBadge(tabId, posts);
}
})
.catch(e => {
if (bgOpts.autorun.retryError) {
setTimeout(() => searchExact(tabId, url, retryCount + 1), BG_RETRY_INTERVAL);
}
handleError(e, tabId);
});
try {
const posts = await findOnReddit(url, true, true)
if (bgOpts.autorun.retryExact && posts.length === 0) {
return searchNonExact(tabId, url);
}
return posts;
} catch (e) {
if (bgOpts.autorun.retryError) {
setTimeout(() => searchExact(tabId, url, retryCount + 1), BG_RETRY_INTERVAL);
}
await handleError(e, tabId);
}
}

function searchNonExact(tabId, url, retryCount = 0) {
async function searchNonExact(tabId, url, retryCount = 0) {
if (retryCount >= MAX_RETRIES) {
return;
}
findOnReddit(url, true, false)
.then(posts => setResultsBadge(tabId, posts))
.catch(e => {
if (bgOpts.autorun.retryError) {
setTimeout(() => searchNonExact(tabId, url, retryCount + 1), BG_RETRY_INTERVAL);
}
handleError(e, tabId);
});
try {
return findOnReddit(url, true, false);
} catch (e) {
if (bgOpts.autorun.retryError) {
setTimeout(() => searchNonExact(tabId, url, retryCount + 1), BG_RETRY_INTERVAL);
}
await handleError(e, tabId);
}
}

function isAllowed(url) {
url = url.toLowerCase();
return !(isChromeUrl(url) || isBlackListed(url));
return (url.length > 0) && !(isChromeUrl(url) || isBlackListed(url));
}

function isBlackListed(url) {
return bgOpts.blacklist.some(s => url.search(s) > -1);
}

function handleError(e, tabId) {
async function handleError(e, tabId) {
console.log(e);
return setErrorBadge(tabId);
}

function isChromeUrl(url) {
return /^chrome/.test(url);
}

function setErrorBadge(tabId) {
async function setErrorBadge(tabId) {
return setBadge(tabId, 'X', BADGE_COLORS.error);
}

function numToBadgeText(n) {
if (n < 1_000) {
return `${n}`;
} else if (n < 1_000_000) {
return `${Math.trunc(n / 1_000)}K`;
return `${Math.trunc(n / 1_000)}K+`;
} else if (n < 1_000_000_000) {
return `${Math.trunc(n / 1_000_000)}M`;
return `${Math.trunc(n / 1_000_000)}M+`;
}
}

function setResultsBadge(tabId, posts) {
let color = BADGE_COLORS.success;
async function setResultsBadge(tabId, posts) {
const color = BADGE_COLORS.success;
if (!posts || posts.length === 0) {
return setBadge(tabId, '0', color);
}
if (bgOpts.autorun.badgeContent === 'num_comments') {
let numComments = posts.reduce((acc, p) => acc + p.data.num_comments, 0);
const numComments = posts.reduce((acc, p) => acc + p.data.num_comments, 0);
return setBadge(tabId, `${numToBadgeText(numComments)}`, color);
} else {
let numPosts = posts.length;
const numPosts = posts.length;
return setBadge(tabId, `${numToBadgeText(numPosts)}`, color);
}
}

function removeBadge(tabId) {
return setResultsBadge(tabId, '');
async function removeBadge(tabId) {
return setBadge(tabId, '', BADGE_COLORS.success);
}

function setBadge(tabId, text, color) {
let badge = { text: text, tabId: tabId };
let bgCol = { color: color, tabId: tabId };
return getTabById(tabId).then(tab => {
async function setBadge(tabId, text, color) {
const badge = { text: text, tabId: tabId };
const bgCol = { color: color, tabId: tabId };
try {
const tab = await getTabById(tabId);
if (!chrome.runtime.lastError) {
chrome.action.setBadgeText(badge);
}
if (!chrome.runtime.lastError) {
chrome.action.setBadgeBackgroundColor(bgCol);
}
}).catch(ignoreRejection);
} catch (args) {
return ignoreRejection(args);
}
}
19 changes: 9 additions & 10 deletions chrome.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {allOptions} from './query.js';

export function getCurrentTabUrl() {
return getCurrentTab().then(tab => tab.url);
export async function getCurrentTabUrl() {
const tab = await getCurrentTab();
return tab.url;
}

export function getCurrentTab() {
let query = {
const query = {
active: true,
currentWindow: true
};
Expand All @@ -20,12 +20,11 @@ export function getTabById(tabId) {
});
}

export function navigateTo(url) {
return getCurrentTab().then(tab => {
if (!chrome.runtime.lastError) {
chrome.tabs.update(tab.id, {url: url});
}
});
export async function navigateTo(url) {
const tab = await getCurrentTab();
if (!chrome.runtime.lastError) {
chrome.tabs.update(tab.id, { url: url });
}
}

export function searchCache(query) {
Expand Down
57 changes: 30 additions & 27 deletions options.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ let DOM;

function init() {
DOM = fetchDomHandles();
restoreOptions();
DOM.saveButton.click(saveOptions);
restoreOptions();
}

const CACHE_MAX = 60 * 24;
function saveOptions() {
let options = {
async function saveOptions() {
const options = {
oldReddit: DOM.opts.oldReddit.prop('checked'),
search: {
exactMatch: DOM.opts.exactMatch.prop('checked'),
Expand All @@ -38,37 +38,40 @@ function saveOptions() {
cache: { period: getCachePeriod() },
blacklist: getBlacklist()
};
updateOptions(options)
.then(notifySuccess)
.then(restoreOptions)
.catch(notifyFailure);
try {
await updateOptions(options);
} catch(e) {
notifyFailure();
}
notifySuccess();
await restoreOptions();
}

function restoreOptions() {
getOptions(allOptions).then(opts => {
async function restoreOptions() {
const opts = await getOptions(allOptions);
console.log(opts);

DOM.opts.oldReddit.prop('checked', opts.oldReddit);
DOM.opts.exactMatch.prop('checked', opts.search.exactMatch);
DOM.opts.ignoreQs.prop('checked', opts.search.ignoreQs);
DOM.opts.ytHandling.prop('checked', opts.search.ytHandling);
DOM.opts.oldReddit.prop('checked', opts.oldReddit);

DOM.opts.exactMatch.prop('checked', opts.search.exactMatch);
DOM.opts.ignoreQs.prop('checked', opts.search.ignoreQs);
DOM.opts.ytHandling.prop('checked', opts.search.ytHandling);

DOM.opts.updated.prop('checked', opts.autorun.updated);
DOM.opts.activated.prop('checked', opts.autorun.activated);
DOM.opts.retryExact.prop('checked', opts.autorun.retryExact);
DOM.opts.retryError.prop('checked', opts.autorun.retryError);
DOM.opts.updated.prop('checked', opts.autorun.updated);
DOM.opts.activated.prop('checked', opts.autorun.activated);
DOM.opts.retryExact.prop('checked', opts.autorun.retryExact);
DOM.opts.retryError.prop('checked', opts.autorun.retryError);

DOM.opts.newtab.prop('checked', opts.popup.newtab);
DOM.opts.newtabInBg.prop('checked', opts.popup.newtabInBg);
DOM.opts.newtab.prop('checked', opts.popup.newtab);
DOM.opts.newtabInBg.prop('checked', opts.popup.newtabInBg);

DOM.opts.badgeContent.val(opts.autorun.badgeContent);
DOM.opts.badgeContent.val(opts.autorun.badgeContent);

DOM.opts.orderBy.val(opts.popup.results.orderBy);
DOM.opts.orderDesc.prop('checked', opts.popup.results.desc);
DOM.opts.orderBy.val(opts.popup.results.orderBy);
DOM.opts.orderDesc.prop('checked', opts.popup.results.desc);

DOM.opts.cachePeriod.val(opts.cache.period);
DOM.opts.blacklist.val(opts.blacklist.join('\n'));
});
DOM.opts.cachePeriod.val(opts.cache.period);
DOM.opts.blacklist.val(opts.blacklist.join('\n'));
}

function getBlacklist() {
Expand All @@ -79,7 +82,7 @@ function getBlacklist() {
}

function getCachePeriod() {
let cachePeriodInput = DOM.opts.cachePeriod.val();
const cachePeriodInput = DOM.opts.cachePeriod.val();
return Math.max(0, Math.min(CACHE_MAX, cachePeriodInput));
}

Expand Down
Loading

0 comments on commit 2c4b692

Please sign in to comment.