-
-
Notifications
You must be signed in to change notification settings - Fork 561
/
index.js
450 lines (366 loc) · 11.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
'use strict';
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const {darkMode, is} = require('electron-util');
const log = require('electron-log');
const {autoUpdater} = require('electron-updater');
const isDev = require('electron-is-dev');
const updateAppMenu = require('./menu');
const config = require('./config');
const tray = require('./tray');
const {sendAction, sendBackgroundAction} = require('./util');
const emoji = require('./emoji');
require('./touch-bar'); // eslint-disable-line import/no-unassigned-import
require('electron-debug')({
enabled: true, // TODO: This is only enabled to allow `Command+R` because messenger sometimes gets stuck after computer waking up
showDevTools: false
});
require('electron-dl')();
require('electron-context-menu')();
const domain = config.get('useWorkChat') ? 'facebook.com' : 'messenger.com';
const {app, ipcMain, Menu, nativeImage, Notification, systemPreferences} = electron;
app.setAppUserModelId('com.sindresorhus.caprine');
// Disables broken color space correction in Chromium.
// You can see differing background color on the login screen.
// https://github.com/electron/electron/issues/9671
app.commandLine.appendSwitch('disable-color-correct-rendering');
if (!config.get('hardwareAcceleration')) {
app.disableHardwareAcceleration();
}
if (!isDev) {
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
const FOUR_HOURS = 1000 * 60 * 60 * 4;
setInterval(() => autoUpdater.checkForUpdates(), FOUR_HOURS);
autoUpdater.checkForUpdates();
}
let mainWindow;
let isQuitting = false;
let prevMessageCount = 0;
let dockMenu;
if (!app.requestSingleInstanceLock()) {
app.quit();
}
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
}
});
function updateBadge(conversations) {
// Ignore `Sindre messaged you` blinking
if (!Array.isArray(conversations)) {
return;
}
const messageCount = conversations.filter(({unread}) => unread).length;
if (is.macos || is.linux) {
if (config.get('showUnreadBadge')) {
app.setBadgeCount(messageCount);
}
if (is.macos && config.get('bounceDockOnMessage') && prevMessageCount !== messageCount) {
app.dock.bounce('informational');
prevMessageCount = messageCount;
}
}
if (is.linux || is.windows) {
if (config.get('showUnreadBadge')) {
tray.setBadge(messageCount);
}
if (config.get('flashWindowOnMessage')) {
mainWindow.flashFrame(messageCount !== 0);
}
}
if (is.windows) {
if (config.get('showUnreadBadge')) {
if (messageCount === 0) {
mainWindow.setOverlayIcon(null, '');
} else {
// Delegate drawing of overlay icon to renderer process
mainWindow.webContents.send('render-overlay-icon', messageCount);
}
}
}
}
ipcMain.on('update-overlay-icon', (event, data, text) => {
const img = electron.nativeImage.createFromDataURL(data);
mainWindow.setOverlayIcon(img, text);
});
function enableHiresResources() {
const scaleFactor = Math.max(...electron.screen.getAllDisplays().map(x => x.scaleFactor));
if (scaleFactor === 1) {
return;
}
const filter = {urls: [`*://*.${domain}/`]};
electron.session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
let cookie = details.requestHeaders.Cookie;
if (cookie && details.method === 'GET') {
if (/(; )?dpr=\d/.test(cookie)) {
cookie = cookie.replace(/dpr=\d/, `dpr=${scaleFactor}`);
} else {
cookie = `${cookie}; dpr=${scaleFactor}`;
}
details.requestHeaders.Cookie = cookie;
}
callback({
cancel: false,
requestHeaders: details.requestHeaders
});
});
}
function initRequestsFiltering() {
const filter = {
urls: [
`*://*.${domain}/*typ.php*`, // Type indicator blocker
`*://*.${domain}/*change_read_status.php*`, // Seen indicator blocker
'*://static.xx.fbcdn.net/images/emoji.php/v9/*', // Emoji
'*://facebook.com/images/emoji.php/v9/*' // Emoji
]
};
electron.session.defaultSession.webRequest.onBeforeRequest(filter, ({url}, callback) => {
if (url.includes('emoji.php')) {
callback(emoji.process(url));
} else if (url.includes('typ.php')) {
callback({cancel: config.get('block.typingIndicator')});
} else if (url.includes('change_read_status.php')) {
callback({cancel: config.get('block.chatSeen')});
}
});
}
function setUserLocale() {
const facebookLocales = require('facebook-locales');
const userLocale = facebookLocales.bestFacebookLocaleFor(app.getLocale().replace('-', '_'));
const cookie = {
url: 'https://www.messenger.com/',
name: 'locale',
value: userLocale
};
electron.session.defaultSession.cookies.set(cookie, () => {});
}
function setNotificationsMute(status) {
const label = 'Mute Notifications';
const muteMenuItem = Menu.getApplicationMenu().getMenuItemById('mute-notifications');
config.set('notificationsMuted', status);
muteMenuItem.checked = status;
if (is.macos) {
const item = dockMenu.items.find(x => x.label === label);
item.checked = status;
}
}
function createMainWindow() {
const lastWindowState = config.get('lastWindowState');
const isDarkMode = config.get('darkMode');
// Messenger or Work Chat
const mainURL = config.get('useWorkChat')
? 'https://work.facebook.com/chat'
: 'https://www.messenger.com/login/';
const win = new electron.BrowserWindow({
title: app.getName(),
show: false,
x: lastWindowState.x,
y: lastWindowState.y,
width: lastWindowState.width,
height: lastWindowState.height,
icon: is.linux && path.join(__dirname, 'static/Icon.png'),
minWidth: 400,
minHeight: 200,
alwaysOnTop: config.get('alwaysOnTop'),
titleBarStyle: 'hiddenInset',
autoHideMenuBar: config.get('autoHideMenuBar'),
darkTheme: isDarkMode, // GTK+3
webPreferences: {
preload: path.join(__dirname, 'browser.js'),
nodeIntegration: false,
contextIsolation: true,
plugins: true
}
});
setUserLocale();
initRequestsFiltering();
darkMode.onChange(() => {
win.webContents.send('set-dark-mode');
});
if (is.macos) {
win.setSheetOffset(40);
}
win.loadURL(mainURL);
win.on('close', e => {
if (config.get('quitOnWindowClose')) {
app.quit();
return;
}
if (!isQuitting) {
e.preventDefault();
// Workaround for electron/electron#10023
win.blur();
win.hide();
}
});
win.on('focus', () => {
if (config.get('flashWindowOnMessage')) {
// This is a security in the case where messageCount is not reset by page title update
win.flashFrame(false);
}
});
return win;
}
(async () => {
await app.whenReady();
const trackingUrlPrefix = `https://l.${domain}/l.php`;
updateAppMenu();
mainWindow = createMainWindow();
tray.create(mainWindow);
if (is.macos) {
const firstItem = {
label: 'Mute Notifications',
type: 'checkbox',
checked: config.get('notificationsMuted'),
click() {
mainWindow.webContents.send('toggle-mute-notifications');
}
};
dockMenu = electron.Menu.buildFromTemplate([firstItem]);
app.dock.setMenu(dockMenu);
ipcMain.on('conversations', (event, conversations) => {
if (conversations.length === 0) {
return;
}
const items = conversations.map(({label, icon}, index) => {
return {
label: `${label}`,
icon: nativeImage.createFromDataURL(icon),
click: () => {
mainWindow.show();
sendAction('jump-to-conversation', index + 1);
}
};
});
app.dock.setMenu(electron.Menu.buildFromTemplate([firstItem, {type: 'separator'}, ...items]));
});
}
// Update badge on conversations change
ipcMain.on('conversations', (event, conversations) => updateBadge(conversations));
enableHiresResources();
const {webContents} = mainWindow;
webContents.on('dom-ready', () => {
webContents.insertCSS(fs.readFileSync(path.join(__dirname, 'browser.css'), 'utf8'));
webContents.insertCSS(fs.readFileSync(path.join(__dirname, 'dark-mode.css'), 'utf8'));
webContents.insertCSS(fs.readFileSync(path.join(__dirname, 'vibrancy.css'), 'utf8'));
if (config.get('useWorkChat')) {
webContents.insertCSS(fs.readFileSync(path.join(__dirname, 'workchat.css'), 'utf8'));
}
if (fs.existsSync(path.join(app.getPath('userData'), 'custom.css'))) {
webContents.insertCSS(
fs.readFileSync(path.join(app.getPath('userData'), 'custom.css'), 'utf8')
);
}
if (config.get('launchMinimized') || app.getLoginItemSettings().wasOpenedAsHidden) {
mainWindow.hide();
} else {
mainWindow.show();
}
webContents.send('toggle-mute-notifications', config.get('notificationsMuted'));
webContents.send('toggle-message-buttons', config.get('showMessageButtons'));
webContents.executeJavaScript(
fs.readFileSync(path.join(__dirname, 'notifications-isolated.js'), 'utf8')
);
});
webContents.on('new-window', (event, url, frameName, disposition, options) => {
event.preventDefault();
if (url === 'about:blank') {
if (frameName !== 'about:blank') {
// Voice/video call popup
options.show = true;
options.titleBarStyle = 'default';
options.webPreferences.nodeIntegration = false;
options.webPreferences.preload = path.join(__dirname, 'browser-call.js');
event.newGuest = new electron.BrowserWindow(options);
}
} else {
if (url.startsWith(trackingUrlPrefix)) {
url = new URL(url).searchParams.get('u');
}
electron.shell.openExternal(url);
}
});
webContents.on('will-navigate', (event, url) => {
const isMessengerDotCom = url => {
const {hostname} = new URL(url);
return hostname === 'www.messenger.com';
};
const isTwoFactorAuth = url => {
const twoFactorAuthURL = 'https://www.facebook.com/checkpoint/start';
return url.startsWith(twoFactorAuthURL);
};
const isWorkChat = url => {
const {hostname, pathname} = new URL(url);
if (hostname === 'work.facebook.com') {
return true;
}
if (
// Example: https://company-name.facebook.com/login
hostname.endsWith('.facebook.com') &&
(pathname.startsWith('/login') || pathname.startsWith('/chat'))
) {
return true;
}
if (hostname === 'login.microsoftonline.com') {
return true;
}
return false;
};
if (isMessengerDotCom(url) || isTwoFactorAuth(url) || isWorkChat(url)) {
return;
}
event.preventDefault();
electron.shell.openExternal(url);
});
})();
if (is.macos) {
ipcMain.on('set-vibrancy', () => {
mainWindow.setVibrancy('sidebar');
if (config.get('followSystemAppearance')) {
systemPreferences.setAppLevelAppearance(systemPreferences.isDarkMode() ? 'dark' : 'light');
} else {
systemPreferences.setAppLevelAppearance(config.get('darkMode') ? 'dark' : 'light');
}
});
}
ipcMain.on('mute-notifications-toggled', (event, status) => {
setNotificationsMute(status);
});
app.on('activate', () => {
mainWindow.show();
});
app.on('before-quit', () => {
isQuitting = true;
config.set('lastWindowState', mainWindow.getNormalBounds());
});
const notifications = new Map();
ipcMain.on('notification', (event, {id, title, body, icon, silent}) => {
const notification = new Notification({
title,
body,
hasReply: true,
icon: nativeImage.createFromDataURL(icon),
silent
});
notifications.set(id, notification);
notification.on('click', () => {
mainWindow.show();
sendAction('notification-callback', {callbackName: 'onclick', id});
notifications.delete(id);
});
notification.on('reply', (event, reply) => {
// We use onclick event used by messenger to go to the right convo
sendBackgroundAction('notification-reply-callback', {callbackName: 'onclick', id, reply});
notifications.delete(id);
});
notification.on('close', () => {
sendAction('notification-callback', {callbackName: 'onclose', id});
notifications.delete(id);
});
notification.show();
});