Skip to content

Commit

Permalink
Merge pull request #145 from mikepsinn/develop
Browse files Browse the repository at this point in the history
FDAi Act, Chrome Extension, Amazon Extractor
  • Loading branch information
mikepsinn authored Mar 4, 2024
2 parents 47e6549 + 84831e4 commit ad04c72
Showing 92 changed files with 4,079 additions and 1,398 deletions.
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# Get this from https://platform.openai.com/account/api-keys
OPENAI_API_KEY=YOUR_API_KEY

# Get this from https://lightsail.aws.amazon.com/ls/webapp/us-east-1/buckets
AWS_ACCESS_KEY_ID=your_access_key_id
AWS_SECRET_ACCESS_KEY=your_secret_access_key
AWS_REGION=your_aws_region
BUCKET_NAME=your_s3_bucket_name
203 changes: 197 additions & 6 deletions apps/browser-extension/background.js
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ chrome.alarms.onAlarm.addListener((alarm) => {
console.log("Time to show the daily popup!");
// Open a window instead of creating a notification
chrome.windows.create({
url: 'popup.html',
url: 'https://safe.fdai.earth/app/public/android_popup.html',
type: 'popup',
width: 300,
height: 200,
@@ -44,10 +44,12 @@ chrome.runtime.onStartup.addListener(() => {
});

function redirectToLogin() {
//const currentUrl = encodeURIComponent("Your extension's main or current URL here");
const currentUrl = encodeURIComponent(window.location.href);
const loginUrl = `https://safe.fdai.earth/login?intended_url=${currentUrl}`;
chrome.tabs.create({ url: loginUrl });
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// Handle the case where there are no active tabs
const loginUrl = `https://safe.fdai.earth/app/public`;
chrome.tabs.create({ url: loginUrl });

});
}

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
@@ -57,7 +59,7 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
const quantimodoAccessToken = url.searchParams.get("quantimodoAccessToken");
if (quantimodoAccessToken) {
chrome.storage.sync.set({ quantimodoAccessToken }, () => {
console.log("Access token saved:", quantimodoAccessToken);
console.log("Access token saved:")// quantimodoAccessToken);
// Optionally, redirect the user to the intended URL or show some UI indication
});
}
@@ -74,3 +76,192 @@ chrome.storage.sync.get("quantimodoAccessToken", ({ quantimodoAccessToken }) =>
}
});

chrome.action.onClicked.addListener((tab) => {
// Perform the action when the extension button is clicked
chrome.tabs.create({url: "https://safe.fdai.earth/app/public"});
});

// background.js

// Create a new context menu item.
chrome.contextMenus.create({
id: "extractAndSaveAmazon", // Add this line
title: "Extract and Save Product Details",
contexts: ["page"], // This will show the item when you right click on a page
});

// Listen for click events on your context menu item
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "extractAndSaveAmazon") {
// Inject the script into the current tab
// chrome.scripting.executeScript({
// target: {tabId: tab.id},
// function: extractAndSaveAmazon
// });
chrome.tabs.create({url: "https://www.amazon.com/gp/css/order-history?ref_=nav_orders_first"});
}
});

// Listen for messages from the content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "navigate") {
// Navigate to the specified URL
chrome.tabs.update({url: request.url});
}
});

function parseDate(deliveryDate) {
deliveryDate = deliveryDate.replace(/[^0-9]/g, "Delivered ");
deliveryDate += ", " + new Date().getFullYear();
// convert to ISO date
return new Date(deliveryDate).toISOString();
}

// Listen for tab updates
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
console.log("Tab updated:", changeInfo);
// Check if the updated tab's URL is the Amazon order history page
if (changeInfo.url === "https://www.amazon.com/gp/css/order-history?ref_=nav_orders_first") {
debugger
console.log("Amazon order history page loaded");
// Execute the extractAndSaveAmazon function
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: extractAndSaveAmazon
});
}
});

async function getQuantimodoAccessToken() {
return new Promise((resolve, reject) => {
chrome.storage.sync.get("quantimodoAccessToken", ({ quantimodoAccessToken }) => {
if (quantimodoAccessToken) {
resolve(quantimodoAccessToken);
} else {
reject("Access token not found");
}
});
});
}

async function extractAndSaveAmazon() {
const productBoxes = document.querySelectorAll('.a-fixed-left-grid.item-box.a-spacing-small, .a-fixed-left-grid.item-box.a-spacing-none');
const deliveryDate = document.querySelector('.delivery-box__primary-text').textContent.trim();
const storedProducts = JSON.parse(localStorage.getItem('products')) || [];
let measurements = [];

for (const box of productBoxes) {
const productImage = box.querySelector('.product-image a img').src;
const productTitle = box.querySelector('.yohtmlc-product-title').textContent.trim();
const productLink = box.querySelector('.product-image a').href;

// Check if the product is already in localStorage
const isProductStored = storedProducts.some(product => product.url === productLink);

if (!isProductStored) {
// If not stored, add the product to the array and localStorage
const newProduct = {
date: deliveryDate,
title: productTitle,
image: productImage,
url: productLink
};
storedProducts.push(newProduct);
localStorage.setItem('products', JSON.stringify(storedProducts));

// Add the product details to the array
measurements.push({
startAt: parseDate(deliveryDate),
variableName: productTitle,
unitName: "Count",
value: 1,
url: productLink,
image: productImage
});
}
}

if(measurements.length > 0) {
const quantimodoAccessToken = await getQuantimodoAccessToken();
const response = await fetch('https://safe.fdai.earth/api/v1/measurements', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${quantimodoAccessToken}`
},
body: JSON.stringify(measurements)
});
const data = await response.json();
console.log('Response from Quantimodo API:', data);
}

console.log(`Processed ${productBoxes.length} products.`);
}

function hasAccessToken() {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(["quantimodoAccessToken"], ({ quantimodoAccessToken }) => {
if (quantimodoAccessToken) {
resolve(true);
} else {
resolve(false);
}
});
});
}

// background.js

// Check if the user has an access token when the extension is loaded
hasAccessToken().then(hasToken => {
if (!hasToken) {
redirectToLogin();
}
});


// Listen for all web requests
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
// Parse the URL from the details
const url = new URL(details.url);

// Check if the URL has the 'quantimodoAccessToken' query parameter
const quantimodoAccessToken = url.searchParams.get("quantimodoAccessToken");
if (quantimodoAccessToken) {
// Save the token to local storage
chrome.storage.sync.set({ quantimodoAccessToken }, () => {
console.log("Access token saved:")//, quantimodoAccessToken);
});
}
},
// filters
{
urls: ["https://safe.fdai.earth/*"],
types: ["main_frame"]
}
);

let currentUrl = '';
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Check if the updated tab's URL is the reminders inbox page
if (changeInfo.status === "loading" && changeInfo.url) {
currentUrl = changeInfo.url;
}
//console.log("changeInfo", changeInfo);
if (changeInfo.status === "complete" &&
currentUrl &&
currentUrl.indexOf("https://safe.fdai.earth/app/public/#/app/") > -1) {
// Execute your function here
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
//console.log("tabs", tabs);
chrome.tabs.sendMessage(tabs[0].id, {message: "getFdaiLocalStorage", key: "accessToken"}, function(response) {
//console.log(response.data);
chrome.storage.sync.set({quantimodoAccessToken: response.data}, function() {
console.log('Access token saved:')//, response.data);
});
});
});
}
});

7 changes: 7 additions & 0 deletions apps/browser-extension/contentScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Function to extract the data
function extractAndSaveAmazon() {
// Send a message to the background script to navigate to the Amazon order history page
chrome.runtime.sendMessage({action: "navigate", url: "https://www.amazon.com/gp/css/order-history?ref_=nav_orders_first"});

// Rest of your function code here...
}
10 changes: 10 additions & 0 deletions apps/browser-extension/contentScriptForFdai.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
console.log('contentScriptForFdai.js loaded');
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log('contentScriptForFdai.js received a message', request);
if (request.message === "getFdaiLocalStorage") {
sendResponse({data: localStorage.getItem(request.key)});
}
}
);

27 changes: 25 additions & 2 deletions apps/browser-extension/manifest.json
Original file line number Diff line number Diff line change
@@ -2,12 +2,35 @@
"manifest_version": 3,
"name": "Digital Twin Safe",
"version": "1.0",
"description": "Easily record your diet, symptoms, and treatments to figure out what's fucking you up!",
"permissions": ["alarms", "notifications", "storage", "activeTab", "tabs"],
"description": "Easily record your diet, symptoms, and treatments to accelerate clinical discovery!",
"permissions": [
"alarms",
"contextMenus",
"scripting",
"notifications",
"storage",
"activeTab",
"tabs",
"webRequest"
],
"host_permissions": [
"https://www.amazon.com/"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
},
{
"matches": ["https://safe.fdai.earth/*"],
"js": ["contentScriptForFdai.js"]
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon_16.png",
"48": "icons/icon_48.png",
Loading

0 comments on commit ad04c72

Please sign in to comment.