forked from NeonGeckoCom/skill-alerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
2014 lines (1809 loc) · 84 KB
/
__init__.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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework
# All trademark and other rights reserved by their respective owners
# Copyright 2008-2022 Neongecko.com Inc.
# Contributors: Daniel McKnight, Guy Daniels, Elon Gasper, Richard Leeds,
# Regina Bloomstine, Casimiro Ferreira, Andrii Pernatii, Kirill Hrymailo
# BSD-3 License
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import time
from datetime import datetime, timedelta
from threading import RLock
from typing import List, Optional
from dateutil.relativedelta import relativedelta
from ovos_bus_client.message import Message
from ovos_date_parser import nice_date_time, nice_time, nice_duration
from ovos_number_parser import pronounce_number
from ovos_skill_alerts.util import AlertState, MatchLevel, AlertPriority, WEEKDAYS
from ovos_skill_alerts.util.alert import Alert, AlertType, DAVType, LOCAL_USER
from ovos_skill_alerts.util.alert_manager import AlertManager, SYNC_LOCK
from ovos_skill_alerts.util.config import use_24h_format, get_default_tz, DEFAULT_SETTINGS
from ovos_skill_alerts.util.locale import (
translate,
voc_match,
spoken_duration,
spoken_alert_type,
spoken_weekday,
get_alert_dialog_data,
get_alert_type_from_intent,
datetime_display
)
from ovos_skill_alerts.util.media import (
ocp_query,
ocp_request,
get_media_source_from_intent
)
from ovos_skill_alerts.util.parse_utils import (
tokenize_utterance,
build_alert_from_intent,
parse_alert_name_from_message,
parse_alert_time_from_message,
parse_timedelta_from_message,
parse_relative_time_from_message,
parse_timeframe_from_message,
parse_alert_name_and_time_from_message,
parse_end_condition_from_message,
parse_alert_priority_from_message,
parse_audio_file_from_message,
parse_repeat_from_message,
get_week_range,
validate_dt_or_delta,
validate_number,
fuzzy_match,
fuzzy_match_alerts
)
from ovos_skill_alerts.util.ui_models import build_gui_data
from ovos_utils import create_daemon, classproperty
from ovos_utils.log import LOG
from ovos_utils.process_utils import RuntimeRequirements
from ovos_utils.sound import play_audio
from ovos_utterance_normalizer import UtteranceNormalizerPlugin
from ovos_workshop.decorators import intent_handler
from ovos_workshop.intents import IntentBuilder
from ovos_workshop.skills import OVOSSkill
from ovos_workshop.skills.ovos import join_word_list
class AlertSkill(OVOSSkill):
def __init__(self, *args, **kwargs):
# kwarg only used for unittests
if "alerts_path" in kwargs:
self.alerts_path = kwargs.pop("alerts_path")
else:
self.alerts_path = None
self._alert_manager = None
self._gui_timer_lock = RLock()
super().__init__(*args, **kwargs)
@classproperty
def runtime_requirements(self):
return RuntimeRequirements(internet_before_load=False,
network_before_load=False,
gui_before_load=False,
requires_internet=False,
requires_network=False,
requires_gui=False,
no_internet_fallback=True,
no_network_fallback=True,
no_gui_fallback=True)
@property
def alert_manager(self) -> AlertManager:
"""
Get the AlertManager that tracks all Alert objects and their statuses.
"""
if not self._alert_manager:
raise RuntimeError("Requested AlertManager before initialize")
return self._alert_manager
@property
def speak_alarm(self) -> bool:
"""
If true, speak dialog for expired alarms instead of playing audio files.
"""
return self.settings.get('speak_alarm', False)
@property
def speak_timer(self) -> bool:
"""
If true, speak dialog for expired alarms instead of playing audio files.
"""
return self.settings.get('speak_timer', True)
@property
def alarm_sound_file(self) -> str:
"""
Return the path to a valid alarm sound resource file
"""
filename = self.settings.get('sound_alarm') or 'default-alarm.wav'
if os.path.isfile(filename):
return filename
file = self.find_resource(filename)
if not file:
LOG.warning(f'Could not resolve requested file: {filename}')
file = os.path.join(os.path.dirname(__file__), 'res', 'snd',
'default-alarm.wav')
if not file:
raise FileNotFoundError(f"Could not resolve sound: {filename}")
return file
@property
def timer_sound_file(self) -> str:
"""
Return the path to a valid timer sound resource file
"""
filename = self.settings.get('sound_timer') or 'default-timer.wav'
if os.path.isfile(filename):
return filename
file = self.find_resource(filename)
if not file:
LOG.warning(f'Could not resolve requested file: {filename}')
file = os.path.join(os.path.dirname(__file__), 'res', 'snd',
'default-timer.wav')
if not file:
raise FileNotFoundError(f"Could not resolve sound: {filename}")
return file
@property
def play_volume(self) -> int:
"""
Return the volume to play audio files at
"""
LOG.debug(f"play_volume: {int(self.settings.get('play_volume', 100))}")
return int(self.settings.get('play_volume', 100)) / 100
@property
def snooze_duration(self) -> timedelta:
"""
Get default snooze duration
"""
snooze_minutes = self.settings.get('snooze_mins') or 15
if not isinstance(snooze_minutes, int):
LOG.error(f'Invalid `snooze_minutes` in settings. '
f'Expected int but got: {snooze_minutes}')
snooze_minutes = 15
return timedelta(minutes=snooze_minutes)
@property
def alert_timeout_seconds(self) -> int:
"""
Return the number of seconds to repeat an alert before marking it missed
"""
timeout_minutes = self.settings.get('timeout_min') or 1
if not isinstance(timeout_minutes, (int, float,)):
LOG.error(f'Invalid `timeout_min` in settings. '
f'Expected int/float but got: {type(timeout_minutes)}')
timeout_minutes = 1
return 60 * timeout_minutes
@property
def use_24hour(self) -> bool:
return use_24h_format()
def initialize(self):
# merge default settings
for k, v in DEFAULT_SETTINGS.items():
if k not in self.settings:
self.settings[k] = v
# Initialize manager with any cached alerts
self._alert_manager = AlertManager(
self.alerts_path or self.file_system.path,
self.event_scheduler,
(
self._alert_prenotification,
self._alert_expired,
),
)
self.dav_services = list()
self.sync_frequency: int = 0
# settings callback
self.settings_change_callback = self._init_dav_clients
# Update Homescreen UI models
# this is (falsely) assuming gui connected == skill homescreen
if self.gui.connected:
self.add_event("ovos.homescreen.displayed", self.on_ready, once=True) # homescreen >0.0.3a6
else:
self.add_event("mycroft.ready", self.on_ready, once=True)
self.add_event("ovos.alerts.get_alerts", self._event_get_alerts)
self.add_event("ovos.alerts.dismiss_notification",
self._gui_dismiss_notification)
self.add_event("ovos.gui.show.active.timers", self._on_display_gui)
self.add_event("ovos.gui.show.active.alarms", self._on_display_gui)
self.gui.register_handler("ovos.alerts.cancel_timer",
self._gui_cancel_timer)
self.gui.register_handler("ovos.alerts.cancel_alarm",
self._event_cancel_alarm)
self.add_event("ovos.alerts.cancel_alarm",
self._event_cancel_alarm)
self.gui.register_handler("ovos.alerts.snooze_alarm",
self._event_snooze_alarm)
self.add_event("ovos.alerts.snooze_alarm",
self._event_snooze_alarm)
def on_ready(self, _: Message):
"""
On ready, update the Home screen elements
"""
# wait until gui is ready to receive update_homescreen messages
time.sleep(2)
self._update_homescreen()
self._init_dav_clients()
def _init_dav_clients(self):
# Initialize DAV clients and voice errors regarding DAV
with SYNC_LOCK:
dav_services = self.settings.get("services", "").split(",")
sync_frequency = int(self.settings.get("frequency", 15))
if dav_services != self.dav_services or \
sync_frequency != self.sync_frequency:
if dav_services[0]:
LOG.debug(f"Init DAV Client for {','.join(dav_services)}")
errors = self._alert_manager.init_dav_clients(dav_services,
sync_frequency)
for dialog, services in errors.items():
if services:
self.speak_dialog(dialog,
{"services": join_word_list(services,
connector="and",
sep=",",
lang=self.lang)})
self.dav_services = dav_services
self.sync_frequency = sync_frequency
# Intent Handlers
#@killable_intent()
@intent_handler(IntentBuilder("CreateAlarm").require("alarm")
.require("create").optionally("question")
.optionally("playable").optionally("weekdays")
.optionally("weekends").optionally("everyday")
.optionally("repeat").optionally("until")
.optionally("priority"))
def handle_create_alarm(self, message: Message):
"""
Intent handler for creating an alarm
:param message: Message associated with request
"""
alarm = build_alert_from_intent(message)
if alarm.expiration is None:
time_ = self.get_response(
"alarm_ask_time", validator=validate_dt_or_delta, num_retries=0
)
if isinstance(time_, datetime):
alarm.expiration = time_
elif isinstance(time_, timedelta):
alarm.expiration = alarm.created + time_
else:
self.speak_dialog("error_no_time", {"kind": "alarm"}, wait=True)
return
self.confirm_alert(alarm, message)
@intent_handler(IntentBuilder("CreateAlarmAlt").require("wake")
.optionally("question").optionally("playable")
.optionally("weekdays").optionally("weekends")
.optionally("everyday").optionally("repeat")
.optionally("until").optionally("priority"))
def handle_create_alarm_alt(self, message: Message):
"""
Alternate intent handler for creating an alarm
:param message: Message associated with request
"""
return self.handle_create_alarm(message)
@intent_handler(IntentBuilder("CreateOcpAlarm").require("alarm")
.require("media").require("create").optionally("question"))
def handle_ocp_alarm(self, message: Message):
if not self.bus.wait_for_response(Message("ovos.common_play.ping"),
"ovos.common_play.pong"):
return self.speak_dialog("ocp_missing")
ocp_result = self._ocp_query(message)
if ocp_result is None:
return self.speak_dialog("ocp_breaking_up")
alert_time = parse_alert_time_from_message(message)
# in case no time was specified, use the next upcoming alarm
if not alert_time:
alarms = self._get_alerts_list(AlertType.ALARM)
if not alarms:
return self.speak_dialog("list_alert_none_upcoming",
{"kind": spoken_alert_type(AlertType.ALARM, self.lang)})
alarms[0].ocp_request = ocp_result
else:
alarm = build_alert_from_intent(message)
alarm.ocp_request = ocp_result
assert alarm.media_type == "ocp"
self.confirm_alert(alarm, message)
@intent_handler(IntentBuilder("CreateOcpAlarmAlt").require("wake")
.require("media").optionally("question"))
def handle_ocp_alarm_alt(self, message: Message):
return self.handle_ocp_alarm(message)
#@killable_intent()
@intent_handler(IntentBuilder("CreateTimer").require("create")
.require("timer").optionally("question")
.optionally("until"))
def handle_create_timer(self, message: Message):
"""
Intent handler for creating a timer
:param message: Message associated with request
"""
alert = build_alert_from_intent(message)
# stopwatch mode (without time specified - counts from now)
# gets no expiration notification treatment
if alert.stopwatch_mode:
self.alert_manager._active_alerts[alert.ident] = alert
self.speak_dialog('confirm_timer_started', {"remaining": ""})
self._display_alert(alert)
self._activate()
return
self.confirm_alert(alert, message)
#@killable_intent()
@intent_handler(IntentBuilder("CreateReminder").require("create")
.require("reminder").optionally("question")
.optionally("playable").optionally("weekdays")
.optionally("weekends").optionally("everyday")
.optionally("repeat").optionally("until")
.optionally("priority"))
def handle_create_reminder(self, message: Message):
"""
Intent handler for creating a reminder
:param message: Message associated with request
"""
alert = build_alert_from_intent(message)
alert_type, spoken_type = get_alert_type_from_intent(message)
# if alert.alert_name is None:
# return
if alert.expiration is None:
time_ = self.get_response(
"reminder_ask_time", validator=validate_dt_or_delta, num_retries=0
)
#if response and response != "no":
if isinstance(time_, datetime):
alert.expiration = time_
elif isinstance(time_, timedelta):
alert.expiration = alert.created + time_
# will be handled as todo entry
else:
alert.alert_type = AlertType.TODO
alert.dav_type = DAVType.VTODO
return self.handle_create_todo(message, alert)
# check for overlapping reminder
overlapping = \
self.alert_manager.get_alerts_in_timeframe(alert.expiration,
alert.until,
alert_type)
if overlapping:
dialog_data = {"event": join_word_list([r.alert_name for r in overlapping],
connector="and", sep=",", lang=self.lang)}
end = [a.until for a in overlapping if a.until]
if end:
dialog_data["begin"] = nice_time(min([a.expiration for a in overlapping]), lang=self.lang)
dialog_data["end"] = nice_time(max(end), lang=self.lang)
dialog = "alert_overlapping_duration_ask"
else:
dialog_data["begin"] = join_word_list([nice_time(a.expiration, lang=self.lang) for a in overlapping],
connector="and", sep=",", lang=self.lang)
dialog = "alert_overlapping_ask"
if self.ask_yesno(dialog, dialog_data) in ("no", None):
return
if alert.alert_type == AlertType.EVENT:
self.ask_for_prenotification(alert)
if self.alert_manager.dav_active:
self.specify_dav_attributes(alert, spoken_type)
self.confirm_alert(alert, message)
#@killable_intent()
@intent_handler(IntentBuilder("CreateReminderAlt").require("remind")
.optionally("question").optionally("playable")
.optionally("weekdays").optionally("weekends")
.optionally("everyday").optionally("repeat")
.optionally("until"))
def handle_create_reminder_alt(self, message: Message):
"""
Alternate intent handler for creating a reminder
:param message: Message associated with request
"""
self.handle_create_reminder(message)
#@killable_intent()
@intent_handler(IntentBuilder("CreateEvent")
.require("create").require("event")
.optionally("question").optionally("playable")
.optionally("everyday").optionally("weekdays")
.optionally("weekends").optionally("repeat")
.optionally("until").optionally("priority")
.optionally("remind").optionally("all_day"))
def handle_create_event(self, message: Message):
"""
Intent handler for creating an event. Wraps handle_create_reminder
:param message: Message associated with request
"""
LOG.debug("Create Event calling Reminder")
self.handle_create_reminder(message)
@intent_handler(IntentBuilder("RescheduleAlert")
.require("change").optionally("next")
.one_of("alarm", "reminder", "event", "timer")
.optionally("question").optionally("earlier")
.optionally("all_day"))
def handle_reschedule_alert(self, message: Message):
"""
Intent to reschedule an alarm, reminder, event or timer
:param message: Message associated with request
"""
alert_type, spoken_type = get_alert_type_from_intent(message)
alert = self._resolve_requested_alert(message, alert_type)
if alert is None:
return self.speak_dialog("error_no_scheduled_kind",
{"kind": spoken_type}, wait=True)
# ref_day = convenience experimental because of repeating alerts
# user only have to state the time instead remembering the day
ref_day = alert.expiration.replace(hour=0, minute=0, second=0)
anchor_time = ref_day if alert.has_repeat else None
if message.data.get("all_day"):
# the appropriate time is set by the object
alert.is_all_day = True
rescheduled_time = alert.expiration.date()
dialog = "alert_rescheduled_all_day"
else:
alert.is_all_day = False
rescheduled_time = parse_relative_time_from_message(message, anchor_time=anchor_time)
dialog = "alert_rescheduled"
if rescheduled_time is None:
return self.speak_dialog("error_no_time", {"kind": spoken_type}, wait=True)
once = True
if alert.has_repeat and \
self.ask_yesno("reschedule_recurring_ask",
{"type": spoken_type}) == "yes":
once = False
rescheduled = self.alert_manager.reschedule_alert(alert, rescheduled_time, once)
self._display_alert(rescheduled)
dialog_data = get_alert_dialog_data(rescheduled, self.lang)
self.speak_dialog(dialog, dialog_data, wait=True)
# ask if prenotification should be adjusted
if rescheduled.prenotification:
self.ask_for_prenotification(rescheduled,
"alert_rescheduled_prenotification",
dialog_data)
@intent_handler(IntentBuilder("RescheduleAlertAlt")
.one_of("earlier", "later").optionally("next")
.one_of("alarm", "reminder", "event", "timer")
.optionally("question"))
def handle_reschedule_alert_alt(self, message: Message):
LOG.debug("alt schedule")
return self.handle_reschedule_alert(message)
@intent_handler(IntentBuilder("ChangeProperties")
.require("change").optionally("next")
.one_of("alarm", "reminder", "event", "timer")
.one_of("until", "repeat", "priority")
.optionally("weekdays").optionally("weekends")
.optionally("everyday").optionally("question"))
def handle_change_properties(self, message: Message):
"""
Intent to reschedule an alarm, reminder, event or timer
:param message: Message associated with request
"""
alert_type, spoken_type = get_alert_type_from_intent(message)
alert: Alert = self._resolve_requested_alert(message, alert_type)
if alert is None:
return self.speak_dialog("error_no_scheduled_kind",
{"kind": spoken_type}, wait=True)
if message.data.get("priority"):
old_priority = alert.priority
priority = parse_alert_priority_from_message(message)
if old_priority != priority:
alert.priority = priority
self.speak_dialog("property_changed_priority",
{"num": priority})
else:
return self.speak_dialog("error_same_priority")
elif message.data.get("until"):
end = parse_end_condition_from_message(message)
if end:
alert.until = end
dialog_data = get_alert_dialog_data(alert, self.lang)
self.speak_dialog("alert_rescheduled_end", dialog_data)
else:
return self.speak_dialog("error_no_time", {"kind": spoken_type})
elif message.data.get("repeat"):
repeat = parse_repeat_from_message(message)
if repeat:
if self.alert_manager.reschedule_repeat(alert, repeat):
dialog_data = get_alert_dialog_data(alert, self.lang)
self.speak_dialog("alert_rescheduled_repeat", dialog_data)
else:
pass
else:
self.speak_dialog("error_no_repeat", {"kind": spoken_type})
else:
return
self._display_alert(alert)
self.alert_manager.sync_dav_item(alert)
@intent_handler(IntentBuilder("ChangeMediaProperties")
.require("change").optionally("next")
.one_of("alarm", "reminder", "event", "timer")
.require("playable"))
def handle_change_media_properties(self, message: Message):
alert_type, spoken_type = get_alert_type_from_intent(message)
alert: Alert = self._resolve_requested_alert(message, alert_type)
old_media = alert.media_type
new_media = get_media_source_from_intent(message)
if new_media == "file":
audio = parse_audio_file_from_message(message)
if audio:
alert.audio_file = f"file:/{audio}"
else:
return self.speak_dialog("error_no_script", {"kind": spoken_type})
if old_media:
self.speak_dialog("media_type_changed",
{"old": translate(old_media, lang=self.lang),
"new": translate(new_media, lang=self.lang)})
else:
self.speak_dialog("media_type_set",
{"new": translate(new_media, lang=self.lang)})
# Query Alerts
@intent_handler(IntentBuilder("ListAlerts").require("query")
.one_of("alarm", "reminder", "event", "alert", "remind")
.optionally("and").optionally("stored"))
def handle_event_timeframe_check(self, message: Message):
"""
Intent to check if there are events stored at a given datetime /
within a given timeframe. If no datetime is passed list all of given type
Examples:
Are there any events pending between monday 10:00 am and 12:00 am
Are there any events stored on tuesday
Are there any events at 8 pm
:param message: Message associated with request
"""
normalizer = UtteranceNormalizerPlugin.get_normalizer(lang=self.lang)
utterance = normalizer.normalize(message.data.get("utterance", "")).lower()
alert_type, spoken_type = get_alert_type_from_intent(message)
begin, end = parse_timeframe_from_message(message)
# week range
if self.voc_match("week", utterance):
now = datetime.now(get_default_tz())
# hack bc LF return None on "this week"
begin, end = get_week_range(begin or now)
elif not begin and not end:
if self.voc_match("next", utterance):
return self.handle_next_alert(message)
return self.handle_list_all_alerts(message)
overlapping = self.alert_manager.get_alerts_in_timeframe(begin,
end,
alert_type)
if overlapping:
self._display_alerts(alert_type, overlapping)
self.speak_dialog("list_alert_timeframe_intro",
{"num": len(overlapping),
"type": spoken_type})
for alert in overlapping:
data = get_alert_dialog_data(alert, self.lang, begin)
if "end" in data and not alert.is_all_day:
self.speak_dialog("list_alert_w_duration", data)
else:
self.speak_dialog("list_alert_wo_duration", data)
else:
self.speak_dialog("list_alert_timeframe_none")
def handle_list_all_alerts(self, message: Message):
"""
Handler to handle request for all alerts (kind optional)
:param message: Message associated with request
"""
alert_type, spoken_type = get_alert_type_from_intent(message)
alerts_list = self._get_alerts_list(alert_type,
disposition=AlertState.PENDING)
if not alerts_list:
self.speak_dialog("list_alert_none_upcoming",
{"kind": spoken_type}, wait=True)
return
self._display_alerts(alert_type, alerts_list)
if message.data.get("alert"):
kinds = {(a.alert_type.value, spoken_alert_type(a.alert_type))
for a in alerts_list if a.expiration is not None}
else:
kinds = {(alert_type.value, spoken_type)}
# Restrict to max 10(?) alerts
if len(alerts_list) > 10:
alerts_list = alerts_list[:10]
for id, kind in kinds:
self.speak_dialog("list_alert_intro", {"kind": kind},
wait=True)
for alert in alerts_list:
if alert.alert_type.value != id:
continue
data = get_alert_dialog_data(alert, self.lang)
dialog = ""
if data["name"]:
dialog = f"{data['name']} -"
if "repeat" in data:
dialog = f"{dialog} {self.resources.render_dialog('repeating_every', data)}"
if alert_type == AlertType.TIMER:
dialog = f"{dialog} {self.resources.render_dialog('in_time', data)}\n"
else:
dialog = f"{dialog} {self.resources.render_dialog('at_time', data)}\n"
self.speak(dialog, wait=True)
# short break in between different alert types
time.sleep(1)
def handle_next_alert(self, message: Message):
"""
Intent handler to handle request for the next alert (kind optional)
:param message: Message associated with request
"""
alert_type, spoken_type = get_alert_type_from_intent(message)
alerts_list = self._get_alerts_list(alert_type,
disposition=AlertState.PENDING)
if not alerts_list:
return self.speak_dialog("list_alert_none_upcoming",
{"kind": spoken_type},
wait=True)
alert = alerts_list[0] # sorted time ascending
data = get_alert_dialog_data(alert, self.lang)
self._display_alert(alert)
if alert.alert_type == AlertType.TIMER:
dialog = "next_alert_timer"
else:
dialog = "next_alert"
self.speak_dialog(dialog, data, wait=True)
@intent_handler(IntentBuilder("TimerStatus").one_of("time", "timer").require("remaining").optionally("query"))
def handle_timer_status(self, message: Message):
"""
Intent handler to handle request for timer status (name optional)
:param message: Message associated with request
"""
name = parse_alert_name_from_message(message)
user_timers = self._get_alerts_list(AlertType.TIMER, name=name)
if not user_timers:
return self.speak_dialog("timer_status_none_active", wait=True)
# show timers if not already up
self._display_alerts(AlertType.TIMER, user_timers)
for i, timer in enumerate(user_timers):
dialog_data = get_alert_dialog_data(timer, self.lang)
if not dialog_data["name"] and len(user_timers) > 1:
dialog_data["name"] = pronounce_number(i + 1, ordinals=True)
self.speak_dialog("timer_status", dialog_data, wait=True)
# TODO - connect this to naptime skill - mycroft.awoken bus message
@intent_handler("missed_alerts.intent")
def handle_missed_alerts(self, _: Message):
"""
Intent to handle any alerts that have been missed.
:param message: Message associated with request
"""
missed_alerts = self._get_alerts_list(AlertType.ALL,
disposition=AlertState.MISSED)
if missed_alerts: # TODO: Unit test this DM
self.speak_dialog("list_alert_missed_intro", wait=True)
for alert in missed_alerts:
data = get_alert_dialog_data(alert, self.lang)
self.speak_dialog("list_alert_missed", data, wait=True)
self._dismiss_alert(alert.ident, speak=False)
else:
self.speak_dialog("list_alert_none_missed", wait=True)
@intent_handler(IntentBuilder("CancelAlert").require("cancel")
.optionally("stored").optionally("next").optionally("and")
.one_of("alarm", "timer", "reminder", "event", "alert"))
def handle_cancel_alert(self, message: Message):
"""
Intent handler to handle request to cancel alerts
:param message: Message associated with request
"""
alert_type, spoken_type = get_alert_type_from_intent(message)
begin, end = parse_timeframe_from_message(message)
if begin and end:
alerts = self.alert_manager.get_alerts_in_timeframe(begin,
end,
alert_type)
else:
alerts = self._get_alerts_list(alert_type,
disposition=AlertState.PENDING)
# Notify nothing to cancel
if not alerts:
if alert_type in (AlertType.ALL, AlertType.UNKNOWN):
self.speak_dialog("error_nothing_to_cancel", wait=True)
else:
self.speak_dialog("error_no_scheduled_kind",
{"kind": spoken_type}, wait=True)
return
# Cancel all alerts of some specified type
if message.data.get("stored") or (begin and end):
# TODO add saveguard for DAV conten?
for alert in alerts:
self._dismiss_alert(alert.ident, drop_dav=True)
return self.speak_dialog("confirm_cancel_timeframe" if begin else "confirm_cancel_all",
{"kind": spoken_type, "num": len(alerts)},
wait=True)
# Only one candidate alert
elif len(alerts) == 1 or message.data.get("next"):
alert = alerts[0]
# Resolve the requested alert
else:
alert = self._resolve_requested_alert(message, alert_type)
if alert is None:
self.speak_dialog("error_nothing_to_cancel", wait=True)
return
# if default name, replace alert_type substring
name = alert.alert_name.replace(spoken_type, "").strip()
self._dismiss_alert(alert.ident, drop_dav=True)
self.speak_dialog('confirm_cancel_alert',
{'kind': spoken_type,
'name': name}, wait=True)
# Todo Lists
#@killable_intent()
@intent_handler(IntentBuilder("CreateList").require("create").require("list"))
def handle_create_todo(self, message: Message, alert: Optional[Alert] = None):
"""
Intent to create a todo list
:param message: Message associated with request
"""
if alert:
name = alert.alert_name
else:
name = parse_alert_name_from_message(message)
todo_lists = self._get_alerts_list(AlertType.TODO, name=name)
if todo_lists:
self.speak_dialog(
"list_todo_already_exist", {"name": name}, wait=True
)
return
if not alert:
alert = Alert.create(
alert_name=name, alert_type=AlertType.TODO, dav_type=DAVType.VTODO, lang=self.lang
)
if self.alert_manager.dav_active:
self.specify_dav_attributes(alert,
spoken_alert_type(AlertType.TODO, self.lang))
self.alert_manager.add_alert(alert)
# NOTE: the alert might be a redirected reminder
if "list" in message.data:
return self.handle_add_subitem_to_todo(message)
self.speak_dialog("confirm_todo_set", wait=True)
#@killable_intent()
@intent_handler(
IntentBuilder("AddListSubitems")
.require("create").require("list").require("items")
)
def handle_add_subitem_to_todo(self, message: Message):
"""
Intent to add a/multiple subitems to an existing todo list (eg shopping)
:param message: Message associated with request
"""
name = parse_alert_name_from_message(message)
todo = self._resolve_requested_alert(message, AlertType.TODO)
if todo is None:
return self.speak_dialog("list_todo_dont_exist", {"name": name})
# I guess the best bet is to voice out/show the existing entries to avoid duplicates
if len(todo.children) > 0:
self.handle_todo_list_entries(alert=todo)
# get_response in rapid sucession
items = self._get_response_cascade(
"list_todo_add_ask",
data={"name": todo.alert_name, "lang": self.lang},
message=message
)
for item in items:
alert = Alert.create(
alert_name=item,
alert_type=AlertType.TODO,
dav_calendar=todo.calendar,
dav_service=todo.service,
context=dict(related_to=todo.ident),
lang=self.lang
)
self.alert_manager.add_alert(alert)
self.speak_dialog(
"list_todo_subitems_added",
{"num": pronounce_number(len(items))},
)
@intent_handler(
IntentBuilder("QueryListNames")
.require("query").require("list").optionally("stored")
)
def handle_query_todo_list_names(self, message: Message):
"""
Intent to get a list of todos (todos WITH subitems)
:param message: Message associated with request
"""
# only lists
todos = self.alert_manager.get_connected_alerts(type=AlertType.TODO)
names = [todo.alert_name for todo in todos]
LOG.debug(names)
if todos:
if self.gui.connected:
self._display_list(todos)
self.speak_dialog(
"list_todo_lists",
{"num": pronounce_number(len(names)),
"lists": join_word_list(names, connector="and", sep=",", lang=self.lang)},
)
else:
self.speak_dialog("list_todo_no_lists")
@intent_handler(
IntentBuilder("QueryTodoEntries")
.require("query").require("todo").optionally("items")
.optionally("stored")
)
def handle_query_todo_reminder_names(self, message: Message):
"""
Intent to get a list of todos (todos WITHOUT subitems)
:param message: Message associated with request
"""
# only todos without children (and parents)
todos = self.alert_manager.get_unconnected_alerts(type=AlertType.TODO)
if todos:
if self.gui.connected:
self._display_list(todos)
self.speak_dialog(
"list_todo_reminder",
{"reminders": join_word_list([todo.alert_name for todo in todos],
connector="and", sep=",", lang=self.lang)},
)
else:
self.speak_dialog("list_todo_no_reminder")
@intent_handler(
IntentBuilder("QueryListEntries")
.require("query").require("list").require("items")
)
def handle_todo_list_entries(self, message: Optional[Message] = None, alert: Optional[Alert] = None):
"""
Intent to get the items from a specific todo list
:param message: Message associated with request
"""
if message:
name = parse_alert_name_from_message(message)
alert = self._resolve_requested_alert(message, AlertType.TODO)
if alert is None:
return self.speak_dialog("list_todo_dont_exist", {"name": name})
list_entries = self.alert_manager.get_children(alert.ident)
if list_entries:
self.speak_dialog(
"list_todo_subitems",
{"name": alert.alert_name,
"items": join_word_list([alert.alert_name for alert in list_entries],
connector="and", sep=",", lang=self.lang)},
wait=True,
)
else:
self.speak_dialog("list_todo_no_subitems")
if list_entries and self.gui.connected:
self._display_list(list_entries, alert.alert_name)
# delay if this handler is used in context
time.sleep(2)
#@killable_intent()
@intent_handler(
IntentBuilder("DeleteListEntries")
.require("delete").require("items").require("list").optionally("stored")
)
def handle_delete_todo_list_entries(self, message: Message):
"""
Intent to delete one or more todo items
:param message: Message associated with request
"""
todo = self._resolve_requested_alert(message,
AlertType.TODO,
dialog="list_item_delete_selection_intro")
if todo is None:
return
if message.data.get("stored"):
to_delete = [todo.alert_name for todo in
self.alert_manager.get_children(todo.ident)]
else:
# show/voice entries
self.handle_todo_list_entries(alert=todo)
to_delete = self._get_response_cascade("remove_list_items_ask",
{"lang": self.lang},
message=message)
deleted = to_delete[:]
for item in to_delete:
entries = self._get_alerts_list(AlertType.TODO, name=item)
# ensure no entries from another list
entries = list(
filter(lambda alert: alert.related_to == todo.ident, entries)
)
entry = self._pick_one_by_name(entries, "pick_multiple_entries")
if entry:
self.alert_manager.mark_todo_complete(entry)
else: