Files
Whatsapp-Desktop/main.js
T
JustZoe101 02f5b05265 Add WhatsApp media downloads and completion toasts
- Save WhatsApp media downloads without overwriting existing files
- Show download notifications with open and folder actions
- Display the app version and update Linux package metadata
2026-11-10 10:59:28 +01:00

253 lines
5.9 KiB
JavaScript

const {
app,
BrowserWindow,
dialog,
shell,
session
} = require('electron');
const fs = require('node:fs');
const path = require('node:path');
const downloadToast = require('./download-toast');
const version = require('./version');
const WHATSAPP_URL = 'https://web.whatsapp.com/';
const WHATSAPP_ORIGIN = new URL(WHATSAPP_URL).origin;
const PARTITION = 'persist:whatsapp';
function isWhatsAppUrl(rawUrl) {
try {
const url = new URL(rawUrl);
return (
url.protocol === 'https:' &&
url.hostname === 'web.whatsapp.com'
);
} catch {
return false;
}
}
function isExternalUrl(rawUrl) {
try {
const url = new URL(rawUrl);
return url.protocol === 'https:';
} catch {
return false;
}
}
// WhatsApp Web decrypts media in the page and hands it to the download manager
// as a blob: URL that belongs to the WhatsApp origin.
function isWhatsAppBlobUrl(rawUrl) {
try {
const url = new URL(rawUrl);
return (
url.protocol === 'blob:' &&
url.origin === WHATSAPP_ORIGIN
);
} catch {
return false;
}
}
// Regular attachments are served from the whatsapp.net CDN.
function isWhatsAppCdnUrl(rawUrl) {
try {
const url = new URL(rawUrl);
return (
url.protocol === 'https:' &&
(url.hostname === 'whatsapp.net' ||
url.hostname.endsWith('.whatsapp.net'))
);
} catch {
return false;
}
}
// Save next to existing files instead of silently overwriting them.
function nextAvailableDownloadPath(filename) {
const directory = app.getPath('downloads');
fs.mkdirSync(directory, { recursive: true });
const name = path.basename(filename || 'download') || 'download';
const extension = path.extname(name);
const base = path.basename(name, extension);
let candidate = path.join(directory, name);
let counter = 1;
while (fs.existsSync(candidate)) {
candidate = path.join(directory, `${base} (${counter})${extension}`);
counter += 1;
}
return candidate;
}
function handleDownload(event, item, webContents) {
const itemUrl = item.getURL();
const startedByWhatsApp = webContents
? isWhatsAppUrl(webContents.getURL())
: false;
// Blob URLs can only be created by the WhatsApp origin itself, so they are
// trusted even when Electron reports no initiating webContents.
if (!isWhatsAppBlobUrl(itemUrl) &&
!(startedByWhatsApp && isWhatsAppCdnUrl(itemUrl))) {
event.preventDefault();
return;
}
const filename = item.getFilename();
item.setSavePath(nextAvailableDownloadPath(filename));
item.once('done', (_doneEvent, state) => {
if (state === 'completed') {
downloadToast.show(item.getSavePath());
return;
}
if (state === 'interrupted') {
dialog.showErrorBox(
'Download mislukt',
`"${filename}" kon niet worden opgeslagen in je downloadmap.`
);
}
});
}
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 850,
minWidth: 750,
minHeight: 550,
title: 'WhatsApp Desktop',
icon: path.join(__dirname, 'build', 'icon.png'),
autoHideMenuBar: true,
backgroundColor: '#111b21',
webPreferences: {
partition: PARTITION,
preload: path.join(__dirname, 'toast-preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
devTools: false
}
});
// Identify as Chromium rather than Electron.
const chromeVersion = process.versions.chrome;
win.webContents.setUserAgent(
`Mozilla/5.0 (X11; Linux x86_64) ` +
`AppleWebKit/537.36 (KHTML, like Gecko) ` +
`Chrome/${chromeVersion} Safari/537.36`
);
// Keep the version visible in the window title and in the page itself.
const windowTitle = `WhatsApp Desktop v${app.getVersion()}`;
win.setTitle(windowTitle);
win.on('page-title-updated', (event) => {
event.preventDefault();
win.setTitle(windowTitle);
});
// Re-apply after every full page load (e.g. after logging in).
win.webContents.on('dom-ready', () => {
version.injectVersionStyles(win.webContents).catch(() => {});
version.injectVersionBadge(win.webContents).catch(() => {});
downloadToast.injectStyles(win.webContents).catch(() => {});
});
win.webContents.on('did-navigate-in-page', () => {
version.injectVersionBadge(win.webContents).catch(() => {});
});
downloadToast.setWindow(win);
win.on('closed', () => {
downloadToast.closeAll();
});
// Block navigation outside WhatsApp Web.
win.webContents.on('will-navigate', (event, url) => {
if (!isWhatsAppUrl(url)) {
event.preventDefault();
if (isExternalUrl(url)) {
shell.openExternal(url);
}
}
});
// Prevent new Electron windows.
win.webContents.setWindowOpenHandler(({ url }) => {
if (isExternalUrl(url) && !isWhatsAppUrl(url)) {
shell.openExternal(url);
}
return { action: 'deny' };
});
// Load WhatsApp Web.
win.loadURL(WHATSAPP_URL);
return win;
}
app.whenReady().then(() => {
const whatsappSession = session.fromPartition(PARTITION);
// Only allow notifications from WhatsApp Web.
whatsappSession.setPermissionRequestHandler(
(_webContents, permission, callback, details) => {
const trusted = isWhatsAppUrl(
details.requestingUrl || ''
);
callback(
trusted &&
permission === 'notifications'
);
}
);
whatsappSession.setPermissionCheckHandler(
(_webContents, permission, requestingOrigin) => {
return (
permission === 'notifications' &&
isWhatsAppUrl(requestingOrigin)
);
}
);
// Allow WhatsApp media downloads; block downloads from anywhere else.
whatsappSession.on('will-download', handleDownload);
downloadToast.registerIpc();
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});