-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2135 lines (1817 loc) · 63.9 KB
/
Copy pathapp.js
File metadata and controls
2135 lines (1817 loc) · 63.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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Global interval variables
let overdueInterval;
let dueTimeInterval;
// Score for popped bubbles
const SCORE_KEY = 'bubblePopScore';
function loadScore() {
const saved = localStorage.getItem(SCORE_KEY);
return saved ? parseInt(saved, 10) : 0;
}
function saveScore(score) {
localStorage.setItem(SCORE_KEY, score.toString());
}
function updateScoreDisplay() {
const scoreEl = document.getElementById('score-value');
if (scoreEl) {
scoreEl.textContent = loadScore();
}
}
function incrementScore() {
const newScore = loadScore() + 1;
saveScore(newScore);
updateScoreDisplay();
}
// Toggle for change document title
let titleBlinkInterval = null;
// Connection status
const dot = document.getElementById('statusDot');
const text = document.getElementById('statusText');
// Connection status Terminal
const dotTerminal = document.getElementById('statusDotTerminal');
const textTerminal = document.getElementById('statusTextTerminal');
// Connection colour
const vividSkyBlue = "#00b9fe";
const greenPrimary = "#4CAF50";
// Session (in-memory) credentials when user clicks “Use”
let sessionTelegram = { botToken: null, chatId: null, toggle: "OFF" };
// Telegram polling state: taskId -> { messageId, intervalId, lastUpdateId }
let telegramPollingState = {};
// Exponential backoff delays for Telegram notifications (in minutes): 2, 4, 8, 16, 32, 64, 128, then 256
const TELEGRAM_BACKOFF_DELAYS = [2, 4, 8, 16, 32, 64, 128, 256];
// Helper: Get notification state for a task
function getTaskNotificationState(taskId) {
const state = localStorage.getItem(`telegramNotify_${taskId}`);
return state ? JSON.parse(state) : null;
}
// Helper: Save notification state for a task
function saveTaskNotificationState(taskId, state) {
localStorage.setItem(`telegramNotify_${taskId}`, JSON.stringify(state));
}
// Helper: Clear notification state for a task
function clearTaskNotificationState(taskId) {
localStorage.removeItem(`telegramNotify_${taskId}`);
}
// Helper: Check if we should send a Telegram notification for a task
function shouldSendTelegramNotification(taskId) {
const now = Date.now();
const state = getTaskNotificationState(taskId);
if (!state) {
// First notification - always send
return true;
}
const sendCount = state.sendCount || 0;
const lastSent = state.lastSent || 0;
// Get the appropriate delay based on send count
let delayMinutes;
if (sendCount < TELEGRAM_BACKOFF_DELAYS.length) {
delayMinutes = TELEGRAM_BACKOFF_DELAYS[sendCount - 1]; // -1 because first notification is sendCount=1
} else {
delayMinutes = 256; // After 128, always 256
}
const delayMs = delayMinutes * 60 * 1000;
const timeSinceLastSent = now - lastSent;
return timeSinceLastSent >= delayMs;
}
// Helper: Get reminder text based on notification count
function getReminderText(sendCount) {
if (sendCount === 1) return "";
if (sendCount === 2) return " (Reminder 1)";
return ` (Reminder ${sendCount - 1})`;
}
// Function to load check frequency from localStorage, default to 1 minute if not set
function loadCheckFrequency() {
return localStorage.getItem('checkFrequency') || "1";
}
// Function to save check frequency to localStorage
function saveCheckFrequency(frequency) {
localStorage.setItem('checkFrequency', frequency);
}
// Function to set up intervals based on selected frequency
function setupIntervals() {
// Clear any existing intervals
if (overdueInterval) clearInterval(overdueInterval);
if (dueTimeInterval) clearInterval(dueTimeInterval);
// Get selected frequency (value in minutes)
const frequencyDropdown = document.getElementById('check-frequency');
const frequencyMinutes = parseInt(frequencyDropdown.value, 10);
const frequencyMs = frequencyMinutes * 60000;
// Save the selected frequency
saveCheckFrequency(frequencyDropdown.value);
// Set new intervals using the selected frequency
overdueInterval = setInterval(checkOverdueTasks, frequencyMs);
dueTimeInterval = setInterval(checkDueTime, frequencyMs);
}
// On page load, set the frequency dropdown value from localStorage and initialize intervals
document.addEventListener("DOMContentLoaded", () => {
const frequencyDropdown = document.getElementById('check-frequency');
frequencyDropdown.value = loadCheckFrequency();
setupIntervals();
});
// Listen to changes in the frequency dropdown
document.getElementById('check-frequency').addEventListener('change', setupIntervals);
// Helper: get tasks from localStorage
function getTasks() {
const tasksJSON = localStorage.getItem('tasks');
const tasks = tasksJSON ? JSON.parse(tasksJSON) : [];
let changed = false;
tasks.forEach(task => {
if (!Array.isArray(task.activeDays) || task.activeDays.length === 0) {
task.activeDays = [0, 1, 2, 3, 4, 5, 6];
changed = true;
}
});
if (changed) {
saveTasks(tasks);
}
return tasks;
}
let isUpdatingFromSSE = false;
// Helper: save tasks to localStorage
function saveTasks(tasks) {
localStorage.setItem('tasks', JSON.stringify(tasks));
}
// Helper: generate a unique id (using timestamp + random component)
function generateId() {
return Date.now().toString() + Math.floor(Math.random() * 10000).toString();
}
const WEEK_DAYS = [
{ label: "Mon", value: 1 },
{ label: "Tue", value: 2 },
{ label: "Wed", value: 3 },
{ label: "Thu", value: 4 },
{ label: "Fri", value: 5 },
{ label: "Sat", value: 6 },
{ label: "Sun", value: 0 }
];
function isTaskActiveOnDay(task, dayIndex) {
if (!Array.isArray(task.activeDays) || task.activeDays.length === 0) return true;
return task.activeDays.includes(dayIndex);
}
function isTaskActiveToday(task) {
return isTaskActiveOnDay(task, new Date().getDay());
}
function formatActiveDays(activeDays) {
if (!Array.isArray(activeDays) || activeDays.length === 0 || activeDays.length === 7) {
return "Every day";
}
const dayLabels = WEEK_DAYS.filter(d => activeDays.includes(d.value)).map(d => d.label);
return dayLabels.join(" ");
}
function getNextActiveDate(task, fromDate) {
for (let i = 0; i < 7; i++) {
const candidate = new Date(fromDate);
candidate.setDate(fromDate.getDate() + i);
if (isTaskActiveOnDay(task, candidate.getDay())) {
return candidate;
}
}
return new Date(fromDate);
}
// Preset tasks definitions that'SeveranceGame needs adjustment
const presetTasks = {
training: [
{ time: "05:00", name: "Wake up" },
{ time: "05:15", name: "Drink 500ml water" },
{ time: "05:30", name: "Dynamic stretching" },
{ time: "05:45", name: "Cardio warm-up" },
{ time: "06:00", name: "Main workout" },
{ time: "07:00", name: "Cool down" },
{ time: "07:15", name: "Protein shake" },
{ time: "07:30", name: "Shower" },
{ time: "08:00", name: "Healthy breakfast" }
],
learning: [
{ time: "09:00", name: "Set daily learning goals" },
{ time: "09:15", name: "Read technical material" },
{ time: "10:15", name: "Take detailed notes" },
{ time: "10:45", name: "Rest eyes - look at distance" },
{ time: "11:00", name: "Practice exercises" },
{ time: "12:00", name: "Lunch break" },
{ time: "13:00", name: "Review morning materials" },
{ time: "14:00", name: "Deep work session" },
{ time: "15:30", name: "Take a walk - process information" }
],
motivational: [
{ time: "06:30", name: "Good morning! You're up and making progress!" },
{ time: "08:30", name: "Great start to the day - keep the momentum!" },
{ time: "10:30", name: "Stay focused, you're doing fantastic work!" },
{ time: "12:30", name: "Halfway through the day - you got this!" },
{ time: "14:30", name: "Your dedication is inspiring!" },
{ time: "16:30", name: "Push through - excellence takes persistence!" },
{ time: "18:30", name: "Reflect on today'SeveranceGame wins, big and small" },
{ time: "20:30", name: "Wind down - you've earned your rest" }
],
productivity: [
{ time: "08:30", name: "Plan your day and set priorities" },
{ time: "09:00", name: "Focus on most important task" },
{ time: "10:30", name: "Check and respond to urgent emails" },
{ time: "11:00", name: "Second important task" },
{ time: "12:30", name: "Reflect on morning progress" },
{ time: "13:30", name: "Third important task" },
{ time: "15:00", name: "Quick administrative work" },
{ time: "16:00", name: "Plan for tomorrow" },
{ time: "17:00", name: "Review day'SeveranceGame accomplishments" }
],
wellness: [
{ time: "07:00", name: "Morning meditation" },
{ time: "10:00", name: "Hydration check" },
{ time: "12:00", name: "Mindful eating lunch" },
{ time: "14:00", name: "Quick breathing exercise" },
{ time: "15:30", name: "Stretch break" },
{ time: "17:00", name: "Evening walk" },
{ time: "19:00", name: "Screen-free time" },
{ time: "21:00", name: "Evening reflection" },
{ time: "22:00", name: "Sleep preparation routine" }
],
work: [
{ time: "10:00", name: "Eye'SeveranceGame break" },
{ time: "12:30", name: "OTL" },
{ time: "13:00", name: "Break" },
{ time: "15:30", name: "Eye'SeveranceGame break" },
{ time: "17:30", name: "Take that walk!" },
],
work2: [
{ time: "09:10", name: "Emails" },
{ time: "10:30", name: "Coffee break" },
{ time: "11:30", name: "20 20 20 rule" },
{ time: "13:00", name: "Break" },
{ time: "15:30", name: "Eye'SeveranceGame break" },
{ time: "16:30", name: "Update Kimble" },
{ time: "17:00", name: "Drink Water" },
{ time: "18:00", name: "Take that walk!" },
]
};
// --- Page Title Mode ---
function savePageTitleMode(mode) {
localStorage.setItem('pageTitleMode', mode);
}
function loadPageTitleMode() {
return localStorage.getItem('pageTitleMode') || 'blinkingTitle';
}
// On page load, select the radio button saved in localStorage
document.addEventListener('DOMContentLoaded', () => {
const savedMode = loadPageTitleMode();
const radio = document.querySelector(`input[name="pageTitle"][value="${savedMode}"]`);
if (radio) {
radio.checked = true;
}
});
// Listen for changes to the radio buttons
document.querySelectorAll('input[name="pageTitle"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const selected = e.target.value;
savePageTitleMode(selected);
// Stop any active interval immediately if switching modes
if (titleBlinkInterval) {
clearInterval(titleBlinkInterval);
titleBlinkInterval = null;
}
document.title = `Did I take it?`;
checkOverdueTasks(); // immediately apply new mode
});
});
// Render the task list on the page
function renderTasks() {
const tasks = getTasks();
const list = document.getElementById('task-list');
list.innerHTML = '';
// Sort tasks by dueTime (earlier due times first)
tasks.sort((a, b) => new Date(a.dueTime) - new Date(b.dueTime));
tasks.forEach(task => {
const activeToday = isTaskActiveToday(task);
const li = document.createElement('li');
if (!activeToday) {
li.classList.add('inactive-task');
}
li.innerHTML = `
<div class="container">
<div>
<input type="checkbox" id="task-${task.id}" ${task.checked ? 'checked' : ''} onchange="toggleTask('${task.id}', this.checked)">
</div>
<div>
<label for="task-${task.id}">
<span>${task.name} (${activeToday ? `Due: ${new Date(task.dueTime).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false})}` : 'Inactive today'})</span>
<span class="task-days">Active: ${formatActiveDays(task.activeDays)}</span>
</label>
</div>
<div>
<button onclick="deleteTask('${task.id}')" class="deleteButton">Delete</button>
<button onclick="editTask('${task.id}')" class="editButton">Edit</button>
<button onclick="toggleDaysEditor('${task.id}')" class="editButton">Days</button>
</div>
</div>
<div id="days-editor-${task.id}" class="day-editor" aria-label="Edit active days">
${WEEK_DAYS.map(d => {
const checked = task.activeDays && task.activeDays.includes(d.value) ? 'checked' : '';
return `<label><input type="checkbox" onchange="updateTaskDays('${task.id}', ${d.value}, this.checked)" ${checked}>${d.label}</label>`;
}).join('')}
</div>
${task.alarmTriggered && activeToday ? '<strong style="color:red;"> Unfinished Task!</strong>' : ''}
`;
list.appendChild(li);
});
}
function toggleDaysEditor(id) {
const editor = document.getElementById(`days-editor-${id}`);
if (!editor) return;
editor.classList.toggle('show');
}
function updateTaskDays(id, dayValue, checked) {
const tasks = getTasks();
const task = tasks.find(t => t.id === id);
if (!task) return;
if (!Array.isArray(task.activeDays) || task.activeDays.length === 0) {
task.activeDays = [0, 1, 2, 3, 4, 5, 6];
}
if (checked) {
if (!task.activeDays.includes(dayValue)) {
task.activeDays.push(dayValue);
}
} else {
task.activeDays = task.activeDays.filter(d => d !== dayValue);
}
if (task.activeDays.length === 0) {
task.activeDays = [0, 1, 2, 3, 4, 5, 6];
}
saveTasks(tasks);
renderTasks();
checkOverdueTasks();
}
// Toggle a task'SeveranceGame checked state
function toggleTask(id, checked) {
const tasks = getTasks();
const task = tasks.find(t => t.id === id);
if (task) {
task.checked = checked;
if (checked) {
task.alarmTriggered = false;
clearTaskNotificationState(id);
stopTelegramPolling(id);
}
saveTasks(tasks);
renderTasks();
checkOverdueTasks();
}
}
// Delete a task
function deleteTask(id) {
let tasks = getTasks();
tasks = tasks.filter(t => t.id !== id);
saveTasks(tasks);
renderTasks();
}
// Edit a task'SeveranceGame name and due time, and mark it as not preset
function editTask(id) {
const tasks = getTasks();
const task = tasks.find(t => t.id === id);
if (!task) return;
// Prompt for new name; if Cancel is pressed, no change is made.
const newName = prompt("Edit task name:", task.name);
if (newName === null) return;
const currentDueTime = new Date(task.dueTime).toLocaleTimeString([], {
hour: '2-digit',
minute:'2-digit',
hour12: false
});
const newDueTime = prompt("Edit task due time (HH:MM):", currentDueTime);
if (newDueTime === null) return;
const today = new Date();
const [hours, minutes] = newDueTime.split(':').map(Number);
today.setHours(hours, minutes, 0, 0);
// Update task properties
task.name = newName;
task.dueTime = today.toISOString();
task.isPreset = false;
saveTasks(tasks);
renderTasks();
}
// Function to send Telegram message for overdue tasks
function sendTelegramMessage(allOverdueTasks, triggeringTaskId) {
if (!allOverdueTasks || allOverdueTasks.length === 0) return;
// Update notification state for the triggering task only
const now = Date.now();
let state = getTaskNotificationState(triggeringTaskId);
if (!state) {
state = { taskId: triggeringTaskId, firstSent: now, lastSent: now, sendCount: 0 };
}
state.lastSent = now;
state.sendCount = (state.sendCount || 0) + 1;
saveTaskNotificationState(triggeringTaskId, state);
let raw = localStorage.getItem("telegramDidITakeIt");
let botToken, chatId, toggle, chatName;
if (raw) {
const parsed = JSON.parse(raw);
botToken = parsed.value1;
chatId = parsed.value2;
toggle = parsed.toggle;
chatName = parsed.chatName || 'there';
}
// If persisted were empty, fall back to session creds
if (!botToken || !chatId) {
if (sessionTelegram.botToken && sessionTelegram.chatId) {
botToken = sessionTelegram.botToken;
chatId = sessionTelegram.chatId;
toggle = sessionTelegram.toggle;
chatName = loadChatName() || 'there';
} else {
console.warn("No Telegram credentials found (neither saved nor in session).");
return;
}
}
if (toggle !== "ON") {
console.log("Telegram notifications are OFF in settings.");
return;
}
// Build message showing all overdue tasks with their individual reminder counts
const triggeringTask = allOverdueTasks.find(t => t.id === triggeringTaskId);
const triggeringTaskState = getTaskNotificationState(triggeringTaskId);
const triggeringReminderText = getReminderText(triggeringTaskState ? triggeringTaskState.sendCount : 1);
let messageText;
if (allOverdueTasks.length === 1) {
const task = allOverdueTasks[0];
const dueTimeStr = new Date(task.dueTime).toLocaleString([], {hour: '2-digit', minute:'2-digit', hour12: false});
messageText = `Hi ${chatName}!, ${task.name} (Due: ${dueTimeStr})${triggeringReminderText}`;
} else {
const taskList = allOverdueTasks.map(t => {
const dueTimeStr = new Date(t.dueTime).toLocaleString([], {hour: '2-digit', minute:'2-digit', hour12: false});
const tState = getTaskNotificationState(t.id);
const tReminderText = getReminderText(tState ? tState.sendCount : 0);
return `- ${t.name} (Due: ${dueTimeStr})${tReminderText}`;
}).join('\n');
messageText = `Hi ${chatName}! You have ${allOverdueTasks.length} overdue tasks:\n${taskList}`;
}
const url = `https://api.telegram.org/bot${botToken}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent(messageText)}`;
fetch(url)
.then(response => response.json())
.then(data => {
if (!data.ok) {
console.error("Failed to send Telegram message. Description:", data.description);
return;
}
// Start polling for DONE replies for this task
const messageId = data.result.message_id;
startTelegramPolling(triggeringTaskId, botToken, chatId, messageId);
})
.catch(error => {
console.error("Error sending Telegram message (fetch failed):", error);
});
}
// Start polling for DONE replies to a specific Telegram message
function startTelegramPolling(taskId, botToken, chatId, messageId) {
// Don't start if already polling for this task
if (telegramPollingState[taskId]) {
return;
}
console.log(`Starting Telegram polling for task ${taskId}, message ${messageId}`);
// Poll every 30 seconds
const intervalId = setInterval(() => {
pollTelegramForDone(taskId, botToken, chatId, messageId);
}, 30000);
telegramPollingState[taskId] = {
messageId: messageId,
intervalId: intervalId,
lastUpdateId: 0
};
}
// Poll Telegram for DONE replies
function pollTelegramForDone(taskId, botToken, chatId, messageId) {
const url = `https://api.telegram.org/bot${botToken}/getUpdates?chat_id=${chatId}`;
fetch(url)
.then(response => response.json())
.then(data => {
if (!data.ok) {
console.error("Failed to get Telegram updates:", data.description);
return;
}
const updates = data.result;
const pollingState = telegramPollingState[taskId];
if (!pollingState) return;
// Process new updates
for (const update of updates) {
if (update.update_id <= pollingState.lastUpdateId) continue;
// Check if this is a reply to our message
if (update.message && update.message.reply_to_message) {
const replyToMsg = update.message.reply_to_message;
if (replyToMsg.message_id === messageId) {
const text = update.message.text || "";
if (text.toLowerCase() === "done") {
// Mark task as complete
console.log(`Received DONE for task ${taskId} from Telegram`);
markTaskCompleteFromTelegram(taskId);
stopTelegramPolling(taskId);
break;
}
}
}
pollingState.lastUpdateId = update.update_id;
}
})
.catch(error => {
console.error("Error polling Telegram:", error);
});
}
// Mark task complete from Telegram DONE command
function markTaskCompleteFromTelegram(taskId) {
const tasks = getTasks();
const task = tasks.find(t => t.id === taskId);
if (task && !task.checked) {
task.checked = true;
task.alarmTriggered = false;
saveTasks(tasks);
renderTasks();
// Stop title blinking if no more overdue
const overdueTasks = tasks.filter(t =>
isTaskActiveToday(t) && !t.checked && new Date(t.dueTime) <= new Date()
);
if (overdueTasks.length === 0 && titleBlinkInterval) {
clearInterval(titleBlinkInterval);
titleBlinkInterval = null;
document.title = 'Did I take it?';
}
}
// Clear notification state
clearTaskNotificationState(taskId);
}
// Stop polling for a task (when completed or manually checked)
function stopTelegramPolling(taskId) {
const state = telegramPollingState[taskId];
if (state) {
console.log(`Stopping Telegram polling for task ${taskId}`);
clearInterval(state.intervalId);
delete telegramPollingState[taskId];
}
}
// Check for overdue tasks and trigger the alarm and Telegram message if needed
function checkOverdueTasks() {
// console.log("checkOverdueTasks called at", new Date().toLocaleTimeString());
const tasks = getTasks();
const now = new Date();
let shouldPlayAlarm = false;
let tasksUpdated = false;
const overdueTasks = [];
let triggeringTaskId = null;
// First pass: collect all overdue tasks and find which one should trigger notification
tasks.forEach(task => {
if (!isTaskActiveToday(task)) {
return;
}
const taskDue = new Date(task.dueTime);
const localTaskDue = new Date(taskDue.getFullYear(), taskDue.getMonth(), taskDue.getDate(), taskDue.getHours(), taskDue.getMinutes(), taskDue.getSeconds());
if (!task.checked && localTaskDue <= now) {
// console.log(`Task "${task.name}" is overdue.`);
if (!task.alarmTriggered) {
// console.log(`Alarm not yet triggered for "${task.name}". Triggering now.`);
task.alarmTriggered = true;
tasksUpdated = true;
}
overdueTasks.push(task);
shouldPlayAlarm = true;
// Check if this task should trigger a notification
if (shouldSendTelegramNotification(task.id)) {
triggeringTaskId = task.id;
}
}
});
// Send consolidated Telegram message if any task triggered it
if (overdueTasks.length > 0 && triggeringTaskId) {
sendTelegramMessage(overdueTasks, triggeringTaskId);
}
if (tasksUpdated) {
saveTasks(tasks);
renderTasks();
}
if (shouldPlayAlarm) {
playAlarmSound();
if (!titleBlinkInterval) {
const mode = loadPageTitleMode();
if (mode === 'marquee') {
marqueeTittle();
} else if (mode === 'blinkingTitle') {
blinkingTitle();
} else {
// default just sets normal title
document.title = 'Did I take it?';
}
}
} else {
// no overdue tasks — stop blinking/marquee
if (titleBlinkInterval) {
clearInterval(titleBlinkInterval);
titleBlinkInterval = null;
}
document.title = `Did I take it?`;
}
}
// Blinking title
function blinkingTitle() {
let toggle = true;
titleBlinkInterval = setInterval(() => {
document.title = toggle ? "You have task to do!" : "⚠️ Let'SeveranceGame do it! 🔴🟡🟢";
toggle = !toggle;
}, 1600);
}
// Marquee Title
function marqueeTittle() {
const tasks = getTasks();
const task = tasks.find((t) => !t.checked && t.alarmTriggered);
// stop if no unchecked tasks
if (!task || !task.name) {
if (titleBlinkInterval) {
clearInterval(titleBlinkInterval);
titleBlinkInterval = null;
}
document.title = `Did I take it?`;
return;
}
// stop existing interval before starting new one
if (titleBlinkInterval) {
clearInterval(titleBlinkInterval);
titleBlinkInterval = null;
}
let title = task.name;
let position = 0;
titleBlinkInterval = setInterval(() => {
document.title = title.substring(position) + " • " + title.substring(0, position);
position = (position + 1) % title.length;
}, 300);
}
// Reset all tasks at 4 AM (this checks every minute)
function resetTasksAtFourAM() {
const now = new Date();
if (now.getUTCHours() === 4 && now.getUTCMinutes() === 0) {
const tasks = getTasks();
tasks.forEach(task => {
task.checked = false;
task.alarmTriggered = false;
});
saveTasks(tasks);
renderTasks();
}
}
function checkDueTime() {
const tasks = getTasks();
let changed = false;
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
tasks.forEach(task => {
const taskDue = new Date(task.dueTime);
const taskDueDate = new Date(taskDue.getFullYear(), taskDue.getMonth(), taskDue.getDate());
// If the task'SeveranceGame due date is before today, update it to next active day (preserving the time)
if (taskDueDate < today) {
const nextActiveDate = getNextActiveDate(task, today);
let newDueTime = new Date(nextActiveDate.getFullYear(), nextActiveDate.getMonth(), nextActiveDate.getDate());
newDueTime.setHours(taskDue.getHours(), taskDue.getMinutes(), taskDue.getSeconds(), taskDue.getMilliseconds());
task.dueTime = newDueTime.toISOString();
task.alarmTriggered = false;
changed = true;
task.checked = false;
}
});
if (changed) {
saveTasks(tasks);
renderTasks();
}
}
// Event listener for the preset drop-down
document.getElementById('preset-select').addEventListener('change', function(e) {
const newPreset = e.target.value;
let tasks = getTasks();
// Remove all tasks that were added by a preset (identified by isPreset property)
tasks = tasks.filter(task => !task.isPreset);
// Only add preset tasks if a valid preset is selected (non-empty value)
if (newPreset && presetTasks[newPreset]) {
presetTasks[newPreset].forEach(item => {
// Create a date for today with the preset task time
const today = new Date();
// Split time string "HH:MM" into hours and minutes
const [hours, minutes] = item.time.split(':').map(Number);
const dueTimeDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hours, minutes, 0, 0);
// Create the preset task and mark it with isPreset and presetType
tasks.push({
id: generateId(),
name: item.name,
dueTime: dueTimeDate.toISOString(),
checked: false,
alarmTriggered: false,
isPreset: true,
presetType: newPreset,
activeDays: [0, 1, 2, 3, 4, 5, 6]
});
});
}
saveTasks(tasks);
renderTasks();
});
// Handle task form submission (manual task addition)
document.getElementById('task-form').addEventListener('submit', function(e) {
e.preventDefault();
const name = document.getElementById('task-name').value;
const timeInput = document.getElementById('due-time').value;
const selectedDays = Array.from(document.querySelectorAll('.day-checkbox:checked')).map(cb => Number(cb.value));
if (selectedDays.length === 0) {
alert("Select at least one active day.");
return;
}
const now = new Date();
const [hours, minutes] = timeInput.split(':');
now.setHours(hours, minutes, 0, 0);
const newTask = {
id: generateId(),
name: name,
dueTime: now.toISOString(),
checked: false,
alarmTriggered: false,
isPreset: false,
activeDays: selectedDays
};
const tasks = getTasks();
tasks.push(newTask);
saveTasks(tasks);
renderTasks();
e.target.reset();
document.querySelectorAll('.day-checkbox').forEach(cb => {
cb.checked = true;
});
});
// Initial render of tasks on page load
renderTasks();
// Select elements
const container = document.querySelector('.telegram-container');
const inputs = container.querySelectorAll('.inputs input');
const useButton = container.querySelector('.buttons .use');
const saveButton = container.querySelector('.buttons .save');
const toggleButton = container.querySelector('.buttons .off');
const clearButton = document.querySelector('.buttons .clear');
inputs[0].type = "password";
inputs[1].type = "password";
// Function to toggle use button
function updateUseButtonClasses() {
if (useButton.textContent === "Use") {
useButton.classList.add("addButton");
useButton.classList.remove("editButton");
} else {
useButton.classList.add("editButton");
useButton.classList.remove("addButton");
}
}
// Function to update toggle button classes
function updateToggleButtonClasses() {
if (toggleButton.textContent === "ON") {
toggleButton.classList.add("addButton");
toggleButton.classList.remove("deleteButton");
} else {
toggleButton.classList.add("deleteButton");
toggleButton.classList.remove("addButton");
}
}
// Function to update save button classes
function updateSaveButtonClasses() {
if (saveButton.textContent === "Save") {
saveButton.classList.add("addButton");
saveButton.classList.remove("editButton");
} else if (saveButton.textContent === "Update") {
saveButton.classList.add("editButton");
saveButton.classList.remove("addButton");
}
}
// Function to load state from localStorage
function loadState() {
const savedState = localStorage.getItem("telegramDidITakeIt");
if (savedState) {
const { value1, value2, toggle, chatName } = JSON.parse(savedState);
inputs[0].value = value1 || '';
inputs[1].value = value2 || '';
inputs[2].value = chatName || '';
toggleButton.textContent = toggle || "OFF";
inputs[0].disabled = true;
inputs[1].disabled = true;
inputs[2].disabled = true;
saveButton.textContent = "Update";
// Hide chatName input if empty
if (!chatName) {
inputs[2].style.display = "none";
} else {
inputs[2].style.display = "block";
}
} else {
toggleButton.textContent = "OFF";
saveButton.textContent = "Save";
inputs[0].disabled = false;
inputs[1].disabled = false;
inputs[2].disabled = false;
inputs[2].value = '';
}
useButton.textContent = "Update";
updateToggleButtonClasses();
updateSaveButtonClasses();
updateUseButtonClasses();
}
// Function to save state to localStorage
function saveState() {
const value1 = inputs[0].value;
const value2 = inputs[1].value;
const toggle = toggleButton.textContent;
const chatNameInput = document.querySelector('input[placeholder="Chat Name"]');
const chatName = chatNameInput ? chatNameInput.value : '';
localStorage.setItem("telegramDidITakeIt", JSON.stringify({ value1, value2, toggle, chatName }));
}
// Function to save state ON OFF to localStorage
function saveStateONOFF() {
const savedState = localStorage.getItem("telegramDidITakeIt");
let state = savedState ? JSON.parse(savedState) : {};
state.toggle = toggleButton.textContent;
localStorage.setItem("telegramDidITakeIt", JSON.stringify(state));
}
// Load initial state
loadState();
// Event listener for save/update button
saveButton.addEventListener('click', () => {
if (saveButton.textContent === "Save") {
const ok = confirm(
"Storing your bot token & chat ID in localStorage could be insecure.\n" +
"Press OK to proceed, or Cancel if you’d rather not save."
);
if (!ok) return;
saveState();
inputs[0].disabled = true;
inputs[1].disabled = true;
inputs[2].disabled = true;
saveButton.textContent = "Update";
inputs[0].type = "password";
inputs[1].type = "password";
inputs[2].type = "text";
} else {
inputs[0].disabled = false;
inputs[1].disabled = false;
inputs[2].style.display = "block";
inputs[2].disabled = false;
saveButton.textContent = "Save";
inputs[0].type = "password";
inputs[1].type = "password";
inputs[2].type = "text";
}
updateSaveButtonClasses();
});
// “Use” button logic (session‑only, not persisted)
useButton.addEventListener('click', () => {
const isUsing = useButton.textContent === "Use";
if (isUsing) {
sessionTelegram.botToken = inputs[0].value;
sessionTelegram.chatId = inputs[1].value;
sessionTelegram.toggle = toggleButton.textContent;
inputs[0].disabled = true;
inputs[1].disabled = true;
inputs[2].disabled = true;
useButton.textContent = "Update";
} else {
inputs[0].disabled = false;
inputs[1].disabled = false;
inputs[2].disabled = false;
useButton.textContent = "Use";