This repository was archived by the owner on Nov 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBhamGoogleCalendarMaker.py
More file actions
162 lines (142 loc) · 7.23 KB
/
BhamGoogleCalendarMaker.py
File metadata and controls
162 lines (142 loc) · 7.23 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
from __future__ import print_function
import datetime
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import pprint
import time
import config
import pytz
import pickle
logger = config.initilise_logging()
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/calendar'
args = tools.argparser.parse_args()
args.noauth_local_webserver = True
accountNumPath = "/home/tomhmoses/mysite_ttc/lastAccountNo.pickle"
filePaths = [{"token":"/home/tomhmoses/mysite_ttc/token.json", "creds":"/home/tomhmoses/mysite_ttc/credentials.json"},
{"token":"/home/tomhmoses/mysite_ttc/token2.json", "creds":"/home/tomhmoses/mysite_ttc/credentials2.json"},
{"token":"/home/tomhmoses/mysite_ttc/token3.json", "creds":"/home/tomhmoses/mysite_ttc/credentials3.json"},
{"token":"/home/tomhmoses/mysite_ttc/token4.json", "creds":"/home/tomhmoses/mysite_ttc/credentials4.json"},
{"token":"/home/tomhmoses/mysite_ttc/token5.json", "creds":"/home/tomhmoses/mysite_ttc/credentials5.json"},
{"token":"/home/tomhmoses/mysite_ttc/token6.json", "creds":"/home/tomhmoses/mysite_ttc/credentials6.json"},
{"token":"/home/tomhmoses/mysite_ttc/token7.json", "creds":"/home/tomhmoses/mysite_ttc/credentials7.json"},
{"token":"/home/tomhmoses/mysite_ttc/token8.json", "creds":"/home/tomhmoses/mysite_ttc/credentials8.json"},
{"token":"/home/tomhmoses/mysite_ttc/token9.json", "creds":"/home/tomhmoses/mysite_ttc/credentials9.json"},
{"token":"/home/tomhmoses/mysite_ttc/token10.json", "creds":"/home/tomhmoses/mysite_ttc/credentials10.json"},
{"token":"/home/tomhmoses/mysite_ttc/token11.json", "creds":"/home/tomhmoses/mysite_ttc/credentials11.json"}]
def main(username, email, csv, shortenTitle, customTitle):
for count in range(len(filePaths)):
account_no = getNextAccount_no()
try:
return create_calendar(username, email, csv, shortenTitle, customTitle, account_no)
except:
logger.warn("failed with account_no: " + str(account_no))
time.sleep(20)
def getNextAccount_no():
account_no = loadPickle(accountNumPath)
account_no = (account_no+1)%len(filePaths)
savePickle(accountNumPath,account_no)
return account_no
def create_calendar(username, email, csv, shortenTitle, customTitle, account_no):
logger.info("starting creating calendar for: " + username + " with account number: " + str(account_no))
store = file.Storage(filePaths[account_no]["token"])
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(filePaths[account_no]["creds"], SCOPES)
creds = tools.run_flow(flow, store, args)
service = build('calendar', 'v3', http=creds.authorize(Http())) #maybe , cache_discovery=False
summary = "UoB Timetable: " + username
if customTitle != "":
summary = customTitle
timeZone = "Europe/London"
calendar = {
'summary': summary,
'timeZone': timeZone
}
logger.info("Creating calendar")
created_calendar = service.calendars().insert(body=calendar).execute()
calID = created_calendar["id"]
csv_events = csv.split("\n")
csv_events = csv_events[1:]
counter = 0
for csvEvent in csv_events:
details = csvEvent.split(",")
if to_date_time(details[0], details[3]) == "":
logger.warn("error occurred setting datetime so skipped.")
else:
if shortenTitle:
shortTitle = details[2]
for each in ["LM","LI","LC","LH","LANS"]:
shortTitle = shortTitle.replace(each+"/", "")
shortTitle = shortTitle.replace(each+" ", "")
s = shortTitle
shortTitle = s[:s.find("(")] + " · " + s[s.find(")/") + len(")/"):]
while " " in shortTitle:
shortTitle = shortTitle.replace(" ", " ")
logger.debug("made short title: " + shortTitle)
details[2] = shortTitle
eventDetails = {
'summary': details[2],
'location': details[5],
'description': details[6].replace("~n","\n"),
'start': {
'dateTime': to_date_time(details[0], details[3]),
'timeZone': timeZone,
},
'end': {
'dateTime': to_date_time(details[1], details[4]),
'timeZone': timeZone,
},
}
try:
event = service.events().insert(calendarId=calID, body=eventDetails).execute()
time.sleep(0.2)
counter += 1
except:
logger.warn("failed making calendar with account_no: " + str(counter))
logger.info("uploaded " + str(counter) + "/" + str(len(csv_events)) + " events for " + username + " using account number: " + str(account_no))
pp = pprint.PrettyPrinter(indent=4)
rule = {
'scope': {
'type': 'default',
'value': '',
},
'role': 'reader'
}
logger.debug("sleeping for 5 seconds...")
time.sleep(5)
created_rule = service.acl().insert(calendarId=calID, body=rule).execute()
pp.pprint(created_rule)
rule = {
'scope': {
'type': 'user',
'value': email,
},
'role': 'owner'
}
logger.debug("sleeping for 5 seconds...")
time.sleep(5)
created_rule = service.acl().insert(calendarId=calID, body=rule).execute()
pp.pprint(created_rule)
#if this failed then perhaps a 5 second delay is too short.
return "https://calendar.google.com/calendar/r?cid=" + calID
def to_date_time(date_string, time_string):
local_tz = pytz.timezone ("Europe/London")
datetime_without_tz = datetime.datetime.strptime(date_string + " " +time_string, "%m/%d/%Y %H:%M")
datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=None) # No daylight saving time
datetime_in_utc = datetime_with_tz.astimezone(pytz.utc)
dt_string = datetime_in_utc.strftime('%Y-%m-%dT%H:%M:00Z')
return dt_string
def savePickle(file_name, obj):
with open(file_name, 'wb') as fobj:
pickle.dump(obj, fobj)
def loadPickle(file_name):
with open(file_name, 'rb') as fobj:
return pickle.load(fobj)
if __name__ == '__main__':
print(str(datetime.datetime.now()))
#csv = "ThisBitIsRemoved\n01/14/2019,01/14/2019,LC Logic & Computation(30180)/Lecture,12:00,13:00,Gisbert Kapp LT2 (E202),With: Professor Loupin. Activity: LC Logic & Computation(30180)/Lecture. Type: Lecture. Department: Computer Science\n06/14/2019,06/14/2019,LC Logic & Computation(30180)/Lecture,12:00,13:00,Gisbert Kapp LT2 (E202),With: Professor Loupin. Activity: LC Logic & Computation(30180)/Lecture. Type: Lecture. Department: Computer Science\n08/14/2019,08/14/2019,LC Logic & Computation(30180)/Lecture,12:00,13:00,Gisbert Kapp LT2 (E202),With: Professor Loupin. Activity: LC Logic & Computation(30180)/Lecture. Type: Lecture. Department: Computer Science"
#create_calendar("thm2000","thomas@tmoses.co.uk",csv,True,"Test"+str(datetime.datetime.now()),5)
print(getNextAccount_no())
print(getNextAccount_no())