-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
executable file
·440 lines (387 loc) · 12.7 KB
/
main.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
const electron = require('electron');
const { app, BrowserWindow, Menu, shell, TouchBar, nativeImage, clipboard} = require('electron');
const contextMenu = require('electron-context-menu');
const Store = require('electron-store');
const path = require('path');
const url = require('url');
const fetch = require('electron-fetch').default;
const AsyncPolling = require('async-polling');
const notifier = require('node-notifier');
const { TouchBarLabel, TouchBarButton, TouchBarSpacer } = TouchBar;
const store = new Store();
const BASE_DOMAIN = "soapboxhq.com";
const API_HOST = "api.goodtalk.soapboxhq.com";
const electronLinks = [
'https://slack.com/signin',
'https://slack.com/oauth',
'https://accounts.google.com/o/oauth2',
'https://www.googleapis.com/oauth2',
'https://accounts.google.com/signin'
];
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
var unreadCount = 0;
var unreadChannelInfo = [];
const agendaButton = new TouchBarButton({
label: '📒 Agenda',
backgroundColor: '#97E5FF',
click: () => {
console.log('Agenda open!');
//document.querySelector('.channel-header__footer .tab-bar a:nth-child(1)');
}
});
const pastMeetingButton = new TouchBarButton({
label: '🗓 Past Meetings',
backgroundColor: '#97FFE5',
click: () => {
console.log('Agenda open!');
//document.querySelector('.channel-header__footer .tab-bar a:nth-child(2)');
}
});
const insightsButton = new TouchBarButton({
label: '📈 Insights',
backgroundColor: '#E597FF',
click: () => {
console.log('Agenda open!');
//document.querySelector('.channel-header__footer .tab-bar a:nth-child(3)');
}
});
const notesButton = new TouchBarButton({
label: '📝 Notes',
backgroundColor: '#FFE597',
click: () => {
console.log('Agenda open!');
}
});
const settingsButton = new TouchBarButton({
label: '⚙️ Settings',
backgroundColor: '#828282',
click: () => {
}
});
const touchBar = new TouchBar({
items: [
agendaButton,
pastMeetingButton,
insightsButton,
new TouchBarSpacer({size: 'flexible'}),
notesButton,
settingsButton
]
});
//Right click - context menu
contextMenu({
prepend: (defaultActions, params, browserWindow) => [
{
label: 'Share this page',
visible: mainWindow.webContents.getURL() ? true : false,
click: () => {
NotifyUserOfShareLinkCopiedToClipboard();
clipboard.writeText(mainWindow.webContents.getURL());
}
},
// {
// label: 'Rainbow',
// // Only show it when right-clicking images
// visible: params.mediaType === 'image'
// // },
// {
// label: 'Search Google for “{selection}”',
// // Only show it when right-clicking text
// visible: params.selectionText.trim().length > 0,
// click: () => {
// shell.openExternal(`https://google.com/search?q=${encodeURIComponent(params.selectionText)}`);
// }
// }
]
});
function createWindow () {
if (store.get('unreadCount')) {
unreadCount = store.get('unreadCount');
}
// Create the browser window.
mainWindow = new BrowserWindow({
// titleBarStyle: 'hidden-inset',
backgroundColor: '#f8f8f8',
titleBarStyle: 'hidden',
width: 1200,
height: 800,
minWidth: 660,
minHeight: 400,
webPreferences: {
javascript: true,
plugins: true,
nodeIntegration: false, // node globals causes problems with complex web apps
webSecurity: false,
preload: path.join(__dirname, 'preload.js'),
},
// after webpack path here should reference `resources/app/`
icon: path.join(__dirname, 'icon.png'),
});
mainWindow.loadURL(url.format({
pathname: getSoapboxURL(),
protocol: 'https:',
slashes: true
}))
mainWindow.setTouchBar(touchBar);
// Open links in the browser
mainWindow.webContents.on('new-window', function(e, url) {
var openExternally = true;
for (link of electronLinks) {
test = url.toLowerCase();
link = link.toLowerCase();
openExternally = !test.includes(link) && openExternally;
}
if (openExternally) {
e.preventDefault();
shell.openExternal(url);
}
});
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow = null
});
var template = [{
label: "Application",
submenu: [
{ label: "About", selector: "orderFrontStandardAboutPanel:" },
{ label: "Choose Soapbox", accelerator: "Shift+Command+C",
click: function() {
mainWindow.loadURL(url.format({
pathname: 'app.soapboxhq.com',
protocol: 'https:',
slashes: true
}))
}},
{ label: "Sign Out", accelerator: "Shift+Command+L",
click: function() {
DeleteStoredData();
mainWindow.webContents.session.clearStorageData();
mainWindow.reload();
}},
{ type: "separator" },
{ label: "Quit", accelerator: "Command+Q",
click: function() {
app.quit();
}}
]}, {
label: "Edit",
submenu: [
{ label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
{ label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
{ type: "separator" },
{ label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
{ label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
{ label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
]},{
label: 'View',
submenu: [
{ label: 'Reload', accelerator: 'CmdOrCtrl+R',
click(item, focusedWindow) {
mainWindow.reload();
}},
{ label: "Back", accelerator: "CmdOrCtrl+Left", click: function() {
if(mainWindow.webContents.canGoBack()) {
mainWindow.webContents.goBack();
}
}},
{ label: "Forward", accelerator: "CmdOrCtrl+Right", click: function() {
if(mainWindow.webContents.canGoForward()) {
mainWindow.webContents.goForward();
}
}},
{ label: "Share", accelerator: "CmdOrCtrl+L", click: function() {
if(mainWindow.webContents.getURL()) {
NotifyUserOfShareLinkCopiedToClipboard();
clipboard.writeText(mainWindow.webContents.getURL());
}
}},
{ label: 'Toggle Dev Tools', accelerator: 'CmdOrCtrl+I',
click(item, focusedWindow) {
mainWindow.webContents.openDevTools();
}},
{ label: 'Load test notification', accelerator: 'CmdOrCtrl+N',
click(item, focusedWindow) {
NotifyUserOfUnreadChannels();
}},
]}
];
AsyncPolling(function (end) {
updateUnreadBadgeCount();
// Then notify the polling when your job is done:
end();
// This will schedule the next call.
}, 15000).run();
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
app.setAppUserModelId("com.soapboxhq.soapbox-desktop-app");
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', function () {
createWindow();
});
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
console.log("activate window");
checkIfShouldReloadContent();
updateUnreadBadgeCount();
});
function DeleteStoredData() {
store.delete('soapboxUrl');
store.delete('me');
store.delete('token');
}
function getSoapboxURL() {
var url = 'app.soapboxhq.com';
var token = store.get('token');
var soapboxUrl = store.get('soapboxUrl');
if(soapboxUrl && token) {
url = soapboxUrl.replace(/(^\w+:|^)\/\//, '');
}
return url;
}
function NotifyUserOfShareLinkCopiedToClipboard() {
notifier.notify({
title: 'Copied to clipboard 📋!',
appID: 'com.soapboxhq.soapbox-desktop-app',
message: 'The share link to this page has been copied to your clipboard.',
sound: true,
appName: "com.soapboxhq.soapbox-desktop-app",
});
}
function checkIfShouldReloadContent() {
var shouldReloadAppContent = false;
var currentDatetime = new Date();
var storedDatetime = null;
if(!store.get('lastRefreshDatetime')) {
store.set('lastRefreshDatetime', currentDatetime.getTime());
storedDatetime = currentDatetime;
} else {
var storedDateAsLong = store.get('lastRefreshDatetime');
storedDatetime = new Date(storedDateAsLong);
}
var timeDiff = Math.abs(currentDatetime.getTime() - storedDatetime.getTime());
var diffHours = Math.floor(timeDiff / (1000 * 60 * 60));
shouldReloadAppContent = (diffHours > 4) ? true : false;
if(shouldReloadAppContent) {
store.set('lastRefreshDatetime', currentDatetime.getTime());
mainWindow.reload();
}
}
function updateUnreadBadgeCount(){
var token = store.get('token');
var soapboxUrl = store.get('soapboxUrl');
if (token && soapboxUrl) {
var options = {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
}
var localUnreadCount = 0;
unreadChannelInfo = [];
var apiURL = `https://${API_HOST}/channels`;
fetch(apiURL, options)
.then(res => res.json())
.then(json => {
json.data.forEach(function(channel){
//console.log(channel);
var attributes = channel.attributes
if(attributes['is-read'] != undefined && attributes['is-read'] == false) {
localUnreadCount++;
var item = [];
item['channelId'] = channel['id'];
item['name'] = attributes['name'];
item['avatar'] = attributes['avatar'];
item['background-gradient'] = attributes['background-gradient'];
item['mascot'] = attributes['mascot'];
unreadChannelInfo.push(item);
}
});
if(localUnreadCount > unreadCount) {
NotifyUserOfUnreadChannels();
}
UpdateUnreadTouchBarItems();
unreadCount = localUnreadCount;
app.badgeCount = unreadCount;
store.set('unreadCount', unreadCount);
}).catch(function() {
console.log("error");
});
} else {
app.badgeCount = unreadCount;
}
}
function NotifyUserOfUnreadChannels(desiredURL) {
var url = desiredURL ? desiredURL : undefined;
//url = 'com.soapboxhq.soapbox-desktop-app';
notifier.notify({
title: 'New unread items! 📫 ',
appID: 'com.soapboxhq.soapbox-desktop-app',
message: 'You have new unread channels on Soapbox. Check them out now.',
//open: url,
sound: true,
appName: "com.soapboxhq.soapbox-desktop-app",
}).on('click', function() {
//console.log(arguments);
mainWindow.show();
});
}
function UpdateUnreadTouchBarItems() {
var touchBarItems = [];
var todayButton = new TouchBarButton({
'label': '📅 Today',
'backgroundColor': '#97E5FF',
'click': () => {
mainWindow.loadURL(url.format({
pathname: getSoapboxURL(),
protocol: 'https:',
slashes: true
}));
}
});
touchBarItems.push(todayButton);
if(unreadChannelInfo.length > 0) {
unreadChannelInfo.forEach(function(channel) {
var color = '#' + channel['background-gradient'].split('-')[0];
var link = getSoapboxURL() + '/channels/'+ channel['channelId'] + '/inbox';
//var image = nativeImage.createFromDataURL(channel.avatar).resize({width: 16,height: 16});
var unreadButton = new TouchBarButton({
'label': channel.name, //channel.mascot + ' ' +
'backgroundColor': color,
'click': () => {
mainWindow.loadURL(url.format({
pathname: link,
protocol: 'https:',
slashes: true
}));
},
// 'icon': image,
// 'iconPosition': 'center',
});
touchBarItems.push(unreadButton);
});
}
var newTouchBar = new TouchBar({
items: touchBarItems
});
mainWindow.setTouchBar(newTouchBar);
}
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.