Skip to content

Commit

Permalink
Merge pull request #196 from cachho/fix/InitialUsage
Browse files Browse the repository at this point in the history
fix: initial usage
  • Loading branch information
cachho authored Dec 4, 2024
2 parents deaef8f + f760d1e commit 32d706c
Show file tree
Hide file tree
Showing 3 changed files with 127 additions and 90 deletions.
85 changes: 4 additions & 81 deletions src/background.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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();
38 changes: 29 additions & 9 deletions src/content_script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,18 @@ 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';

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);

Expand Down Expand Up @@ -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
);
});
}
});
});
});
Expand All @@ -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);
}
});
};
94 changes: 94 additions & 0 deletions src/lib/initializeExtension.ts
Original file line number Diff line number Diff line change
@@ -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));
}
}

0 comments on commit 32d706c

Please sign in to comment.