195 lines
6.6 KiB
TypeScript
195 lines
6.6 KiB
TypeScript
import { app, BrowserWindow, desktopCapturer } from "electron";
|
|
import * as fs from "fs";
|
|
import path from "path";
|
|
import axios from 'axios';
|
|
import https from 'https';
|
|
import sharp from 'sharp';
|
|
import { saveToken } from "./tokenHelper.js";
|
|
import { activeWindow } from "get-windows";
|
|
import { exec } from "child_process";
|
|
import { getUIPath } from "../pathResolver.js";
|
|
|
|
const httpsAgent = new https.Agent({
|
|
rejectUnauthorized: false
|
|
});
|
|
|
|
|
|
// Blur using an offscreen canvas
|
|
async function blurAndCompressBase64Image(base64: string): Promise<Buffer> {
|
|
const buffer = Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ''), 'base64');
|
|
const outputBuffer = await sharp(buffer)
|
|
.blur(8) // adjust blur radius here
|
|
.jpeg({ quality: 70 }) // compress output
|
|
.toBuffer();
|
|
return outputBuffer;
|
|
}
|
|
|
|
export const takeScreenshot = async () => {
|
|
// const sources = await desktopCapturer.getSources({ types: ["screen"] });
|
|
const sources = await desktopCapturer.getSources({
|
|
types: ['window'], thumbnailSize: {
|
|
height: 768,
|
|
width: 1366
|
|
}
|
|
});
|
|
|
|
|
|
// Capture the first screen (you can choose others by filtering sources)
|
|
const screen = sources[0];
|
|
let image = screen.thumbnail.toDataURL();
|
|
console.log("blurAndCompressBase64Image Calling")
|
|
|
|
const blurredBuffer = await blurAndCompressBase64Image(image);
|
|
|
|
const folderPath = "C:\\Users\\Public\\vatracker\\screenshots";
|
|
|
|
// Ensure directory exists
|
|
if (!fs.existsSync(folderPath)) {
|
|
fs.mkdirSync(folderPath, { recursive: true });
|
|
}
|
|
|
|
const filePath = path.join(folderPath, `screenshot-${Date.now()}.png`);
|
|
fs.writeFileSync(filePath, blurredBuffer);
|
|
|
|
|
|
|
|
console.log(`Screenshot saved at: ${filePath}`);
|
|
}
|
|
|
|
export const handleLogin = async (credentials: { email: string, password: string }) => {
|
|
try {
|
|
// Call your login API
|
|
console.log("🟡 login Request received", credentials);
|
|
|
|
console.log("app.getAppPath()", app.getAppPath());
|
|
console.log("UIPATH", getUIPath());
|
|
console.log("Doom 1");
|
|
|
|
try {
|
|
console.log("➡️ Calling API...");
|
|
const response = await axios.post(
|
|
'quality-friendly-goldfish.ngrok-free.app/api/v1/va/login',
|
|
{ userDetails: { ...credentials } },
|
|
{ headers: { "ngrok-skip-browser-warning": 69420 }, httpsAgent }
|
|
);
|
|
|
|
console.log("API CAlled", response)
|
|
const { accessToken, refreshToken } = response.data;
|
|
|
|
await saveToken("ACCESS_TOKEN", accessToken);
|
|
await saveToken("REFRESH_TOKEN", refreshToken);
|
|
|
|
return { success: true, user: response.data.user };
|
|
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
if ("response" in error && typeof (error.response) == "object" && error.response !== null && ("data" in error.response)) {
|
|
console.log("❌ login API call failed:", error?.response.data);
|
|
console.log("Server responded:", error?.response.data);
|
|
return { success: false, error: error?.response.data || "Request failed" };
|
|
} else {
|
|
return { success: false, error: error?.message || "Check you Internet connection and try again" };
|
|
}
|
|
}
|
|
}
|
|
|
|
} catch (err) {
|
|
if (err instanceof Error) {
|
|
return { success: false, error: err.message };
|
|
}
|
|
|
|
if (typeof err === "object" && err !== null && "response" in err) {
|
|
const axiosErr = err as any;
|
|
return { success: false, error: axiosErr.response?.data?.message || "Unknown error" };
|
|
}
|
|
|
|
return { success: false, error: "Unexpected error occurred" };
|
|
}
|
|
}
|
|
|
|
// Get active window info with timestamp
|
|
export const getActiveApp = async () => {
|
|
const result = await activeWindow();
|
|
const dataWithTime = { ...result, timestamp: new Date().toISOString() };
|
|
// console.log("🪟 Active Window with Time:", dataWithTime);
|
|
return dataWithTime;
|
|
};
|
|
|
|
// Periodically send active window updates
|
|
export const startWindowPolling = (win: BrowserWindow) => {
|
|
console.log("⏱️ Started active window polling (every 5s)");
|
|
setInterval(async () => {
|
|
try {
|
|
const app = await getActiveApp();
|
|
if (app) win.webContents.send("window:updated", app);
|
|
} catch (err) {
|
|
console.error("❌ Polling error:", err);
|
|
}
|
|
}, 5000);
|
|
};
|
|
|
|
|
|
export const getRunningAppsList = async () => {
|
|
try {
|
|
// PowerShell command: Get only apps with visible windows (non-background)
|
|
const sources = await desktopCapturer.getSources({
|
|
types: ['window', 'screen'],
|
|
thumbnailSize: { width: 150, height: 150 } // Optional: set thumbnail size
|
|
});
|
|
|
|
console.log(sources, "Sources Retrieved");
|
|
|
|
const app = sources.map(source => ({
|
|
name: source.name,
|
|
pid: source.id,
|
|
// thumbnail: source.thumbnail // Can be used as screenshot
|
|
}));
|
|
|
|
return app
|
|
} catch (error) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
|
|
export const captureSpecificApp = async (windowTitle: string): Promise<string> => {
|
|
try {
|
|
const sources = await desktopCapturer.getSources({
|
|
types: ['window', 'screen'],
|
|
thumbnailSize: { width: 650, height: 430 }
|
|
});
|
|
const targetSource = sources.find(source => source.name === windowTitle);
|
|
if (targetSource) {
|
|
|
|
let image = targetSource.thumbnail.toDataURL();
|
|
const blurredBuffer = await blurAndCompressBase64Image(image);
|
|
|
|
// Convert buffer → base64 string
|
|
const base64String = `data:image/png;base64,${blurredBuffer.toString('base64')}`;
|
|
|
|
// ✅ Return the processed base64 instead of saving
|
|
return base64String;
|
|
|
|
// const folderPath = "C:\\Users\\Public\\vatracker\\screenshots";
|
|
|
|
// // Ensure directory exists
|
|
// if (!fs.existsSync(folderPath)) {
|
|
// fs.mkdirSync(folderPath, { recursive: true });
|
|
// }
|
|
|
|
// const filePath = path.join(folderPath, `screenshot-${Date.now()}.png`);
|
|
// fs.writeFileSync(filePath, blurredBuffer);
|
|
|
|
// console.log(`Screenshot saved to ${filePath}`);
|
|
} else {
|
|
console.log(`Window with title "${windowTitle}" not found.`);
|
|
return "Not Found"
|
|
}
|
|
} catch (error) {
|
|
console.error('Error capturing screenshot:', error);
|
|
return 'Failed to capture screenshot.';
|
|
}
|
|
}
|
|
|
|
|
|
// timmer stop after 4-5 sec check it..
|