Skip to content

Commit

Permalink
use indexeddb as well as fix message listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
kheina committed Jun 25, 2023
1 parent eaf52eb commit 5f0105a
Show file tree
Hide file tree
Showing 6 changed files with 213 additions and 85 deletions.
69 changes: 51 additions & 18 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { api, logstr, ReasonExternal, SoupcanExtensionId } from '../constants';
import { abbreviate, PopulateVerifiedDb } from '../utilities';
import { api, logstr, ErrorStatus, IsVerifiedAction, ReasonExternal, SoupcanExtensionId, SuccessStatus, DefaultOptions } from '../constants';
import { abbreviate, CheckDbIsUserLegacyVerified, PopulateVerifiedDb } from '../utilities';
import { BlockQueue } from '../models/block_queue';

api.action.setBadgeBackgroundColor({ color: '#666' });
Expand All @@ -14,27 +14,54 @@ api.storage.local.onChanged.addListener((items) => {
}
});

api.storage.sync.get({ skipVerified: false, suspendedBlockCollection: false, soupcan: false }).then(items => {
api.storage.sync.get(DefaultOptions).then(async items => {
// set initial extension state
api.action.setIcon({ path: items.suspendedBlockCollection ? "/icon/icon-128-greyscale.png" : "/icon/icon-128.png" });
if (items.skipVerified) {
PopulateVerifiedDb();
await PopulateVerifiedDb();
}
});

// populate verified db
api.storage.sync.onChanged.addListener((items) => {
api.storage.sync.onChanged.addListener(async items => {
if (items.hasOwnProperty('skipVerified') && items.skipVerified.newValue) {
PopulateVerifiedDb();
await PopulateVerifiedDb();
}
});

api.runtime.onMessage.addListener((m, s, r) => { (async (_message, sender, respond) => {
// messages are ALWAYS expected to be:
// 1. objects
// 2. contain a string value stored under message.action. should be one defined above
// other message contents change based on the defined action
switch (_message?.action) {
case IsVerifiedAction:
const message = _message as { action: string, user_id: string, handle: string };
try {
const isVerified = await CheckDbIsUserLegacyVerified(message.user_id, message.handle);
const response = { status: SuccessStatus, result: isVerified };
respond(response);
} catch (e) {
const response = { status: ErrorStatus, message: "unknown error", error: e };
respond(response);
}
break;

default:
console.error(logstr, "got a message that couldn't be handled from sender:", sender, _message);
const response = { status: ErrorStatus, message: "unknown action", error: null };
respond(response);
}
return true;
})(m, s, r); return true });

////////////////////////////////////////////////// EXTERNAL MESSAGE HANDLING //////////////////////////////////////////////////

const queue = new BlockQueue(api.storage.local);
const [errorStatus, successStatus] = ["ERROR", "SUCCESS"];
const [blockAction] = ["BLOCK"];
const allowedExtensionIds = new Set([SoupcanExtensionId]);

api.runtime.onMessageExternal.addListener(async (message, sender, respond) => {
api.runtime.onMessageExternal.addListener((m, s, r) => { (async (_message, sender, respond) => {
if (!allowedExtensionIds.has(sender?.id ?? "")) {
return;
}
Expand All @@ -43,16 +70,22 @@ api.runtime.onMessageExternal.addListener(async (message, sender, respond) => {
// 1. objects
// 2. contain a string value stored under message.action. should be one defined above
// other message contents change based on the defined action
switch (message?.action) {
switch (_message?.action) {
case blockAction:
// expected message format: { action, user_id: string, name: string, screen_name: string, reason: string }
// TODO: figure out a better structure of user that only takes the things we need for blocking (name, handle)
await queue.push({ user_id: message.user_id, user: { name: message.name, screen_name: message.screen_name }, reason: ReasonExternal, external_reason: message.reason });
respond({ status: successStatus, message: "user queued for blocking" });
break;
const message = _message as { action: string, user_id: string, name: string, screen_name: string, reason: string };
try {
await queue.push({ user_id: message.user_id, user: { name: message.name, screen_name: message.screen_name }, reason: ReasonExternal, external_reason: message.reason });
const response = { status: SuccessStatus, message: "user queued for blocking" };
respond(response);
} catch (e) {
const response = { status: ErrorStatus, message: "unknown error", error: e };
respond(response);
}
return;

default:
console.error(logstr, "got a message that couldn't be handled from sender:", sender, message);
respond({ status: errorStatus, message: "unknown action" });
}
});
console.error(logstr, "got a message that couldn't be handled from sender:", sender, _message);
const response = { status: ErrorStatus, message: "unknown action", error: null };
respond(response);
}
})(m, s, r); return true });
4 changes: 4 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export const LegacyVerifiedUrl: string = "https://gist.githubusercontent.com/tra
export const Browser = chrome.runtime.getManifest()?.browser_specific_settings?.gecko === undefined ? "chrome" : "firefox";
export const SoupcanExtensionId = Browser === "chrome" ? "hcneafegcikghlbibfmlgadahjfckonj" : "[email protected]";

// internal message actions
export const [IsVerifiedAction] = ["is_verified"];
export const [ErrorStatus, SuccessStatus] = ["ERROR", "SUCCESS"];

// multi-tab event keys
export const EventKey = "MultiTabEvent";
export const ErrorEvent = "ErrorEvent";
Expand Down
11 changes: 2 additions & 9 deletions src/content/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ClearCache, SetHeaders } from '../shared';
import { SetHeaders } from '../shared';
import { api, logstr, DefaultOptions, ErrorEvent, EventKey } from '../constants';
import { HandleInstructionsResponse } from '../parsers/instructions';
import { HandleForYou } from '../parsers/timeline';
Expand All @@ -15,7 +15,7 @@ script.type = 'text/javascript';
document.head.prepend(script);

let l = document.createElement('link');
l.href = api.runtime.getURL('src/injected/toasts.css'); // MUST BE ABSOLUTE PATH
l.href = api.runtime.getURL('src/injected/style.css'); // MUST BE ABSOLUTE PATH
l.rel = 'stylesheet';
(document.head || document.documentElement).appendChild(l);

Expand All @@ -24,20 +24,13 @@ t.id = 'injected-blue-block-toasts';
document.body.appendChild(t);

document.addEventListener('blue-blocker-event', function (e: CustomEvent<BlueBlockerEvent>) {
// TODO: we may want to seriously consider clearing the cache on a much less frequent
// cadence since we're no longer able to block users immediately and need the queue

// TODO: probably also check status code here so that we're not parsing error responses
// for no reason

if (e.detail.status < 300) {
SetHeaders(e.detail.request.headers);
} else {
// we got an error response, we don't really care to parse it.
return;
}

ClearCache();
api.storage.sync.get(DefaultOptions).then(_config => {
const config = _config as Config;
const body_str = e.detail.body;
Expand Down
File renamed without changes.
10 changes: 5 additions & 5 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
MessageEvent,
ReasonTransphobia,
} from './constants';
import { commafy, IsUserLegacyVerified, FormatLegacyName } from './utilities';
import { commafy, FormatLegacyName, IsUserLegacyVerified } from './utilities';

// Define constants that shouldn't be exported to the rest of the addon
const queue = new BlockQueue(api.storage.local);
Expand All @@ -33,6 +33,8 @@ export function SetHeaders(headers: { [k: string]: string }) {
});
}

setInterval(blockCache.clear, 10 * 60e3); // clear the cache every 10 minutes

function unblockUser(user: { name: string, screen_name: string }, user_id: string, reason: number, attempt: number = 1) {
api.storage.sync.get({ unblocked: { } }).then(items => {
items.unblocked[String(user_id)] = null;
Expand Down Expand Up @@ -143,6 +145,8 @@ function unblockUser(user: { name: string, screen_name: string }, user_id: strin
const UserBlockedEvent = 'UserBlockedEvent';
api.storage.local.onChanged.addListener((items) => {
// we're using local storage as a really dirty event driver
// TODO: replace this with chrome.tabs.sendmessage at some point. (requires adding tabs permission)

if (!items.hasOwnProperty(EventKey)) {
return;
}
Expand Down Expand Up @@ -211,10 +215,6 @@ api.storage.local.onChanged.addListener((items) => {
});
});

export function ClearCache() {
blockCache.clear();
}

function queueBlockUser(user: BlueBlockerUser, user_id: string, reason: number) {
if (blockCache.has(user_id)) {
return;
Expand Down
Loading

0 comments on commit 5f0105a

Please sign in to comment.