-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
356 lines (318 loc) · 7.96 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
import { app, Menu, Tray, BrowserWindow, ipcMain } from 'electron';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import fetch from 'node-fetch';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const appVersion = app.getVersion();
const downloadUrl = 'https://github.com/Adib23704/Tuya-Smart-Taskbar/releases/latest';
let tray = null;
let currentContextMenu = null;
let configWindow = null;
let aboutWindow = null;
let devices = [];
let config;
let tuya;
const configPath = path.join(app.getPath('userData'), 'config.json');
const defaultIconPath = path.join(__dirname, 'assets/icon.ico');
const loadingIconPath = path.join(__dirname, 'assets/loading.ico');
function loadConfig() {
if (fs.existsSync(configPath)) {
const configFile = fs.readFileSync(configPath);
return JSON.parse(configFile);
}
return {
baseUrl: '',
accessKey: '',
secretKey: '',
userId: '',
runOnStartup: true,
};
}
function saveConfig(config) {
fs.writeFileSync(configPath, JSON.stringify(config));
}
function updateStartupSettings(runOnStartup) {
app.setLoginItemSettings({
openAtLogin: runOnStartup,
openAsHidden: runOnStartup
});
}
function createTuyaContext() {
if (config.baseUrl && config.accessKey && config.secretKey && config.userId) {
return new TuyaContext({
baseUrl: config.baseUrl,
accessKey: config.accessKey,
secretKey: config.secretKey,
});
}
return null;
};
function setTrayIconLoading(isLoading) {
if (isLoading) {
tray.setImage(loadingIconPath);
} else {
tray.setImage(defaultIconPath);
}
}
async function fetchDevices() {
if (!tuya) return;
try {
const response = await tuya.request({
method: 'GET',
path: `/v1.0/users/${config.userId}/devices`,
});
return response.result;
} catch (error) {
console.error('Error fetching devices:', error);
return [];
}
}
async function fetchDeviceStatus(deviceId) {
if (!tuya) return;
try {
const response = await tuya.request({
method: 'GET',
path: `/v1.0/devices/${deviceId}/status`,
});
return response.result;
} catch (error) {
console.error('Error fetching device status:', error);
return [];
}
}
async function toggleDeviceState(deviceId, code, currentState) {
if (!tuya) return;
try {
const command = {
commands: [
{
code,
value: (typeof currentState === 'boolean') ? !currentState : currentState,
},
],
};
await tuya.request({
method: 'POST',
path: `/v1.0/devices/${deviceId}/commands`,
body: command,
});
} catch (error) {
console.error('Error toggling device state:', error);
}
}
function createDeviceMenu(device, status) {
let statusItems = status.map((s) => {
if (typeof s.value === 'boolean') {
return {
label: `${(s.code.charAt(0).toUpperCase() + s.code.slice(1)).replace(/_/g, ' ')}`,
click: async () => {
await toggleDeviceState(device.id, s.code, s.value);
updateMenu();
},
enabled: true,
type: 'checkbox',
checked: s.value,
};
}
if (s.code === 'fan_speed_percent') {
s.value = parseInt(s.value, 10);
return {
label: 'Fan Speed',
submenu: Array.from({ length: 5 }, (_, i) => ({
label: `${i + 1}`,
click: async () => {
await toggleDeviceState(device.id, s.code, (i + 1).toString());
updateMenu();
},
type: 'checkbox',
checked: s.value === i + 1,
})),
};
} else if (s.code === 'temp_set') {
return {
label: 'Temperature',
submenu: Array.from({ length: 15 }, (_, i) => ({
label: `${i + 16}`,
click: async () => {
await toggleDeviceState(device.id, s.code, i + 16);
updateMenu();
},
type: 'checkbox',
checked: s.value === i + 16,
})),
};
} else if (s.code === 'windspeed') {
s.value = parseInt(s.value, 10);
return {
label: 'AC Fan Speed',
submenu: Array.from({ length: 4 }, (_, i) => ({
label: `${i + 1}`,
click: async () => {
await toggleDeviceState(device.id, s.code, (i + 1).toString());
updateMenu();
},
type: 'checkbox',
checked: s.value === i + 1,
})),
};
} else if (s.code === 'mode') {
return {
label: 'AC Mode',
submenu: ['auto', 'cold', 'dry', 'wind'].map((mode) => ({
label: mode.charAt(0).toUpperCase() + mode.slice(1),
click: async () => {
await toggleDeviceState(device.id, s.code, mode);
updateMenu();
},
type: 'checkbox',
checked: s.value === mode,
})),
};
}
return null;
});
statusItems = statusItems.filter((item) => item !== null);
return {
label: device.name,
submenu: statusItems,
};
}
async function updateMenu(auto = false) {
if (!tuya) {
currentContextMenu = [
{
label: 'Open Configuration',
click: openConfigWindow,
},
{ label: 'Quit', role: 'quit' },
];
} else {
if (!auto) setTrayIconLoading(true);
devices = await fetchDevices();
let deviceMenuItems = await Promise.all(
devices.map(async (device) => {
if (device.online) {
const status = await fetchDeviceStatus(device.id);
return createDeviceMenu(device, status);
}
return null;
})
);
deviceMenuItems = deviceMenuItems.filter((item) => item !== null);
currentContextMenu = [
...deviceMenuItems,
{ type: 'separator' },
{
label: 'Open Configuration',
click: openConfigWindow,
},
{
label: 'About',
click: openAboutWindow,
},
{ label: 'Quit', role: 'quit' },
];
}
tray.setContextMenu(Menu.buildFromTemplate(currentContextMenu));
if (!auto) setTrayIconLoading(false);
};
function openConfigWindow() {
if (configWindow) {
configWindow.focus();
return;
}
configWindow = new BrowserWindow({
width: 400,
height: 580,
resizable: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
title: 'Tuya Smart Taskbar Config',
icon: defaultIconPath,
autoHideMenuBar: true,
center: true,
fullscreenable: false,
movable: true
});
configWindow.loadFile('html/config.html');
configWindow.on('closed', () => {
configWindow = null;
});
configWindow.webContents.on('did-finish-load', () => {
configWindow.webContents.send('config-data', config);
});
}
function openAboutWindow() {
if (aboutWindow) {
aboutWindow.focus();
return;
}
aboutWindow = new BrowserWindow({
width: 400,
height: 500,
resizable: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
title: 'About Tuya Smart Taskbar',
icon: defaultIconPath,
autoHideMenuBar: true,
center: true,
fullscreenable: false,
movable: true
});
aboutWindow.loadFile('html/about.html');
aboutWindow.on('closed', () => {
aboutWindow = null;
});
aboutWindow.webContents.on('did-finish-load', () => {
aboutWindow.webContents.send('about-data', appVersion);
});
}
app.whenReady().then(() => {
tray = new Tray(defaultIconPath);
tray.setToolTip('Tuya Smart Taskbar');
config = loadConfig();
updateStartupSettings(config.runOnStartup);
tuya = createTuyaContext();
updateMenu();
startAutoRefresh();
ipcMain.on('save-config', (event, newConfig) => {
config = newConfig;
saveConfig(config);
updateStartupSettings(config.runOnStartup);
tuya = createTuyaContext();
updateMenu();
});
ipcMain.on('check-for-update', async (event) => {
try {
const response = await fetch(
'https://raw.githubusercontent.com/Adib23704/Tuya-Smart-Taskbar/refs/heads/master/package.json'
);
const data = await response.json();
const latestVersion = data.version;
console.log('Latest version:', latestVersion);
if (latestVersion !== appVersion) {
event.sender.send('update-available', true, latestVersion, downloadUrl);
} else {
event.sender.send('update-available', false);
}
} catch (error) {
console.error('Error checking for update:', error);
event.sender.send('update-check-failed');
}
});
app.on('window-all-closed', (event) => {
event.preventDefault();
});
});
function startAutoRefresh() {
setInterval(async () => {
await updateMenu(true);
}, 5000);
}