Fix: create screenshot directory if missing before saving files

main
ishaanJ91 1 year ago
parent 46fe6b22fb
commit 4172d8edc1

@ -1,37 +1,40 @@
// ScreenshotHelper.ts // ScreenshotHelper.ts
import path from "node:path" import path from "node:path";
import fs from "node:fs" import fs from "node:fs";
import { app } from "electron" import { app } from "electron";
import { v4 as uuidv4 } from "uuid" import { v4 as uuidv4 } from "uuid";
import { execFile } from "child_process" import { execFile } from "child_process";
import { promisify } from "util" import { promisify } from "util";
import screenshot from "screenshot-desktop" import screenshot from "screenshot-desktop";
import os from "os" import os from "os";
const execFileAsync = promisify(execFile) const execFileAsync = promisify(execFile);
export class ScreenshotHelper { export class ScreenshotHelper {
private screenshotQueue: string[] = [] private screenshotQueue: string[] = [];
private extraScreenshotQueue: string[] = [] private extraScreenshotQueue: string[] = [];
private readonly MAX_SCREENSHOTS = 5 private readonly MAX_SCREENSHOTS = 5;
private readonly screenshotDir: string private readonly screenshotDir: string;
private readonly extraScreenshotDir: string private readonly extraScreenshotDir: string;
private readonly tempDir: string private readonly tempDir: string;
private view: "queue" | "solutions" | "debug" = "queue" private view: "queue" | "solutions" | "debug" = "queue";
constructor(view: "queue" | "solutions" | "debug" = "queue") { constructor(view: "queue" | "solutions" | "debug" = "queue") {
this.view = view this.view = view;
// Initialize directories // Initialize directories
this.screenshotDir = path.join(app.getPath("userData"), "screenshots") this.screenshotDir = path.join(app.getPath("userData"), "screenshots");
this.extraScreenshotDir = path.join( this.extraScreenshotDir = path.join(
app.getPath("userData"), app.getPath("userData"),
"extra_screenshots" "extra_screenshots"
) );
this.tempDir = path.join(app.getPath("temp"), "interview-coder-screenshots") this.tempDir = path.join(
app.getPath("temp"),
"interview-coder-screenshots"
);
// Create directories if they don't exist // Create directories if they don't exist
this.ensureDirectoriesExist(); this.ensureDirectoriesExist();
@ -41,7 +44,11 @@ export class ScreenshotHelper {
} }
private ensureDirectoriesExist(): void { private ensureDirectoriesExist(): void {
const directories = [this.screenshotDir, this.extraScreenshotDir, this.tempDir]; const directories = [
this.screenshotDir,
this.extraScreenshotDir,
this.tempDir,
];
for (const dir of directories) { for (const dir of directories) {
if (!fs.existsSync(dir)) { if (!fs.existsSync(dir)) {
@ -60,9 +67,10 @@ export class ScreenshotHelper {
try { try {
// Clean main screenshots directory // Clean main screenshots directory
if (fs.existsSync(this.screenshotDir)) { if (fs.existsSync(this.screenshotDir)) {
const files = fs.readdirSync(this.screenshotDir) const files = fs
.filter(file => file.endsWith('.png')) .readdirSync(this.screenshotDir)
.map(file => path.join(this.screenshotDir, file)); .filter((file) => file.endsWith(".png"))
.map((file) => path.join(this.screenshotDir, file));
// Delete each screenshot file // Delete each screenshot file
for (const file of files) { for (const file of files) {
@ -77,9 +85,10 @@ export class ScreenshotHelper {
// Clean extra screenshots directory // Clean extra screenshots directory
if (fs.existsSync(this.extraScreenshotDir)) { if (fs.existsSync(this.extraScreenshotDir)) {
const files = fs.readdirSync(this.extraScreenshotDir) const files = fs
.filter(file => file.endsWith('.png')) .readdirSync(this.extraScreenshotDir)
.map(file => path.join(this.extraScreenshotDir, file)); .filter((file) => file.endsWith(".png"))
.map((file) => path.join(this.extraScreenshotDir, file));
// Delete each screenshot file // Delete each screenshot file
for (const file of files) { for (const file of files) {
@ -99,27 +108,27 @@ export class ScreenshotHelper {
} }
public getView(): "queue" | "solutions" | "debug" { public getView(): "queue" | "solutions" | "debug" {
return this.view return this.view;
} }
public setView(view: "queue" | "solutions" | "debug"): void { public setView(view: "queue" | "solutions" | "debug"): void {
console.log("Setting view in ScreenshotHelper:", view) console.log("Setting view in ScreenshotHelper:", view);
console.log( console.log(
"Current queues - Main:", "Current queues - Main:",
this.screenshotQueue, this.screenshotQueue,
"Extra:", "Extra:",
this.extraScreenshotQueue this.extraScreenshotQueue
) );
this.view = view this.view = view;
} }
public getScreenshotQueue(): string[] { public getScreenshotQueue(): string[] {
return this.screenshotQueue return this.screenshotQueue;
} }
public getExtraScreenshotQueue(): string[] { public getExtraScreenshotQueue(): string[] {
console.log("Getting extra screenshot queue:", this.extraScreenshotQueue) console.log("Getting extra screenshot queue:", this.extraScreenshotQueue);
return this.extraScreenshotQueue return this.extraScreenshotQueue;
} }
public clearQueues(): void { public clearQueues(): void {
@ -127,10 +136,10 @@ export class ScreenshotHelper {
this.screenshotQueue.forEach((screenshotPath) => { this.screenshotQueue.forEach((screenshotPath) => {
fs.unlink(screenshotPath, (err) => { fs.unlink(screenshotPath, (err) => {
if (err) if (err)
console.error(`Error deleting screenshot at ${screenshotPath}:`, err) console.error(`Error deleting screenshot at ${screenshotPath}:`, err);
}) });
}) });
this.screenshotQueue = [] this.screenshotQueue = [];
// Clear extraScreenshotQueue // Clear extraScreenshotQueue
this.extraScreenshotQueue.forEach((screenshotPath) => { this.extraScreenshotQueue.forEach((screenshotPath) => {
@ -139,10 +148,10 @@ export class ScreenshotHelper {
console.error( console.error(
`Error deleting extra screenshot at ${screenshotPath}:`, `Error deleting extra screenshot at ${screenshotPath}:`,
err err
) );
}) });
}) });
this.extraScreenshotQueue = [] this.extraScreenshotQueue = [];
} }
private async captureScreenshot(): Promise<Buffer> { private async captureScreenshot(): Promise<Buffer> {
@ -150,14 +159,16 @@ export class ScreenshotHelper {
console.log("Starting screenshot capture..."); console.log("Starting screenshot capture...");
// For Windows, try multiple methods // For Windows, try multiple methods
if (process.platform === 'win32') { if (process.platform === "win32") {
return await this.captureWindowsScreenshot(); return await this.captureWindowsScreenshot();
} }
// For macOS and Linux, use buffer directly // For macOS and Linux, use buffer directly
console.log("Taking screenshot on non-Windows platform"); console.log("Taking screenshot on non-Windows platform");
const buffer = await screenshot({ format: 'png' }); const buffer = await screenshot({ format: "png" });
console.log(`Screenshot captured successfully, size: ${buffer.length} bytes`); console.log(
`Screenshot captured successfully, size: ${buffer.length} bytes`
);
return buffer; return buffer;
} catch (error) { } catch (error) {
console.error("Error capturing screenshot:", error); console.error("Error capturing screenshot:", error);
@ -174,13 +185,17 @@ export class ScreenshotHelper {
// Method 1: Try screenshot-desktop with filename first // Method 1: Try screenshot-desktop with filename first
try { try {
const tempFile = path.join(this.tempDir, `temp-${uuidv4()}.png`); const tempFile = path.join(this.tempDir, `temp-${uuidv4()}.png`);
console.log(`Taking Windows screenshot to temp file (Method 1): ${tempFile}`); console.log(
`Taking Windows screenshot to temp file (Method 1): ${tempFile}`
);
await screenshot({ filename: tempFile }); await screenshot({ filename: tempFile });
if (fs.existsSync(tempFile)) { if (fs.existsSync(tempFile)) {
const buffer = await fs.promises.readFile(tempFile); const buffer = await fs.promises.readFile(tempFile);
console.log(`Method 1 successful, screenshot size: ${buffer.length} bytes`); console.log(
`Method 1 successful, screenshot size: ${buffer.length} bytes`
);
// Cleanup temp file // Cleanup temp file
try { try {
@ -214,22 +229,29 @@ export class ScreenshotHelper {
$bmp = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height $bmp = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
$graphics = [System.Drawing.Graphics]::FromImage($bmp) $graphics = [System.Drawing.Graphics]::FromImage($bmp)
$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bounds.Size) $graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bounds.Size)
$bmp.Save('${tempFile.replace(/\\/g, '\\\\')}', [System.Drawing.Imaging.ImageFormat]::Png) $bmp.Save('${tempFile.replace(
/\\/g,
"\\\\"
)}', [System.Drawing.Imaging.ImageFormat]::Png)
$graphics.Dispose() $graphics.Dispose()
$bmp.Dispose() $bmp.Dispose()
`; `;
// Execute PowerShell // Execute PowerShell
await execFileAsync('powershell', [ await execFileAsync("powershell", [
'-NoProfile', "-NoProfile",
'-ExecutionPolicy', 'Bypass', "-ExecutionPolicy",
'-Command', psScript "Bypass",
"-Command",
psScript,
]); ]);
// Check if file exists and read it // Check if file exists and read it
if (fs.existsSync(tempFile)) { if (fs.existsSync(tempFile)) {
const buffer = await fs.promises.readFile(tempFile); const buffer = await fs.promises.readFile(tempFile);
console.log(`Method 2 successful, screenshot size: ${buffer.length} bytes`); console.log(
`Method 2 successful, screenshot size: ${buffer.length} bytes`
);
// Cleanup // Cleanup
try { try {
@ -246,14 +268,21 @@ export class ScreenshotHelper {
console.warn("Windows PowerShell screenshot failed:", psError); console.warn("Windows PowerShell screenshot failed:", psError);
// Method 3: Last resort - create a tiny placeholder image // Method 3: Last resort - create a tiny placeholder image
console.log("All screenshot methods failed, creating placeholder image"); console.log(
"All screenshot methods failed, creating placeholder image"
);
// Create a 1x1 transparent PNG as fallback // Create a 1x1 transparent PNG as fallback
const fallbackBuffer = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64'); const fallbackBuffer = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
"base64"
);
console.log("Created placeholder image as fallback"); console.log("Created placeholder image as fallback");
// Show the error but return a valid buffer so the app doesn't crash // Show the error but return a valid buffer so the app doesn't crash
throw new Error("Could not capture screenshot with any method. Please check your Windows security settings and try again."); throw new Error(
"Could not capture screenshot with any method. Please check your Windows security settings and try again."
);
} }
} }
} }
@ -262,14 +291,14 @@ export class ScreenshotHelper {
hideMainWindow: () => void, hideMainWindow: () => void,
showMainWindow: () => void showMainWindow: () => void
): Promise<string> { ): Promise<string> {
console.log("Taking screenshot in view:", this.view) console.log("Taking screenshot in view:", this.view);
hideMainWindow() hideMainWindow();
// Increased delay for window hiding on Windows // Increased delay for window hiding on Windows
const hideDelay = process.platform === 'win32' ? 500 : 300; const hideDelay = process.platform === "win32" ? 500 : 300;
await new Promise((resolve) => setTimeout(resolve, hideDelay)) await new Promise((resolve) => setTimeout(resolve, hideDelay));
let screenshotPath = "" let screenshotPath = "";
try { try {
// Get screenshot buffer using cross-platform method // Get screenshot buffer using cross-platform method
const screenshotBuffer = await this.captureScreenshot(); const screenshotBuffer = await this.captureScreenshot();
@ -280,69 +309,77 @@ export class ScreenshotHelper {
// Save and manage the screenshot based on current view // Save and manage the screenshot based on current view
if (this.view === "queue") { if (this.view === "queue") {
screenshotPath = path.join(this.screenshotDir, `${uuidv4()}.png`) screenshotPath = path.join(this.screenshotDir, `${uuidv4()}.png`);
await fs.promises.writeFile(screenshotPath, screenshotBuffer) const screenshotDir = path.dirname(screenshotPath);
console.log("Adding screenshot to main queue:", screenshotPath) if (!fs.existsSync(screenshotDir)) {
this.screenshotQueue.push(screenshotPath) fs.mkdirSync(screenshotDir, { recursive: true });
}
await fs.promises.writeFile(screenshotPath, screenshotBuffer);
console.log("Adding screenshot to main queue:", screenshotPath);
this.screenshotQueue.push(screenshotPath);
if (this.screenshotQueue.length > this.MAX_SCREENSHOTS) { if (this.screenshotQueue.length > this.MAX_SCREENSHOTS) {
const removedPath = this.screenshotQueue.shift() const removedPath = this.screenshotQueue.shift();
if (removedPath) { if (removedPath) {
try { try {
await fs.promises.unlink(removedPath) await fs.promises.unlink(removedPath);
console.log( console.log(
"Removed old screenshot from main queue:", "Removed old screenshot from main queue:",
removedPath removedPath
) );
} catch (error) { } catch (error) {
console.error("Error removing old screenshot:", error) console.error("Error removing old screenshot:", error);
} }
} }
} }
} else { } else {
// In solutions view, only add to extra queue // In solutions view, only add to extra queue
screenshotPath = path.join(this.extraScreenshotDir, `${uuidv4()}.png`) screenshotPath = path.join(this.extraScreenshotDir, `${uuidv4()}.png`);
await fs.promises.writeFile(screenshotPath, screenshotBuffer) const screenshotDir = path.dirname(screenshotPath);
console.log("Adding screenshot to extra queue:", screenshotPath) if (!fs.existsSync(screenshotDir)) {
this.extraScreenshotQueue.push(screenshotPath) fs.mkdirSync(screenshotDir, { recursive: true });
}
await fs.promises.writeFile(screenshotPath, screenshotBuffer);
console.log("Adding screenshot to extra queue:", screenshotPath);
this.extraScreenshotQueue.push(screenshotPath);
if (this.extraScreenshotQueue.length > this.MAX_SCREENSHOTS) { if (this.extraScreenshotQueue.length > this.MAX_SCREENSHOTS) {
const removedPath = this.extraScreenshotQueue.shift() const removedPath = this.extraScreenshotQueue.shift();
if (removedPath) { if (removedPath) {
try { try {
await fs.promises.unlink(removedPath) await fs.promises.unlink(removedPath);
console.log( console.log(
"Removed old screenshot from extra queue:", "Removed old screenshot from extra queue:",
removedPath removedPath
) );
} catch (error) { } catch (error) {
console.error("Error removing old screenshot:", error) console.error("Error removing old screenshot:", error);
} }
} }
} }
} }
} catch (error) { } catch (error) {
console.error("Screenshot error:", error) console.error("Screenshot error:", error);
throw error throw error;
} finally { } finally {
// Increased delay for showing window again // Increased delay for showing window again
await new Promise((resolve) => setTimeout(resolve, 200)) await new Promise((resolve) => setTimeout(resolve, 200));
showMainWindow() showMainWindow();
} }
return screenshotPath return screenshotPath;
} }
public async getImagePreview(filepath: string): Promise<string> { public async getImagePreview(filepath: string): Promise<string> {
try { try {
if (!fs.existsSync(filepath)) { if (!fs.existsSync(filepath)) {
console.error(`Image file not found: ${filepath}`); console.error(`Image file not found: ${filepath}`);
return ''; return "";
} }
const data = await fs.promises.readFile(filepath) const data = await fs.promises.readFile(filepath);
return `data:image/png;base64,${data.toString("base64")}` return `data:image/png;base64,${data.toString("base64")}`;
} catch (error) { } catch (error) {
console.error("Error reading image:", error) console.error("Error reading image:", error);
return '' return "";
} }
} }
@ -351,22 +388,22 @@ export class ScreenshotHelper {
): Promise<{ success: boolean; error?: string }> { ): Promise<{ success: boolean; error?: string }> {
try { try {
if (fs.existsSync(path)) { if (fs.existsSync(path)) {
await fs.promises.unlink(path) await fs.promises.unlink(path);
} }
if (this.view === "queue") { if (this.view === "queue") {
this.screenshotQueue = this.screenshotQueue.filter( this.screenshotQueue = this.screenshotQueue.filter(
(filePath) => filePath !== path (filePath) => filePath !== path
) );
} else { } else {
this.extraScreenshotQueue = this.extraScreenshotQueue.filter( this.extraScreenshotQueue = this.extraScreenshotQueue.filter(
(filePath) => filePath !== path (filePath) => filePath !== path
) );
} }
return { success: true } return { success: true };
} catch (error) { } catch (error) {
console.error("Error deleting file:", error) console.error("Error deleting file:", error);
return { success: false, error: error.message } return { success: false, error: error.message };
} }
} }
@ -379,10 +416,10 @@ export class ScreenshotHelper {
console.error( console.error(
`Error deleting extra screenshot at ${screenshotPath}:`, `Error deleting extra screenshot at ${screenshotPath}:`,
err err
) );
}) });
} }
}) });
this.extraScreenshotQueue = [] this.extraScreenshotQueue = [];
} }
} }

Loading…
Cancel
Save