Skip to content

Commit

Permalink
Merge branch 'develop' into dependabot/npm_and_yarn/apps/dfda-1/publi…
Browse files Browse the repository at this point in the history
…c/app/es5-ext-0.10.64
  • Loading branch information
mikepsinn authored Mar 16, 2024
2 parents 8f871cd + 74da2e6 commit 673c8aa
Show file tree
Hide file tree
Showing 152 changed files with 15,629 additions and 1,437 deletions.
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
# Get this from https://platform.openai.com/account/api-keys
OPENAI_API_KEY=YOUR_API_KEY
OPENAI_MODEL=gpt-3.5-turbo-0125

# 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ litellm_uuid.txt
.smart-connections
.space
.makemd
desktop.ini
222 changes: 207 additions & 15 deletions apps/browser-extension/background.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { extractAndSaveAmazon } from './extractAndSaveAmazon.js';

chrome.runtime.onInstalled.addListener(() => {
setDailyAlarm(); // Set an alarm on installation
});

function setDailyAlarm() {
chrome.storage.sync.get("frequency", ({ frequency }) => {
const minutes = parseInt(frequency, 10) || 1440; // Default to 1440 minutes (once a day) if not set
chrome.alarms.create("dailyPopup", { periodInMinutes: minutes });
chrome.alarms.create("trackingPopup", { periodInMinutes: minutes });
});
}

Expand All @@ -18,20 +20,63 @@ chrome.storage.onChanged.addListener((changes, namespace) => {
}
});

chrome.alarms.onAlarm.addListener((alarm) => {
console.log("Got an alarm!", alarm);
if (alarm.name === "dailyPopup") {
console.log("Time to show the daily popup!");
// Open a window instead of creating a notification
let popupId = null;

function showTrackingPopup() {
debugger
console.log('Time to show the daily popup!');

let origin = 'https://safe.fdai.earth';
//origin = 'https://local.quantimo.do';

if (popupId !== null) {
chrome.windows.get(popupId, { populate: true }, (win) => {
if (chrome.runtime.lastError) {
// The window was closed or never created. Create it.
chrome.windows.create({
url: origin + '/app/public/android_popup.html',
type: 'popup',
width: 1,
height: 1,
left: 100,
top: 100,
focused: false
}, (win) => {
popupId = win.id;
});
} else {
// The window exists. Update it.
chrome.windows.update(popupId, { focused: true });
}
});
} else {
// No window ID, create a new window.
chrome.windows.create({
url: 'popup.html',
url: origin + '/app/public/android_popup.html',
type: 'popup',
width: 300,
height: 200,
width: 1,
height: 1,
left: 100,
top: 100
top: 100,
focused: false
}, (win) => {
popupId = win.id;
});
}
}

// background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "showTrackingPopup") {
showTrackingPopup();
}
});

chrome.alarms.onAlarm.addListener((alarm) => {
console.log("Got an alarm!", alarm);
if (alarm.name === "trackingPopup") {
showTrackingPopup();
}
});

chrome.runtime.onStartup.addListener(() => {
Expand All @@ -44,10 +89,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) => {
Expand All @@ -57,7 +104,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
});
}
Expand All @@ -74,3 +121,148 @@ 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"});
}
});

// 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 && changeInfo.url.startsWith("https://www.amazon.com/gp/css/order-history")) {
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");
}
});
});
}



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);
if(!tabs[0]) {
console.log("No active tabs. Tabs:", tabs);
return;
}
chrome.tabs.sendMessage(tabs[0].id, {message: "getFdaiLocalStorage", key: "accessToken"}, function(response) {
if(!response) {
console.error("No response from getFdaiLocalStorage");
return;
}
//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"});

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

99 changes: 99 additions & 0 deletions apps/browser-extension/extractAndSaveAmazon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
function showNotification(title, message) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon.png', // Path to the icon for the notification
title: title,
message: message
});
}

export async function extractAndSaveAmazon(html) {
debugger

html = html || document;

const orderCards = html.querySelectorAll('.order-card');
let measurements = JSON.parse(localStorage.getItem('measurements')) || [];
for (const orderCard of orderCards) {
console.log('Order card:', orderCard);
debugger
let startAt = orderCard.querySelector('.delivery-box__primary-text').textContent.trim();
if(startAt === 'Order received') {
continue;
}
if(startAt.includes('Arriving')) {
continue;
}
startAt = startAt.replace('Delivered ', '').trim();
startAt = startAt + ', ' + new Date().getFullYear();
startAt = parseDate(startAt);
const productBoxes = orderCard.querySelectorAll('.a-fixed-left-grid.item-box.a-spacing-small, .a-fixed-left-grid.item-box.a-spacing-none');
for (const box of productBoxes) {
const image = box.querySelector('.product-image a img').src;
const variableName = "Purchase of " + box.querySelector('.yohtmlc-product-title').textContent.trim();
const url = box.querySelector('.product-image a').href;

showNotification('Saving Purchase Data', `Saving ${variableName} from Amazon`);


// Check if the product is already in localStorage
const isMeasurementStored = measurements.some(measurement => measurement.url === url && measurement.startAt === startAt);

if (!isMeasurementStored) {

// Add the product details to the array
measurements.push({
startAt,
variableName,
unitName: "Count",
value: 1,
variableCategoryName: "Treatments",
sourceName: "Amazon",
url,
image
});
}
}
console.log(`Processed ${orderCards.length} products. Measurements:`, measurements);
}

if(typeof global.apiOrigin === 'undefined') {
global.apiOrigin = 'https://safe.fdai.earth';
}

if(measurements.length > 0) {
console.log('Saving measurements:', measurements);
const quantimodoAccessToken = await getQuantimodoAccessToken();
let input = global.apiOrigin + '/api/v1/measurements?XDEBUG_SESSION_START=PHPSTORM';
const response = await fetch(input, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${quantimodoAccessToken}`,
'X-CLIENT-ID': 'digital-twin-safe',
},
body: JSON.stringify(measurements)
});
// const response = await fetch('https://local.quantimo.do/api/v1/measurements', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': `Bearer demo`,
// },
// body: JSON.stringify([])
// });
if (!response.ok) {
const text = await response.text();
console.error('Error response:', text);
throw new Error(`HTTP error! status: ${response.status}`);
} else {
const data = await response.json();
console.log('Post Measurement Response from API:', data);
localStorage.setItem('measurements', JSON.stringify(measurements));
}
}
return measurements;

}

//module.exports = extractAndSaveAmazon;
Loading

0 comments on commit 673c8aa

Please sign in to comment.