gws-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1377 @@
1
+ """Google Calendar service operations."""
2
+
3
+ from datetime import datetime, timezone
4
+ from typing import Any
5
+
6
+ from googleapiclient.errors import HttpError
7
+
8
+ from gws.services.base import BaseService
9
+ from gws.output import output_success, output_error
10
+ from gws.exceptions import ExitCode
11
+
12
+
13
+ class CalendarService(BaseService):
14
+ """Google Calendar operations."""
15
+
16
+ SERVICE_NAME = "calendar"
17
+ VERSION = "v3"
18
+
19
+ def list_calendars(self) -> dict[str, Any]:
20
+ """List all accessible calendars."""
21
+ try:
22
+ result = self.execute(
23
+ self.service.calendarList().list(
24
+ fields="items(id,summary,primary,accessRole,backgroundColor),nextPageToken"
25
+ )
26
+ )
27
+
28
+ calendars = [
29
+ {
30
+ "id": cal["id"],
31
+ "summary": cal.get("summary", ""),
32
+ "primary": cal.get("primary", False),
33
+ "access_role": cal.get("accessRole", ""),
34
+ "background_color": cal.get("backgroundColor", ""),
35
+ }
36
+ for cal in result.get("items", [])
37
+ ]
38
+
39
+ output_success(
40
+ operation="calendar.list_calendars",
41
+ calendar_count=len(calendars),
42
+ calendars=calendars,
43
+ )
44
+ return result
45
+ except HttpError as e:
46
+ output_error(
47
+ error_code="API_ERROR",
48
+ operation="calendar.list_calendars",
49
+ message=f"Calendar API error: {e.reason}",
50
+ )
51
+ raise SystemExit(ExitCode.API_ERROR)
52
+
53
+ def list_events(
54
+ self,
55
+ calendar_id: str = "primary",
56
+ time_min: str | None = None,
57
+ time_max: str | None = None,
58
+ max_results: int = 10,
59
+ query: str | None = None,
60
+ ) -> dict[str, Any]:
61
+ """List events from a calendar."""
62
+ try:
63
+ params: dict[str, Any] = {
64
+ "calendarId": calendar_id,
65
+ "maxResults": max_results,
66
+ "singleEvents": True,
67
+ "orderBy": "startTime",
68
+ }
69
+
70
+ if time_min:
71
+ params["timeMin"] = time_min
72
+ else:
73
+ # Default to now
74
+ params["timeMin"] = datetime.now(timezone.utc).isoformat()
75
+
76
+ if time_max:
77
+ params["timeMax"] = time_max
78
+
79
+ if query:
80
+ params["q"] = query
81
+
82
+ result = self.execute(self.service.events().list(**params))
83
+
84
+ events = []
85
+ for event in result.get("items", []):
86
+ start = event.get("start", {})
87
+ end = event.get("end", {})
88
+
89
+ event_data: dict[str, Any] = {
90
+ "id": event["id"],
91
+ "summary": event.get("summary", "(no title)"),
92
+ "start": start.get("dateTime", start.get("date", "")),
93
+ "end": end.get("dateTime", end.get("date", "")),
94
+ "location": event.get("location", ""),
95
+ "description": event.get("description", "")[:200] if event.get("description") else "",
96
+ "status": event.get("status", ""),
97
+ "html_link": event.get("htmlLink", ""),
98
+ }
99
+ # Include colorId if event has a custom color
100
+ if "colorId" in event:
101
+ event_data["color_id"] = event["colorId"]
102
+ events.append(event_data)
103
+
104
+ output_success(
105
+ operation="calendar.list",
106
+ calendar_id=calendar_id,
107
+ event_count=len(events),
108
+ events=events,
109
+ )
110
+ return result
111
+ except HttpError as e:
112
+ output_error(
113
+ error_code="API_ERROR",
114
+ operation="calendar.list",
115
+ message=f"Calendar API error: {e.reason}",
116
+ )
117
+ raise SystemExit(ExitCode.API_ERROR)
118
+
119
+ def get_event(
120
+ self,
121
+ event_id: str,
122
+ calendar_id: str = "primary",
123
+ ) -> dict[str, Any]:
124
+ """Get a specific event by ID."""
125
+ try:
126
+ event = self.execute(
127
+ self.service.events()
128
+ .get(calendarId=calendar_id, eventId=event_id)
129
+ )
130
+
131
+ start = event.get("start", {})
132
+ end = event.get("end", {})
133
+
134
+ output_success(
135
+ operation="calendar.get",
136
+ event_id=event["id"],
137
+ summary=event.get("summary", "(no title)"),
138
+ start=start.get("dateTime", start.get("date", "")),
139
+ end=end.get("dateTime", end.get("date", "")),
140
+ location=event.get("location", ""),
141
+ description=event.get("description", ""),
142
+ status=event.get("status", ""),
143
+ attendees=[
144
+ {"email": a["email"], "response": a.get("responseStatus", "")}
145
+ for a in event.get("attendees", [])
146
+ ],
147
+ html_link=event.get("htmlLink", ""),
148
+ )
149
+ return event
150
+ except HttpError as e:
151
+ output_error(
152
+ error_code="API_ERROR",
153
+ operation="calendar.get",
154
+ message=f"Calendar API error: {e.reason}",
155
+ )
156
+ raise SystemExit(ExitCode.API_ERROR)
157
+
158
+ def create_event(
159
+ self,
160
+ summary: str,
161
+ start: str,
162
+ end: str,
163
+ calendar_id: str = "primary",
164
+ description: str | None = None,
165
+ location: str | None = None,
166
+ attendees: list[str] | None = None,
167
+ all_day: bool = False,
168
+ ) -> dict[str, Any]:
169
+ """Create a new event."""
170
+ try:
171
+ event_body: dict[str, Any] = {
172
+ "summary": summary,
173
+ }
174
+
175
+ if all_day:
176
+ # All-day events use date format (YYYY-MM-DD)
177
+ event_body["start"] = {"date": start}
178
+ event_body["end"] = {"date": end}
179
+ else:
180
+ # Timed events use dateTime format
181
+ event_body["start"] = {"dateTime": start}
182
+ event_body["end"] = {"dateTime": end}
183
+
184
+ if description:
185
+ event_body["description"] = description
186
+ if location:
187
+ event_body["location"] = location
188
+ if attendees:
189
+ event_body["attendees"] = [{"email": email} for email in attendees]
190
+
191
+ event = self.execute(
192
+ self.service.events()
193
+ .insert(calendarId=calendar_id, body=event_body)
194
+ )
195
+
196
+ output_success(
197
+ operation="calendar.create",
198
+ event_id=event["id"],
199
+ summary=summary,
200
+ start=start,
201
+ end=end,
202
+ html_link=event.get("htmlLink", ""),
203
+ )
204
+ return event
205
+ except HttpError as e:
206
+ output_error(
207
+ error_code="API_ERROR",
208
+ operation="calendar.create",
209
+ message=f"Calendar API error: {e.reason}",
210
+ )
211
+ raise SystemExit(ExitCode.API_ERROR)
212
+
213
+ def update_event(
214
+ self,
215
+ event_id: str,
216
+ calendar_id: str = "primary",
217
+ summary: str | None = None,
218
+ start: str | None = None,
219
+ end: str | None = None,
220
+ description: str | None = None,
221
+ location: str | None = None,
222
+ ) -> dict[str, Any]:
223
+ """Update an existing event."""
224
+ try:
225
+ # Get existing event
226
+ event = self.execute(
227
+ self.service.events()
228
+ .get(calendarId=calendar_id, eventId=event_id)
229
+ )
230
+
231
+ # Update fields if provided
232
+ if summary is not None:
233
+ event["summary"] = summary
234
+ if description is not None:
235
+ event["description"] = description
236
+ if location is not None:
237
+ event["location"] = location
238
+ if start is not None:
239
+ if "date" in event.get("start", {}):
240
+ event["start"] = {"date": start}
241
+ else:
242
+ event["start"] = {"dateTime": start}
243
+ if end is not None:
244
+ if "date" in event.get("end", {}):
245
+ event["end"] = {"date": end}
246
+ else:
247
+ event["end"] = {"dateTime": end}
248
+
249
+ updated_event = self.execute(
250
+ self.service.events()
251
+ .update(calendarId=calendar_id, eventId=event_id, body=event)
252
+ )
253
+
254
+ output_success(
255
+ operation="calendar.update",
256
+ event_id=updated_event["id"],
257
+ summary=updated_event.get("summary", ""),
258
+ html_link=updated_event.get("htmlLink", ""),
259
+ )
260
+ return updated_event
261
+ except HttpError as e:
262
+ output_error(
263
+ error_code="API_ERROR",
264
+ operation="calendar.update",
265
+ message=f"Calendar API error: {e.reason}",
266
+ )
267
+ raise SystemExit(ExitCode.API_ERROR)
268
+
269
+ def delete_event(
270
+ self,
271
+ event_id: str,
272
+ calendar_id: str = "primary",
273
+ ) -> dict[str, Any]:
274
+ """Delete an event."""
275
+ try:
276
+ self.execute(self.service.events().delete(
277
+ calendarId=calendar_id, eventId=event_id
278
+ ))
279
+
280
+ output_success(
281
+ operation="calendar.delete",
282
+ event_id=event_id,
283
+ calendar_id=calendar_id,
284
+ )
285
+ return {"id": event_id, "deleted": True}
286
+ except HttpError as e:
287
+ output_error(
288
+ error_code="API_ERROR",
289
+ operation="calendar.delete",
290
+ message=f"Calendar API error: {e.reason}",
291
+ )
292
+ raise SystemExit(ExitCode.API_ERROR)
293
+
294
+ # ===== Recurring Events =====
295
+
296
+ def create_recurring_event(
297
+ self,
298
+ summary: str,
299
+ start: str,
300
+ end: str,
301
+ rrule: str,
302
+ calendar_id: str = "primary",
303
+ timezone_str: str = "UTC",
304
+ description: str | None = None,
305
+ location: str | None = None,
306
+ attendees: list[str] | None = None,
307
+ ) -> dict[str, Any]:
308
+ """Create a recurring event.
309
+
310
+ Args:
311
+ summary: Event title.
312
+ start: Start time (ISO format or HH:MM for time only).
313
+ end: End time (ISO format or HH:MM for time only).
314
+ rrule: RRULE recurrence rule (e.g., "FREQ=WEEKLY;BYDAY=MO,WE,FR").
315
+ calendar_id: Calendar ID.
316
+ timezone_str: Timezone for the event.
317
+ description: Event description.
318
+ location: Event location.
319
+ attendees: List of attendee email addresses.
320
+ """
321
+ try:
322
+ event_body: dict[str, Any] = {
323
+ "summary": summary,
324
+ "start": {"dateTime": start, "timeZone": timezone_str},
325
+ "end": {"dateTime": end, "timeZone": timezone_str},
326
+ "recurrence": [f"RRULE:{rrule}"],
327
+ }
328
+
329
+ if description:
330
+ event_body["description"] = description
331
+ if location:
332
+ event_body["location"] = location
333
+ if attendees:
334
+ event_body["attendees"] = [{"email": email} for email in attendees]
335
+
336
+ event = self.execute(
337
+ self.service.events()
338
+ .insert(calendarId=calendar_id, body=event_body)
339
+ )
340
+
341
+ output_success(
342
+ operation="calendar.create_recurring",
343
+ event_id=event["id"],
344
+ summary=summary,
345
+ start=start,
346
+ end=end,
347
+ rrule=rrule,
348
+ html_link=event.get("htmlLink", ""),
349
+ )
350
+ return event
351
+ except HttpError as e:
352
+ output_error(
353
+ error_code="API_ERROR",
354
+ operation="calendar.create_recurring",
355
+ message=f"Calendar API error: {e.reason}",
356
+ )
357
+ raise SystemExit(ExitCode.API_ERROR)
358
+
359
+ def get_instances(
360
+ self,
361
+ event_id: str,
362
+ calendar_id: str = "primary",
363
+ time_min: str | None = None,
364
+ time_max: str | None = None,
365
+ max_results: int = 25,
366
+ ) -> dict[str, Any]:
367
+ """Get instances of a recurring event.
368
+
369
+ Args:
370
+ event_id: The recurring event ID.
371
+ calendar_id: Calendar ID.
372
+ time_min: Lower bound for instances (ISO format).
373
+ time_max: Upper bound for instances (ISO format).
374
+ max_results: Maximum number of instances to return.
375
+ """
376
+ try:
377
+ params: dict[str, Any] = {
378
+ "calendarId": calendar_id,
379
+ "eventId": event_id,
380
+ "maxResults": max_results,
381
+ }
382
+
383
+ if time_min:
384
+ params["timeMin"] = time_min
385
+ else:
386
+ params["timeMin"] = datetime.now(timezone.utc).isoformat()
387
+
388
+ if time_max:
389
+ params["timeMax"] = time_max
390
+
391
+ result = self.execute(self.service.events().instances(**params))
392
+
393
+ instances = []
394
+ for event in result.get("items", []):
395
+ start = event.get("start", {})
396
+ end = event.get("end", {})
397
+
398
+ instances.append({
399
+ "id": event["id"],
400
+ "summary": event.get("summary", "(no title)"),
401
+ "start": start.get("dateTime", start.get("date", "")),
402
+ "end": end.get("dateTime", end.get("date", "")),
403
+ "status": event.get("status", ""),
404
+ })
405
+
406
+ output_success(
407
+ operation="calendar.get_instances",
408
+ event_id=event_id,
409
+ instance_count=len(instances),
410
+ instances=instances,
411
+ )
412
+ return result
413
+ except HttpError as e:
414
+ output_error(
415
+ error_code="API_ERROR",
416
+ operation="calendar.get_instances",
417
+ message=f"Calendar API error: {e.reason}",
418
+ )
419
+ raise SystemExit(ExitCode.API_ERROR)
420
+
421
+ # ===== Attendee Management =====
422
+
423
+ def add_attendees(
424
+ self,
425
+ event_id: str,
426
+ emails: list[str],
427
+ calendar_id: str = "primary",
428
+ send_notifications: bool = True,
429
+ ) -> dict[str, Any]:
430
+ """Add attendees to an event.
431
+
432
+ Args:
433
+ event_id: The event ID.
434
+ emails: List of email addresses to add.
435
+ calendar_id: Calendar ID.
436
+ send_notifications: Whether to send email notifications.
437
+ """
438
+ try:
439
+ # Get existing event
440
+ event = self.execute(
441
+ self.service.events()
442
+ .get(calendarId=calendar_id, eventId=event_id)
443
+ )
444
+
445
+ # Add new attendees
446
+ existing_attendees = event.get("attendees", [])
447
+ existing_emails = {a["email"] for a in existing_attendees}
448
+
449
+ for email in emails:
450
+ if email not in existing_emails:
451
+ existing_attendees.append({"email": email})
452
+
453
+ event["attendees"] = existing_attendees
454
+
455
+ # Update event
456
+ send_updates = "all" if send_notifications else "none"
457
+ updated_event = self.execute(
458
+ self.service.events()
459
+ .update(
460
+ calendarId=calendar_id,
461
+ eventId=event_id,
462
+ body=event,
463
+ sendUpdates=send_updates,
464
+ )
465
+ )
466
+
467
+ output_success(
468
+ operation="calendar.add_attendees",
469
+ event_id=event_id,
470
+ added_emails=emails,
471
+ attendee_count=len(updated_event.get("attendees", [])),
472
+ )
473
+ return updated_event
474
+ except HttpError as e:
475
+ output_error(
476
+ error_code="API_ERROR",
477
+ operation="calendar.add_attendees",
478
+ message=f"Calendar API error: {e.reason}",
479
+ )
480
+ raise SystemExit(ExitCode.API_ERROR)
481
+
482
+ def remove_attendees(
483
+ self,
484
+ event_id: str,
485
+ emails: list[str],
486
+ calendar_id: str = "primary",
487
+ send_notifications: bool = True,
488
+ ) -> dict[str, Any]:
489
+ """Remove attendees from an event.
490
+
491
+ Args:
492
+ event_id: The event ID.
493
+ emails: List of email addresses to remove.
494
+ calendar_id: Calendar ID.
495
+ send_notifications: Whether to send email notifications.
496
+ """
497
+ try:
498
+ # Get existing event
499
+ event = self.execute(
500
+ self.service.events()
501
+ .get(calendarId=calendar_id, eventId=event_id)
502
+ )
503
+
504
+ # Filter out specified attendees
505
+ emails_to_remove = set(emails)
506
+ event["attendees"] = [
507
+ a for a in event.get("attendees", [])
508
+ if a["email"] not in emails_to_remove
509
+ ]
510
+
511
+ # Update event
512
+ send_updates = "all" if send_notifications else "none"
513
+ updated_event = self.execute(
514
+ self.service.events()
515
+ .update(
516
+ calendarId=calendar_id,
517
+ eventId=event_id,
518
+ body=event,
519
+ sendUpdates=send_updates,
520
+ )
521
+ )
522
+
523
+ output_success(
524
+ operation="calendar.remove_attendees",
525
+ event_id=event_id,
526
+ removed_emails=emails,
527
+ attendee_count=len(updated_event.get("attendees", [])),
528
+ )
529
+ return updated_event
530
+ except HttpError as e:
531
+ output_error(
532
+ error_code="API_ERROR",
533
+ operation="calendar.remove_attendees",
534
+ message=f"Calendar API error: {e.reason}",
535
+ )
536
+ raise SystemExit(ExitCode.API_ERROR)
537
+
538
+ def get_attendees(
539
+ self,
540
+ event_id: str,
541
+ calendar_id: str = "primary",
542
+ ) -> dict[str, Any]:
543
+ """Get attendees and their RSVP status for an event.
544
+
545
+ Args:
546
+ event_id: The event ID.
547
+ calendar_id: Calendar ID.
548
+ """
549
+ try:
550
+ event = self.execute(
551
+ self.service.events()
552
+ .get(calendarId=calendar_id, eventId=event_id)
553
+ )
554
+
555
+ attendees = [
556
+ {
557
+ "email": a["email"],
558
+ "display_name": a.get("displayName", ""),
559
+ "response_status": a.get("responseStatus", "needsAction"),
560
+ "organizer": a.get("organizer", False),
561
+ "optional": a.get("optional", False),
562
+ }
563
+ for a in event.get("attendees", [])
564
+ ]
565
+
566
+ output_success(
567
+ operation="calendar.get_attendees",
568
+ event_id=event_id,
569
+ summary=event.get("summary", ""),
570
+ attendee_count=len(attendees),
571
+ attendees=attendees,
572
+ )
573
+ return {"event_id": event_id, "attendees": attendees}
574
+ except HttpError as e:
575
+ output_error(
576
+ error_code="API_ERROR",
577
+ operation="calendar.get_attendees",
578
+ message=f"Calendar API error: {e.reason}",
579
+ )
580
+ raise SystemExit(ExitCode.API_ERROR)
581
+
582
+ def respond_to_event(
583
+ self,
584
+ event_id: str,
585
+ response: str,
586
+ calendar_id: str = "primary",
587
+ ) -> dict[str, Any]:
588
+ """Respond to an event invitation (RSVP).
589
+
590
+ Args:
591
+ event_id: The event ID.
592
+ response: Response status (accepted, declined, tentative).
593
+ calendar_id: Calendar ID.
594
+ """
595
+ try:
596
+ valid_responses = {"accepted", "declined", "tentative"}
597
+ if response.lower() not in valid_responses:
598
+ output_error(
599
+ error_code="INVALID_ARGS",
600
+ operation="calendar.respond",
601
+ message=f"Response must be one of: {valid_responses}",
602
+ )
603
+ raise SystemExit(ExitCode.INVALID_ARGS)
604
+
605
+ # Get event and find self in attendees
606
+ event = self.execute(
607
+ self.service.events()
608
+ .get(calendarId=calendar_id, eventId=event_id)
609
+ )
610
+
611
+ # Update self's response status
612
+ for attendee in event.get("attendees", []):
613
+ if attendee.get("self", False):
614
+ attendee["responseStatus"] = response.lower()
615
+ break
616
+
617
+ updated_event = self.execute(
618
+ self.service.events()
619
+ .update(
620
+ calendarId=calendar_id,
621
+ eventId=event_id,
622
+ body=event,
623
+ )
624
+ )
625
+
626
+ output_success(
627
+ operation="calendar.respond",
628
+ event_id=event_id,
629
+ response=response.lower(),
630
+ summary=updated_event.get("summary", ""),
631
+ )
632
+ return updated_event
633
+ except HttpError as e:
634
+ output_error(
635
+ error_code="API_ERROR",
636
+ operation="calendar.respond",
637
+ message=f"Calendar API error: {e.reason}",
638
+ )
639
+ raise SystemExit(ExitCode.API_ERROR)
640
+
641
+ def quick_add(
642
+ self,
643
+ text: str,
644
+ calendar_id: str = "primary",
645
+ ) -> dict[str, Any]:
646
+ """Create an event from natural language text.
647
+
648
+ Args:
649
+ text: Natural language description (e.g., "Meeting tomorrow at 3pm").
650
+ calendar_id: Calendar ID.
651
+ """
652
+ try:
653
+ event = self.execute(
654
+ self.service.events()
655
+ .quickAdd(calendarId=calendar_id, text=text)
656
+ )
657
+
658
+ start = event.get("start", {})
659
+ end = event.get("end", {})
660
+
661
+ output_success(
662
+ operation="calendar.quick_add",
663
+ event_id=event["id"],
664
+ summary=event.get("summary", ""),
665
+ start=start.get("dateTime", start.get("date", "")),
666
+ end=end.get("dateTime", end.get("date", "")),
667
+ html_link=event.get("htmlLink", ""),
668
+ )
669
+ return event
670
+ except HttpError as e:
671
+ output_error(
672
+ error_code="API_ERROR",
673
+ operation="calendar.quick_add",
674
+ message=f"Calendar API error: {e.reason}",
675
+ )
676
+ raise SystemExit(ExitCode.API_ERROR)
677
+
678
+ # =========================================================================
679
+ # FREE/BUSY QUERIES
680
+ # =========================================================================
681
+
682
+ def get_freebusy(
683
+ self,
684
+ time_min: str,
685
+ time_max: str,
686
+ calendar_ids: list[str] | None = None,
687
+ timezone_str: str = "UTC",
688
+ ) -> dict[str, Any]:
689
+ """Query free/busy information for calendars.
690
+
691
+ Args:
692
+ time_min: Start time (ISO 8601 format).
693
+ time_max: End time (ISO 8601 format).
694
+ calendar_ids: List of calendar IDs to query (default: primary).
695
+ timezone_str: Timezone for the query.
696
+ """
697
+ try:
698
+ if not calendar_ids:
699
+ calendar_ids = ["primary"]
700
+
701
+ items = [{"id": cal_id} for cal_id in calendar_ids]
702
+
703
+ body = {
704
+ "timeMin": time_min,
705
+ "timeMax": time_max,
706
+ "timeZone": timezone_str,
707
+ "items": items,
708
+ }
709
+
710
+ result = self.execute(self.service.freebusy().query(body=body))
711
+
712
+ calendars = {}
713
+ for cal_id, cal_data in result.get("calendars", {}).items():
714
+ busy_times = []
715
+ for busy in cal_data.get("busy", []):
716
+ busy_times.append({
717
+ "start": busy.get("start"),
718
+ "end": busy.get("end"),
719
+ })
720
+ calendars[cal_id] = {
721
+ "busy": busy_times,
722
+ "errors": cal_data.get("errors", []),
723
+ }
724
+
725
+ output_success(
726
+ operation="calendar.get_freebusy",
727
+ time_min=time_min,
728
+ time_max=time_max,
729
+ calendars=calendars,
730
+ )
731
+ return {"calendars": calendars}
732
+ except HttpError as e:
733
+ output_error(
734
+ error_code="API_ERROR",
735
+ operation="calendar.get_freebusy",
736
+ message=f"Calendar API error: {e.reason}",
737
+ )
738
+ raise SystemExit(ExitCode.API_ERROR)
739
+
740
+ # =========================================================================
741
+ # CALENDAR SHARING (ACL)
742
+ # =========================================================================
743
+
744
+ def list_acl(
745
+ self,
746
+ calendar_id: str = "primary",
747
+ ) -> dict[str, Any]:
748
+ """List access control rules for a calendar.
749
+
750
+ Args:
751
+ calendar_id: Calendar ID.
752
+ """
753
+ try:
754
+ result = self.execute(self.service.acl().list(calendarId=calendar_id))
755
+
756
+ rules = []
757
+ for rule in result.get("items", []):
758
+ rules.append({
759
+ "rule_id": rule.get("id"),
760
+ "scope_type": rule.get("scope", {}).get("type"),
761
+ "scope_value": rule.get("scope", {}).get("value"),
762
+ "role": rule.get("role"),
763
+ })
764
+
765
+ output_success(
766
+ operation="calendar.list_acl",
767
+ calendar_id=calendar_id,
768
+ rule_count=len(rules),
769
+ rules=rules,
770
+ )
771
+ return {"rules": rules}
772
+ except HttpError as e:
773
+ output_error(
774
+ error_code="API_ERROR",
775
+ operation="calendar.list_acl",
776
+ message=f"Calendar API error: {e.reason}",
777
+ )
778
+ raise SystemExit(ExitCode.API_ERROR)
779
+
780
+ def add_acl(
781
+ self,
782
+ scope_type: str,
783
+ scope_value: str,
784
+ role: str,
785
+ calendar_id: str = "primary",
786
+ ) -> dict[str, Any]:
787
+ """Add an access control rule to a calendar.
788
+
789
+ Args:
790
+ scope_type: Scope type (user, group, domain, default).
791
+ scope_value: Email address or domain.
792
+ role: Role to grant (reader, writer, owner, freeBusyReader, none).
793
+ calendar_id: Calendar ID.
794
+ """
795
+ try:
796
+ valid_scope_types = {"user", "group", "domain", "default"}
797
+ if scope_type.lower() not in valid_scope_types:
798
+ output_error(
799
+ error_code="INVALID_ARGS",
800
+ operation="calendar.add_acl",
801
+ message=f"scope_type must be one of: {valid_scope_types}",
802
+ )
803
+ raise SystemExit(ExitCode.INVALID_ARGS)
804
+
805
+ valid_roles = {"reader", "writer", "owner", "freeBusyReader", "none"}
806
+ if role.lower() not in {r.lower() for r in valid_roles}:
807
+ output_error(
808
+ error_code="INVALID_ARGS",
809
+ operation="calendar.add_acl",
810
+ message=f"role must be one of: {valid_roles}",
811
+ )
812
+ raise SystemExit(ExitCode.INVALID_ARGS)
813
+
814
+ body = {
815
+ "scope": {
816
+ "type": scope_type.lower(),
817
+ "value": scope_value,
818
+ },
819
+ "role": role,
820
+ }
821
+
822
+ result = self.execute(self.service.acl().insert(calendarId=calendar_id, body=body))
823
+
824
+ output_success(
825
+ operation="calendar.add_acl",
826
+ calendar_id=calendar_id,
827
+ rule_id=result.get("id"),
828
+ scope_type=scope_type,
829
+ scope_value=scope_value,
830
+ role=role,
831
+ )
832
+ return result
833
+ except HttpError as e:
834
+ output_error(
835
+ error_code="API_ERROR",
836
+ operation="calendar.add_acl",
837
+ message=f"Calendar API error: {e.reason}",
838
+ )
839
+ raise SystemExit(ExitCode.API_ERROR)
840
+
841
+ def remove_acl(
842
+ self,
843
+ rule_id: str,
844
+ calendar_id: str = "primary",
845
+ ) -> dict[str, Any]:
846
+ """Remove an access control rule from a calendar.
847
+
848
+ Args:
849
+ rule_id: The ACL rule ID to remove.
850
+ calendar_id: Calendar ID.
851
+ """
852
+ try:
853
+ self.execute(self.service.acl().delete(calendarId=calendar_id, ruleId=rule_id))
854
+
855
+ output_success(
856
+ operation="calendar.remove_acl",
857
+ calendar_id=calendar_id,
858
+ rule_id=rule_id,
859
+ )
860
+ return {"rule_id": rule_id, "status": "removed"}
861
+ except HttpError as e:
862
+ output_error(
863
+ error_code="API_ERROR",
864
+ operation="calendar.remove_acl",
865
+ message=f"Calendar API error: {e.reason}",
866
+ )
867
+ raise SystemExit(ExitCode.API_ERROR)
868
+
869
+ def update_acl(
870
+ self,
871
+ rule_id: str,
872
+ role: str,
873
+ calendar_id: str = "primary",
874
+ ) -> dict[str, Any]:
875
+ """Update an access control rule.
876
+
877
+ Args:
878
+ rule_id: The ACL rule ID to update.
879
+ role: New role (reader, writer, owner, freeBusyReader, none).
880
+ calendar_id: Calendar ID.
881
+ """
882
+ try:
883
+ valid_roles = {"reader", "writer", "owner", "freeBusyReader", "none"}
884
+ if role.lower() not in {r.lower() for r in valid_roles}:
885
+ output_error(
886
+ error_code="INVALID_ARGS",
887
+ operation="calendar.update_acl",
888
+ message=f"role must be one of: {valid_roles}",
889
+ )
890
+ raise SystemExit(ExitCode.INVALID_ARGS)
891
+
892
+ # First get the existing rule to preserve scope
893
+ existing = self.execute(self.service.acl().get(calendarId=calendar_id, ruleId=rule_id))
894
+
895
+ body = {
896
+ "scope": existing.get("scope"),
897
+ "role": role,
898
+ }
899
+
900
+ result = self.execute(self.service.acl().update(
901
+ calendarId=calendar_id, ruleId=rule_id, body=body
902
+ ))
903
+
904
+ output_success(
905
+ operation="calendar.update_acl",
906
+ calendar_id=calendar_id,
907
+ rule_id=rule_id,
908
+ role=role,
909
+ )
910
+ return result
911
+ except HttpError as e:
912
+ output_error(
913
+ error_code="API_ERROR",
914
+ operation="calendar.update_acl",
915
+ message=f"Calendar API error: {e.reason}",
916
+ )
917
+ raise SystemExit(ExitCode.API_ERROR)
918
+
919
+ # =========================================================================
920
+ # REMINDERS
921
+ # =========================================================================
922
+
923
+ def get_event_reminders(
924
+ self,
925
+ event_id: str,
926
+ calendar_id: str = "primary",
927
+ ) -> dict[str, Any]:
928
+ """Get reminders for an event.
929
+
930
+ Args:
931
+ event_id: The event ID.
932
+ calendar_id: Calendar ID.
933
+ """
934
+ try:
935
+ event = self.execute(self.service.events().get(
936
+ calendarId=calendar_id, eventId=event_id
937
+ ))
938
+
939
+ reminders = event.get("reminders", {})
940
+
941
+ output_success(
942
+ operation="calendar.get_event_reminders",
943
+ calendar_id=calendar_id,
944
+ event_id=event_id,
945
+ event_title=event.get("summary", ""),
946
+ use_default=reminders.get("useDefault", True),
947
+ overrides=reminders.get("overrides", []),
948
+ )
949
+ return reminders
950
+ except HttpError as e:
951
+ if e.resp.status == 404:
952
+ output_error(
953
+ error_code="NOT_FOUND",
954
+ operation="calendar.get_event_reminders",
955
+ message=f"Event not found: {event_id}",
956
+ )
957
+ raise SystemExit(ExitCode.NOT_FOUND)
958
+ output_error(
959
+ error_code="API_ERROR",
960
+ operation="calendar.get_event_reminders",
961
+ message=f"Calendar API error: {e.reason}",
962
+ )
963
+ raise SystemExit(ExitCode.API_ERROR)
964
+
965
+ def set_event_reminders(
966
+ self,
967
+ event_id: str,
968
+ reminders: list[dict[str, Any]] | None = None,
969
+ use_default: bool = False,
970
+ calendar_id: str = "primary",
971
+ ) -> dict[str, Any]:
972
+ """Set reminders for an event.
973
+
974
+ Args:
975
+ event_id: The event ID.
976
+ reminders: List of reminders [{method: "email"|"popup", minutes: int}].
977
+ use_default: Use calendar's default reminders.
978
+ calendar_id: Calendar ID.
979
+ """
980
+ try:
981
+ body: dict[str, Any] = {
982
+ "reminders": {
983
+ "useDefault": use_default,
984
+ }
985
+ }
986
+
987
+ if not use_default and reminders:
988
+ body["reminders"]["overrides"] = reminders
989
+
990
+ result = self.execute(self.service.events().patch(
991
+ calendarId=calendar_id,
992
+ eventId=event_id,
993
+ body=body,
994
+ ))
995
+
996
+ output_success(
997
+ operation="calendar.set_event_reminders",
998
+ calendar_id=calendar_id,
999
+ event_id=event_id,
1000
+ use_default=use_default,
1001
+ reminders=reminders if not use_default else "using defaults",
1002
+ )
1003
+ return result
1004
+ except HttpError as e:
1005
+ if e.resp.status == 404:
1006
+ output_error(
1007
+ error_code="NOT_FOUND",
1008
+ operation="calendar.set_event_reminders",
1009
+ message=f"Event not found: {event_id}",
1010
+ )
1011
+ raise SystemExit(ExitCode.NOT_FOUND)
1012
+ output_error(
1013
+ error_code="API_ERROR",
1014
+ operation="calendar.set_event_reminders",
1015
+ message=f"Calendar API error: {e.reason}",
1016
+ )
1017
+ raise SystemExit(ExitCode.API_ERROR)
1018
+
1019
+ def get_default_reminders(
1020
+ self,
1021
+ calendar_id: str = "primary",
1022
+ ) -> dict[str, Any]:
1023
+ """Get default reminders for a calendar.
1024
+
1025
+ Args:
1026
+ calendar_id: Calendar ID.
1027
+ """
1028
+ try:
1029
+ calendar = self.execute(self.service.calendarList().get(
1030
+ calendarId=calendar_id
1031
+ ))
1032
+
1033
+ reminders = calendar.get("defaultReminders", [])
1034
+
1035
+ output_success(
1036
+ operation="calendar.get_default_reminders",
1037
+ calendar_id=calendar_id,
1038
+ calendar_summary=calendar.get("summary", ""),
1039
+ default_reminders=reminders,
1040
+ )
1041
+ return {"default_reminders": reminders}
1042
+ except HttpError as e:
1043
+ if e.resp.status == 404:
1044
+ output_error(
1045
+ error_code="NOT_FOUND",
1046
+ operation="calendar.get_default_reminders",
1047
+ message=f"Calendar not found: {calendar_id}",
1048
+ )
1049
+ raise SystemExit(ExitCode.NOT_FOUND)
1050
+ output_error(
1051
+ error_code="API_ERROR",
1052
+ operation="calendar.get_default_reminders",
1053
+ message=f"Calendar API error: {e.reason}",
1054
+ )
1055
+ raise SystemExit(ExitCode.API_ERROR)
1056
+
1057
+ def set_default_reminders(
1058
+ self,
1059
+ reminders: list[dict[str, Any]],
1060
+ calendar_id: str = "primary",
1061
+ ) -> dict[str, Any]:
1062
+ """Set default reminders for a calendar.
1063
+
1064
+ Args:
1065
+ reminders: List of reminders [{method: "email"|"popup", minutes: int}].
1066
+ calendar_id: Calendar ID.
1067
+ """
1068
+ try:
1069
+ result = self.execute(self.service.calendarList().patch(
1070
+ calendarId=calendar_id,
1071
+ body={"defaultReminders": reminders},
1072
+ ))
1073
+
1074
+ output_success(
1075
+ operation="calendar.set_default_reminders",
1076
+ calendar_id=calendar_id,
1077
+ default_reminders=reminders,
1078
+ )
1079
+ return result
1080
+ except HttpError as e:
1081
+ if e.resp.status == 404:
1082
+ output_error(
1083
+ error_code="NOT_FOUND",
1084
+ operation="calendar.set_default_reminders",
1085
+ message=f"Calendar not found: {calendar_id}",
1086
+ )
1087
+ raise SystemExit(ExitCode.NOT_FOUND)
1088
+ output_error(
1089
+ error_code="API_ERROR",
1090
+ operation="calendar.set_default_reminders",
1091
+ message=f"Calendar API error: {e.reason}",
1092
+ )
1093
+ raise SystemExit(ExitCode.API_ERROR)
1094
+
1095
+ def clear_event_reminders(
1096
+ self,
1097
+ event_id: str,
1098
+ calendar_id: str = "primary",
1099
+ ) -> dict[str, Any]:
1100
+ """Remove all reminders from an event.
1101
+
1102
+ Args:
1103
+ event_id: The event ID.
1104
+ calendar_id: Calendar ID.
1105
+ """
1106
+ try:
1107
+ body = {
1108
+ "reminders": {
1109
+ "useDefault": False,
1110
+ "overrides": [],
1111
+ }
1112
+ }
1113
+
1114
+ result = self.execute(self.service.events().patch(
1115
+ calendarId=calendar_id,
1116
+ eventId=event_id,
1117
+ body=body,
1118
+ ))
1119
+
1120
+ output_success(
1121
+ operation="calendar.clear_event_reminders",
1122
+ calendar_id=calendar_id,
1123
+ event_id=event_id,
1124
+ cleared=True,
1125
+ )
1126
+ return result
1127
+ except HttpError as e:
1128
+ if e.resp.status == 404:
1129
+ output_error(
1130
+ error_code="NOT_FOUND",
1131
+ operation="calendar.clear_event_reminders",
1132
+ message=f"Event not found: {event_id}",
1133
+ )
1134
+ raise SystemExit(ExitCode.NOT_FOUND)
1135
+ output_error(
1136
+ error_code="API_ERROR",
1137
+ operation="calendar.clear_event_reminders",
1138
+ message=f"Calendar API error: {e.reason}",
1139
+ )
1140
+ raise SystemExit(ExitCode.API_ERROR)
1141
+
1142
+ # =========================================================================
1143
+ # CALENDAR MANAGEMENT
1144
+ # =========================================================================
1145
+
1146
+ def create_calendar(
1147
+ self,
1148
+ summary: str,
1149
+ description: str | None = None,
1150
+ timezone: str | None = None,
1151
+ ) -> dict[str, Any]:
1152
+ """Create a new calendar.
1153
+
1154
+ Args:
1155
+ summary: Calendar name/title.
1156
+ description: Calendar description.
1157
+ timezone: Timezone (e.g., 'America/New_York'). Uses user default if not specified.
1158
+ """
1159
+ try:
1160
+ body: dict[str, Any] = {"summary": summary}
1161
+ if description:
1162
+ body["description"] = description
1163
+ if timezone:
1164
+ body["timeZone"] = timezone
1165
+
1166
+ result = self.execute(
1167
+ self.service.calendars().insert(body=body)
1168
+ )
1169
+
1170
+ output_success(
1171
+ operation="calendar.create_calendar",
1172
+ calendar_id=result.get("id"),
1173
+ summary=result.get("summary"),
1174
+ timezone=result.get("timeZone"),
1175
+ )
1176
+ return result
1177
+ except HttpError as e:
1178
+ output_error(
1179
+ error_code="API_ERROR",
1180
+ operation="calendar.create_calendar",
1181
+ message=f"Calendar API error: {e.reason}",
1182
+ )
1183
+ raise SystemExit(ExitCode.API_ERROR)
1184
+
1185
+ def delete_calendar(self, calendar_id: str) -> dict[str, Any]:
1186
+ """Delete a secondary calendar.
1187
+
1188
+ Args:
1189
+ calendar_id: The calendar ID to delete. Cannot delete primary calendar.
1190
+ """
1191
+ try:
1192
+ self.execute(self.service.calendars().delete(calendarId=calendar_id))
1193
+
1194
+ output_success(
1195
+ operation="calendar.delete_calendar",
1196
+ calendar_id=calendar_id,
1197
+ deleted=True,
1198
+ )
1199
+ return {"deleted": True, "calendar_id": calendar_id}
1200
+ except HttpError as e:
1201
+ if e.resp.status == 404:
1202
+ output_error(
1203
+ error_code="NOT_FOUND",
1204
+ operation="calendar.delete_calendar",
1205
+ message=f"Calendar not found: {calendar_id}",
1206
+ )
1207
+ raise SystemExit(ExitCode.NOT_FOUND)
1208
+ output_error(
1209
+ error_code="API_ERROR",
1210
+ operation="calendar.delete_calendar",
1211
+ message=f"Calendar API error: {e.reason}",
1212
+ )
1213
+ raise SystemExit(ExitCode.API_ERROR)
1214
+
1215
+ def clear_calendar(self, calendar_id: str) -> dict[str, Any]:
1216
+ """Clear all events from a calendar.
1217
+
1218
+ Args:
1219
+ calendar_id: The calendar ID to clear. Only works on primary calendar.
1220
+ """
1221
+ try:
1222
+ self.execute(self.service.calendars().clear(calendarId=calendar_id))
1223
+
1224
+ output_success(
1225
+ operation="calendar.clear_calendar",
1226
+ calendar_id=calendar_id,
1227
+ cleared=True,
1228
+ )
1229
+ return {"cleared": True, "calendar_id": calendar_id}
1230
+ except HttpError as e:
1231
+ output_error(
1232
+ error_code="API_ERROR",
1233
+ operation="calendar.clear_calendar",
1234
+ message=f"Calendar API error: {e.reason}",
1235
+ )
1236
+ raise SystemExit(ExitCode.API_ERROR)
1237
+
1238
+ # =========================================================================
1239
+ # EVENT OPERATIONS (extended)
1240
+ # =========================================================================
1241
+
1242
+ def move_event(
1243
+ self,
1244
+ event_id: str,
1245
+ source_calendar_id: str,
1246
+ destination_calendar_id: str,
1247
+ ) -> dict[str, Any]:
1248
+ """Move an event to a different calendar.
1249
+
1250
+ Args:
1251
+ event_id: The event ID to move.
1252
+ source_calendar_id: The source calendar ID.
1253
+ destination_calendar_id: The destination calendar ID.
1254
+ """
1255
+ try:
1256
+ result = self.execute(
1257
+ self.service.events().move(
1258
+ calendarId=source_calendar_id,
1259
+ eventId=event_id,
1260
+ destination=destination_calendar_id,
1261
+ )
1262
+ )
1263
+
1264
+ output_success(
1265
+ operation="calendar.move_event",
1266
+ event_id=event_id,
1267
+ source_calendar_id=source_calendar_id,
1268
+ destination_calendar_id=destination_calendar_id,
1269
+ )
1270
+ return result
1271
+ except HttpError as e:
1272
+ if e.resp.status == 404:
1273
+ output_error(
1274
+ error_code="NOT_FOUND",
1275
+ operation="calendar.move_event",
1276
+ message=f"Event not found: {event_id}",
1277
+ )
1278
+ raise SystemExit(ExitCode.NOT_FOUND)
1279
+ output_error(
1280
+ error_code="API_ERROR",
1281
+ operation="calendar.move_event",
1282
+ message=f"Calendar API error: {e.reason}",
1283
+ )
1284
+ raise SystemExit(ExitCode.API_ERROR)
1285
+
1286
+ # =========================================================================
1287
+ # COLORS
1288
+ # =========================================================================
1289
+
1290
+ def get_colors(self) -> dict[str, Any]:
1291
+ """Get the color definitions for calendars and events."""
1292
+ try:
1293
+ result = self.execute(self.service.colors().get())
1294
+
1295
+ output_success(
1296
+ operation="calendar.get_colors",
1297
+ calendar_color_count=len(result.get("calendar", {})),
1298
+ event_color_count=len(result.get("event", {})),
1299
+ calendar_colors=result.get("calendar"),
1300
+ event_colors=result.get("event"),
1301
+ )
1302
+ return result
1303
+ except HttpError as e:
1304
+ output_error(
1305
+ error_code="API_ERROR",
1306
+ operation="calendar.get_colors",
1307
+ message=f"Calendar API error: {e.reason}",
1308
+ )
1309
+ raise SystemExit(ExitCode.API_ERROR)
1310
+
1311
+ # =========================================================================
1312
+ # CALENDAR LIST (subscriptions)
1313
+ # =========================================================================
1314
+
1315
+ def subscribe_calendar(self, calendar_id: str) -> dict[str, Any]:
1316
+ """Subscribe to (add) a public calendar to the user's calendar list.
1317
+
1318
+ Args:
1319
+ calendar_id: The calendar ID to subscribe to.
1320
+ """
1321
+ try:
1322
+ result = self.execute(
1323
+ self.service.calendarList().insert(body={"id": calendar_id})
1324
+ )
1325
+
1326
+ output_success(
1327
+ operation="calendar.subscribe",
1328
+ calendar_id=calendar_id,
1329
+ summary=result.get("summary"),
1330
+ )
1331
+ return result
1332
+ except HttpError as e:
1333
+ if e.resp.status == 404:
1334
+ output_error(
1335
+ error_code="NOT_FOUND",
1336
+ operation="calendar.subscribe",
1337
+ message=f"Calendar not found: {calendar_id}",
1338
+ )
1339
+ raise SystemExit(ExitCode.NOT_FOUND)
1340
+ output_error(
1341
+ error_code="API_ERROR",
1342
+ operation="calendar.subscribe",
1343
+ message=f"Calendar API error: {e.reason}",
1344
+ )
1345
+ raise SystemExit(ExitCode.API_ERROR)
1346
+
1347
+ def unsubscribe_calendar(self, calendar_id: str) -> dict[str, Any]:
1348
+ """Unsubscribe from (remove) a calendar from the user's calendar list.
1349
+
1350
+ Args:
1351
+ calendar_id: The calendar ID to unsubscribe from.
1352
+ """
1353
+ try:
1354
+ self.execute(
1355
+ self.service.calendarList().delete(calendarId=calendar_id)
1356
+ )
1357
+
1358
+ output_success(
1359
+ operation="calendar.unsubscribe",
1360
+ calendar_id=calendar_id,
1361
+ unsubscribed=True,
1362
+ )
1363
+ return {"unsubscribed": True, "calendar_id": calendar_id}
1364
+ except HttpError as e:
1365
+ if e.resp.status == 404:
1366
+ output_error(
1367
+ error_code="NOT_FOUND",
1368
+ operation="calendar.unsubscribe",
1369
+ message=f"Calendar not found in list: {calendar_id}",
1370
+ )
1371
+ raise SystemExit(ExitCode.NOT_FOUND)
1372
+ output_error(
1373
+ error_code="API_ERROR",
1374
+ operation="calendar.unsubscribe",
1375
+ message=f"Calendar API error: {e.reason}",
1376
+ )
1377
+ raise SystemExit(ExitCode.API_ERROR)