-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcal3.py
239 lines (192 loc) · 7.91 KB
/
cal3.py
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
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import subprocess
import os
import time
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
path = os.path.dirname(os.path.abspath(__file__))
def setup():
if os.path.isfile('./myconfig.txt'):
f = open("myconfig.txt", "r")
config = f.readlines()
f.close()
if len(config) == 4:
print("checking myconfig.txt")
setupdic = {}
for line in config:
comps = line.split("=")
varname = comps[0]
val = comps[1].strip('\n')
setupdic[varname] = val
else:
setupdic = question_asker()
else:
setupdic = question_asker()
return setupdic
def question_asker():
inputdic = {}
noAccounts = input("How many google accounts would you like to be monitored? ")
imessage = input("Would you like an iMessage notication? (y/n) ")
if imessage.lower() == "y" or imessage.lower() == "yes":
phoneno = input("What phone number is associated with your iMessage account? Please include the + sign followed by your country code ")
else:
phoneno = ""
notification = input("Would you like a notification on your Mac? (y/n) ")
text = "noAccounts=" + noAccounts + "\nimessage=" + imessage + "\nnotification=" + notification + "\nphoneno=" + phoneno + "\n"
f = open("myconfig.txt", "w")
f.write(text)
print("wrote to myconfig.txt")
f.close()
inputdic["noAccounts"] = noAccounts
inputdic["imessage"] = imessage
inputdic["phoneno"] = phoneno
inputdic["notification"] = notification
return inputdic
def getEvents(path):
# Call the Calendar API
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists(path):
with open(path, 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user 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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(path, 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
#now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
tomorrow = datetime.datetime.today() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=0, minute=0, second=0)
days_after = tomorrow + datetime.timedelta(days=7)
iso_start = tomorrow.isoformat() + "Z"
iso_end = days_after.isoformat() + "Z"
events_result = service.events().list(calendarId='primary', timeMin=iso_start,
timeMax=iso_end, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
return events
def check_for_conflicts(events):
all = []
if not events:
print('No upcoming events found.')
else:
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
name = event['summary']
end = event['end'].get('dateTime', event['end'].get('date'))
tup = (name, (start, end))
all.append(tup)
conflicts = ["Conflicts: \n\n", ]
i=0
if "+" in all[0][1][1]:
timediff = all[0][1][1].split("+")[1]
timediffhours = 24 - int(timediff.split(":")[0])
timediffmin = int(timediff.split(":")[1])
timediffdelta = datetime.timedelta(hours=timediffhours, minutes=timediffmin)
else:
timediffdelta = datetime.timedelta(hours=0)
for element in all:
start = datetime.datetime.fromisoformat(element[1][0]) - timediffdelta
end = datetime.datetime.fromisoformat(element[1][1]) - timediffdelta
startdate = start.date()
starttime = start.time()
enddate = end.date()
endtime = end.time()
name = element[0]
i=i+1
for other_event in all[i:]:
otherstart = datetime.datetime.fromisoformat(other_event[1][0]) - timediffdelta
otherend = datetime.datetime.fromisoformat(other_event[1][1]) - timediffdelta
otherstartdate = otherstart.date()
otherstarttime = otherstart.time()
otherenddate = otherend.date()
otherendtime = otherend.time()
othername = other_event[0]
if startdate == otherstartdate and enddate == otherenddate:
overlap = max(starttime, otherstarttime) < min(endtime, otherendtime)
if overlap:
line = startdate.strftime("%m/%d/%Y") + ": " + name + " and " + othername + " share a conflict\n"
conflicts.append(line)
return conflicts
def send_message(conflicts, phoneno):
##send imessage
msg = "".join(conflicts)
scpt = "sendMessage.scpt"
args = [phoneno, msg]
p = subprocess.Popen(
['/usr/bin/osascript', scpt] + [str(arg) for arg in args],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode:
print('ERROR:', stderr)
else:
print(stdout)
def create_notication(conflicts):
##create notification
script = "notification.scpt"
p = subprocess.Popen(
['/usr/bin/osascript', script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode:
print('ERROR:', stderr)
else:
print(stdout)
def create_cron(path):
##create cronjob
p = subprocess.Popen(
['sh', 'schedule.sh', path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode:
print('ERROR:', stderr)
else:
print(stdout)
def run():
eventlist = []
setupdic = setup()
for num in range(int(setupdic["noAccounts"])):
tokenno = "token" + str(num) + ".pickle"
events = getEvents(tokenno)
if events:
eventlist.append(events)
print("\n\nChecking tomorrows events...\n")
if len(eventlist) > 0:
all_events = [item for sublist in eventlist for item in sublist]
else:
all_events = None
if all_events:
conflicts = check_for_conflicts(all_events)
if len(conflicts) > 1:
print("Uh oh! Conflicts found!")
if setupdic["imessage"].lower() == "y" or setupdic["imessage"].lower() == "yes":
print("Sending iMessage...")
send_message(conflicts, setupdic["phoneno"])
if setupdic["notification"].lower() == "y" or setupdic["notification"].lower() == "yes":
print("Creating notification...")
create_notication(conflicts)
time.sleep(6)
print("Creating cronjob...")
create_cron(path)
print("\n\nAll done! Your conflict detector has been set up and will now automatically run every hour. You will only be notified if you have a conflict! \n\n")
else:
print("No conflicts tomorrow")
print("Creating cronjob...")
create_cron(path)
print("\n\nAll done! Your conflict detector has been set up and will now automatically run every hour. You will only be notified if you have a conflict")
run()