Skip to content
This repository has been archived by the owner on Sep 26, 2024. It is now read-only.

Commit

Permalink
integrate with the rest of the app
Browse files Browse the repository at this point in the history
  • Loading branch information
elg0nz committed May 29, 2024
1 parent b2c5bcb commit c6ef6b9
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 304 deletions.
84 changes: 36 additions & 48 deletions apps/mocksi-lite/background.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChromeMessageNames } from "./content/constants";
import { WebSocketURL } from "./content/constants";

interface ChromeMessage {
message: string;
Expand All @@ -10,6 +10,14 @@ interface ChromeMessageWithData extends ChromeMessage {
data: string;
}

addEventListener("install", () => {
// TODO test if this works on other browsers
// TODO2 Read from environment variable the correct URL to redirect after install
chrome.tabs.create({
url: "https://mocksi-auth.onrender.com/",
});
});

chrome.action.onClicked.addListener((tab) => {
chrome.cookies.get(
{ url: "https://mocksi-auth.onrender.com/", name: "sessionid" },
Expand Down Expand Up @@ -131,7 +139,6 @@ chrome.runtime.onMessage.addListener(
console.log("Received message:", request);
if (request.message === "tabSelected") {
console.log("Received tabSelected message:", request);

if (currentTabId) {
chrome.debugger.detach({ tabId: currentTabId });
}
Expand All @@ -156,58 +163,15 @@ chrome.runtime.onMessage.addListener(
sendResponse({ message: request.message, status: "success" });
return true; // Indicate that the response is sent asynchronously
}
// FIXME: this is probably not needed anymore
if (request.message === "getCurrentTabId") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length === 0) {
console.error("No active tabs found");
sendResponse({
message: request.message,
status: "error",
tabId: undefined,
});
return;
}
const currentTab = tabs[0];
console.log("Current tab:", currentTab.id);
if (currentTab.id === undefined) {
console.error("Current tab ID is undefined");
sendResponse({
message: request.message,
status: "error",
tabId: undefined,
});
return;
}
const tabId = currentTab.id;
chrome.scripting.executeScript({
target: { tabId },
func: () => {
console.log("added yellow background");
},
});
sendResponse({
message: request.message,
status: "ok",
tabId: tabId.toString(),
});
});
return true; // Indicate that the response is sent asynchronously
}

if (request.message === ChromeMessageNames.SEND_RECORDING_PACKET) {
webSocket?.send(request.data);
sendResponse({ message: request.message, status: "ok" });
return true; // Indicate that the response is sent asynchronously
}
sendResponse({ message: request.message, status: "fail" });
return false; // No async response for other messages
},
);

console.log("background script loaded");
console.log("background script loaded 1");

const wsUrl = "ws://localhost:8090/ws";
const webSocket = new WebSocket(wsUrl);
let webSocket = new WebSocket(WebSocketURL);

webSocket.onopen = () => {
keepAlive();
Expand All @@ -219,6 +183,30 @@ webSocket.onmessage = (event) => {

webSocket.onclose = () => {
console.log("websocket connection closed");
const reconnectInterval = 5000; // 5 seconds
let reconnectTimeout = 10000;

function reconnectWebSocket() {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
}
reconnectTimeout = setTimeout(() => {
console.log("Reconnecting websocket...");
webSocket = new WebSocket(WebSocketURL);
webSocket.onopen = () => {
console.log("Websocket reconnected");
keepAlive();
};
webSocket.onmessage = (event) => {
console.log(`Websocket received message: ${event.data}`);
};
webSocket.onclose = () => {
reconnectWebSocket();
};
}, reconnectInterval);
}

reconnectWebSocket();
};

function disconnect() {
Expand Down
5 changes: 4 additions & 1 deletion apps/mocksi-lite/content/ContentApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ export default function ContentApp({ isOpen, sessionCookie }: ContentProps) {

if (!isdialogOpen) return null;
return (
<div className="border border-grey/40 rounded bg-white h-11 w-64 mt-4 mr-8 flex flex-row items-center">
<div
className="border border-grey/40 rounded bg-white h-11 w-64 mt-4 mr-8 flex flex-row items-center"
style={{ marginTop: "90px" }}
>
<div className="flex flex-row w-[80%] gap-2">
<div
className="ml-2 cursor-pointer"
Expand Down
11 changes: 3 additions & 8 deletions apps/mocksi-lite/content/constants.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
enum EventNames {
RECORDING_DATA_CAPTURED = "recordingDataCaptured",
}
// const WebSocketURL = "wss://crowllectordb.onrender.com/ws";
const WebSocketURL = "ws://localhost:8090/ws";

enum ChromeMessageNames {
SEND_RECORDING_PACKET = "sendRecordingPacket",
}

export { EventNames, ChromeMessageNames };
export { WebSocketURL };
60 changes: 12 additions & 48 deletions apps/mocksi-lite/content/content.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,7 @@
import ReactDOM from "react-dom/client";
import ContentApp from "./ContentApp";
import { ChromeMessageNames, EventNames } from "./constants";

// Define the expected response type
interface TabIdResponse {
tabId?: number;
}

chrome.runtime.sendMessage(
{ message: "getCurrentTabId" },
(response: TabIdResponse) => {
if (response?.tabId !== undefined) {
console.log("Received tabId:", response.tabId);
} else {
console.error("Failed to get current tab ID or tabId is undefined");
}
},
);

let root: ReactDOM.Root;
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const selectedTabId = localStorage.getItem("selected-tabId") || null;
if (selectedTabId && msg.text === "clickedIcon") {
const extensionRoot = document.getElementById("extension-root");
if (extensionRoot) {
if (root) {
root.unmount();
}
root = ReactDOM.createRoot(extensionRoot);
// FIXME: bring back the session cookie
root.render(<ContentApp isOpen={true} sessionCookie={"whatever"} />);
}
}
});

function initial() {
const rootDiv =
Expand All @@ -41,21 +10,16 @@ function initial() {
document.body.appendChild(rootDiv);
}

setTimeout(initial, 1000);
setTimeout(initial, 200);

document.addEventListener(
EventNames.RECORDING_DATA_CAPTURED,
(e: Event): void => {
const jsonHolder = document.getElementById("jsonHolder");
const data = jsonHolder?.getAttribute("src") || "";
jsonHolder?.remove();
chrome.runtime.sendMessage(
{ message: ChromeMessageNames.SEND_RECORDING_PACKET, data },
(response) => {
if (response.status !== "success") {
console.log(response);
}
},
);
},
);
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const extensionRoot = document.getElementById("extension-root");
if (extensionRoot) {
if (root) {
root.unmount();
}
root = ReactDOM.createRoot(extensionRoot);
root.render(<ContentApp isOpen={true} sessionCookie={msg.loginToken} />);
}
sendResponse({ status: "success" });
});
Loading

0 comments on commit c6ef6b9

Please sign in to comment.