Skip to content

Commit

Permalink
feat: ✨ hooking up with background worker.
Browse files Browse the repository at this point in the history
Signed-off-by: Nishant Arora <1895906+whizzzkid@users.noreply.github.com>
  • Loading branch information
whizzzkid committed Jul 20, 2023
1 parent 4a9d055 commit 60a94c7
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 19 deletions.
64 changes: 48 additions & 16 deletions add-on/src/lib/redirect-handler/blockOrObserve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { CompanionState } from '../../types/companion.js'
const log = debug('ipfs-companion:redirect-handler:blockOrObserve')
log.error = debug('ipfs-companion:redirect-handler:blockOrObserve:error')

export const GLOBAL_STATE_CHANGE = 'GLOBAL_STATE_CHANGE'
export const GLOBAL_STATE_OPTION_CHANGE = 'GLOBAL_STATE_OPTION_CHANGE'
export const DELETE_RULE_REQUEST = 'DELETE_RULE_REQUEST'
export const DELETE_RULE_REQUEST_SUCCESS = 'DELETE_RULE_REQUEST_SUCCESS'
export const RULE_REGEX_ENDING = '((?:[^\\.]|$).*)$'

interface regexFilterMap {
id: number
regexSubstitution: string
Expand All @@ -17,17 +23,16 @@ interface redirectHandlerInput {
redirectUrl: string
}

type messageToSelfType = typeof GLOBAL_STATE_CHANGE | typeof GLOBAL_STATE_OPTION_CHANGE | typeof DELETE_RULE_REQUEST
interface messageToSelf {
type: typeof GLOBAL_STATE_CHANGE | typeof GLOBAL_STATE_OPTION_CHANGE
type: messageToSelfType
value?: string | Record<string, unknown>
}

// We need to check if the browser supports the declarativeNetRequest API.
// TODO: replace with check for `Blocking` in `chrome.webRequest.OnBeforeRequestOptions`
// which is currently a bug https://bugs.chromium.org/p/chromium/issues/detail?id=1427952
export const supportsBlock = !(browser.declarativeNetRequest?.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES === 5000)
export const GLOBAL_STATE_CHANGE = 'GLOBAL_STATE_CHANGE'
export const GLOBAL_STATE_OPTION_CHANGE = 'GLOBAL_STATE_OPTION_CHANGE'
export const RULE_REGEX_ENDING = '((?:[^\\.]|$).*)$'

/**
* Notify self about state change.
Expand All @@ -45,16 +50,20 @@ export async function notifyOptionChange (): Promise<void> {
return await sendMessageToSelf(GLOBAL_STATE_OPTION_CHANGE)
}

export async function notifyDeleteRule (id: number): Promise<void> {
return await sendMessageToSelf(DELETE_RULE_REQUEST, id)
}

/**
* Sends message to self to notify about change.
*
* @param msg
*/
async function sendMessageToSelf (msg: typeof GLOBAL_STATE_CHANGE | typeof GLOBAL_STATE_OPTION_CHANGE): Promise<void> {
async function sendMessageToSelf (msg: messageToSelfType, value?: any): Promise<void> {
// this check ensures we don't send messages to ourselves if blocking mode is enabled.
if (!supportsBlock) {
const message: messageToSelf = { type: msg }
await browser.runtime.sendMessage(message)
const message: messageToSelf = { type: msg, value }
await browser.runtime.sendMessage({ message })
}
}

Expand Down Expand Up @@ -172,18 +181,25 @@ export async function cleanupRules (resetInMemory: boolean = false): Promise<voi
}
}

/**
* Clean up a rule by ID.
*
* @param id number
*/
async function cleanupRuleById(id: number) {
const [{ condition: { regexFilter } }] = await browser.declarativeNetRequest.getDynamicRules({ ruleIds: [id] })
savedRegexFilters.delete(regexFilter as string)
await browser.declarativeNetRequest.updateDynamicRules({ addRules: [], removeRuleIds: [id] })
}

/**
* This function sets up the listeners for the extension.
* @param {function} handlerFn
*/
function setupListeners (handlerFn: () => Promise<void>): void {
browser.runtime.onMessage.addListener(async ({ type }: messageToSelf): Promise<void> => {
if (type === GLOBAL_STATE_CHANGE) {
await handlerFn()
}
if (type === GLOBAL_STATE_OPTION_CHANGE) {
await cleanupRules(true)
await handlerFn()
function setupListeners (handlers: Record<messageToSelfType, (value: any) => Promise<void>>): void {
browser.runtime.onMessage.addListener(async ({ message: { type, value } }: { message: messageToSelf }): Promise<void> => {
if (type in handlers) {
await handlers[type](value)
}
})
}
Expand Down Expand Up @@ -354,7 +370,23 @@ export function addRuleToDynamicRuleSetGenerator (
await Promise.all(tabs.map(async tab => await browser.tabs.reload(tab.id)))
}

setupListeners(async (): Promise<void> => await reconcileRulesAndRemoveOld(getState()))
setupListeners({
[GLOBAL_STATE_CHANGE]: async (): Promise<void> => {
await reconcileRulesAndRemoveOld(getState())
},
[GLOBAL_STATE_OPTION_CHANGE]: async (): Promise<void> => {
await cleanupRules(true)
await reconcileRulesAndRemoveOld(getState())
},
[DELETE_RULE_REQUEST]: async (value: number): Promise<void> => {
if (value != null) {
await cleanupRuleById(value)
browser.runtime.sendMessage({ type: DELETE_RULE_REQUEST_SUCCESS })
} else {
cleanupRules(true)
}
}
})
// call to reconcile rules and remove old ones.
await reconcileRulesAndRemoveOld(state)
}
Expand Down
4 changes: 2 additions & 2 deletions add-on/src/options/forms/redirect-rule-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function ruleItem(emit) {
</dt>
</dl>
<div class="flex flex-column rule-delete">
<button class="f6 dim br2 ph3 pv2 mb2 mt2 dib white red" onclick=${emit('redirectRuleDeleteRequest', id)}>X</button>
<button class="f6 dim br2 ph3 pv2 mb2 mt2 dib white red" onclick=${() => emit('redirectRuleDeleteRequest', id)}>X</button>
</div>
</div>
`
Expand Down Expand Up @@ -68,7 +68,7 @@ export default function redirectRuleForm({ emit, redirectRules }) {
</dl>
</label>
<div class="self-center-ns">
<button id="deleteAllRules" class="Button transition-all sans-serif v-mid fw5 nowrap lh-copy bn br1 pa2 pointer focus-outline white bg-red white" onclick=${emit('redirectRuleDeleteRequest')}>${browser.i18n.getMessage('option_redirect_rules_reset_all')}</button>
<button id="deleteAllRules" class="Button transition-all sans-serif v-mid fw5 nowrap lh-copy bn br1 pa2 pointer focus-outline white bg-red white" onclick=${() => emit('redirectRuleDeleteRequest')}>${browser.i18n.getMessage('option_redirect_rules_reset_all')}</button>
</div>
</div>
${redirectRules ? redirectRules.map(ruleItem(emit)) : html`<div>Loading...</div>`}
Expand Down
12 changes: 11 additions & 1 deletion add-on/src/options/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import browser from 'webextension-polyfill'
import { optionDefaults } from '../lib/options.js'
import { RULE_REGEX_ENDING, notifyOptionChange, notifyStateChange } from '../lib/redirect-handler/blockOrObserve.js'
import { DELETE_RULE_REQUEST_SUCCESS, RULE_REGEX_ENDING, notifyDeleteRule, notifyOptionChange, notifyStateChange } from '../lib/redirect-handler/blockOrObserve.js'
import createRuntimeChecks from '../lib/runtime-checks.js'
import { handleConsentFromState, trackView } from '../lib/telemetry.js'

Expand Down Expand Up @@ -39,6 +39,16 @@ export default function optionStore (state, emitter) {
browser.storage.onChanged.addListener(updateStateOptions)
})

emitter.on('redirectRuleDeleteRequest', async (id) => {
console.log('delete rule request', id)
browser.runtime.onMessage.addListener(({ type }) => {
if (type === DELETE_RULE_REQUEST_SUCCESS) {
emitter.emit('render')
}
})
notifyDeleteRule(id)
})

emitter.on('optionChange', async ({ key, value }) => {
browser.storage.local.set({ [key]: value })
if (key === 'active') {
Expand Down

0 comments on commit 60a94c7

Please sign in to comment.