-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
226 lines (211 loc) · 6.28 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
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const readline = require("readline/promises");
const integration = require("./src/integration");
const hardware = require("./src/hardware");
const webview = require("./src/webview");
const { app } = require("electron");
/**
* This promise resolves when the app has finished initializing,
* allowing to safely create browser windows and perform other
* initialization tasks.
*/
app.whenReady().then(async () => {
const lock = app.requestSingleInstanceLock();
if (!lock) {
console.error("TouchKio is already running");
return app.quit();
}
let args = parseArgs(process);
let argsProvided = !!Object.keys(args).length;
let argsFilePath = path.join(app.getPath("userData"), "Arguments.json");
let argsFileExists = fs.existsSync(argsFilePath);
// Setup arguments from file path
if ("setup" in args || (!argsProvided && !argsFileExists)) {
await sleep(3000);
do {
args = await promptArgs(process);
} while (!Object.keys(args).length);
writeArgs(argsFilePath, args);
} else if (!argsProvided && argsFileExists) {
args = readArgs(argsFilePath);
}
// Show used arguments
const json = JSON.stringify(args, null, 2);
console.log(`Arguments: ${json}`);
// Chained init functions
const chained = [webview.init, hardware.init, integration.init];
for (const init of chained) {
if (!(await init(args))) {
break;
}
}
});
/**
* Parses command-line arguments from the given process object.
*
* @param {Object} proc - The process object.
* @returns {Object} An object mapping argument names to their corresponding values.
*/
const parseArgs = (proc) => {
let args = {};
proc.argv.slice(1).forEach((arg) => {
if (arg !== ".") {
const [key, value] = arg.split("=");
args[key.replace("--", "").replace("-", "_")] = value;
}
});
return args;
};
/**
* Prompts argument values on the command-line.
*
* @param {Object} proc - The process object.
* @returns {Object} An object mapping argument names to their corresponding values.
*/
const promptArgs = async (proc) => {
const read = readline.createInterface({
input: proc.stdin,
output: proc.stdout,
});
// Array of prompts
const prompts = [
{
key: "web_url",
question: "\nEnter WEB url",
fallback: "http://192.168.1.42:8123",
},
{
key: "web_theme",
question: "Enter WEB theme",
fallback: "dark",
},
{
key: "web_zoom",
question: "Enter WEB zoom level",
fallback: "1.25",
},
{
key: "mqtt",
question: "\nConnect to MQTT Broker?",
fallback: "y/N",
},
{
key: "mqtt_url",
question: "\nEnter MQTT url",
fallback: "mqtt://192.168.1.42:1883",
},
{
key: "mqtt_user",
question: "Enter MQTT username",
fallback: "kiosk",
},
{
key: "mqtt_password",
question: "Enter MQTT password",
fallback: "password",
},
{
key: "mqtt_discovery",
question: "Enter MQTT discovery prefix",
fallback: "homeassistant",
},
{
key: "check",
question: "\nEverything looks good?",
fallback: "Y/n",
},
];
// Prompt questions and wait for the answers
let args = {};
let ignore = [];
for (const { key, question, fallback } of prompts) {
if (key === "mqtt") {
const prompt = `${question} (${fallback}): `;
const answer = await read.question(prompt);
const value = (answer.trim() || fallback.match(/[YN]/)[0]).toLowerCase();
if (!["y", "yes"].includes(value)) {
ignore = ignore.concat(["mqtt_url", "mqtt_user", "mqtt_password", "mqtt_discovery"]);
}
} else if (key === "check") {
const json = JSON.stringify(args, null, 2);
const prompt = `${question}\n${json}\n(${fallback}): `;
const answer = await read.question(prompt);
const value = (answer.trim() || fallback.match(/[YN]/)[0]).toLowerCase();
if (!["y", "yes"].includes(value)) {
args = {};
}
} else if (!ignore.includes(key)) {
const prompt = `${question} (${fallback}): `;
const answer = await read.question(prompt);
const value = answer.trim() || fallback;
args[key] = value;
}
}
read.close();
return args;
};
/**
* Writes argument values to the filesystem.
*
* @param {string} path - Path of the .json file.
* @param {Object} args - The arguments object.
*/
const writeArgs = (path, args) => {
const argc = Object.assign({}, args);
if ("mqtt_password" in argc) {
argc.mqtt_password = encrypt(argc.mqtt_password);
}
fs.writeFileSync(path, JSON.stringify(argc, null, 2));
};
/**
* Reads argument values from the filesystem.
*
* @param {string} path - Path of the .json file.
* @returns {Object} The arguments object.
*/
const readArgs = (path) => {
const args = JSON.parse(fs.readFileSync(path));
if ("mqtt_password" in args) {
args.mqtt_password = decrypt(args.mqtt_password);
}
return args;
};
/**
* Helper function for string encryption.
*
* @param {string} value - Plain text value.
* @returns {string} Encrypted value.
*/
const encrypt = (value) => {
const iv = crypto.randomBytes(16);
const key = crypto.scryptSync(hardware.getMachineId(), app.getName(), 32);
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let encrypted = cipher.update(value, "utf8", "hex");
encrypted += cipher.final("hex");
return Buffer.from(iv.toString("hex") + ":" + encrypted).toString("base64");
};
/**
* Helper function for string decryption.
*
* @param {string} value - Encrypted value.
* @returns {string} Plain text value.
*/
const decrypt = (value) => {
const p = Buffer.from(value, "base64").toString("utf8").split(":");
const iv = Buffer.from(p.shift(), "hex");
const key = crypto.scryptSync(hardware.getMachineId(), app.getName(), 32);
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
const buffer = Buffer.from(p.join(":"), "hex");
let decrypted = decipher.update(buffer, "binary", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
};
/**
* Helper function for asynchronous sleep.
*
* @param {number} ms - Sleep time in milliseconds.
* @returns {Promise} A promise resolving after the timeout.
*/
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));