-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendar.py
348 lines (266 loc) · 13.3 KB
/
calendar.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python3
#A full-featured Linux-based calendar utility for blind users with Grade2 braille support (requires adgenda.py)
#Copyright Blazie Technologies LLC., All rights reserved
#by Stephen Blazie
import calendar, configparser, os, louis, time
from BTSpeak import host, dialogs, script, adgenda, braille
from datetime import datetime, timedelta
from calendar import monthrange
class Browse():
def __init__(self):
settings = adgenda.Settings()
self.contractedBraille = settings.getSettings().getboolean('braille input')
if settings.getSettings().getboolean('default date') == True:
self.defaultDatePrompt = adgenda.todaysDate()
else:
self.defaultDatePrompt = None
def promptChoice(self, listChoices, message, defaultChoice):
while True:
choice=dialogs.requestChoice(listChoices,
default=defaultChoice,
allowEmptyChoice=True,
okayLabel="Select",
cancelLabel="Back",
message=message
)
if choice is None:
return None, None
else:
choiceName, defaultChoice = choice
choiceLabel = choice.label
return choiceLabel, defaultChoice
def editEvents(self, event, date, time):
defaultChoice = None
editMenu=[
'Edit event',
'Edit time',
'Edit date',
'Delete event'
]
calendar = adgenda.calendar()
editMenuMessage = f"Select an operation to perform on calendar entry {date} {time} {event}"
editAction, defaultChoice = self.promptChoice(editMenu, editMenuMessage, defaultChoice)
if editAction is None:
return
elif editAction == 'Edit event':
newEvent = dialogs.requestInput("Edit the event:",
initialText = adgenda.translateInitial(event, self.contractedBraille)
)
if newEvent is None: return
if self.contractedBraille:
newEvent = adgenda.translateBraille(newEvent, backTranslate=True)
calendar.editEvent(date, event, time, newEvent)
elif editAction == 'Edit time':
newTime = dialogs.requestInput(f"Edit the time for {event}:",
initialText = adgenda.translateInitial(time, self.contractedBraille)
)
if newTime is None: return
if self.contractedBraille:
newTime = adgenda.translateBraille(newTime, backTranslate=True)
calendar.editTime(date, event, time, newTime)
elif editAction == 'Edit date':
date = convertDateFormat(date)
newDate = dialogs.requestInput("Edit the date:",
initialText = adgenda.translateInitial(date, self.contractedBraille)
)
if newDate is None: return
if self.contractedBraille:
newDate = adgenda.translateBraille(newDate, backTranslate=True)
calendar.editDate(convertDateFormat(date), event, time, newDate)
elif editAction == 'Delete event':
calendar.removeEntry(date, time, event)
return
def getEventData(self, eventsDict, eventString):
date = eventsDict[eventString]['date']
time = eventsDict[eventString]['time']
event = eventsDict[eventString]['event']
reminder = eventsDict[eventString]['reminder']
return date, time, event, reminder
def todaysEvents(self):
defaultChoice = 1
while True:
calendar=adgenda.calendar()
dateList = [adgenda.todaysDate()]
todaysCalendar=calendar.showEvents(dateList)
if todaysCalendar:
todayDict = self.getEntries(todaysCalendar, dailyEntries = True)
eventStrings = list(todayDict.keys())
eventsMessage=f"Calendar entries for {list(todaysCalendar.keys())[0]}"
eventStringChoice, defaultChoice = self.promptChoice(eventStrings, eventsMessage, defaultChoice)
if eventStringChoice is None:
return
date, time, event, reminder = self.getEventData(todayDict, eventStringChoice)
self.editEvents(event, date, time)
else:
dialogs.showMessage(f"Nothing in your calendar today, {adgenda.todaysDate()}",
okayLabel="Back"
)
return
def generateWeeklyList(self, dateString, next=True):
date = datetime.strptime(dateString, '%A, %B %d, %Y')
dateRange = []
if next:
for i in range(7):
dateRange.append((date + timedelta(days=i)).strftime('%A, %B %d, %Y'))
else:
for i in range(6, -1, -1):
dateRange.append((date - timedelta(days=i)).strftime('%A, %B %d, %Y'))
return dateRange
def generateDateRange(self, dateString, monthly=False, next=True):
date = datetime.strptime(dateString, '%A, %B %d, %Y')
dateRange = []
if monthly:
_, lastDay = monthrange(date.year, date.month)
startDate = datetime(date.year, date.month, 1)
endDate = datetime(date.year, date.month, lastDay)
while startDate <= endDate:
dateRange.append(startDate.strftime('%A, %B %d, %Y'))
startDate += timedelta(days=1)
else:
dateRange = self.generateWeeklyList(dateString, next)
return dateRange
def getEntries(self, weekCalendar, dailyEntries = False):
entriesDict = {}
for date, eventsList in weekCalendar.items():
for event in eventsList:
if dailyEntries:
eventString = f"{event['time']} {event['event']}" if event['time'] else f"{event['event']}"
else:
eventString = f"{date} {event['time']} {event['event']}" if event['time'] else f"{date} {event['event']}"
entriesDict[eventString] = {'date': date, 'time': event['time'], 'event': event['event'], 'reminder': event['reminder']}
return entriesDict
def browseDateRange(self, monthly=False):
startDate = adgenda.todaysDate()
dateRange = self.generateDateRange(startDate, monthly)
defaultChoice = 2
eventStringChoice = None
while True:
startDateDT = convertToDatetime(startDate, "%A, %B %d, %Y")
weekCalendar = adgenda.calendar().showEvents(dateRange)
if weekCalendar:
eventStrings, weekDict = self.getEventStrings(weekCalendar)
else:
eventStrings = ['No events']
eventStrings.insert(0, 'previous')
eventStrings.append('next')
eventStringChoice, defaultChoice = self.promptChoice(eventStrings,
self.getMessage(startDateDT, dateRange, monthly),
defaultChoice
)
if eventStringChoice is None:
return
if eventStringChoice == 'previous':
startDate, dateRange = self.handlePrevious(startDate, dateRange, monthly)
defaultChoice = 2
elif eventStringChoice == 'next':
startDate, dateRange = self.handleNext(startDate, dateRange, monthly)
defaultChoice = 2
elif eventStringChoice != 'No events':
date, time, event, reminder = self.getEventData(weekDict, eventStringChoice)
self.editEvents(event, date, time)
def getEventStrings(self, weekCalendar):
weekDict = self.getEntries(weekCalendar)
return list(weekDict.keys()), weekDict
def getMessage(self, startDate, dateRange, monthly):
if monthly:
return f"Entries for month of {calendar.month_name[startDate.month]} {startDate.year}"
else:
return f"Entries for week of {dateRange[0]} to {dateRange[-1]}"
def handlePrevious(self, startDate, dateRange, monthly):
startDate = convertToDatetime(dateRange[0], "%A, %B %d, %Y") - timedelta(days=1)
startDate = startDate.strftime("%A, %B %d, %Y")
dateRange = self.generateDateRange(startDate, monthly, next=False)
return startDate, dateRange
def handleNext(self, startDate, dateRange, monthly):
startDate = convertToDatetime(dateRange[-1], "%A, %B %d, %Y") + timedelta(days=1)
startDate = startDate.strftime("%A, %B %d, %Y")
dateRange = self.generateDateRange(startDate, monthly, next=True)
return startDate, dateRange
def searchEvent(self):
eventQuery = dialogs.requestInput("Event to search:")
defaultChoice = None
if len(eventQuery)==0:
return
if self.contractedBraille:
eventQuery = adgenda.translateBraille(eventQuery, backTranslate=True)
while True:
searchResultsCalendar = adgenda.calendar().searchEvent(eventQuery)
if searchResultsCalendar:
host.say(f"Showing results for {eventQuery}")
searchResultsDict = self.getEntries(searchResultsCalendar, dailyEntries = False)
eventStrings = list(searchResultsDict.keys())
eventsMessage=f"Calendar entries containing {eventQuery}"
eventStringChoice, defaultChoice = self.promptChoice(eventStrings, eventsMessage, defaultChoice)
if eventStringChoice is None:
return
date, time, event, reminder = self.getEventData(searchResultsDict, eventStringChoice)
self.editEvents(event, date, time)
else:
dialogs.showMessage(f"No events in your calendar match {eventQuery}",
okayLabel="Back"
)
return
def searchDate(self):
dateQuery = dialogs.requestInput("Date to search:")
defaultChoice = None
if dateQuery is None or len(dateQuery) == 0:
return
if self.contractedBraille:
dateQuery = adgenda.translateBraille(dateQuery, backTranslate=True)
while True:
searchResultsCalendar = adgenda.calendar().searchDate(dateQuery)
if searchResultsCalendar is None:
return
elif not searchResultsCalendar:
dialogs.showMessage(f"Nothing in your calendar for {dateQuery}",
okayLabel="Back"
)
return
else:
host.say(f"Showing results for {dateQuery}")
searchResultsDict = self.getEntries(searchResultsCalendar, dailyEntries = True)
eventStrings = list(searchResultsDict.keys())
eventsMessage=f"Calendar entries for {list(searchResultsCalendar.keys())[0]}"
eventStringChoice, defaultChoice = self.promptChoice(eventStrings, eventsMessage, defaultChoice)
if eventStringChoice is None:
return
date, time, event, reminder = self.getEventData(searchResultsDict, eventStringChoice)
self.editEvents(event, date, time)
def addEntry(self):
return adgenda.calendar().appendEntry()
def convertToDatetime(dateString, dateFormat):
dateStringDT = datetime.strptime(dateString, dateFormat)
return dateStringDT
def convertDateFormat(dateString):
try:
date = datetime.strptime(dateString, '%A, %B %d, %Y')
date = datetime.strftime(date, '%B %d, %Y')
except ValueError:
try:
date = datetime.strptime(dateString, '%B %d, %Y')
date = datetime.strftime(date, '%A, %B %d, %Y')
except ValueError:
date = None
return date
script.addOption(
"a", argument="action", label="action",
default="action",
help="Select a caledar option. Options are: today (shows a list of today's events, ordered by time of day), weeklyEvents (shows weekly events in the calendar ordered by date), searchEvent (executes a search prompt for specific event(s) in the calendar), searchDate (executes a search prompt for a specific date and displays the list of events for the chosen date)"
)
option = script.parseArguments().action
functions={
"today": lambda: Browse.todaysEvents(),
"week": lambda: Browse.browseDateRange(),
"month": lambda: Browse.browseDateRange(monthly=True),
"searchEvent": lambda: Browse.searchEvent(),
"searchDate": lambda: Browse.searchDate(),
"add": lambda: Browse.addEntry(),
"brailleSettings": lambda: Settings.promptSettings(settingName = 'braille input'),
"defaultDateSettings": lambda: Settings.promptSettings(settingName = 'default date'),
"saveCalendar": lambda: Settings.saveCalendar()
}
if option in functions:
Browse = Browse()
Settings = adgenda.Settings()
perform=functions[option]
perform()