-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathgoogle-calendar
executable file
·208 lines (166 loc) · 6.43 KB
/
google-calendar
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
#!/usr/bin/env python3
#
# This script depends on python-dateutil and python-pytz for properly handling
# times and time zones of calendar events.
import argparse
import datetime
import itertools
import logging
import os
import sys
import time
from typing import List, Optional, Set, Tuple
import dateutil.parser
import pytz
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
import zulip
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
CLIENT_SECRET_FILE = "client_secret.json" # noqa: S105
APPLICATION_NAME = "Zulip"
HOME_DIR = os.path.expanduser("~")
# Our cached view of the calendar, updated periodically.
events: List[Tuple[int, datetime.datetime, str]] = []
# Unique keys for events we've already sent, so we don't remind twice.
sent: Set[Tuple[int, datetime.datetime]] = set()
sys.path.append(os.path.dirname(__file__))
parser = zulip.add_default_arguments(
argparse.ArgumentParser(
r"""
google-calendar --calendar [email protected]
This integration can be used to send yourself reminders, on Zulip, of Google Calendar Events.
Specify your Zulip API credentials and server in a ~/.zuliprc file or using the options.
Before running this integration make sure you run the get-google-credentials file to give Zulip
access to certain aspects of your Google Account.
This integration should be run on your local machine. Your API key and other information are
revealed to local users through the command line.
Depends on: google-api-python-client
"""
)
)
parser.add_argument(
"--interval",
dest="interval",
default=30,
type=int,
action="store",
help="Minutes before event for reminder [default: 30]",
metavar="MINUTES",
)
parser.add_argument(
"--calendar",
dest="calendarID",
default="primary",
type=str,
action="store",
help="Calendar ID for the calendar you want to receive reminders from.",
)
options = parser.parse_args()
if not options.zulip_email:
parser.error("You must specify --user")
zulip_client = zulip.init_from_options(options)
def get_credentials() -> Credentials:
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the user will be prompted to authenticate.
Returns:
Credentials, the obtained credential.
"""
credential_path = os.path.join(HOME_DIR, "google-credentials.json")
creds = None
# Load credentials from file if they exist
if os.path.exists(credential_path):
creds = Credentials.from_authorized_user_file(credential_path, SCOPES)
# If there are no (valid) credentials available, prompt the user to log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(credential_path, "w") as token:
token.write(creds.to_json())
return creds
def populate_events() -> Optional[None]:
credentials = get_credentials()
service = build("calendar", "v3", credentials=credentials)
now = datetime.datetime.now(pytz.utc).isoformat()
feed = (
service.events()
.list(
calendarId=options.calendarID,
timeMin=now,
maxResults=5,
singleEvents=True,
orderBy="startTime",
)
.execute()
)
events.clear()
for event in feed["items"]:
try:
start = dateutil.parser.parse(event["start"]["dateTime"])
# According to the API documentation, a time zone offset is required
# for start.dateTime unless a time zone is explicitly specified in
# start.timeZone.
if start.tzinfo is None:
event_timezone = pytz.timezone(event["start"]["timeZone"])
# pytz timezones include an extra localize method that's not part
# of the tzinfo base class.
start = event_timezone.localize(start)
except KeyError:
# All-day events can have only a date.
start_naive = dateutil.parser.parse(event["start"]["date"])
# All-day events don't have a time zone offset; instead, we use the
# time zone of the calendar.
calendar_timezone = pytz.timezone(feed["timeZone"])
# pytz timezones include an extra localize method that's not part
# of the tzinfo base class.
start = calendar_timezone.localize(start_naive)
try:
events.append((event["id"], start, event["summary"]))
except KeyError:
events.append((event["id"], start, "(No Title)"))
def send_reminders() -> Optional[None]:
messages = []
keys = set()
now = datetime.datetime.now(tz=pytz.utc)
for id, start, summary in events:
dt = start - now
if dt.days == 0 and dt.seconds < 60 * options.interval:
# The unique key includes the start time, because of
# repeating events.
key = (id, start)
if key not in sent:
if start.hour == 0 and start.minute == 0:
line = f"{summary} is today."
else:
line = "{} starts at {}".format(summary, start.strftime("%H:%M"))
print("Sending reminder:", line)
messages.append(line)
keys.add(key)
if not messages:
return
if len(messages) == 1:
message = "Reminder: " + messages[0]
else:
message = "Reminder:\n\n" + "\n".join("* " + m for m in messages)
zulip_client.send_message(
dict(type="private", to=options.zulip_email, sender=options.zulip_email, content=message)
)
sent.update(keys)
# Loop forever
for i in itertools.count():
try:
# We check reminders every minute, but only
# download the calendar every 10 minutes.
if not i % 10:
populate_events()
send_reminders()
except Exception:
logging.exception("Couldn't download Google calendar and/or couldn't post to Zulip.")
time.sleep(60)