-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtaskmate.py
More file actions
1532 lines (1328 loc) · 67.4 KB
/
taskmate.py
File metadata and controls
1532 lines (1328 loc) · 67.4 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
import os
import sys
import asyncio
import json
import logging
from dotenv import load_dotenv
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_date
from typing import List, Dict, Any
from msal import PublicClientApplication, SerializableTokenCache
from openai import OpenAI, OpenAIError, RateLimitError, APIConnectionError
from rich.console import Console
from rich.prompt import Prompt
from rich.table import Table
from cachetools import TTLCache
import aiohttp
from dateparser import parse as parse_natural_date
import pytz
from prompt_toolkit import PromptSession
from prompt_toolkit.styles import Style
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import FileHistory
from prompt_toolkit.key_binding import KeyBindings
from pydantic import BaseModel
def get_custom_prompt(current_datetime):
return f'Calendar Assistant ({current_datetime})> '
def get_history():
return FileHistory('.calendar_assistant_history')
def get_key_bindings():
kb = KeyBindings()
@kb.add('c-d')
def _(event):
"Exit when 'c-d' is pressed."
event.app.exit()
@kb.add('c-l')
def _(event):
"Clear the screen when 'c-l' is pressed."
event.app.current_buffer.text = ''
return kb
logging.basicConfig(
filename='chatbot.log',
filemode='a',
format='%(asctime)s %(levelname)s:%(message)s',
level=logging.DEBUG
)
logger = logging.getLogger(__name__)
console = Console()
load_dotenv()
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
OPENAI_PACKAGE_VERSION = os.getenv('OPENAI_PACKAGE_VERSION', '1.0.0')
CLIENT_ID = os.getenv('CLIENT_ID')
TENANT_ID = os.getenv('TENANT_ID')
AUTHORITY = f'https://login.microsoftonline.com/{TENANT_ID}'
SCOPES = ['Calendars.ReadWrite']
missing_vars = []
if not OPENAI_API_KEY:
missing_vars.append('OPENAI_API_KEY')
if not CLIENT_ID:
missing_vars.append('CLIENT_ID')
if not TENANT_ID:
missing_vars.append('TENANT_ID')
if missing_vars:
console.print(f"[bold red]Error: Missing environment variables: {', '.join(missing_vars)}[/bold red]")
sys.exit(1)
client = OpenAI(api_key=OPENAI_API_KEY)
token_cache = SerializableTokenCache()
app = PublicClientApplication(
CLIENT_ID,
authority=AUTHORITY,
token_cache=token_cache
)
def get_access_token() -> str:
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(SCOPES, account=accounts[0])
else:
result = app.acquire_token_interactive(SCOPES)
if 'access_token' in result:
return result['access_token']
else:
error_description = result.get('error_description', 'Unknown error')
console.print(f"[bold red]Error acquiring token: {error_description}[/bold red]")
logger.error(f"Error acquiring token: {error_description}")
sys.exit(1)
conversation_history: List[Dict[str, Any]] = []
def trim_conversation_history(history: List[Dict[str, Any]], max_length: int = 10) -> List[Dict[str, Any]]:
return history[-max_length:]
def parse_natural_language_date(date_str: str, tz_str: str = 'America/New_York') -> datetime:
try:
timezone = pytz.timezone(tz_str)
except pytz.UnknownTimeZoneError:
logger.error(f"Unknown timezone: {tz_str}")
raise ValueError(f"Unknown timezone: {tz_str}")
logger.debug(f"Parsing date string: '{date_str}' with RELATIVE_BASE '{datetime.now(timezone).isoformat()}'")
parsed_date = parse_natural_date(
date_str,
settings={
'RETURN_AS_TIMEZONE_AWARE': True,
'RELATIVE_BASE': datetime.now(timezone),
'TIMEZONE': tz_str,
'TO_TIMEZONE': tz_str
}
)
if not parsed_date:
logger.error(f"Unable to parse date: {date_str}")
raise ValueError(f"Unable to parse date: {date_str}")
# Ensure the parsed date is timezone-aware
if parsed_date.tzinfo is None:
parsed_date = timezone.localize(parsed_date)
logger.debug(f"Parsed date: {parsed_date.isoformat()}")
return parsed_date
def format_datetime_us(dt_str: str) -> str:
dt = parse_date(dt_str)
if dt:
return dt.strftime('%A, %B %d, %Y at %I:%M %p')
return ''
id_cache = TTLCache(maxsize=1000, ttl=3600)
async def cache_calendars() -> List[Dict[str, Any]]:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
url = 'https://graph.microsoft.com/v1.0/me/calendars?$select=id,name,isDefaultCalendar'
calendars = []
async with aiohttp.ClientSession() as session:
while url:
try:
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
calendars.extend(data.get('value', []))
url = data.get('@odata.nextLink')
else:
error_text = await response.text()
console.print(f"[bold red]Failed to get calendars: {response.status} {error_text}[/bold red]")
logger.error(f"Failed to get calendars: {response.status} {error_text}")
return []
except aiohttp.ClientError as e:
console.print(f"[bold red]Request exception while fetching calendars: {e}[/bold red]")
logger.exception("Request exception while fetching calendars")
return []
if not calendars:
logger.error("No calendars retrieved from Microsoft 365")
console.print("[bold red]Failed to retrieve any calendars. Please check your account settings.[/bold red]")
return []
for calendar in calendars:
id_cache[calendar['name'].lower()] = calendar['id']
if calendar.get('isDefaultCalendar'):
id_cache['default'] = calendar['id']
logger.debug(f"Cached calendars: {id_cache}")
return calendars
def get_default_calendar_id() -> str:
default_id = id_cache.get('default')
if default_id:
return default_id
# If no default calendar is set, return the first calendar in the cache
return next(iter(id_cache.values()), None)
async def make_api_call(method: str, url: str, headers: Dict[str, str], **kwargs) -> Dict[str, Any]:
async with aiohttp.ClientSession() as session:
func = getattr(session, method.lower())
try:
if 'json' in kwargs:
logger.debug(f"API Request JSON: {json.dumps(kwargs['json'], indent=4)}")
async with func(url, headers=headers, **kwargs) as response:
text = await response.text()
logger.debug(f"API Response Status: {response.status}, Body: {text}")
if response.status in (200, 201, 204):
return {} if response.status == 204 else json.loads(text)
else:
logger.error(f"API call failed: {response.status} {text}")
return {'error': f"{response.status}: {text}"}
except Exception as e:
logger.exception("API call exception")
return {'error': str(e)}
def format_event_preview(event_data: Dict[str, Any]) -> None:
table = Table(title="Event Preview")
table.add_column("Field", style="bold")
table.add_column("Value")
for field in ['subject', 'body', 'start', 'end', 'location', 'attendees',
'recurrence', 'reminderMinutesBeforeStart', 'categories', 'isAllDay']:
value = event_data.get(field)
if field in ('start', 'end'):
if event_data.get('isAllDay', False):
date = value.get('date', '')
value = f"{date} (All day)"
else:
date_time = value.get('dateTime', '')
time_zone = value.get('timeZone', 'UTC')
try:
formatted_dt = format_datetime_us(date_time)
value = f"{formatted_dt} ({time_zone})"
except Exception as e:
value = f"{date_time} ({time_zone})"
logger.error(f"Error formatting datetime for field '{field}': {e}")
elif field == 'location' and isinstance(value, dict):
value = value.get('displayName', '')
elif field == 'attendees':
if isinstance(value, list) and value:
attendees_formatted = ', '.join([att.get('emailAddress', {}).get('address', '') for att in value])
value = attendees_formatted if attendees_formatted else 'None'
else:
value = 'None'
elif field == 'recurrence' and not value:
value = 'None'
elif field == 'categories' and not value:
value = 'None'
elif field == 'reminderMinutesBeforeStart' and not value:
value = 'None'
elif field == 'isAllDay':
value = 'Yes' if value else 'No'
table.add_row(field.capitalize(), str(value))
console.print(table)
def validate_event_data(event_data: Dict[str, Any]) -> bool:
required_fields = ['subject', 'start', 'end']
for field in required_fields:
if field not in event_data:
console.print(f"[bold red]Error: '{field}' is a required field for events.[/bold red]")
return False
# Additional validation checks
if not event_data['subject'].strip():
console.print("[bold red]Error: 'subject' cannot be empty.[/bold red]")
return False
try:
start = parse_natural_language_date(event_data['start'])
end = parse_natural_language_date(event_data['end'])
if end <= start:
console.print("[bold red]Error: End time must be after start time.[/bold red]")
return False
except ValueError as ve:
console.print(f"[bold red]Error: Invalid date format - {ve}[/bold red]")
return False
return True
class CalendarEvent(BaseModel):
subject: str
start: str
end: str
location: str = ""
attendees: List[str] = []
reminderMinutesBeforeStart: int = 15
categories: List[str] = []
isAllDay: bool = False
body: str = ""
import time
async def create_event(event_data: dict, tz_str: str = 'America/New_York', max_retries: int = 3) -> None:
try:
event_data = CalendarEvent(**event_data)
except ValueError as e:
console.print(f"[bold red]Error: Invalid event data provided - {e}[/bold red]")
return
start_datetime = parse_natural_language_date(event_data.start, tz_str=tz_str)
end_datetime = parse_natural_language_date(event_data.end, tz_str=tz_str)
new_event = {
'subject': event_data.subject,
'body': {
'contentType': 'text',
'content': event_data.body
},
'isAllDay': event_data.isAllDay,
'start': {
'dateTime': start_datetime.isoformat() if not event_data.isAllDay else start_datetime.date().isoformat(),
'timeZone': tz_str
},
'end': {
'dateTime': end_datetime.isoformat() if not event_data.isAllDay else end_datetime.date().isoformat(),
'timeZone': tz_str
}
}
if event_data.location:
new_event['location'] = {'displayName': event_data.location}
if event_data.attendees:
new_event['attendees'] = [{'emailAddress': {'address': email}} for email in event_data.attendees]
if event_data.reminderMinutesBeforeStart is not None:
new_event['reminderMinutesBeforeStart'] = event_data.reminderMinutesBeforeStart
if event_data.categories:
new_event['categories'] = event_data.categories
logger.debug(f"Event payload: {json.dumps(new_event, indent=2)}")
console.print("\n[bold yellow]Event Preview:[/bold yellow]")
format_event_preview(new_event)
calendars = await cache_calendars()
console.print("\n[bold cyan]Available Calendars:[/bold cyan]")
for idx, calendar in enumerate(calendars, start=1):
console.print(f"{idx}. {calendar['name']}")
calendar_completer = WordCompleter([str(i) for i in range(1, len(calendars)+1)])
session = PromptSession()
while True:
calendar_choice = await session.prompt_async("Select a calendar (number): ", completer=calendar_completer)
try:
calendar_index = int(calendar_choice) - 1
if 0 <= calendar_index < len(calendars):
selected_calendar = calendars[calendar_index]
break
else:
console.print("[bold red]Invalid selection. Please try again.[/bold red]")
except ValueError:
console.print("[bold red]Please enter a valid number.[/bold red]")
calendar_id = selected_calendar['id']
for attempt in range(max_retries):
try:
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}/events'
response = await make_api_call('POST', url, headers, json=new_event)
if 'error' in response:
error_code = response['error'].get('code', '')
if error_code == 'UnableToDeserializePostBody':
logger.error(f"Deserialization error. Payload: {json.dumps(new_event, indent=2)}")
console.print("[bold red]Error: The event data couldn't be processed. Please check the event details.[/bold red]")
return
raise Exception(f"Failed to create event: {response['error']}")
console.print(f"[bold green]Event '{event_data.subject}' created successfully in calendar '{selected_calendar['name']}'.[/bold green]")
logger.info(f"Event '{event_data.subject}' created successfully in calendar '{selected_calendar['name']}'.")
return
except Exception as e:
logger.error(f"Attempt {attempt + 1} failed: {str(e)}")
if attempt < max_retries - 1:
wait_time = (2 ** attempt) * 0.5 # Exponential backoff
console.print(f"[bold yellow]Retrying in {wait_time:.1f} seconds... (Attempt {attempt + 2} of {max_retries})[/bold yellow]")
time.sleep(wait_time)
else:
console.print(f"[bold red]Failed to create event after {max_retries} attempts: {str(e)}[/bold red]")
return
async def create_events(calendar_id: str, events_data: Any, tz_str: str = 'America/New_York') -> None:
if isinstance(events_data, str):
try:
events_data = json.loads(events_data)
logger.debug("Deserialized 'events_data' from string to list.")
except json.JSONDecodeError:
console.print(
"[bold red]Error: 'events' should be a valid JSON string representing a list of events.[/bold red]")
logger.error(f"Invalid JSON for 'events': {events_data}")
return
if not isinstance(events_data, list):
console.print("[bold red]Error: 'events' should be a list of event objects.[/bold red]")
logger.error(f"'events' is not a list: {events_data}")
return
console.print(f"\n[bold yellow]Preview of Events to be Created:[/bold yellow]")
for idx, event in enumerate(events_data, start=1):
console.print(f"\n[bold yellow]Event {idx}:[/bold yellow]")
format_event_preview(event)
confirmation = Prompt.ask("Do you want to proceed with creating ALL these events? (yes/no)",
choices=["yes", "no"], default="no")
if confirmation.lower() == "yes":
for event in events_data:
await create_event(calendar_id, event, tz_str=tz_str)
await asyncio.sleep(1)
console.print(f"[bold green]Created {len(events_data)} event(s) successfully.[/bold green]")
logger.info(f"Created {len(events_data)} event(s).")
else:
console.print("[bold red]Event creation canceled by the user.[/bold red]")
logger.info("User canceled event creation.")
async def create_calendar(calendar_name: str, color: str = None) -> None:
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
payload = {
'name': calendar_name,
'color': color if color else 'auto'
}
url = 'https://graph.microsoft.com/v1.0/me/calendars'
response = await make_api_call('POST', url, headers, json=payload)
if 'error' in response:
console.print(f"[bold red]Failed to create calendar: {response['error']}[/bold red]")
logger.error(f"Failed to create calendar '{calendar_name}': {response['error']}")
else:
console.print(f"[bold green]Calendar '{calendar_name}' created successfully.[/bold green]")
logger.info(f"Calendar '{calendar_name}' created successfully.")
async def update_event(calendar_id: str, event_id: str, updates: Dict[str, Any], apply_to_series: bool,
tz_str: str = 'America/New_York') -> None:
if not event_id or not isinstance(event_id, str):
console.print("[bold red]Error: 'event_id' is required and must be a valid string.[/bold red]")
logger.error("Attempted to update event with invalid 'event_id'.")
return
try:
is_all_day = updates.get('isAllDay')
if 'start' in updates:
start_datetime = parse_natural_language_date(updates['start'], tz_str=tz_str)
updates['start'] = {
'dateTime': start_datetime.isoformat() if not is_all_day else start_datetime.date().isoformat(),
'timeZone': tz_str
}
if 'end' in updates:
end_datetime = parse_natural_language_date(updates['end'], tz_str=tz_str)
updates['end'] = {
'dateTime': end_datetime.isoformat() if not is_all_day else (end_datetime.date() + timedelta(days=1)).isoformat(),
'timeZone': tz_str
}
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}/events/{event_id}'
if apply_to_series:
url += '/instances'
response = await make_api_call('PATCH', url, headers, json=updates)
if 'error' in response:
raise Exception(f"Failed to update event: {response['error']}")
console.print(f"[bold green]Event '{event_id}' updated successfully.[/bold green]")
logger.info(f"Event '{event_id}' updated successfully.")
except Exception as e:
console.print(f"[bold red]Error updating event: {str(e)}[/bold red]")
logger.error(f"Error updating event: {str(e)}")
async def delete_calendar(calendar_name: str) -> None:
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}'
}
# Get the calendar ID from the cache or fetch it first
calendar_id = id_cache.get(calendar_name.lower())
if not calendar_id:
console.print(f"[bold red]Calendar '{calendar_name}' not found.[/bold red]")
logger.error(f"Calendar '{calendar_name}' not found in cache.")
return
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}'
response = await make_api_call('DELETE', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to delete calendar: {response['error']}[/bold red]")
logger.error(f"Failed to delete calendar '{calendar_name}': {response['error']}")
else:
console.print(f"[bold green]Calendar '{calendar_name}' deleted successfully.[/bold green]")
logger.info(f"Calendar '{calendar_name}' deleted successfully.")
async def create_calendar(calendar_name: str, color: str = None) -> None:
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
payload = {
'name': calendar_name,
'color': color if color else 'auto'
}
url = 'https://graph.microsoft.com/v1.0/me/calendars'
response = await make_api_call('POST', url, headers, json=payload)
if 'error' in response:
console.print(f"[bold red]Failed to create calendar: {response['error']}[/bold red]")
logger.error(f"Failed to create calendar '{calendar_name}': {response['error']}")
else:
console.print(f"[bold green]Calendar '{calendar_name}' created successfully.[/bold green]")
logger.info(f"Calendar '{calendar_name}' created successfully.")
# Update the cache with the new calendar
await cache_calendars()
async def delete_event(calendar_id: str, event_id: str, cancel_occurrence: bool, cancel_series: bool) -> None:
if not event_id or not isinstance(event_id, str):
console.print("[bold red]Error: 'event_id' is required and must be a valid string.[/bold red]")
logger.error("Attempted to delete event with invalid 'event_id'.")
return
try:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}/events/{event_id}'
if cancel_occurrence:
url += '/instances'
elif cancel_series:
url += '/series'
response = await make_api_call('DELETE', url, headers)
if 'error' in response:
raise Exception(f"Failed to delete event: {response['error']}")
console.print(f"[bold green]Event '{event_id}' deleted successfully.[/bold green]")
logger.info(f"Event '{event_id}' deleted successfully.")
except Exception as e:
console.print(f"[bold red]Error deleting event: {str(e)}[/bold red]")
logger.error(f"Error deleting event: {str(e)}")
async def list_events(calendar_id: str, filters: Dict[str, Any], tz_str: str = 'America/New_York') -> None:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}/events'
query_params = []
if 'start_datetime' in filters and filters['start_datetime'] and 'end_datetime' in filters and filters[
'end_datetime']:
try:
start_datetime = parse_natural_language_date(filters['start_datetime'], tz_str=tz_str).isoformat()
end_datetime = parse_natural_language_date(filters['end_datetime'], tz_str=tz_str).isoformat()
query_params.append(f"start/dateTime ge '{start_datetime}'")
query_params.append(f"end/dateTime le '{end_datetime}'")
logger.debug(f"Filter start_datetime: {start_datetime}")
logger.debug(f"Filter end_datetime: {end_datetime}")
except ValueError as ve:
console.print(f"[bold red]{ve}[/bold red]")
logger.error(f"Date parsing error in filters: {ve}")
return
if 'categories' in filters and filters['categories']:
categories = ','.join([f"'{cat}'" for cat in filters['categories']])
query_params.append(f"categories/any(c:c in ({categories}))")
if 'subject_contains' in filters and filters['subject_contains']:
subject = filters['subject_contains']
query_params.append(f"contains(subject,'{subject}')")
if query_params:
filter_query = ' and '.join(query_params)
url += f"?$filter={filter_query}"
logger.debug(f"Filter query: {filter_query}")
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to list events: {response['error']}[/bold red]")
logger.error(f"Failed to list events: {response['error']}")
else:
events = response.get('value', [])
if not events:
console.print("[bold yellow]No events found.[/bold yellow]")
logger.info("No events found with the given filters.")
return
table = Table(title="Events")
table.add_column("Subject")
table.add_column("Start")
table.add_column("End")
for event in events:
table.add_row(
event.get('subject', ''),
format_datetime_us(event.get('start', {}).get('dateTime', '')),
format_datetime_us(event.get('end', {}).get('dateTime', ''))
)
console.print(table)
logger.info(f"Listed {len(events)} event(s).")
async def get_event(calendar_id: str, event_id: str, properties: List[str], tz_str: str = 'America/New_York') -> None:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
select_params = ','.join(properties) if properties else ''
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}/events/{event_id}'
if select_params:
url += f"?$select={select_params}"
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to get event: {response['error']}[/bold red]")
logger.error(f"Failed to get event {event_id}: {response['error']}")
else:
event = response
table = Table(title="Event Details")
table.add_column("Property", style="bold")
table.add_column("Value")
for prop in properties:
value = event.get(prop, '')
if isinstance(value, dict):
if prop in ['start', 'end']:
if event.get('isAllDay', False):
date = value.get('date', '')
value = f"{date} (All day)"
else:
date_time = value.get('dateTime', '')
time_zone = value.get('timeZone', 'UTC')
try:
formatted_dt = format_datetime_us(date_time)
value = f"{formatted_dt} ({time_zone})"
except Exception as e:
value = f"{date_time} ({time_zone})"
logger.error(f"Error formatting datetime for property '{prop}': {e}")
else:
value = json.dumps(value, indent=2)
elif isinstance(value, list):
if prop == 'attendees':
attendees_formatted = ', '.join([att.get('emailAddress', {}).get('address', '') for att in value])
value = attendees_formatted if attendees_formatted else 'None'
else:
value = ', '.join([str(item) for item in value]) if value else 'None'
elif prop == 'isAllDay':
value = 'Yes' if value else 'No'
elif not value:
value = 'None'
table.add_row(prop.capitalize(), str(value))
console.print(table)
logger.info(f"Retrieved details for event '{event_id}'.")
async def list_calendars(filter_query: str, order_by: str) -> None:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
url = 'https://graph.microsoft.com/v1.0/me/calendars?$select=id,name'
query_params = []
if filter_query:
query_params.append(f"$filter={filter_query}")
if order_by:
query_params.append(f"$orderby={order_by}")
if query_params:
url += '&' + '&'.join(query_params)
logger.debug(f"Calendars filter/order query: {'&'.join(query_params)}")
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to list calendars: {response['error']}[/bold red]")
logger.error(f"Failed to list calendars: {response['error']}")
elif 'value' in response:
calendars = response['value']
if not calendars:
console.print("[bold yellow]No calendars found.[/bold yellow]")
logger.info("No calendars found.")
return
table = Table(title="Calendars")
table.add_column("Name")
for calendar in calendars:
table.add_row(calendar.get('name', ''))
console.print(table)
logger.info(f"Listed {len(calendars)} calendar(s).")
else:
console.print(f"[bold red]Unexpected response format: {response}[/bold red]")
logger.error(f"Unexpected response format when listing calendars: {response}")
async def get_calendar(calendar_id: str, properties: List[str]) -> None:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
select_params = ','.join(properties) if properties else ''
url = f'https://graph.microsoft.com/v1.0/me/calendars/{calendar_id}'
if select_params:
url += f"?$select={select_params}"
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to get calendar: {response['error']}[/bold red]")
logger.error(f"Failed to get calendar {calendar_id}: {response['error']}")
else:
calendar = response
table = Table(title="Calendar Details")
table.add_column("Property", style="bold")
table.add_column("Value")
for prop in properties:
value = calendar.get(prop, '')
if isinstance(value, dict):
value = json.dumps(value, indent=2)
elif isinstance(value, list):
value = ', '.join([str(item) for item in value]) if value else 'None'
elif not value:
value = 'None'
table.add_row(prop.capitalize(), str(value))
console.print(table)
logger.info(f"Retrieved details for calendar '{calendar_id}'.")
async def search_events(query: str, calendar_names: List[str], start_datetime: str, end_datetime: str,
categories: List[str], tz_str: str = 'America/New_York') -> None:
access_token = get_access_token()
headers = {'Authorization': f'Bearer {access_token}'}
search_url = 'https://graph.microsoft.com/v1.0/me/events'
filters = []
if query:
filters.append(f"contains(subject,'{query}') or contains(body/content,'{query}')")
if calendar_names:
calendar_ids = [id_cache.get(name.lower()) for name in calendar_names if id_cache.get(name.lower())]
calendar_ids = [cid for cid in calendar_ids if cid]
if calendar_ids:
calendar_id_list = ','.join([f"'{cid}'" for cid in calendar_ids])
filters.append(f"calendar/id in ({calendar_id_list})")
if start_datetime and end_datetime:
try:
start_dt = parse_natural_language_date(start_datetime, tz_str=tz_str).isoformat()
end_dt = parse_natural_language_date(end_datetime, tz_str=tz_str).isoformat()
filters.append(f"start/dateTime ge '{start_dt}' and end/dateTime le '{end_dt}'")
logger.debug(f"Search filter start_datetime: {start_dt}")
logger.debug(f"Search filter end_datetime: {end_dt}")
except ValueError as ve:
console.print(f"[bold red]{ve}[/bold red]")
logger.error(f"Date parsing error in search filters: {ve}")
return
if categories:
categories_quoted = ','.join([f"'{cat}'" for cat in categories])
filters.append(f"categories/any(c:c in ({categories_quoted}))")
filter_query = ' and '.join(filters)
if filter_query:
search_url += f"?$filter={filter_query}"
logger.debug(f"Search filter query: {filter_query}")
response = await make_api_call('GET', search_url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to search events: {response['error']}[/bold red]")
logger.error(f"Failed to search events: {response['error']}")
else:
events = response.get('value', [])
if not events:
console.print("[bold yellow]No events matched the search criteria.[/bold yellow]")
logger.info("No events matched the search criteria.")
return
table = Table(title="Search Results")
table.add_column("Subject")
table.add_column("Start")
table.add_column("End")
for event in events:
table.add_row(
event.get('subject', ''),
format_datetime_us(event.get('start', {}).get('dateTime', '')),
format_datetime_us(event.get('end', {}).get('dateTime', ''))
)
console.print(table)
logger.info(f"Search returned {len(events)} event(s).")
async def manage_categories(action: str, category_name: str, new_category_name: str = None, color: str = None) -> None:
action_completer = WordCompleter(['create', 'update', 'delete'])
color_completer = WordCompleter(['auto', 'lightBlue', 'lightGreen', 'lightOrange', 'lightGray', 'lightPink', 'lightRed', 'lightYellow'])
session = PromptSession()
if not action:
action = await session.prompt_async("Choose an action (create/update/delete): ", completer=action_completer)
if not category_name:
category_name = await session.prompt_async("Enter category name: ")
if action == 'update' and not new_category_name:
new_category_name = await session.prompt_async("Enter new category name: ")
if (action == 'create' or action == 'update') and not color:
color = await session.prompt_async("Choose a color: ", completer=color_completer)
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
url = 'https://graph.microsoft.com/v1.0/me/outlook/masterCategories'
if action == "create":
payload = {
"name": category_name,
"color": color if color else "preset0"
}
response = await make_api_call('POST', url, headers, json=payload)
if 'error' in response:
console.print(f"[bold red]Failed to create category: {response['error']}[/bold red]")
logger.error(f"Failed to create category '{category_name}': {response['error']}")
else:
console.print(f"[bold green]Category '{category_name}' created successfully.[/bold green]")
logger.info(f"Category '{category_name}' created successfully.")
elif action == "update":
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to retrieve categories: {response['error']}[/bold red]")
logger.error(f"Failed to retrieve categories for update: {response['error']}")
return
categories = response.get('value', [])
category = next((cat for cat in categories if cat.get('name', '').lower() == category_name.lower()), None)
if not category:
console.print(f"[bold red]Category '{category_name}' not found.[/bold red]")
logger.error(f"Category '{category_name}' not found for update.")
return
category_id = category.get('id')
update_url = f"{url}/{category_id}"
payload = {}
if new_category_name:
payload["name"] = new_category_name
if color:
payload["color"] = color
if not payload:
console.print("[bold yellow]No updates provided.[/bold yellow]")
logger.warning("No updates provided for category management.")
return
response = await make_api_call('PATCH', update_url, headers, json=payload)
if 'error' in response:
console.print(f"[bold red]Failed to update category: {response['error']}[/bold red]")
logger.error(f"Failed to update category '{category_name}': {response['error']}")
else:
console.print(f"[bold green]Category '{category_name}' updated successfully.[/bold green]")
logger.info(f"Category '{category_name}' updated successfully.")
elif action == "delete":
response = await make_api_call('GET', url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to retrieve categories: {response['error']}[/bold red]")
logger.error(f"Failed to retrieve categories for deletion: {response['error']}")
return
categories = response.get('value', [])
category = next((cat for cat in categories if cat.get('name', '').lower() == category_name.lower()), None)
if not category:
console.print(f"[bold red]Category '{category_name}' not found.[/bold red]")
logger.error(f"Category '{category_name}' not found for deletion.")
return
category_id = category.get('id')
delete_url = f"{url}/{category_id}"
response = await make_api_call('DELETE', delete_url, headers)
if 'error' in response:
console.print(f"[bold red]Failed to delete category: {response['error']}[/bold red]")
logger.error(f"Failed to delete category '{category_name}': {response['error']}")
else:
console.print(f"[bold green]Category '{category_name}' deleted successfully.[/bold green]")
logger.info(f"Category '{category_name}' deleted successfully.")
else:
console.print("[bold red]Invalid action. Please choose from create, update, or delete.[/bold red]")
logger.warning(f"Invalid category management action: {action}")
def get_function_schemas() -> List[Dict[str, Any]]:
return [
{
"name": "create_calendar",
"description": "Create a new calendar with the specified name and optional color.",
"parameters": {
"type": "object",
"properties": {
"calendar_name": {
"type": "string",
"description": "The name of the calendar to create."
},
"color": {
"type": "string",
"description": "The optional color for the calendar. Defaults to 'auto'.",
"enum": ["auto", "lightBlue", "lightGreen", "lightOrange", "lightGray", "lightPink", "lightRed", "lightYellow"]
}
},
"required": ["calendar_name"]
}
},
{
"name": "delete_calendar",
"description": "Delete a calendar by its name.",
"parameters": {
"type": "object",
"properties": {
"calendar_name": {
"type": "string",
"description": "The name of the calendar to delete."
}
},
"required": ["calendar_name"]
}
},
{
"name": "create_event",
"description": "Create a new calendar event.",
"parameters": {
"type": "object",
"properties": {
"calendar_name": {"type": "string"},
"event": {
"type": "object",
"properties": {
"subject": {"type": "string"},
"body": {"type": "string"},
"start": {"type": "string", "format": "date-time"},
"end": {"type": "string", "format": "date-time"},
"location": {"type": "string"},
"attendees": {
"type": "array",
"items": {"type": "string", "format": "email"}
},
"recurrence": {"type": "string"},
"categories": {
"type": "array",
"items": {"type": "string"}
},
"reminderMinutesBeforeStart": {"type": "integer"},
"isReminderOn": {"type": "boolean"},
"isAllDay": {"type": "boolean"}
},
"required": ["subject", "start", "end"]
}
},
"required": ["calendar_name", "event"]
}
},
{
"name": "create_events",
"description": "Create multiple calendar events at once.",
"parameters": {
"type": "object",
"properties": {
"calendar_name": {"type": "string"},
"events": {
"type": "array",
"items": {
"type": "object",
"properties": {
"subject": {"type": "string"},
"body": {"type": "string"},
"start": {"type": "string", "format": "date-time"},
"end": {"type": "string", "format": "date-time"},
"location": {"type": "string"},
"attendees": {
"type": "array",
"items": {"type": "string", "format": "email"}
},
"recurrence": {"type": "string"},
"categories": {
"type": "array",
"items": {"type": "string"}
},
"reminderMinutesBeforeStart": {"type": "integer"},
"isReminderOn": {"type": "boolean"}
},
"required": ["subject", "start", "end"]
}
}
},
"required": ["calendar_name", "events"]