-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
700 lines (545 loc) · 21.8 KB
/
main.js
File metadata and controls
700 lines (545 loc) · 21.8 KB
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
const { app, BrowserWindow, ipcMain,Tray, Menu, globalShortcut, dialog } = require('electron');
const { autoUpdater } = require("electron-updater");
const { startStreaming, stopStreaming } = require('./streamHandler'); // Import the streaming module
//const axios = require('axios'); // Import axios for API requests
const path = require("path");
//const fs = require("fs");
const { exec } = require("child_process");
const baseURL = "https://pbx.sipcentric.com/api/v1/"
const debug = !app.isPackaged;
let store;
let Store;
let win;
let tray;
console.log("Process started with arguments:", process.argv);
const gotTheLock = app.requestSingleInstanceLock();
const server = "https://github.com/speakdigital/Nimvelo-Dialer/releases/latest";
if (!gotTheLock) {
/* let logFilePath = path.join(app.getPath("userData"), "log.txt");
let message = "Second instans started with arguments: "+process.argv.toString();
fs.appendFileSync(logFilePath, `[${new Date().toISOString()}] ${message}\n`, "utf8"); */
console.log("Process quitting as no second instance allowed");
const telUrl = process.argv.find(arg => arg.startsWith("tel:"));
if (telUrl) {
// Send the tel URL to the existing instance
console.log("Sending the tel: ardgument to the main instance");
app.emit("second-instance", null, process.argv);
}
app.quit();
} else
{ app.whenReady().then(async() => {
autoUpdater.autoDownload = true; // Automatically download updates
autoUpdater.on("update-downloaded", () => {
dialog
.showMessageBox({
type: "question",
buttons: ["Restart", "Later"],
defaultId: 0,
title: "Update Ready",
message: "Update downloaded. Restart the app to install?",
})
.then((result) => {
if (result.response === 0) {
autoUpdater.quitAndInstall();
}
});
});
autoUpdater.on("error", (err) => {
console.error("Update error:", err);
});
console.log("Checking for updates. My version is", app.getVersion());
autoUpdater.checkForUpdatesAndNotify();
console.log("Initializing Electron Store...");
Store = (await import('electron-store')).default;
store = new Store(); // Initialize after import
console.log("Electron Store Ready!");
const contextMenu = await import('electron-context-menu');
contextMenu.default({
showCopyImage: false,
showSaveImageAs: false,
showInspectElement: false
});
// Check if all required credentials are stored
const username = store.get("username");
const password = store.get("password");
const customer = store.get("customer");
const extension = store.get("extension");
// Determine which page to load
let startPage = 'welcome.html';
if (username && password && customer && extension)
{ const authResult = await authenticateUser(username, password);
if (authResult.success === true) {
startPage = 'home.html';
startStreaming();
}
}
win = new BrowserWindow({
width: 400,
height: 600,
resizable: false,
webPreferences: { nodeIntegration: true, contextIsolation: false },
icon: process.platform === 'win32'
? path.join(__dirname, 'assets', 'icon128x128.png') // Windows icon
: path.join(__dirname, 'assets', 'icon.icns')
});
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(__dirname, 'assets', 'icon1024x1024.png'));
}
win.setMenu(null);
win.loadFile(path.join(__dirname, `./renderer/${startPage}`));
if (debug) {
win.webContents.once('did-finish-load', () => {
win.webContents.openDevTools();
});
}
globalShortcut.register("CommandOrControl+Shift+D", () => {
if (win.isMinimized()) {
win.restore();
}
win.show();
win.focus();
win.webContents.send("focus-dialer");
});
createTray();
if (!debug) {
if (process.platform === "win32") {
registerProtocol();
}
}
});
}
ipcMain.handle("set-auto-launch", async (event, enable) => {
app.setLoginItemSettings({
openAtLogin: enable,
path: app.getPath("exe")
});
return enable;
});
ipcMain.handle("get-auto-launch-status", async () => {
const settings = app.getLoginItemSettings();
return settings.openAtLogin;
});
function registerProtocol() {
const appPath = app.getPath("exe");
const regCommands = [
`reg add "HKCU\\Software\\Classes\\callto" /ve /d "URL:callto" /f`,
`reg add "HKCU\\Software\\Classes\\callto" /v "URL Protocol" /d "" /f`,
`reg add "HKCU\\Software\\Classes\\tel" /ve /d "URL:tel" /f`,
`reg add "HKCU\\Software\\Classes\\tel" /v "URL Protocol" /d "" /f`,
`reg add "HKCU\\Software\\Classes\\NimveloDialer.callto" /f`,
`reg add "HKCU\\Software\\Classes\\NimveloDialer.callto\\Shell" /f`,
`reg add "HKCU\\Software\\Classes\\NimveloDialer.callto\\Shell\\Open" /f`,
`reg add "HKCU\\Software\\Classes\\NimveloDialer.callto\\Shell\\Open\\Command" /ve /d "\\"${appPath}\\" \\"%1\\"" /f`,
`reg add "HKCU\\Software\\NimveloDialer" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities" /v "ApplicationDescription" /d "NimveloDialer" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities" /v "ApplicationName" /d "NimveloDialer" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities\\URLAssociations" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities\\URLAssociations" /v "callto" /d "NimveloDialer.callto" /f`,
`reg add "HKCU\\Software\\NimveloDialer\\Capabilities\\URLAssociations" /v "tel" /d "NimveloDialer.callto" /f`,
`reg add "HKCU\\Software\\RegisteredApplications" /v "NimveloDialer" /d "Software\\NimveloDialer\\Capabilities" /f`
];
function runCommand(index) {
if (index >= regCommands.length) {
console.log("Protocol registration completed successfully.");
return;
}
exec(regCommands[index], (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${regCommands[index]}`, error);
}
runCommand(index + 1);
});
}
runCommand(0);
}
// this is for Mac Only
app.on("open-url", (event, url) => {
event.preventDefault();
console.log("Open URL Called");
handleTelLink(url);
});
// Handle "tel:" links (Windows/Linux when app is already running)
app.on("second-instance", (event, argv) => {
console.log("Second instance called");
const telUrl = argv.find(arg => arg.startsWith("tel:"));
if (telUrl) handleTelLink(telUrl);
});
function handleTelLink(url) {
console.log("Dialing from URL: ", url);
const phoneNumber = url.replace("tel:", "").replace("%20", "").trim();
// Integrate with your VoIP provider API or your dialer UI
if (win) {
if (win.isMinimized()) win.restore();
win.focus();
win.webContents.send("dial-phone", phoneNumber);
}
}
function createTray() {
const iconPath = path.join(__dirname, 'assets/icon24x24.png'); // Ensure the path is correct
tray = new Tray(iconPath);
const contextMenu = Menu.buildFromTemplate([
{ label: 'Show App', click: () => win.show() },
{ label: 'Quit', click: () => {
app.isQuiting = true;
tray.destroy();
app.exit(); // ✅ Force exit the app immediately
}}
]);
tray.setToolTip('Nimvelo Dialer');
tray.setContextMenu(contextMenu);
// Hide window instead of quitting when closing
win.on('close', (event) => {
event.preventDefault();
win.hide();
});
tray.on('click', () => {
win.show();
});
}
app.on('window-all-closed', (event) => {
if (!app.isQuiting) {
event.preventDefault(); // Prevents quitting when windows are closed
} else {
app.quit(); // Allow quitting
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
ipcMain.handle("show-confirm-dialog", async (event, options) => {
const result = await dialog.showMessageBox({
type: "warning",
buttons: ["Cancel", options.button],
defaultId: 1,
title: options.title || "Confirm",
message: options.message || "Are you sure?",
});
return result.response === 1; // Returns true if "Delete" is clicked
});
ipcMain.on('show-login', () => {
win.loadFile(path.join(__dirname, './renderer/login.html')); // Switch to the login page
});
ipcMain.on('show-registerext', () => {
win.loadFile(path.join(__dirname, './renderer/registerext.html')); // Switch to extension setup page
stopStreaming(win);
});
ipcMain.on('show-home', () => {
win.loadFile(path.join(__dirname, './renderer/home.html')); // Switch to extension setup page
startStreaming(win);
});
ipcMain.handle("get-app-version", () => {
return app.getVersion();
});
ipcMain.handle('get-store-data', (event, key) => {
return store.get(key, '');
});
ipcMain.handle('set-store-data', (event, key, value) => {
store.set(key, value);
});
ipcMain.on("close-app", () => {
console.log("Closing application");
app.isQuiting = true;
app.exit();
});
ipcMain.handle("reset-app", () => {
// Clear all data
store.clear();
console.log("Electron Store has been cleared!");
win.loadFile(path.join(__dirname, `./renderer/welcome.html`));
});
async function authenticateUser(username, password) {
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const thispath = new URL('customers/me', baseURL).toString();
try {
const response = await fetch(thispath, {
method: 'HEAD',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
if (response.ok) {
store.set('username', username);
store.set('password', password);
return { success: true, message: "Login successful!" };
} else {
return { success: false, message: "Invalid credentials" };
}
} catch (error) {
return { success: false, message: "Network error. Please try again." };
}
}
// Make authenticateUser accessible via IPC
ipcMain.handle('authenticate-user', async (event, username, password) => {
return await authenticateUser(username, password);
});
// Handle getting customers from API with Basic Auth
ipcMain.handle('get-customers', async () => {
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const requestURL = new URL('customers', baseURL).toString();
// Retrieve stored credentials
const username = store.get('username', '');
const password = store.get('password', '');
console.log("About to fecth customers from ",requestURL);
try {
const response = await fetch(requestURL, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
const data = await response.json();
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
const localCustomers = [];
data.items.forEach(item => {
let label = item.company;
if (item.partnerCompany) {
label += ' - ' + item.partnerCompany;
}
localCustomers.push({ label: label, value: item.id });
});
return localCustomers; // Send back to renderer
} catch (error) {
console.error("Error fetching customers:", error);
return [];
}
});
ipcMain.handle('get-extensions', async (event, customerId) => {
if (!customerId) {
console.error("No customer ID provided. Tying from settings.");
customerId = store.get('customer', '');
if (!customerId) return [];
}
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const requestURL = new URL(`customers/${customerId}/endpoints`, baseURL).toString();
console.log("about to get extension list from ",requestURL);
// Retrieve stored credentials
const username = store.get('username', '');
const password = store.get('password', '');
console.log("About to get extensions from ",requestURL);
try {
const response = await fetch(requestURL, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
const data = await response.json();
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
const localExtensions = [];
console.log("Received extension list: ",data);
data.items.forEach(item => {
if (item.type == "phone") {
let label = `${item.name} - ${item.shortNumber}`;
localExtensions.push({
label: label,
value: item.id,
name: item.name, shortNumber: item.shortNumber,
readonly: item.hasOwnProperty('readOnly') ? Boolean(item.readOnly) : false,
defaultCallerId: item.defaultCallerId
});
}
});
return localExtensions; // Send back to renderer
} catch (error) {
console.error("Error fetching extensions:", error);
return [];
}
});
ipcMain.handle('get-phonebook', async (event) => {
const customer = store.get('customer', '');
// Retrieve stored credentials
const username = store.get('username', '');
const password = store.get('password', '');
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const requestURL = new URL(`customers/${customer}/phonebook?pageSize=200`, baseURL).toString();
console.log("about to get phonebook from ",requestURL);
let nextpage = requestURL;
const localPhonebook = [];
try {
do {
const response = await fetch(nextpage, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
const data = await response.json();
nextpage = "";
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
data.items.forEach(item => {
if (item.type == "phonebookentry") {
localPhonebook.push({
id: item.id,
name: item.name,
phoneNumber: item.phoneNumber
});
}
});
nextpage = data.nextPage || "";
} while (nextpage !== "")
return localPhonebook; // Send back to renderer
} catch (error) {
console.error("Error fetching extensions:", error);
return [];
}
});
ipcMain.handle('get-me', async (event) => {
const customer = store.get('customer', '');
const extension = store.get('extension', '');
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const requestURL = new URL(`customers/${customer}/endpoints/${extension}`, baseURL).toString();
console.log("about to get my extension from ",requestURL);
// Retrieve stored credentials
const username = store.get('username', '');
const password = store.get('password', '');
try {
const response = await fetch(requestURL, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
const data = await response.json();
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return data; // Send back to renderer
} catch (error) {
console.error("Error fetching my extension:", error);
return [];
}
});
ipcMain.handle('get-outgoingnumers', async (event) => {
const customer = store.get('customer', '');
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const requestURL = new URL(`customers/${customer}/outgoingcallerids?pageSize=200`, baseURL).toString();
// Retrieve stored credentials
const username = store.get('username', '');
const password = store.get('password', '');
console.log("about to get outgoing numbers from ",requestURL);
try {
const response = await fetch(requestURL, {
method: 'GET',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
const data = await response.json();
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
const outgoingNumbers = [];
data.items.forEach(item => {
if (item.type == "outgoingcallerid" && item.allowCalls == true && item.status == "APPROVED") {
let label = `${item.number}`;
outgoingNumbers.push({
label: label,
value: item.id
});
}
});
return outgoingNumbers; // Send back to renderer
} catch (error) {
console.error("Error fetching my extension:", error);
return [];
}
});
ipcMain.handle('dial', async (event, call, selectedCallerId, withhold) => {
console.log(`Dialing ${call} using Caller ID ${selectedCallerId}, Withhold: ${withhold}`);
if (withhold == 1) { call = '*67' + call; }
call = call.replace(/(?:\+44|\(|\)|-|\s)/g, "");
try {
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const username = store.get('username', '');
const password = store.get('password', '');
const customer = store.get('customer', '');
const extension = store.get('extension', '');
const requestURL = new URL(`customers/${customer}/calls`, baseURL).toString();
const endpoint = new URL(`customers/${customer}/endpoints/${extension}`, baseURL).toString();
const outgoingId = new URL(`customers/${customer}/outgoingcallerids/${selectedCallerId}`, baseURL).toString();
var requestBody = {
type: "call",
endpoint: endpoint,
to: call,
callerId: outgoingId
}
console.log("About to make a call using ",requestURL, " with data ",requestBody)
const response = await fetch(requestURL, {
method: 'POST',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64'),
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return { success: true, message: "Call initiated successfully!" };
} catch (error) {
console.error("Error dialing:", error);
return { success: false, message: error.message };
}
});
ipcMain.handle('delete-contact', async (event, contactid) => {
console.log(`Deleting ${contactid} from address book.`);
try {
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const username = store.get('username', '');
const password = store.get('password', '');
const customer = store.get('customer', '');
const requestURL = new URL(`customers/${customer}/phonebook/${contactid}`, baseURL).toString();
const response = await fetch(requestURL, {
method: 'DELETE',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
});
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return { success: true, message: "Phonebook Entry deleted" };
} catch (error) {
console.error("Error deleting:", error);
return { success: false, message: error.message };
}
});
ipcMain.handle('phonebook-add', async (event, name, number) => {
console.log(`Adding ${name} with number ${number} to address book.`);
try {
const baseURL = "https://pbx.sipcentric.com/api/v1/";
const username = store.get('username', '');
const password = store.get('password', '');
const customer = store.get('customer', '');
const requestURL = new URL(`customers/${customer}/phonebook`, baseURL).toString();
var requestBody = {
type: "phonebookentry",
name: name,
phoneNumber: number
}
const response = await fetch(requestURL, {
method: 'POST',
headers: {
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64') ,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return { success: true, message: "Phonebook Entry added" };
} catch (error) {
console.error("Error deleting:", error);
return { success: false, message: error.message };
}
});