backsplash-app
Version:
An AI powered wallpaper app.
104 lines (87 loc) • 3.1 kB
text/typescript
import { ipcMain, dialog, app } from "electron";
import * as path from "path";
import log from "@/logger";
// Track if handlers have been initialized to prevent duplicates
let downloadHandlersInitialized = false;
/**
* Clean up existing download IPC handlers
*/
export function cleanupDownloadHandlers() {
try {
// Remove download handlers
ipcMain.removeHandler("download:file");
downloadHandlersInitialized = false;
log.info("[Download] Cleaned up existing IPC handlers");
} catch (error) {
// Ignore errors if handlers don't exist
log.debug("[Download] No existing handlers to clean up");
}
}
/**
* Initializes download-related IPC handlers
* @param mainWindow The main Electron BrowserWindow
*/
export async function initializeDownloadHandlers(mainWindow: Electron.BrowserWindow) {
// Prevent duplicate handler registration
if (downloadHandlersInitialized) {
log.warn("[Download] Handlers already initialized, skipping registration...");
return;
}
// Clean up any existing handlers first
cleanupDownloadHandlers();
// Dynamically import electron-dl
const electronDl = await import("electron-dl");
const { download } = electronDl;
// Handle file downloads
ipcMain.handle("download:file", async (event, { url, filename }) => {
try {
if (!url) {
return { success: false, error: "No URL provided" };
}
if (!filename) {
// Use a default filename if none is provided
filename = `backsplash-${Date.now()}.jpg`;
}
// Get the downloads folder path
let downloadsPath;
try {
// Try to get the path from Electron
downloadsPath = app.getPath("downloads");
} catch (error) {
log.error("Failed to get downloads path from Electron:", error);
// Fallback: Ask the user where to save the file
const result = await dialog.showSaveDialog(mainWindow, {
title: "Save Image",
defaultPath: path.join(app.getPath("home"), filename),
filters: [{ name: "Images", extensions: ["jpg", "jpeg", "png"] }],
});
if (result.canceled || !result.filePath) {
return { success: false, error: "Save canceled by user" };
}
downloadsPath = path.dirname(result.filePath);
filename = path.basename(result.filePath);
}
// Download the file using electron-dl
const dl = await download(mainWindow, url, {
directory: downloadsPath,
filename: filename,
saveAs: false,
// Don't open the file after download
openFolderWhenDone: false,
});
log.info(`File downloaded: ${dl.getSavePath()}`);
return {
success: true,
filePath: dl.getSavePath(),
};
} catch (error) {
log.error("Error in download:file handler:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error during download",
};
}
});
downloadHandlersInitialized = true;
log.info("[Download] All handlers registered successfully");
}