-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathupload.py
278 lines (208 loc) · 7.74 KB
/
upload.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
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
from __future__ import print_function
import httplib2
import os
import csv
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# constant
CALENDAR_NAME = 'csv-to-calendar'
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar'
CLIENT_SECRET_FILE = '.client_secret.json'
APPLICATION_NAME = 'CSV to Calendar'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
calendar_id = initCalendar(service, CALENDAR_NAME)
mat = getMatrixFromCSV('timetable.csv')
events = parseMatrixIntoEvents(mat)
for x in events:
uploadEvent(service, x, calendar_id)
def deleteAllCalendars_NO(service, summary):
page_token = None
while True:
calendar_list = service.calendarList().list(pageToken=page_token).execute()
for calendar_list_entry in calendar_list['items']:
if calendar_list_entry['summary'] == summary:
service.calendars().delete(calendarId=calendar_list_entry['id']).execute()
# service.calendars().delete('secondaryCalendarId').execute()
print('Calendar ' + calendar_list_entry['summary'] + ' has been deleted')
page_token = calendar_list.get('nextPageToken')
if not page_token:
break
return None
def getCalendarId(service, calendarSummary):
page_token = None
while True:
calendar_list = service.calendarList().list(pageToken=page_token).execute()
for calendar_list_entry in calendar_list['items']:
if calendar_list_entry['summary'] == calendarSummary:
return calendar_list_entry['id']
page_token = calendar_list.get('nextPageToken')
if not page_token:
break
return None
def uploadEvent(service, event, calenderID):
#print(event)
print('Creating event... ' + event['summary'] + ' @ ' + event['start']['dateTime'])
event = service.events().insert(calendarId=calenderID, body=event).execute()
print('Event created!')
def initCalendar(service, summary):
calenderID = getCalendarId(service, summary)
newID = calenderID
if calenderID != None:
service.calendars().delete(calendarId=calenderID).execute()
print('Calendar ' + summary +' has been deleted')
calendar = {
'summary': summary,
'timeZone': 'Africa/Johannesburg'
}
created_calendar = service.calendars().insert(body=calendar).execute()
print('Calendar ' + summary +' has been created')
newID = created_calendar['id']
return newID
def getColours(service):
colors = service.colors().get().execute()
print(colors)
# Print available calendarListEntry colors.
for id, color in colors['calendar']:
print('colorId: %s'.format(id))
#print' Background: %s' % color['background']
#print ' Foreground: %s' % color['foreground']
# Print available event colors.
for id, color in colors['event']:
print('colorId: %s'.format(id))
#print ' Background: %s' % color['background']
#print ' Foreground: %s' % color['foreground']
def createEvent(dayCount, start, duration, subject, location, colour):
day = 17 + dayCount
day = int(day)
hours = start.split(':')[0]
hours = int(hours)
hours = hours + duration
startTime = start
endTime = '00:00'
if hours < 10:
endTime = '0' + str(hours) + ':' + start.split(':')[1]
else:
endTime = str(hours) + ':' + start.split(':')[1]
googleEvent = {
'summary': subject,
'location': location,
'start': {
'dateTime': '2017-07-' + str(day) + 'T' + str(startTime) + ':00+02:00',
'timeZone': 'Africa/Johannesburg'
},
'end': {
'dateTime': '2017-07-' + str(day) + 'T' + str(endTime) + ':00+02:00',
'timeZone': 'Africa/Johannesburg'
},
'recurrence': [
'RRULE:FREQ=WEEKLY;UNTIL=20181102T000000Z'
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'popup', 'minutes': 15}
],
},
'colorId': str(colour)
}
return googleEvent
def parseMatrixIntoEvents(mat):
# Row 1: Days ['', 'Monday', '', '', 'Tuesday'...]
# COLS:
# 1 (+3): Day
# Last element on index 13
# Row 2: Start time, Subject, Location, Colour, Subject...
# COLS:
# 0: Start Time
# 1 (+3): Subject
# 2 (+3): Location
# 3 (+3): Colour
# Last Element on index 15
# Row 2 -> 12 Times
# 0 based
DATA_START_ROW = 2
DATA_START_COL = 1
HEADER_ROW = 1
TIME_COL = 0
eventList = []
rowCount = 0
for row in mat:
colCount = 0;
for data in row:
if rowCount >= DATA_START_ROW:
if colCount >= DATA_START_COL:
if data != '':
if mat[HEADER_ROW][colCount] == 'Subject':
# Merge entries below
duration = 1
while (rowCount + duration < len(mat) and mat[rowCount + duration][colCount] == data):
mat[rowCount + duration][colCount] = ''
duration += 1
tmpEntryDict = createEvent((colCount - 1) / 3,
mat[rowCount][TIME_COL],
duration, data,
mat[rowCount][colCount + 1],
mat[rowCount][colCount + 2])
eventList.append(tmpEntryDict)
colCount += 1
rowCount += 1
return eventList
def getMatrixFromCSV(csvFile):
rowCount = 0
matrix = []
with open('timetable.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
colCount = 0
if rowCount >= len(matrix):
#print('Adding row to matrix')
matrix.append([])
for col in row:
matrix[rowCount].append(col)
#print('[' + str(rowCount) + '][' + str(colCount) + '] ' + col)
colCount += 1
rowCount += 1
return matrix
if __name__ == '__main__':
main()