forked from LazzaAU/skill_Reminder
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Reminder.py
847 lines (682 loc) · 26.1 KB
/
Reminder.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
import time
from datetime import datetime, timedelta
from core.base.model.AliceSkill import AliceSkill
from core.base.model.Intent import Intent
from core.dialog.model.DialogSession import DialogSession
from core.util.Decorators import IntentHandler
class Reminder(AliceSkill):
"""
Author: @Lazza.
This skill utilises these main methods for functional operation
- addReminder initiates the reminder process between user and Alice
- Then passes onto processTheSpecifiedTime() for processing of the time
- then onto processAndStoreReminder() for finalising the timer
Amongst that process there are methods for converting spoken times to epoch and back to human time
and Various other functions and checks, delete, how long left, etc.
Also, one main Method which allows switching between the three events (Reminder/Timer/Alarm) is the
- setEventType() method. This allows the skill to determine what of the 3 events we are dealing with
"""
INTERNAL_ID = 'internalId TEXT NOT NULL'
DB_MESSAGE = 'message TEXT NOT NULL'
DB_TIMESTAMP = 'timestamp INTEGER NOT NULL'
DB_SITE_ID = 'SiteID TEXT NOT NULL'
DB_EVENT_TYPE = 'EventType TEXT NOT NULL'
_REMINDERDBNAME = 'MyReminders'
_TIMERDBNAME = 'MyTimer'
_ALARMDBNAME = 'MyAlarm'
_DATABASE = {
_REMINDERDBNAME: [
INTERNAL_ID,
DB_MESSAGE,
DB_TIMESTAMP,
DB_SITE_ID,
DB_EVENT_TYPE
],
_TIMERDBNAME : [
INTERNAL_ID,
DB_MESSAGE,
DB_TIMESTAMP,
DB_SITE_ID,
DB_EVENT_TYPE
],
_ALARMDBNAME : [
INTERNAL_ID,
DB_MESSAGE,
DB_TIMESTAMP,
DB_SITE_ID,
DB_EVENT_TYPE
]
}
_INTENT_PREDEFINED_TIMER = Intent('PreDefinedTimerEvent')
_INTENT_ADD_REMINDER = Intent('AddReminderEvent')
_INTENT_ADD_DATE = Intent('ReminderTime')
_INTENT_ANSWER_YES_OR_NO = Intent('AnswerYesOrNo')
_INTENT_TIME_REMAINING = Intent('ReminderRemaining')
_INTENT_SELECT_ITEM = Intent('ChooseListItem')
_INTENT_DELETE_REMINDER = Intent('ReminderDelete')
_INTENT_USER_RANDOM_ANSWER = Intent('UserRandomAnswer')
_DELETE_ALL = 'delete all'
def __init__(self):
self._spokenDuration = ''
self._dateTimeStr = ''
self._dateTimeObject = ''
self._secondsDuration = 0.0
self._reminderMessage = ''
self._dbId = 0
self._theDeviceId = ""
self._dbTableValues = list()
self._selectedMessages = None
self._dbTimeStampList = list()
self._dbMessageList = list()
self._dbRowIdList = list()
self._dbSiteList = list()
self._eventType = list()
self._activeDataBase = 'MyReminders'
self._dataBaseList = ['MyReminders', 'MyTimer', 'MyAlarm']
self._TimerEventType = list()
self._preDefinedEvent = False
self._INTENTS = [
(self._INTENT_PREDEFINED_TIMER, self.determinePreDefinedTimer),
self._INTENT_ANSWER_YES_OR_NO,
self._INTENT_ADD_DATE,
self._INTENT_SELECT_ITEM,
self._INTENT_USER_RANDOM_ANSWER,
(self._INTENT_DELETE_REMINDER, self.deleteRemindersIntent),
(self._INTENT_ADD_REMINDER, self.addReminder)
]
# init Dialog mapping to prevent dialog clashing with other skills
self._INTENT_ANSWER_YES_OR_NO.dialogMapping = {
'ConfirmIfDeletingAllMessages': self.actionFromYesNoAnswer,
# 'ConfirmIfMessageAndTimeCorrect': self.processTheSpecifiedTime
}
self._INTENT_PREDEFINED_TIMER.dialogMapping = {
'DoPredefinedTimerEvent': self.determinePreDefinedTimer,
}
self._INTENT_ADD_REMINDER.dialogMapping = {
'AddMessageToReminder': self.processTheSpecifiedTime
}
self._INTENT_USER_RANDOM_ANSWER.dialogMapping = {
'AddMessageToReminder': self.processTheSpecifiedTime
}
self._INTENT_DELETE_REMINDER.dialogMapping = {
'DeleteSomeReminder': self.deleteRequestedReminder
}
self._INTENT_SELECT_ITEM.dialogMapping = {
#'SelectedItemFromList': self.extractRequestedItemFromList,
'askWhatItemFromList' : self.extractRequestedItemFromList
}
self._INTENT_ADD_DATE.dialogMapping = {
'AddedTheDateOrDuration': self.addReminder,
}
super().__init__(self._INTENTS, databaseSchema=self._DATABASE)
### - MAIN ADD REMINDER INTENT - ###
def addReminder(self, session: DialogSession):
"""
Asks a user for missing details or triggers a short timer if that was requested.
This Method tries to account for the lack of proper session continuation as per dialogView or Telegram
"""
# set the eventType, as Timer or Alarm or Reminder
self.setEventType(session)
food, secs = self.findTheSeconds(session)
# If a user sets a short timer (no topic) do this
if 'ShortTimer' in session.slots and 'Duration' in session.slots:
self._reminderMessage = 'for the timer with no topic'
self.ThreadManager.doLater(
interval=self._secondsDuration,
func=self.runShortTimer,
args=[self._eventType]
)
self.endDialog(
sessionId=session.sessionId,
text=f'Ok, done'
)
return
# Safegaurd for inconsistant session data like dialogView/Telegram etc.
try:
if session.customData['seconds'] and session.input:
return self.processTheSpecifiedTime(session=session)
except:
pass
# If the time requirement has been calculated
if secs > 0:
self.continueDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='respondReminderMessage', replace=[self._eventType]),
intentFilter=[self._INTENT_USER_RANDOM_ANSWER],
customData={
"seconds" : secs,
"food" : food,
"eventType" : self._eventType
},
currentDialogState='AddMessageToReminder',
probabilityThreshold=0.1
)
# If there's no seconds set then ask for one
else :
self.continueDialog(
sessionId=session.sessionId,
text=self.randomTalk(text='respondSetDuration', replace=[self._eventType]),
intentFilter=[self._INTENT_ADD_DATE],
currentDialogState='AddedTheDateOrDuration',
slot='ReminderDateAndTime' or 'Duration'
)
def determinePreDefinedTimer(self, session: DialogSession):
"""
Work out what pre-determined timer event it is and set the message and time accordingly
:param session: The dialog Session
:return:
"""
# set some vars so, we can merge the event with existing timer code
self._theDeviceId = session.deviceUid
self._eventType = 'Timer'
self._activeDataBase = self._TIMERDBNAME
self._preDefinedEvent = True
# work out what pre-determined timer the user is requesting
if session.slotValue('PreDefinedTimer') == 'wash hands':
session.payload['input'] = self.randomTalk(text='washingHands')
self.processTheSpecifiedTime(session, preDefinedTime=20)
if session.slotValue('PreDefinedTimer') == 'brush teeth':
session.payload['input'] = self.randomTalk(text='brushingTeeth')
self.processTheSpecifiedTime(session, preDefinedTime=120)
if session.slotValue('PreDefinedTimer') == 'cup of tea':
session.payload['input'] = self.randomTalk(text='teaReady', replace=['cup'])
self.processTheSpecifiedTime(session, preDefinedTime=180)
if session.slotValue('PreDefinedTimer') == 'pot of tea':
session.payload['input'] = self.randomTalk(text='teaReady', replace=['pot'])
self.processTheSpecifiedTime(session, preDefinedTime=420)
def processTheSpecifiedTime(self, session: DialogSession, preDefinedTime: int = None):
"""
Process the requested Time/Date/Duration, so we can later use that in the reminder
:param session: The dialog Session
:param preDefinedTime: If it's a preDefinedTimer event then this will be the seconds of the timer to use
:return:
"""
if preDefinedTime:
self._reminderMessage = session.payload['input'] # set the reminder message
self.processAndStoreReminder(session=session, secs=preDefinedTime)
return
self._reminderMessage = session.payload['input'] # set the reminder message
# safeGuard for dialogview/telegram calls
try:
if session.customData['food']:
self.setFoodTimer(session, session.customData['seconds'])
except :
pass
else:
self.processAndStoreReminder(session, session.customData['seconds'])
def processAndStoreReminder(self, session: DialogSession, secs: int):
"""
This does the actual setting of the event and the storing to the database
:param session: The dialog Session
:param secs: The seconds between "now" and when the event is to trigger
:return:
"""
self.logDebug(f'The requested time converted to seconds is {secs}')
# count of the amount of rows in the Database
myTablecount = self.tableRowCount()
# Convert to Epoch timestamp in Seconds for storing in Db
timeStampForDb = self.createEpochTimeStamp(secs)
# VocalSeconds is used to give Alice's reply a human friendly response
vocalSeconds = str(timedelta(seconds=secs))
hour, minute, second = vocalSeconds.split(':')
vocalTime = ''
try:
hours = int(hour)
minutes = int(minute)
seconds = int(second)
except ValueError:
self.logWarning(self.randomTalk(text="systemMessage3"))
hours = 0
minutes = 0
seconds = 60
if seconds > 0:
vocalTime = f'{seconds} seconds'
if minutes > 0:
if minutes > 1:
if seconds > 0:
vocalTime = f'{minutes} minutes and {vocalTime}'
else:
vocalTime = f'{minutes} minutes'
else:
if seconds > 0:
vocalTime = f'{minutes} minute and {vocalTime}'
else:
vocalTime = f'{minutes} minute'
if hours > 0:
if hours > 1:
vocalTime = f'{hours} hours, {vocalTime}'
else:
vocalTime = f'{hours} hour and {vocalTime}'
# Set event type for later recall from db when dofiveMinute is called after a reboot
self._TimerEventType = self._eventType
# If timer is under 5 minutes, don't add it to the database, just start a local timer
if secs < 299:
self.ThreadManager.doLater(
interval=secs,
func=self.runReminder,
args=[self._eventType, self._reminderMessage]
)
# write Timer info to the database or not depending on length of time (saves double up reminder from onFive trigger
try:
if secs >= 299:
self.databaseInsert(
tableName=self._activeDataBase,
values={'internalID': myTablecount + 1, 'message': self._reminderMessage, 'timestamp': timeStampForDb, 'SiteID': self._theDeviceId, 'EventType': self._eventType}
)
except Exception as e:
self.logError(f'Failed to enable timer due to **Database** error: {e}')
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('databaseError')
)
return
# Alice Confirming that the Reminder has been set ..........................................................
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondConfirmed', replace=[self._eventType, self._reminderMessage, vocalTime])
)
### - TIMERS AND RUN METHODS - ###
# Respond with The Reminder once time is finished,
def runReminder(self, event: str, savedMessage: str):
self.reminderSound(event)
self.ThreadManager.doLater(interval=5, func=self.say, kwargs={'text': self.randomTalk(text='respondReminder', replace=[event, savedMessage]), 'deviceUid': self._theDeviceId})
# Say the food timer is half way completed time to turn/stir the food.
def foodReminder(self):
self.say(self.randomTalk(text='respondFoodTimer'), deviceUid=self._theDeviceId)
def runShortTimer(self, event: str):
self.reminderSound(event)
self.ThreadManager.doLater(
interval=0.5,
func=self.say(
text='Your short timer has finished'
),
)
# Sets a mid-timer, timer to alert to go check the food
def setFoodTimer(self, session: DialogSession, secs):
checkTheFoodTimer = secs / 2
self.ThreadManager.doLater(
interval=checkTheFoodTimer,
func=self.foodReminder
)
self.processAndStoreReminder(session, secs)
# gets the sound file to play based on the event
def reminderSound(self, event: str):
path = event
if 'Reminder' in event:
soundFile = 'Reminder.wav'
elif 'Timer' in event:
soundFile = 'Timer.wav'
else:
soundFile = 'Alarm.wav'
self.playSound(
soundFilename=soundFile,
location=self.getResource(f'Sounds/{path}'),
sessionId='ReminderTriggered',
deviceUid=self._theDeviceId
)
def askIfTheDetailsAreCorrect(self, session: DialogSession):
"""
Asks user for confirmation if they want to delete all events. customData used for compatibility with dialogView and telegram
:param session: The dialog session
:return:
"""
if self._DELETE_ALL in session.slotValue('ReminderDelete'):
self.continueDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondAskConfirmation', replace=[self._eventType]),
intentFilter=[self._INTENT_ANSWER_YES_OR_NO],
currentDialogState='ConfirmIfDeletingAllMessages',
customData={
"delete" : "all"
},
probabilityThreshold=0.1
)
# do something in responce to a yes or no reply
def actionFromYesNoAnswer(self, session: DialogSession):
if 'ConfirmIfDeletingAllMessages' in session.currentState:
if self.Commons.isYes(session):
self.deleteRequestedReminder(session)
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondToANoReply', replace=[self._eventType]),
)
# This deletes an Item from DB the cleans up the row id's
def deleteRequestedReminder(self, session: DialogSession):
# This block handles the potential missing info from a dialogView or Telegram session
deleteWhat = ""
if 'ReminderDelete' not in session.slots:
try :
if session.customData['delete']:
deleteWhat = session.customData['delete']
except :
pass
else:
if self._DELETE_ALL in session.slotValue('ReminderDelete'):
deleteWhat = "all"
# Delete items from DB
if 'all' not in deleteWhat:
# noinspection SqlResolve
self.DatabaseManager.delete(
tableName=self._activeDataBase,
query='DELETE FROM :__table__ WHERE message = :tmpMessage',
values={'tmpMessage': self._selectedMessages},
callerName=self.name)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondDelete', replace=[self._eventType]),
deviceUid=session.deviceUid,
)
self.logInfo(f'Successfully deleted the requested {self._eventType} from the database')
return
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondDeleteAll', replace=[self._eventType]),
deviceUid=session.deviceUid,
)
# noinspection SqlWithoutWhere
self.DatabaseManager.delete(
tableName=self._activeDataBase,
query='DELETE FROM :__table__ ',
callerName=self.name
)
self.cleanupDeadTimers()
### - MAINTENANCE ITEMS - ###
def cleanupDeadTimers(self):
i = 0
for x in self._dbTimeStampList: # x = a individual timestamp from _dbTimeStampList
epochTimeNow = datetime.now().timestamp() # Returns the epoch time for right now
if x < epochTimeNow:
# noinspection SqlResolve
self.DatabaseManager.delete(
tableName=self._activeDataBase,
query='DELETE FROM :__table__ WHERE timestamp <= :tmpTimestamp',
values={'tmpTimestamp': epochTimeNow},
callerName=self.name
)
i += 1
if i > 0:
self.viewTableValues()
self.logDebug(f'Just deleted {i} redundant event/s from {self._activeDataBase}')
# This returns the amount of rows in the database table
# TODO: this should not be used for calculating the index, but returned by the db on insert!
def tableRowCount(self) -> int:
return self.databaseFetch(tableName=self._activeDataBase, query='SELECT COUNT () AS c FROM :__table__')[0]['c']
# This updates the internalID value to match table rowid
def updateInternalIdNumberOfDb(self):
i = 0
while i <= len(self._dataBaseList) - 1:
if i == 0:
self._eventType = 'Reminder'
self._activeDataBase = self._REMINDERDBNAME
elif i == 1:
self._eventType = 'Timer'
self._activeDataBase = self._TIMERDBNAME
else:
self._eventType = 'Alarm'
self._activeDataBase = self._ALARMDBNAME
self.viewTableValues()
try:
# noinspection SqlResolve
self.DatabaseManager.update(
tableName=self._activeDataBase,
callerName=self.name,
query='UPDATE :__table__ SET internalId = rowid'
)
except:
self.ThreadManager.doLater(
interval=300,
func=self.updateInternalIdNumberOfDb
)
i += 1
def viewTableValues(self):
"""
Retrieve all database values and put into vars to reduce database reads later on
"""
self._dbTableValues = list()
for row in self.databaseFetch(tableName=self._activeDataBase, query='SELECT * FROM :__table__ '):
if row:
self._dbTableValues.append(row)
self._dbSiteList = [x['SiteID'] for x in self._dbTableValues] # get list of SiteId for use on an Alice restart
self._dbTimeStampList = [x['timestamp'] for x in self._dbTableValues] # get list of TimeStamps
self._dbMessageList = [x['message'] for x in self._dbTableValues] # get the list of messages
self._dbRowIdList = [x['internalId'] for x in self._dbTableValues] # get The list of row ID's
self._TimerEventType = [x['EventType'] for x in self._dbTableValues] # get event type from db
self.cleanupDeadTimers()
### - Alice/User QUESTION AND ANSWERS - ###
# Returns the remaining time left on a choosen timer
def getTimeRemaining(self, session: DialogSession):
convertedTime = self.convertEpochMinusNowToHumanReadableTime()
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondTimeRemaining', replace=[convertedTime, self._eventType]),
deviceUid=session.deviceUid
)
# This starts the process of asking the user what item to look up in the list of timers/alarms
def getItemFromList(self, session: DialogSession, currentEvent :str):
completeMessageString = ''
i = 0
# Reads a list of items and adds it to one string
for x in self._dbMessageList:
i += 1
commonString = f'The {self._eventType} number {i} <break time=\"250ms\"/>.'
completeMessageString = f'{completeMessageString} {commonString} {x} <break time=\"250ms\"/>,'
if len(self._dbMessageList) == 0:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondNoActive', replace=[self._eventType])
)
elif len(self._dbMessageList) == 1:
self._selectedMessages = self._dbMessageList[0]
if 'delete' in currentEvent:
self.deleteRequestedReminder(session)
elif f'timeRemaining' in currentEvent:
self.getTimeRemaining(session)
elif f'stopReminder' in currentEvent:
self.userAskedToStopReminder(session)
else:
return
else:
self.askForWhichItems(session, self._dbMessageList, completeMessageString, currentEvent=currentEvent)
# This is used for asking the user to select the item from a list and return it to extractRequestedItemFromList()
def askForWhichItems(self, session: DialogSession, dbMessageList: list, completeMessageString: str, currentEvent: str):
dbMessageList.insert(0, self._eventType)
self.continueDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondListOfItems', replace=[completeMessageString]), # replace=[message for message in self._dbMessageList]),
intentFilter=[self._INTENT_SELECT_ITEM],
currentDialogState='askWhatItemFromList',
probabilityThreshold=0.1,
customData={
"currentEvent" : currentEvent
},
slot='Number'
)
del dbMessageList[0]
# This currently returns the selected number to extractRequestedItemFromList()
def extractRequestedItemFromList(self, session: DialogSession):
intent = session.intentName
if intent == self._INTENT_SELECT_ITEM:
if 'Number' in session.slotsAsObjects:
if session.slotValue('Number') > len(self._dbMessageList):
self.logWarning(f'That number appears to be invalid')
self.getItemFromList(session, currentEvent='')
return
itemChosen = session.slotValue('Number')
itemChosen = int(itemChosen) - 1 # turn float into an int then subtract 1 for indexing the list
self._selectedMessages = self._dbMessageList[itemChosen] # extract the actual requested message
if 'delete' in session.customData['currentEvent']:
self.deleteRequestedReminder(session)
elif 'timeRemaining' in session.customData['currentEvent']:
self.getTimeRemaining(session)
elif 'stopReminder' in session.customData['currentEvent']:
self.userAskedToStopReminder(session)
else:
self.continueDialog(
sessionId=session.sessionId,
text='respondNoNumber',
intentFilter=[self._INTENT_SELECT_ITEM],
currentDialogState='askWhatItemFromList'
)
else:
self.logWarning(f'The expected Intent was not received')
# This stops a current timer on request
def userAskedToStopReminder(self, session: DialogSession):
self.setEventType(session)
# noinspection SqlResolve
self.DatabaseManager.delete(
tableName=self._activeDataBase,
query='DELETE FROM :__table__ WHERE message = :tmpMessage',
values={'tmpMessage': self._selectedMessages},
callerName=self.name)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('respondDelete', replace=[self._eventType]),
deviceUid=session.deviceUid
)
self.cleanupDeadTimers()
### - TIME CONVERSION METHODS - ###
def findTheSeconds(self, session):
"""
Calculate the seconds the user has requested for the event
:param session: The dialog session
:return: food = True if it's a food timer, secs = Duration of the timer in seconds
"""
# Below is a safeguard for if a user uses telegram or dialog view to set an event
# Check if CustomData is used due to continueDialog not transferring session data as per normal
# When using dialogView or Telegram
try :
if session.customData['seconds'] > 0 :
return session.customData['food'], session.customData['seconds']
except:
pass
# Continue as noraml if the session has slot data etc
secs : int = 0
if 'Duration' in session.slots:
self._secondsDuration = self.Commons.getDuration(session)
secs = self._secondsDuration
if 'ReminderDateAndTime' in session.slotsAsObjects:
self._spokenDuration = session.slotValue('ReminderDateAndTime').split() # returns format [2020-04-08, 10:25:00, +10]
del self._spokenDuration[-1] # Removes the timezone off the end
self._dateTimeStr = ' '.join(self._spokenDuration) # converts the list to a string
self._dateTimeObject = datetime.strptime(self._dateTimeStr, '%Y-%m-%d %H:%M:%S')
self._secondsDuration = self._dateTimeObject - datetime.today() # find the difference between requested time and now
secs = round(self._secondsDuration.total_seconds())
food = False
if 'Food' in session.slots:
food = True
return food, secs
@staticmethod
def createEpochTimeStamp(seconds: int) -> int:
"""
Creates an Epoch timestamp
:param seconds: The requested seconds
:return: epoch :int - The Epoch timestamp
"""
timeStampForDatabase = datetime.now() + timedelta(seconds=seconds)
dateTime = str(timeStampForDatabase)
pattern = '%Y-%m-%d %H:%M:%S.%f'
epoch = int(time.mktime(time.strptime(dateTime, pattern)))
return epoch
# Used to Convert the Database Timestamp into seconds
def convertEpochMinusNowToSeconds(self, epochSeconds: int = None) -> float:
epochTimeNow = datetime.now().timestamp() # Returns the epoch time for right now
indexPos = 0
i = 0
if epochSeconds is not None:
epoch2Seconds = (epochSeconds - epochTimeNow)
return epoch2Seconds
else:
length = len(self._dbTableValues)
while i < length:
if self._selectedMessages in self._dbTableValues[i]:
indexPos = i
break
i += 1
timestampActual = self._dbTableValues[indexPos]['timestamp']
differenceInSeconds = (timestampActual - epochTimeNow)
return differenceInSeconds
# Converts Epoch time from DB to a Human readable output
def convertEpochMinusNowToHumanReadableTime(self) -> str:
convertedToSeconds = self.convertEpochMinusNowToSeconds()
return str(timedelta(seconds=round(convertedToSeconds)))
### - onXXXX calls - ###
# This does a 5-minute check of the stored timers and if a timer is within 299 seconds of activating
# then we initiate the actual timer thread
def onFiveMinute(self):
self.viewTableValues()
i = 0
while i <= len(self._dataBaseList) - 1:
self._activeDataBase = self._dataBaseList[i]
if 'MyReminder' in self._activeDataBase:
self._eventType = 'Reminder'
elif 'MyTimer' in self._activeDataBase:
self._eventType = 'Timer'
else:
self._eventType = 'Alarm'
self.viewTableValues()
self.logDebug(f'Checking for active timers in {self._activeDataBase} database')
for x in self._dbTableValues:
timerMessage = x['message']
self._TimerEventType = x['EventType']
theSeconds = x['timestamp']
convertedTime = self.convertEpochMinusNowToSeconds(theSeconds)
float(convertedTime)
vocalSeconds = str(timedelta(seconds=round(convertedTime)))
self.logDebug(f'You have a {self._TimerEventType} with {vocalSeconds} left on it')
cleanUpSeconds = convertedTime + 20.0
if convertedTime < 299.0:
self.ThreadManager.doLater(
interval=convertedTime,
func=self.runReminder,
args=[self._TimerEventType, timerMessage]
)
self.ThreadManager.doLater(
interval=cleanUpSeconds,
func=self.viewTableValues
)
i += 1
# Cleanup the Db on boot up
def onStart(self):
super().onStart()
self.logInfo(f'Doing database maintenance')
self.cleanupDeadTimers()
self.onFiveMinute()
def onBooted(self) -> bool:
self._theDeviceId = self.DeviceManager.getMainDevice().uid
super().onBooted()
return True
# Critical method for allowing reminder/timer/alarm to all play nicely together
def setEventType(self, session: DialogSession):
self._theDeviceId = session.deviceUid
if 'ReminderEvent' in session.slots:
self._eventType = session.slotValue('ReminderEvent')
if 'Reminder' in self._eventType:
self._activeDataBase = self._REMINDERDBNAME
elif 'Timer' in self._eventType:
self._activeDataBase = self._TIMERDBNAME
else:
self._activeDataBase= self._ALARMDBNAME
else:
self.logInfo(f"Weird, no event type set")
self.viewTableValues()
### - INTENTS - ###
# Used for deleting an item(s)
def deleteRemindersIntent(self, session: DialogSession):
self.setEventType(session)
if self._DELETE_ALL in session.slotValue('ReminderDelete'):
self.askIfTheDetailsAreCorrect(session)
else:
self.getItemFromList(session, currentEvent="delete")
# Used for when user asks how long left on timer
@IntentHandler('ReminderRemaining')
def remainingTimeReminderIntent(self, session: DialogSession):
self.setEventType(session)
if 'ReminderRemainingTime' in session.slots :
self.getItemFromList(session, currentEvent='timeRemaining')
# Used for stopping an event
@IntentHandler('ReminderStop')
def stopReminderIntent(self, session: DialogSession):
self.setEventType(session)
self.getItemFromList(session, currentEvent='stopReminder')