diff --git a/src/background.ts b/src/background.ts index f867370..98a6649 100644 --- a/src/background.ts +++ b/src/background.ts @@ -1,84 +1,6 @@ -import { Config } from './Config'; import { redirectListenerUrls } from './data/redirectListenerUrls'; -import { fetchData } from './lib/api/fetchData'; +import { initializeExtension } from './lib/initializeExtension'; import { getStorage, isChromeStorage } from './lib/storage'; -import type { Settings } from './models/Settings'; -import { defaultSettings } from './models/Settings'; - -/** - * This script initializes local storage with default values and from the api. - * @returns void - */ -function initializeExtension( - storage: typeof browser.storage | typeof chrome.storage | null -) { - // Check if we're running in Chrome - if (storage && isChromeStorage(storage)) { - Object.keys(defaultSettings).forEach((key) => { - if (Object.prototype.hasOwnProperty.call(defaultSettings, key)) { - const param: { [key: string]: any } = { [key]: null }; - storage.local.get(param, (result) => { - // Only proceed if the previous local storage does not have the key - if ( - !Object.prototype.hasOwnProperty.call(result, key) || - result[key] === undefined - ) { - const defaultVal = defaultSettings[key as keyof Settings]; - storage.local.set({ [key]: defaultVal }); - storage.local.get(param, (r) => { - if (r[key] !== defaultVal) { - console.error(`Setting unsuccessful: ${r[key]} ${defaultVal}`); - } - }); - } - }); - } - }); - } - - // Check if we're running in Firefox - if (storage && !isChromeStorage(storage)) { - Object.keys(defaultSettings).forEach((key) => { - const params: { [key: string]: any } = {}; - params[key] = null; - storage.local.get(params).then((result) => { - if ( - !Object.prototype.hasOwnProperty.call(result, key) || - !result[key] - ) { - const defaultVal = defaultSettings[key as keyof Settings]; - storage.local.set({ [key]: defaultVal }); - } - }); - }); - } - - if (storage) { - // Only get links if online features are enabled. - if (isChromeStorage(storage)) { - storage.local.get('onlineFeatures', (onlineFeatures) => { - if (onlineFeatures.onlineFeatures) { - fetchData(Config.endpoint.affiliateLinks) - .then((response) => storage.local.set({ affiliate: response.data })) - .catch((error) => console.error('Error fetching data:', error)); - } - }); - } else { - storage.local - .get() - .then((onlineFeatures) => { - if (onlineFeatures.onlineFeatures) { - fetchData(Config.endpoint.affiliateLinks) - .then((response) => - storage.local.set({ affiliate: response.data }) - ) - .catch((error) => console.error('Error fetching data:', error)); - } - }) - .catch((error) => console.error('Error retrieving data:', error)); - } - } -} /** * Adds a listener to listen for redirect events. @@ -116,8 +38,9 @@ function addRedirectListener(isChrome: boolean) { function main() { const storage = getStorage(); - initializeExtension(storage); - addRedirectListener(isChromeStorage(storage)); + initializeExtension(storage).finally(() => { + addRedirectListener(isChromeStorage(storage)); + }); } main(); diff --git a/src/content_script.ts b/src/content_script.ts index cce805f..477f7db 100644 --- a/src/content_script.ts +++ b/src/content_script.ts @@ -14,8 +14,10 @@ import { addQcElement } from './lib/html/addQcElement'; import { getImageAgent } from './lib/html/getImageAgent'; import { getPlatformImage } from './lib/html/getPlatformImage'; import { replaceTextContent } from './lib/html/replaceTextContent'; +import { initializeExtension } from './lib/initializeExtension'; import { isBrokenRedditImageLink } from './lib/isBrokenRedditImageLink'; import { loadSettings } from './lib/loadSettings'; +import { getStorage } from './lib/storage'; import type { Settings } from './models/Settings'; import { settingNames } from './models/Settings'; @@ -23,6 +25,7 @@ async function main(settings: Settings) { // console.log("🚀🚀🚀🚀 Content Script Running 🚀🚀🚀🚀"); // Get the selected agent from local storage const selectedAgent: AgentWithRaw = settings.myAgent; + console.error(selectedAgent); const currentUrl = new URL(window.location.href); @@ -173,7 +176,32 @@ async function main(settings: Settings) { const observer = new MutationObserver((mutations) => { mutations.forEach((_mutation) => { loadSettings(settingNames).then((settings) => { - main(settings as Settings); + if (settings && Object.keys(settings).length > 0) { + main(settings as Settings); + } else { + console.error('RA Browser Extension:', 'No settings found'); + const storage = getStorage(); + console.error('storage', JSON.stringify(storage)); + initializeExtension(storage) + .then(() => { + console.log('RA Browser Extension:', 'Initialized extension'); + }) + .finally(() => { + console.log('RA Browser Extension:', 'Reloading settings'); + loadSettings(settingNames).then((s) => { + if (s && Object.keys(s).length > 0) { + main(s as Settings); + } + }); + }) + .catch((error) => { + console.error( + 'RA Browser Extension:', + 'Error initializing extension', + error + ); + }); + } }); }); }); @@ -187,11 +215,3 @@ const options = { }; observer.observe(document.body, options); -// Run once when the loading is complete -window.onload = () => { - loadSettings(settingNames).then((settings) => { - if (settings) { - main(settings as Settings); - } - }); -}; diff --git a/src/lib/initializeExtension.ts b/src/lib/initializeExtension.ts new file mode 100644 index 0000000..b77a804 --- /dev/null +++ b/src/lib/initializeExtension.ts @@ -0,0 +1,94 @@ +import { Config } from '../Config'; +import type { Settings } from '../models/Settings'; +import { defaultSettings } from '../models/Settings'; +import { fetchData } from './api/fetchData'; +import { isChromeStorage } from './storage'; + +/** + * This script initializes local storage with default values and from the api. + * @returns void + */ +export async function initializeExtension( + storage: typeof browser.storage | typeof chrome.storage | null +) { + if (!storage) { + console.error('Storage is not available.'); + return; + } + // Check if we're running in Chrome + if (isChromeStorage(storage)) { + Object.keys(defaultSettings).forEach((key) => { + if (Object.prototype.hasOwnProperty.call(defaultSettings, key)) { + const param: { [key: string]: any } = { [key]: null }; + storage.local.get(param, (result) => { + // Only proceed if the previous local storage does not have the key + if ( + !Object.prototype.hasOwnProperty.call(result, key) || + result[key] === undefined || + result[key] === null + ) { + const defaultVal = defaultSettings[key as keyof Settings]; + console.debug( + `Key does not exist. Creating key '${key}' with value: ${defaultVal}` + ); + storage.local.set({ [key]: defaultVal }); + storage.local.get(param, (r) => { + if (r[key] !== defaultVal) { + console.error(`Setting unsuccessful: ${r[key]} ${defaultVal}`); + } + }); + } else { + console.debug( + `Key '${key}' already exists with value: ${result[key]}` + ); + } + }); + } + }); + } + + // Check if we're running in Firefox + if (!isChromeStorage(storage)) { + Object.keys(defaultSettings).forEach((key) => { + const params: { [key: string]: any } = {}; + params[key] = null; + storage.local.get(params).then((result) => { + if ( + !Object.prototype.hasOwnProperty.call(result, key) || + !result[key] + ) { + const defaultVal = defaultSettings[key as keyof Settings]; + storage.local.set({ [key]: defaultVal }); + } + }); + }); + } + + // Only get links if online features are enabled. + if (isChromeStorage(storage)) { + storage.local.get('onlineFeatures', async (onlineFeatures) => { + if (onlineFeatures.onlineFeatures) { + const response = await fetchData(Config.endpoint.affiliateLinks); + if (response) { + storage.local.set({ affiliate: response.data }); + } else { + console.error('Error retrieving data:', response); + } + } + }); + } else { + storage.local + .get() + .then(async (onlineFeatures) => { + if (onlineFeatures.onlineFeatures) { + const response = await fetchData(Config.endpoint.affiliateLinks); + if (response) { + storage.local.set({ affiliate: response.data }); + } else { + console.error('Error retrieving data:', response); + } + } + }) + .catch((error) => console.error('Error retrieving data:', error)); + } +}