forked from sindresorhus/caprine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
366 lines (308 loc) · 9.98 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
'use strict';
const path = require('path');
const fs = require('fs');
const {URL} = require('url');
const electron = require('electron');
// -const electronLocalShortcut = require('electron-localshortcut');
const log = require('electron-log');
const {autoUpdater} = require('electron-updater');
const isDev = require('electron-is-dev');
const appMenu = require('./menu');
const config = require('./config');
const tray = require('./tray');
const {sendAction} = require('./util');
require('./touch-bar'); // eslint-disable-line import/no-unassigned-import
require('electron-debug')({enabled: true});
require('electron-dl')();
require('electron-context-menu')();
const domain = config.get('useWorkChat') ? 'facebook.com' : 'messenger.com';
const {app, ipcMain, Menu, nativeImage} = electron;
app.setAppUserModelId('com.sindresorhus.caprine');
if (!isDev) {
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
autoUpdater.checkForUpdates();
}
let mainWindow;
let isQuitting = false;
let prevMessageCount = 0;
let dockMenu;
const isAlreadyRunning = app.makeSingleInstance(() => {
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
}
});
if (isAlreadyRunning) {
app.quit();
}
function updateBadge(title, titlePrefix) {
// ignore `Sindre messaged you` blinking
if (title.indexOf(titlePrefix) === -1) {
return;
}
let messageCount = (/\((\d+)\)/).exec(title);
messageCount = messageCount ? Number(messageCount[1]) : 0;
if (process.platform === 'darwin' || process.platform === 'linux') {
if (config.get('showUnreadBadge')) {
app.setBadgeCount(messageCount);
}
if (process.platform === 'darwin' && config.get('bounceDockOnMessage') && prevMessageCount !== messageCount) {
app.dock.bounce('informational');
prevMessageCount = messageCount;
}
}
if ((process.platform === 'linux' || process.platform === 'win32') && config.get('showUnreadBadge')) {
tray.setBadge(messageCount);
}
if (process.platform === 'win32') {
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);
}
}
if (config.get('flashWindowOnMessage')) {
mainWindow.flashFrame(messageCount !== 0);
}
}
}
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 setUpPrivacyBlocking() {
const ses = electron.session.defaultSession;
const filter = {urls: [`*://*.${domain}/*typ.php*`, `*://*.${domain}/*change_read_status.php*`]};
ses.webRequest.onBeforeRequest(filter, (details, callback) => {
let blocking = false;
if (details.url.includes('typ.php')) {
blocking = config.get('block.typingIndicator');
} else {
blocking = config.get('block.chatSeen');
}
callback({cancel: blocking});
});
}
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().items[0].submenu.items
.find(x => x.label === label);
config.set('notificationsMuted', status);
muteMenuItem.checked = status;
if (process.platform === 'darwin') {
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 titlePrefix = config.get('useWorkChat') ? 'Workplace Chat' : 'Messenger';
const win = new electron.BrowserWindow({
title: app.getName(),
show: false,
x: lastWindowState.x,
y: lastWindowState.y,
width: lastWindowState.width,
height: lastWindowState.height,
icon: process.platform === 'linux' && path.join(__dirname, 'static/Icon.png'),
minWidth: 400,
minHeight: 200,
alwaysOnTop: config.get('alwaysOnTop'),
// Temp workaround for macOS High Sierra, see #295
titleBarStyle: 'hiddenInset',
autoHideMenuBar: config.get('autoHideMenuBar'),
darkTheme: isDarkMode, // GTK+3
webPreferences: {
preload: path.join(__dirname, 'browser.js'),
nodeIntegration: false,
plugins: true
}
});
setUserLocale();
setUpPrivacyBlocking();
if (process.platform === 'darwin') {
win.setSheetOffset(40);
}
win.loadURL(mainURL);
win.on('close', e => {
if (!isQuitting) {
e.preventDefault();
// Workaround for electron/electron#10023
win.blur();
if (process.platform === 'darwin') {
app.hide();
} else {
win.hide();
}
}
});
win.on('page-title-updated', (e, title) => {
e.preventDefault();
updateBadge(title, titlePrefix);
});
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;
}
app.on('ready', () => {
const trackingUrlPrefix = `https://l.${domain}/l.php`;
electron.Menu.setApplicationMenu(appMenu);
mainWindow = createMainWindow();
tray.create(mainWindow);
if (process.platform === 'darwin') {
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]));
});
}
enableHiresResources();
const {webContents} = mainWindow;
// Disabled because of #258
// electronLocalShortcut.register(mainWindow, 'CmdOrCtrl+V', () => {
// const clipboardHasImage = electron.clipboard.availableFormats().some(type => type.includes('image'));
// if (clipboardHasImage && config.get('confirmImagePaste')) {
// electron.dialog.showMessageBox(mainWindow, {
// type: 'info',
// buttons: ['Send', 'Cancel'],
// message: 'Are you sure you want to send the image in the clipboard?',
// icon: electron.clipboard.readImage(),
// checkboxLabel: 'Don\'t ask me again',
// checkboxChecked: false
// }, (resp, checkboxChecked) => {
// if (resp === 0) {
// // User selected send
// webContents.paste();
// config.set('confirmImagePaste', !checkboxChecked);
// }
// });
// } else {
// webContents.paste();
// }
// });
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 (config.get('launchMinimized') || app.getLoginItemSettings().wasOpenedAsHidden) {
mainWindow.hide();
} else {
mainWindow.show();
}
mainWindow.webContents.send('toggle-mute-notifications', config.get('notificationsMuted'));
mainWindow.webContents.send('toggle-message-buttons', config.get('showMessageButtons'));
});
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 {hostname} = new URL(url);
const twoFactorAuthURL = 'https://www.facebook.com/checkpoint/start';
if (hostname === 'www.messenger.com' || url.startsWith(twoFactorAuthURL)) {
return;
}
event.preventDefault();
electron.shell.openExternal(url);
});
});
ipcMain.on('set-vibrancy', () => {
if (config.get('vibrancy')) {
mainWindow.setVibrancy(config.get('darkMode') ? 'ultra-dark' : 'light');
} else {
mainWindow.setVibrancy(null);
}
});
ipcMain.on('mute-notifications-toggled', (event, status) => {
setNotificationsMute(status);
});
app.on('activate', () => {
mainWindow.show();
});
app.on('before-quit', () => {
isQuitting = true;
if (!mainWindow.isFullScreen()) {
config.set('lastWindowState', mainWindow.getBounds());
}
});