-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
337 lines (294 loc) · 10.9 KB
/
Copy pathmain.js
File metadata and controls
337 lines (294 loc) · 10.9 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
const { app, BrowserWindow, ipcMain, Notification, dialog } = require('electron');
const path = require('path');
const fs = require('fs').promises;
let mainWindow;
let notificationCheckInterval = null;
let activeTasks = new Set();
// Path to tasks.json
const tasksFilePath = path.join(__dirname, 'data', 'tasks.json');
const uploadsDir = path.join(__dirname, 'data', 'uploads');
// Ensure data directory exists
async function ensureDataDirectory() {
const dataDir = path.dirname(tasksFilePath);
try {
await fs.access(dataDir);
} catch {
await fs.mkdir(dataDir, { recursive: true });
}
// Ensure uploads directory exists
try {
await fs.access(uploadsDir);
} catch {
await fs.mkdir(uploadsDir, { recursive: true });
}
}
// Copy file to uploads directory
async function copyFileToUploads(filePath) {
try {
await ensureDataDirectory();
const fileName = path.basename(filePath);
const timestamp = Date.now();
const ext = path.extname(fileName);
const nameWithoutExt = path.basename(fileName, ext);
const newFileName = `${nameWithoutExt}_${timestamp}${ext}`;
const destPath = path.join(uploadsDir, newFileName);
await fs.copyFile(filePath, destPath);
return destPath;
} catch (error) {
console.error('Error copying file:', error);
return null;
}
}
// Delete file from uploads
async function deleteUploadedFile(filePath) {
try {
if (filePath && filePath.startsWith(uploadsDir)) {
await fs.unlink(filePath);
return true;
}
return false;
} catch (error) {
console.error('Error deleting file:', error);
return false;
}
}
// Read tasks from JSON file
async function loadTasks() {
try {
await ensureDataDirectory();
const data = await fs.readFile(tasksFilePath, 'utf8');
const parsed = JSON.parse(data);
// Handle legacy format (array) or new format (object)
if (Array.isArray(parsed)) {
return { tasks: parsed, categories: [] };
}
return parsed;
} catch (error) {
// If file doesn't exist, return empty structure
if (error.code === 'ENOENT') {
return { tasks: [], categories: [] };
}
console.error('Error loading tasks:', error);
return { tasks: [], categories: [] };
}
}
// Save tasks to JSON file
async function saveTasks(data) {
try {
await ensureDataDirectory();
await fs.writeFile(tasksFilePath, JSON.stringify(data, null, 2), 'utf8');
return true;
} catch (error) {
console.error('Error saving tasks:', error);
return false;
}
}
// Check and send notifications
async function checkNotifications() {
try {
const data = await loadTasks();
const tasks = data.tasks || [];
const now = new Date();
const nowDateOnly = new Date(now);
nowDateOnly.setHours(0, 0, 0, 0);
tasks.forEach(task => {
if (!task.date || task.completed) return;
// Parse task date (handles both date and datetime strings)
const taskDateFull = new Date(task.date);
const taskDate = new Date(taskDateFull);
taskDate.setHours(0, 0, 0, 0);
if (taskDate < nowDateOnly) return; // Past dates
const daysUntil = Math.floor((taskDate - nowDateOnly) / (1000 * 60 * 60 * 24));
// Initialize notificationsSent if it doesn't exist
if (!task.notificationsSent) {
task.notificationsSent = {
weekBefore: false,
dayBefore: false,
dayOf: false,
oneMinuteBefore: false,
timeReached: false
};
}
if (task.notificationsSent.timeReached === undefined) {
task.notificationsSent.timeReached = false;
}
let shouldNotify = false;
let notificationText = '';
let notificationBody = task.text;
// Check if task has time
const hasTime = task.date.includes('T') && task.date.split('T')[1];
if (hasTime) {
const timeStr = taskDateFull.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
notificationBody = `${task.text} at ${timeStr}`;
// Check if it's exactly the scheduled time (within 1 minute window)
if (daysUntil === 0) {
const timeDiff = Math.abs(now - taskDateFull);
// Check for exactly at the time (within 1 minute window)
if (timeDiff < 60000 && !activeTasks.has(task.id)) {
// Task is now active
activeTasks.add(task.id);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('task-active', task.id);
}
shouldNotify = true;
notificationText = `Now: ${task.text}`;
if (!task.notificationsSent.timeReached) {
task.notificationsSent.timeReached = true;
}
}
// Check if task time has passed (more than 1 minute past)
else if (now > taskDateFull && (now - taskDateFull) > 60000 && activeTasks.has(task.id)) {
// Task is no longer active
activeTasks.delete(task.id);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('task-inactive', task.id);
}
}
}
// Check for 1 minute before the scheduled time
if (daysUntil === 0 && !task.notificationsSent.oneMinuteBefore) {
const oneMinuteBefore = new Date(taskDateFull);
oneMinuteBefore.setMinutes(oneMinuteBefore.getMinutes() - 1);
// Check if current time is within 1 minute of the "1 minute before" time
const timeDiff = Math.abs(now - oneMinuteBefore);
if (timeDiff < 60000 && !shouldNotify) { // Within 1 minute (60 seconds)
shouldNotify = true;
notificationText = `Starting in 1 minute: ${task.text}`;
task.notificationsSent.oneMinuteBefore = true;
}
}
}
// Check for 1 week before (7 days) - only if not already notified
if (!shouldNotify && daysUntil === 7 && !task.notificationsSent.weekBefore) {
shouldNotify = true;
notificationText = `1 week until: ${task.text}`;
task.notificationsSent.weekBefore = true;
}
// Check for 1 day before (1 day)
else if (!shouldNotify && daysUntil === 1 && !task.notificationsSent.dayBefore) {
shouldNotify = true;
notificationText = `Tomorrow: ${task.text}`;
task.notificationsSent.dayBefore = true;
}
// Check for day of (0 days) - only if task doesn't have time or already sent 1-min notification
else if (!shouldNotify && daysUntil === 0 && !task.notificationsSent.dayOf) {
// If task has time, wait for the 1-minute-before notification
// If task doesn't have time, send day-of notification
if (!hasTime) {
shouldNotify = true;
notificationText = `Today: ${task.text}`;
task.notificationsSent.dayOf = true;
}
}
if (shouldNotify) {
sendNotification(notificationText, notificationBody);
// Save updated notification state
saveTasks(data);
}
});
} catch (error) {
console.error('Error checking notifications:', error);
}
}
// Send notification
function sendNotification(title, body) {
if (!Notification.isSupported()) {
console.log('Notifications not supported');
return;
}
const notification = new Notification({
title: title,
body: body,
silent: false
});
notification.show();
}
// Start notification checking
function startNotificationChecker() {
// Check immediately
checkNotifications();
// Check every minute for precise timing (especially for 1-minute-before notifications)
notificationCheckInterval = setInterval(() => {
checkNotifications();
}, 60 * 1000); // 1 minute
}
// Stop notification checking
function stopNotificationChecker() {
if (notificationCheckInterval) {
clearInterval(notificationCheckInterval);
notificationCheckInterval = null;
}
}
// Create the main window
function createWindow() {
mainWindow = new BrowserWindow({
width: 1100,
height: 800,
backgroundColor: '#1e1e1e',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
},
autoHideMenuBar: true
});
mainWindow.loadFile('index.html');
}
// IPC Handlers
ipcMain.handle('load-tasks', async () => {
return await loadTasks();
});
ipcMain.handle('save-tasks', async (event, data) => {
const result = await saveTasks(data);
// Re-check notifications after saving
if (result) {
setTimeout(() => checkNotifications(), 1000);
}
return result;
});
ipcMain.handle('select-file', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp'] },
{ name: 'Documents', extensions: ['pdf', 'doc', 'docx', 'txt'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (result.canceled) {
return null;
}
const filePath = result.filePaths[0];
const copiedPath = await copyFileToUploads(filePath);
return copiedPath;
});
ipcMain.handle('delete-file', async (event, filePath) => {
return await deleteUploadedFile(filePath);
});
// App lifecycle
app.whenReady().then(() => {
// Request notification permission
if (process.platform === 'win32') {
app.setAppUserModelId(app.getName());
}
createWindow();
startNotificationChecker();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
stopNotificationChecker();
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('before-quit', () => {
stopNotificationChecker();
});