-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddyTerminal.py
More file actions
executable file
·1055 lines (847 loc) · 34.2 KB
/
Copy pathBuddyTerminal.py
File metadata and controls
executable file
·1055 lines (847 loc) · 34.2 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
#!/home/emil/Documents/Repo/Buddy-Terminal/venv/bin/python
import asyncio
from datetime import datetime, timezone, timedelta
import traceback
import json
import re
from typing import Optional
from aiohttp import web
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, DataTable, Static, Input
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
WEEK_DAYS = [
("Mon", 1),
("Tue", 2),
("Wed", 3),
("Thu", 4),
("Fri", 5),
("Sat", 6),
("Sun", 0),
]
DAY_TOKEN_MAP = {
"sun": 0,
"sunday": 0,
"mon": 1,
"monday": 1,
"tue": 2,
"tues": 2,
"tuesday": 2,
"wed": 3,
"wednesday": 3,
"thu": 4,
"thur": 4,
"thurs": 4,
"thursday": 4,
"fri": 5,
"friday": 5,
"sat": 6,
"saturday": 6,
}
ALL_DAYS = [0, 1, 2, 3, 4, 5, 6]
def _js_day_from_datetime(dt: datetime) -> int:
return (dt.weekday() + 1) % 7
def _ensure_active_days(task: dict) -> list:
active_days = task.get("activeDays")
if not isinstance(active_days, list) or len(active_days) == 0:
task["activeDays"] = ALL_DAYS.copy()
return task["activeDays"]
def _is_task_active_on_day(task: dict, js_day: int) -> bool:
active_days = task.get("activeDays")
if not isinstance(active_days, list) or len(active_days) == 0:
return True
return js_day in active_days
def _format_active_days(active_days: list) -> str:
if not isinstance(active_days, list) or len(active_days) == 0 or len(active_days) == 7:
return "Every day"
return " ".join(label for label, value in WEEK_DAYS if value in active_days)
def _parse_active_days_input(text: str) -> Optional[list]:
raw = text.strip().lower()
if not raw or raw in {"all", "every", "everyday", "every day", "daily"}:
return ALL_DAYS.copy()
tokens = [t for t in re.split(r"[\s,]+", raw) if t]
if not tokens:
return ALL_DAYS.copy()
picked = set()
for token in tokens:
if token.isdigit():
day_num = int(token)
if 0 <= day_num <= 6:
picked.add(day_num)
else:
return None
else:
key = token[:3]
if key in DAY_TOKEN_MAP:
picked.add(DAY_TOKEN_MAP[key])
elif token in DAY_TOKEN_MAP:
picked.add(DAY_TOKEN_MAP[token])
else:
return None
if not picked:
return None
ordered = [value for _, value in WEEK_DAYS if value in picked]
return ordered
class TaskServer:
def __init__(self, update_callback):
self.update_callback = update_callback
self.current_tasks = []
self.sse_clients = []
self.last_date_check = None
self.app = web.Application()
self.app.add_routes([
web.options('/tasks', self.handle_options),
web.post('/tasks', self.handle_tasks),
web.get('/tasks', self.handle_get_tasks),
web.get('/tasks/stream', self.handle_sse),
web.get('/ping', self.handle_ping),
web.options('/ping', self.handle_options),
])
self.runner = None
self.site = None
def should_update_dates(self):
"""Check if we should update dates (only once per day)"""
now = datetime.now(timezone.utc)
today = datetime(now.year, now.month, now.day, tzinfo=timezone.utc)
if self.last_date_check is None or self.last_date_check < today:
self.last_date_check = now
return True
return False
def update_task_dates_to_today(self, tasks):
"""Update task dates to today if they're from a previous day"""
if not isinstance(tasks, list):
return tasks
now = datetime.now(timezone.utc)
today = datetime(now.year, now.month, now.day, tzinfo=timezone.utc)
changed = False
for task in tasks:
due_time_str = task.get('dueTime')
if not due_time_str:
continue
_ensure_active_days(task)
try:
due_time_str = due_time_str.replace('Z', '+00:00')
task_due = datetime.fromisoformat(due_time_str)
if task_due.tzinfo is None:
task_due = task_due.replace(tzinfo=timezone.utc)
task_due_date = datetime(task_due.year, task_due.month, task_due.day, tzinfo=timezone.utc)
if task_due_date < today:
next_active = self._get_next_active_date(task, today)
new_due_time = datetime(
next_active.year, next_active.month, next_active.day,
task_due.hour, task_due.minute, task_due.second, task_due.microsecond,
tzinfo=timezone.utc
)
task['dueTime'] = new_due_time.isoformat()
task['alarmTriggered'] = False
task['checked'] = False
changed = True
print(
f"✓ [TERMINAL] Updated task '{task.get('name')}' date from {task_due_date.date()} to {today.date()}")
except Exception as e:
print(f"Error updating date for task {task.get('name')}: {e}")
continue
if changed:
# Reset the date check flag when we've made changes
self.last_date_check = now
return tasks
def _get_next_active_date(self, task: dict, from_date: datetime) -> datetime:
active_days = _ensure_active_days(task)
for offset in range(0, 7):
candidate = from_date + timedelta(days=offset)
js_day = _js_day_from_datetime(candidate)
if js_day in active_days:
return candidate
return from_date
async def start(self):
self.runner = web.AppRunner(self.app)
await self.runner.setup()
self.site = web.TCPSite(self.runner, '0.0.0.0', 2137)
await self.site.start()
print(f"DEBUG: Server started on port 2137 with SSE support")
async def stop(self):
if self.site:
await self.site.stop()
if self.runner:
await self.runner.cleanup()
print(f"DEBUG: Server stopped")
async def handle_options(self, request):
return web.Response(headers={
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
})
async def handle_ping(self, request):
return web.Response(text="pong", headers={'Access-Control-Allow-Origin': '*'})
async def handle_get_tasks(self, request):
return web.json_response(self.current_tasks, headers={'Access-Control-Allow-Origin': '*'})
async def handle_sse(self, request):
response = web.StreamResponse(
status=200,
reason='OK',
headers={
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Connection': 'keep-alive',
}
)
await response.prepare(request)
self.sse_clients.append(response)
print(f"✓ SSE client connected (total: {len(self.sse_clients)})")
try:
if self.current_tasks and self.should_update_dates():
print("🔄 First SSE connection today - checking if dates need updating...")
self.current_tasks = self.update_task_dates_to_today(self.current_tasks)
await response.write(f"data: {json.dumps(self.current_tasks)}\n\n".encode('utf-8'))
while True:
await asyncio.sleep(30)
try:
await response.write(": keepalive\n\n".encode('utf-8'))
except:
break
except Exception as e:
print(f"SSE client disconnected: {e}")
finally:
if response in self.sse_clients:
self.sse_clients.remove(response)
print(f"✓ SSE client removed (remaining: {len(self.sse_clients)})")
return response
async def broadcast_tasks(self):
"""Send updated tasks to all connected browsers via SSE"""
if not self.sse_clients:
return
message = f"data: {json.dumps(self.current_tasks)}\n\n".encode('utf-8')
disconnected = []
for client in self.sse_clients:
try:
await client.write(message)
except Exception as e:
print(f"Failed to send to SSE client: {e}")
disconnected.append(client)
for client in disconnected:
if client in self.sse_clients:
self.sse_clients.remove(client)
async def handle_tasks(self, request):
try:
data = await request.json()
data = self.update_task_dates_to_today(data)
self.current_tasks = data
self.update_callback(self.current_tasks)
await self.broadcast_tasks()
return web.Response(text="Received", headers={'Access-Control-Allow-Origin': '*'})
except Exception as e:
traceback.print_exc()
return web.Response(status=500, text=str(e), headers={'Access-Control-Allow-Origin': '*'})
# ==================== MODAL SCREENS ====================
# Modal screen for editing task name
class EditTaskScreen(ModalScreen):
CSS = """
EditTaskScreen {
align: center middle;
}
#edit-dialog {
width: 60;
height: 11;
background: #2a2a2a;
border: heavy #4a4a4a;
padding: 1 2;
}
#edit-title {
width: 100%;
height: 3;
content-align: center middle;
text-style: bold;
color: #49dfb7;
}
#edit-input {
width: 100%;
margin-top: 1;
margin-bottom: 1;
}
#edit-help {
width: 100%;
height: 2;
content-align: center middle;
color: #a0a0a0;
}
"""
def __init__(self, task_name: str):
super().__init__()
self.task_name = task_name
def compose(self) -> ComposeResult:
with Vertical(id="edit-dialog"):
yield Static("Edit Task Name", id="edit-title")
yield Input(
value=self.task_name,
placeholder="Task name",
id="edit-input",
)
yield Static("Press Enter to save, Escape to cancel", id="edit-help")
def on_mount(self) -> None:
input_widget = self.query_one("#edit-input", Input)
input_widget.focus()
input_widget.cursor_position = len(self.task_name)
def on_input_submitted(self, event: Input.Submitted) -> None:
"""Handle Enter key from Input widget"""
self.dismiss(event.value)
def key_escape(self) -> None:
"""Handle Escape key"""
self.dismiss(None)
# Modal screen for adding new task
class AddTaskScreen(ModalScreen):
CSS = """
AddTaskScreen {
align: center middle;
}
#add-dialog {
width: 60;
height: 19;
background: #2a2a2a;
border: heavy #4a4a4a;
padding: 1 2;
}
#add-title {
width: 100%;
height: 3;
content-align: center middle;
text-style: bold;
color: #49dfb7;
}
.input-container {
width: 100%;
height: auto;
margin-top: 1;
}
.input-label {
width: 100%;
color: #a0a0a0;
margin-bottom: 0;
}
#task-name-input, #task-time-input {
width: 100%;
}
#task-days-input {
width: 100%;
}
#add-help {
width: 100%;
height: 2;
content-align: center middle;
color: #a0a0a0;
margin-top: 1;
}
"""
def compose(self) -> ComposeResult:
with Vertical(id="add-dialog"):
yield Static("Add New Task", id="add-title")
with Vertical(classes="input-container"):
yield Static("Task Name:", classes="input-label")
yield Input(
placeholder="Enter task name",
id="task-name-input",
)
with Vertical(classes="input-container"):
yield Static("Due Time (HH:MM):", classes="input-label")
yield Input(
placeholder="14:30",
id="task-time-input",
)
with Vertical(classes="input-container"):
yield Static("Active Days (Mon Tue Wed Thu Fri Sat Sun):", classes="input-label")
yield Input(
placeholder="Every day",
id="task-days-input",
)
yield Static("Tab to switch • Enter to save • Escape to cancel", id="add-help")
def on_mount(self) -> None:
self.query_one("#task-name-input", Input).focus()
def on_input_submitted(self, event: Input.Submitted) -> None:
"""Handle Enter key - collect both inputs and return"""
task_name = self.query_one("#task-name-input", Input).value.strip()
task_time = self.query_one("#task-time-input", Input).value.strip()
task_days = self.query_one("#task-days-input", Input).value.strip()
if task_name and task_time:
self.dismiss({"name": task_name, "time": task_time, "days": task_days})
else:
# Focus on the empty field
if not task_name:
self.query_one("#task-name-input", Input).focus()
elif not task_time:
self.query_one("#task-time-input", Input).focus()
def key_escape(self) -> None:
"""Handle Escape key"""
self.dismiss(None)
# Modal screen for delete confirmation
class DeleteConfirmScreen(ModalScreen):
CSS = """
DeleteConfirmScreen {
align: center middle;
}
#delete-dialog {
width: 60;
height: 11;
background: #2a2a2a;
border: heavy #ff5555;
padding: 1 2;
}
#delete-title {
width: 100%;
height: 3;
content-align: center middle;
text-style: bold;
color: #ff5555;
}
#delete-message {
width: 100%;
height: 3;
content-align: center middle;
color: #ffffff;
margin-top: 1;
}
#delete-help {
width: 100%;
height: 2;
content-align: center middle;
color: #a0a0a0;
margin-top: 1;
}
"""
def __init__(self, task_name: str):
super().__init__()
self.task_name = task_name
def compose(self) -> ComposeResult:
with Vertical(id="delete-dialog"):
yield Static("⚠️ Delete Task?", id="delete-title")
yield Static(f'"{self.task_name}"', id="delete-message")
yield Static("Press Y to confirm • N or Escape to cancel", id="delete-help")
def key_y(self) -> None:
"""Confirm deletion"""
self.dismiss(True)
def key_n(self) -> None:
"""Cancel deletion"""
self.dismiss(False)
def key_escape(self) -> None:
"""Cancel deletion"""
self.dismiss(False)
# Modal screen for editing active days
class EditDaysScreen(ModalScreen):
CSS = """
EditDaysScreen {
align: center middle;
}
#days-dialog {
width: 60;
height: 11;
background: #2a2a2a;
border: heavy #4a4a4a;
padding: 1 2;
}
#days-title {
width: 100%;
height: 3;
content-align: center middle;
text-style: bold;
color: #49dfb7;
}
#days-input {
width: 100%;
margin-top: 1;
margin-bottom: 1;
}
#days-help {
width: 100%;
height: 2;
content-align: center middle;
color: #a0a0a0;
}
"""
def __init__(self, active_days: list):
super().__init__()
self.active_days = active_days
def compose(self) -> ComposeResult:
with Vertical(id="days-dialog"):
yield Static("Edit Active Days", id="days-title")
yield Input(
value=_format_active_days(self.active_days) if self.active_days else "Every day",
placeholder="Mon Tue Wed Thu Fri Sat Sun",
id="days-input",
)
yield Static("Use day names or 0-6 • Enter to save • Escape to cancel", id="days-help")
def on_mount(self) -> None:
input_widget = self.query_one("#days-input", Input)
input_widget.focus()
input_widget.cursor_position = len(input_widget.value)
def on_input_submitted(self, event: Input.Submitted) -> None:
self.dismiss(event.value)
def key_escape(self) -> None:
self.dismiss(None)
# ==================== MAIN APP ====================
class TaskBuddyApp(App):
CSS = """
Screen { background: #373636; align: center middle; }
DataTable { height: 100%; background: #2a2a2a; border: heavy #4a4a4a; color: #ffffff; }
DataTable > .datatable--header { background: #3a3a3a; color: #a0a0a0; text-style: bold; }
DataTable > .datatable--cursor { background: #404040; }
DataTable > .datatable--odd-row { background: #2d2d2d; }
DataTable > .datatable--even-row { background: #323232; }
.status-box { dock: top; height: 3; content-align: center middle; background: #3a3a3a; color: #49dfb7; text-style: bold; border: heavy #4a4a4a; margin-bottom: 1; }
.stats-container { dock: top; height: 3; margin-bottom: 1; }
.stat-box { width: 1fr; height: 100%; content-align: center middle; background: #3a3a3a; border: heavy #4a4a4a; margin-right: 1; }
.stat-box:last-child { margin-right: 0; }
Header { background: #2a2a2a; color: #a0a0a0; }
Footer { background: #373636; color: #a0a0a0; }
"""
BINDINGS = [
("q", "quit", "Quit"),
("a", "decrease_time", "Time -1min"),
("d", "increase_time", "Time +1min"),
("u", "edit_task", "Edit Name"),
("e", "edit_days", "Edit Days"),
("n", "add_task", "New Task"),
("x", "delete_task", "Delete"),
]
def compose(self) -> ComposeResult:
yield Header()
yield Static("Initializing...", id="status", classes="status-box")
with Horizontal(classes="stats-container"):
yield Static("Total: [b]0[/b]", id="stat-total", classes="stat-box")
yield Static("Done: [b]0[/b]", id="stat-done", classes="stat-box")
yield Static("Todo: [b]0[/b]", id="stat-todo", classes="stat-box")
yield Static("Overdue: [b]0[/b]", id="stat-overdue", classes="stat-box")
yield DataTable()
yield Footer()
async def on_mount(self) -> None:
table = self.query_one(DataTable)
table.add_columns("Status", "Time", "Days", "Task Name")
table.cursor_type = "row"
table.focus()
table.zebra_stripes = True
self.server = TaskServer(self.update_tasks)
await self.server.start()
self.query_one("#status").update("Server Running on Port 2137 • Waiting for tasks...")
async def on_unmount(self) -> None:
"""Cleanup when the app is closed"""
if hasattr(self, 'server'):
await self.server.stop()
def update_tasks(self, tasks):
"""Callback from server to update UI"""
tasks = self.server.update_task_dates_to_today(tasks)
self.call_later(self._refresh_table, tasks)
def _refresh_table(self, tasks):
"""Refresh the table display"""
table = self.query_one(DataTable)
# Save current row key
previous_key = None
if table.cursor_row is not None and table.row_count:
for idx, key in enumerate(table.rows.keys()):
if idx == table.cursor_row:
previous_key = key
break
table.clear()
if not isinstance(tasks, list):
return
sorted_tasks = sorted(tasks, key=lambda x: x.get('dueTime', ''))
current_utc = datetime.now(timezone.utc)
current_local = datetime.now().astimezone()
current_js_day = _js_day_from_datetime(current_local)
total_tasks = len(tasks)
done_count = todo_count = overdue_count = 0
for task in sorted_tasks:
name = task.get('name', 'Unknown task')
is_checked = task.get('checked', False)
due_str = task.get('dueTime', '')
task_id = task.get("id", str(hash(name)))
active_days = _ensure_active_days(task)
active_today = _is_task_active_on_day(task, current_js_day)
time_str = "??:??"
time_passed = False
if due_str:
try:
due_str = due_str.replace('Z', '+00:00')
due_utc = datetime.fromisoformat(due_str)
if due_utc.tzinfo is None:
due_utc = due_utc.replace(tzinfo=timezone.utc)
due_local = due_utc.astimezone()
time_str = due_local.strftime("%H:%M")
time_passed = due_utc < current_utc
except Exception:
name = f"[dim]{name} (bad date)[/dim]"
if not active_today:
status = "[blue]⏸ INACTIVE[/blue]"
style_name = f"[dim]{name}[/dim]"
elif is_checked:
status = "[green]✔ DONE[/green]"
style_name = f"[strike]{name}[/strike]"
done_count += 1
elif time_passed:
status = "[red]⚠ LATE[/red]"
style_name = f"[bold red]{name}[/bold red]"
overdue_count += 1
else:
status = "[yellow]○ TODO[/yellow]"
style_name = name
todo_count += 1
days_str = _format_active_days(active_days)
table.add_row(status, time_str, days_str, style_name, key=task_id)
# Restore cursor
if previous_key is not None and table.row_count:
for idx, key in enumerate(table.rows.keys()):
if key == previous_key:
table.move_cursor(row=idx)
break
local_now = datetime.now().strftime("%H:%M:%S")
self.query_one("#status").update(f"Server Active (Port 2137) • Last Update: {local_now}")
self.query_one("#stat-total").update(f"[#a0a0a0]Total:[/] [#49dfb7][b]{total_tasks}[/b]")
self.query_one("#stat-done").update(f"[#a0a0a0]Done:[/] [#50fa7b][b]{done_count}[/b]")
self.query_one("#stat-todo").update(f"[#a0a0a0]Todo:[/] [#f1fa8c][b]{todo_count}[/b]")
self.query_one("#stat-overdue").update(f"[#a0a0a0]Overdue:[/] [#ff5555][b]{overdue_count}[/b]")
def get_selected_task(self):
"""Get the currently selected task"""
table = self.query_one(DataTable)
if table.cursor_row is None or table.cursor_row >= table.row_count:
return None
try:
row_key = None
for idx, key in enumerate(table.rows.keys()):
if idx == table.cursor_row:
row_key = key
break
if row_key is None:
return None
task_id = str(row_key.value)
for task in self.server.current_tasks:
if str(task.get("id")) == task_id:
return task
except Exception as e:
print(f"Error getting selected task: {e}")
traceback.print_exc()
return None
def adjust_task_time(self, minutes_delta: int):
"""Adjust the selected task's time"""
task = self.get_selected_task()
if not task:
return
table = self.query_one(DataTable)
current_row = table.cursor_row
due_str = task.get('dueTime')
if not due_str:
return
try:
due_str = due_str.replace('Z', '+00:00')
due_time = datetime.fromisoformat(due_str)
if due_time.tzinfo is None:
due_time = due_time.replace(tzinfo=timezone.utc)
new_due_time = due_time + timedelta(minutes=minutes_delta)
task['dueTime'] = new_due_time.isoformat()
task['isPreset'] = False
print(f"✓ Adjusted '{task['name']}' time by {minutes_delta} min: {new_due_time.strftime('%H:%M')}")
self.server.current_tasks = self.server.update_task_dates_to_today(self.server.current_tasks)
self._refresh_table(self.server.current_tasks)
asyncio.create_task(self.sync_tasks_to_webapp())
if current_row is not None and current_row < table.row_count:
table.move_cursor(row=current_row)
except Exception as e:
print(f"Error adjusting time: {e}")
def action_decrease_time(self):
"""Decrease selected task time by 1 minute"""
self.adjust_task_time(-1)
def action_increase_time(self):
"""Increase selected task time by 1 minute"""
self.adjust_task_time(1)
def action_edit_task(self):
"""Edit the selected task's name - runs in worker"""
self.run_worker(self._edit_task_worker(), exclusive=True)
async def _edit_task_worker(self):
"""Worker method for editing task"""
task = self.get_selected_task()
if not task:
print("No task selected")
return
table = self.query_one(DataTable)
current_row = table.cursor_row
current_name = task.get('name', '')
result = await self.push_screen_wait(EditTaskScreen(current_name))
if result and result.strip():
task['name'] = result.strip()
task['isPreset'] = False
print(f"✓ Updated task name to: '{result.strip()}'")
self.server.current_tasks = self.server.update_task_dates_to_today(self.server.current_tasks)
self._refresh_table(self.server.current_tasks)
asyncio.create_task(self.sync_tasks_to_webapp())
if current_row is not None and current_row < table.row_count:
table.move_cursor(row=current_row)
table.focus()
else:
print("Task name update cancelled")
table.focus()
def action_add_task(self):
"""Add a new task - runs in worker"""
self.run_worker(self._add_task_worker(), exclusive=True)
async def _add_task_worker(self):
"""Worker method for adding task"""
result = await self.push_screen_wait(AddTaskScreen())
if result and isinstance(result, dict):
task_name = result.get("name", "").strip()
task_time = result.get("time", "").strip()
task_days_raw = result.get("days", "").strip()
if task_name and task_time:
try:
# Parse time (HH:MM format)
hours, minutes = map(int, task_time.split(':'))
active_days = _parse_active_days_input(task_days_raw)
if active_days is None:
print("❌ Invalid active days. Use Mon Tue Wed Thu Fri Sat Sun or 0-6.")
return
# Create due time for TODAY (not a past date)
now = datetime.now(timezone.utc)
due_time = datetime(
now.year, now.month, now.day,
hours, minutes, 0, 0,
tzinfo=timezone.utc
)
# Generate unique ID
task_id = str(int(datetime.now().timestamp() * 1000))
# Create new task
new_task = {
"id": task_id,
"name": task_name,
"dueTime": due_time.isoformat(),
"checked": False,
"alarmTriggered": False,
"isPreset": False,
"activeDays": active_days,
}
self.server.current_tasks.append(new_task)
print(f"✓ Added new task: '{task_name}' at {task_time}")
self.server.current_tasks = self.server.update_task_dates_to_today(self.server.current_tasks)
self._refresh_table(self.server.current_tasks)
asyncio.create_task(self.sync_tasks_to_webapp())
# Move cursor to the new task
table = self.query_one(DataTable)
for idx, key in enumerate(table.rows.keys()):
if str(key.value) == task_id:
table.move_cursor(row=idx)
break
table.focus()
except ValueError:
print(f"❌ Invalid time format: {task_time}. Use HH:MM (e.g., 14:30)")
except Exception as e:
print(f"❌ Error adding task: {e}")
else:
print("Add task cancelled")
table = self.query_one(DataTable)
table.focus()
def action_delete_task(self):
"""Delete the selected task - runs in worker"""
self.run_worker(self._delete_task_worker(), exclusive=True)
def action_edit_days(self):
"""Edit the selected task's active days - runs in worker"""
self.run_worker(self._edit_days_worker(), exclusive=True)
async def _edit_days_worker(self):
task = self.get_selected_task()
if not task:
print("No task selected")
return
table = self.query_one(DataTable)
current_row = table.cursor_row
active_days = _ensure_active_days(task)
result = await self.push_screen_wait(EditDaysScreen(active_days))
if result is not None:
parsed_days = _parse_active_days_input(result)
if parsed_days is None:
print("❌ Invalid active days. Use Mon Tue Wed Thu Fri Sat Sun or 0-6.")
table.focus()
return
task["activeDays"] = parsed_days
task["isPreset"] = False
print(f"✓ Updated active days for '{task.get('name', '')}'")
self.server.current_tasks = self.server.update_task_dates_to_today(self.server.current_tasks)
self._refresh_table(self.server.current_tasks)
asyncio.create_task(self.sync_tasks_to_webapp())
if current_row is not None and current_row < table.row_count:
table.move_cursor(row=current_row)
table.focus()
else:
print("Active days update cancelled")
table.focus()
async def _delete_task_worker(self):
"""Worker method for deleting task"""
task = self.get_selected_task()
if not task:
print("No task selected")
return
task_name = task.get('name', 'Unknown')
# Show confirmation dialog
confirmed = await self.push_screen_wait(DeleteConfirmScreen(task_name))
if confirmed:
table = self.query_one(DataTable)
current_row = table.cursor_row
# Remove task from list
task_id = task.get('id')
self.server.current_tasks = [
t for t in self.server.current_tasks
if t.get('id') != task_id
]
print(f"✓ Deleted task: '{task_name}'")
# ✅ Ensure dates are current before syncing
self.server.current_tasks = self.server.update_task_dates_to_today(self.server.current_tasks)
self._refresh_table(self.server.current_tasks)
asyncio.create_task(self.sync_tasks_to_webapp())
# Move cursor to previous position or one up
if table.row_count > 0:
new_row = min(current_row, table.row_count - 1) if current_row is not None else 0
table.move_cursor(row=new_row)
table.focus()
else:
print("Delete cancelled")
table = self.query_one(DataTable)
table.focus()
async def sync_tasks_to_webapp(self):
"""Send updated tasks back to the web app"""
try:
await self.server.broadcast_tasks()
print("✓ Broadcasted to all connected browsers")
except Exception as e: