-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
320 lines (278 loc) · 9.1 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
// Modules to control application life and create native browser window
const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const rpath = require("path");
const serve = require("electron-serve");
const loadURL = serve({ directory: "public" });
const nodemailer = require("nodemailer");
const pdf = require("pdf-creator-node");
const fs = require("fs");
const os = require('os');
const { SerialPort, ReadlineParser } = require("serialport");
require("dotenv").config();
const tmpdirPath = os.tmpdir();
const tempdir = fs.realpathSync(tmpdirPath);
let serport;
let parser;
const baudRate = 9600;
let allowedPorts = [
"/dev/tty.usbmodem143101",
"/dev/tty.usbmodem143201",
"/dev/tty.usbmodem144101",
"COM1",
"COM2",
"COM3",
"/dev/ttyACM0",
"/dev/ttyACM1"
];
async function listSerialPorts() {
if (serport) return;
await SerialPort.list().then((ports, err) => {
if (err) return;
ports.some((p) => {
if (allowedPorts.includes(p.path)) {
let path = p.path;
serport = new SerialPort({ path, baudRate });
serport.on("error", function (err) {
log(`SerialPort Error: ${err}`);
reportError("RFID Reader Serial Port Error")
serport = undefined;
parser = undefined;
});
parser = serport.pipe(new ReadlineParser());
parser.on("data", (data) => {
mainWindow.webContents.send("rfid", data);
});
}
});
});
}
setInterval(() => {
listSerialPorts();
}, 5000);
//const { SerialPort, ReadlineParser } = require('serialport')
//const allowedSerialPorts = ["/dev/tty.usbmodem143201"]
//log(SerialPort.list())
// Run the command.
//const { portStatus, portList } = listPorts(true);
//let port;
//let parser;
//const path = '/dev/tty.usbmodem143201'
//const baudRate = 9600
//const port = new SerialPort({ path, baudRate })
//const parser = port.pipe(new ReadlineParser())
// 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;
function isDev() {
return !app.isPackaged;
}
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
preload: rpath.join(__dirname, "preload.js"),
enableRemoteModule: true,
contextIsolation: false,
},
icon: rpath.join(__dirname, "public/favicon.png"),
show: false,
autoHideMenuBar: true,
});
/*
// receive data from renderer
ipcMain.on('set-title', (event, title) => {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
})
*/
// send data to renderer
//parser.on('data', data => {
// mainWindow.webContents.send('rfid', data);
//})
ipcMain.on("sendEmail", (event, params) => {
createPdf(params, () => {
params.mailOptions.attachments = [{ // file on disk as an attachment
filename: "Planetopia.pdf",
path: `${tempdir}/wwa.pdf`
}]
sendEmail(params);
if (params.newsletter) {
// override Email options
// keep the order !
let languages = {
"de": "deutschen",
"fr": "französischen",
"en": "englischen",
};
params.mailOptions.html = `<p>Schönen Guten Tag<br /><br />${params.mailOptions.to} interessiert sich für den ${languages[params.language]} Newsletter. <br /><br />Liebe Grüsse aus Planetopia</p>`
params.mailOptions.to = "[email protected]"
params.mailOptions.subject = "Newsletter Abo aus Planetopia"
delete params.mailOptions.attachments
sendEmail(params);
}
event.returnValue = "email_was_sent"
});
});
//mainWindow.webContents.openDevTools()
mainWindow.webContents.on("before-input-event", (event, input) => {
/*
if (input.control && input.key.toLowerCase() === 'i') {
log('Pressed Control+I')
event.preventDefault()
}
*/
if (input.key.toLowerCase() === "0") {
mainWindow.webContents.openDevTools();
event.preventDefault();
}
if (input.key.toLowerCase() === "9") {
mainWindow.setKiosk(!mainWindow.kiosk);
event.preventDefault();
}
if (input.key === "Escape") {
app.quit();
}
});
// This block of code is intended for development purpose only.
// Delete this entire block of code when you are ready to package the application.
if (isDev()) {
mainWindow.loadURL("http://localhost:5000/");
} else {
loadURL(mainWindow);
}
// Uncomment the following line of code when app is ready to be packaged.
// loadURL(mainWindow);
// Open the DevTools and also disable Electron Security Warning.
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = true;
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
// Emitted when the window is ready to be shown
// This helps in showing the window gracefully.
mainWindow.once("ready-to-show", () => {
mainWindow.show();
});
}
// 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', createWindow);
app.whenReady().then(() => {
createWindow();
app.on("activate", function () {
// On macOS 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 (BrowserWindow.getAllWindows().length === 0) createWindow();
});
function enterKiosk() {
mainWindow.setKiosk(!mainWindow.kiosk);
}
if (process.env.IS_PROD === "true") setTimeout(enterKiosk, 500);
});
// Quit when all windows are closed.
app.on("window-all-closed", function () {
// On macOS 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 macOS 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();
});
// 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.
/*
ipcMain.on('ping-good', event => {
// It's so good because below have a delay 5s to execute, and this don't lock rendereder :)
setTimeout(() => {
log('GOOD finshed!')
// Send reply to a renderer
event.sender.send('ping-good-reply', 'pong')
}, 5000)
})
*/
function createPdf(params, callback){
// Read HTML Template
const html = fs.readFileSync(__dirname + "/public/templates/template.html", "utf8");
//const avatar = fs.readFileSync(__dirname + `/public/assets/avatar/${params.avatar}.jpg`).toString('base64');
//const stamp = fs.readFileSync(__dirname + "/public/assets/cert/stamp.svg").toString('base64');
const wwaCert = fs.readFileSync(__dirname + `/public/assets/wwa_cert.png`).toString('base64');
let options = {
format: "A4",
orientation: "portrait",
border: "0mm",
/*
header: {
height: "45mm",
contents: '<div style="text-align: center;">Author: Shyam Hajare</div>'
},
footer: {
height: "28mm",
contents: {
first: 'Cover page',
2: 'Second page', // Any page number is working. 1-based index
default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value
last: 'Last Page'
}
}
*/
};
let document = {
html: html,
data: {
apiurl: process.env.IS_PROD === "true" ? process.env.API_URL : process.env.ALT_API_URL,
wwaCert: wwaCert,
params: params,
},
path: `${tempdir}/wwa.pdf`,
type: "",
};
pdf.create(document, options)
.then((res) => {
console.debug(res);
callback();
})
.catch((error) => {
reportError("PDF Creation failed")
console.error(error);
});
}
function sendEmail(params) {
var transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD,
},
});
if (process.env.EMAIL_TO && process.env.EMAIL_TO !== "") {
// override user inpout with env setting
params.mailOptions.to = process.env.EMAIL_TO
console.info(`Email address was overriden by env variable with ${process.env.EMAIL_TO}`)
}
transporter.sendMail(params.mailOptions, function (err, info) {
if (err) {
reportError("Sending email failed")
console.error(err);
} else {
log(info);
}
});
}
function reportError(errorMessage){
mainWindow.webContents.send('mainError', errorMessage);
}
function log(message){
console.log(message)
mainWindow.webContents.send('mainLog', message);
}