Skip to content

Commit

Permalink
fix:pep8
Browse files Browse the repository at this point in the history
  • Loading branch information
JarbasAl committed Nov 12, 2024
1 parent 4a726ca commit 27b18d5
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 74 deletions.
9 changes: 4 additions & 5 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -949,7 +949,7 @@ def handle_todo_list_entries(self, message: Optional[Message] = None, alert: Opt
"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)},
connector="and", sep=",", lang=self.lang)},
wait=True,
)
else:
Expand Down Expand Up @@ -1043,7 +1043,7 @@ def handle_delete_todo_entries(self, message: Message):
self.speak_dialog(
"list_todo_subitems",
{"items": join_word_list([todo.alert_name for todo in todos],
connector="and", sep=",", lang=self.lang)},
connector="and", sep=",", lang=self.lang)},
wait=True,
)
time.sleep(2)
Expand Down Expand Up @@ -1163,8 +1163,8 @@ def confirm_alert(self, alert: Alert, message: Message,
repeat_interval = translate("weekday", lang=self.lang)
else:
repeat_interval = join_word_list([spoken_weekday(day, self.lang)
for day in alert.repeat_days],
connector="and", sep=",", lang=self.lang)
for day in alert.repeat_days],
connector="and", sep=",", lang=self.lang)

# Notify repeating alert
if alert.audio_file:
Expand Down Expand Up @@ -2012,4 +2012,3 @@ def stop(self):
LOG.debug(f"skill-stop called, all active alerts will be removed")
for alert in self.alert_manager.get_active_alerts():
self._dismiss_alert(alert.ident, speak=True)

114 changes: 55 additions & 59 deletions util/alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,32 +26,30 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from uuid import uuid4
import datetime as dt
from time import time
import json
from time import time
from typing import Set, Optional, Union, List
from uuid import uuid4

import icalendar
from dateutil.relativedelta import relativedelta
from json_database.utils import merge_dict
from ovos_utils.log import LOG
from ovos_config.locale import get_default_tz, get_default_lang
from ovos_config import Configuration


from ovos_config.locale import get_default_tz, get_default_lang
from ovos_skill_alerts.util import AlertType, DAVType, AlertPriority, Weekdays
from ovos_skill_alerts.util.dav_utils import process_ical_event, process_ical_todo
from ovos_utils.log import LOG

LOCAL_USER = "local"
TZID = Configuration().get("location", {}).get("timezone", {}).get("code") or "UTC"


def alert_time_in_range(
start: dt.datetime,
end: Optional[dt.datetime],
ref_start: dt.datetime,
ref_end: Optional[dt.datetime]
start: dt.datetime,
end: Optional[dt.datetime],
ref_start: dt.datetime,
ref_end: Optional[dt.datetime]
) -> bool:
"""
Checks if two alerts with given start and end datetimes
Expand All @@ -67,7 +65,7 @@ def alert_time_in_range(
return False
if end is not None:
return (start <= ref_start < end) \
or (start <= ref_end < end if ref_end else False)
or (start <= ref_end < end if ref_end else False)
# in this case it's the reverse question
return ref_start <= start < ref_end

Expand Down Expand Up @@ -98,8 +96,8 @@ def user(self) -> str:
Return the user associated with this alert
"""
return self.context.get("username") \
or self.context.get("user") \
or LOCAL_USER
or self.context.get("user") \
or LOCAL_USER

@property
def lang(self) -> str:
Expand All @@ -115,22 +113,22 @@ def created(self) -> dt.datetime:
"""
dt_ = dt.datetime.fromtimestamp(self.context.get("created"))
return dt_.astimezone(self.timezone).replace(microsecond=0)

@property
def stopwatch(self):
"""
Returns the time elapsed since the alert was created
"""
return self.now - self.created

@property
def stopwatch_mode(self):
"""
Returns the stopwatch mode
"""
return self.alert_type == AlertType.TIMER and \
self.context.get("stopwatch_mode", False)
self.context.get("stopwatch_mode", False)

@stopwatch_mode.setter
def stopwatch_mode(self, mode: bool):
"""
Expand All @@ -145,7 +143,7 @@ def timezone(self) -> dt.tzinfo:
"""
expiration = self._data.get("next_expiration_time")
return dt.datetime.fromisoformat(expiration).tzinfo if expiration \
else get_default_tz()
else get_default_tz()

@property
def alert_type(self) -> AlertType:
Expand Down Expand Up @@ -200,7 +198,7 @@ def priority(self) -> int:
:returns: the alert priority (1-10)
"""
return self._data.get("priority") or AlertPriority.AVERAGE.value

@priority.setter
def priority(self, num: int):
"""
Expand All @@ -225,7 +223,7 @@ def alert_name(self) -> str:
@property
def now(self):
return dt.datetime.now(tz=self.timezone)

# Expiration
@property
def prenotification(self) -> Optional[dt.datetime]:
Expand All @@ -237,7 +235,7 @@ def prenotification(self) -> Optional[dt.datetime]:
notification = self.expiration + dt.timedelta(
seconds=self._data.get("prenotification")
)
return notification if notification > self.now else None
return notification if notification > self.now else None

@prenotification.setter
def prenotification(self, time_: Union[dt.timedelta, dt.datetime, relativedelta, int]):
Expand Down Expand Up @@ -270,8 +268,8 @@ def expiration(self) -> Optional[dt.datetime]:
@expiration.setter
def expiration(self, new_expiration: Union[dt.datetime, dt.date]):
if new_expiration.__class__ == dt.date:
new_expiration = dt.datetime.combine(new_expiration, dt.time.min)\
.replace(tzinfo=self.timezone)
new_expiration = dt.datetime.combine(new_expiration, dt.time.min) \
.replace(tzinfo=self.timezone)
self._data["next_expiration_time"] = new_expiration.isoformat()

@property
Expand All @@ -293,7 +291,7 @@ def is_expired(self) -> bool:
return False
now = dt.datetime.now(self.timezone)
return now >= dt.datetime.fromisoformat(expiration)

@property
def is_all_day(self) -> bool:
"""
Expand All @@ -311,7 +309,7 @@ def is_all_day(self, all_day: bool):
self._data["all_day"] = all_day
if all_day:
self._data["next_expiration_time"] = \
(self.expiration.replace(hour=0, minute=0, second=0)).isoformat()
(self.expiration.replace(hour=0, minute=0, second=0)).isoformat()
self.until = (self.until or self.expiration).replace(hour=23, minute=59, second=59)

@property
Expand Down Expand Up @@ -348,14 +346,14 @@ def repeat_frequency(self) -> Optional[dt.timedelta]:
if self._data.get("repeat_frequency")
else None
)

@property
def has_repeat(self) -> bool:
"""
:returns: Whether the alert has any repeat information.
"""
return any((self.repeat_days, self.repeat_frequency))

def reset_repeat(self):
"""
Resets the expiration time to the last expiration (or to the
Expand All @@ -371,7 +369,7 @@ def reset_repeat(self):
elif self.repeat_frequency:
expiration = expiration - self.repeat_frequency
self._data["next_expiration_time"] = expiration.isoformat()

def remove_repeat(self) -> None:
"""
Purges repeat information
Expand All @@ -387,28 +385,28 @@ def until(self) -> Optional[dt.datetime]:
"""
end = self._data.get("until")
return dt.datetime.fromisoformat(end) if end else None

@until.setter
def until(self, end: Union[dt.datetime, dt.timedelta]) -> None:
if self.expiration is None:
raise Exception("You can't set an until without expiration")

# relative to expiration
if isinstance(end, dt.timedelta):
self._data["until"] = (self.expiration + end).isoformat()
elif isinstance(end, dt.datetime):
self._data["until"] = end.isoformat()
else:
raise TypeError("until must be a datetime or timedelta object")

# Media associated
@property
def audio_file(self) -> Optional[str]:
"""
Returns the audio filename launched on expiration
"""
return self._data.get("audio_file")

@property
def ocp_request(self) -> str:
"""
Expand All @@ -422,7 +420,7 @@ def ocp_request(self, request: Union[dict, None]):
if not isinstance(request, (dict, type(None))):
raise TypeError("'request' is supposed to be of type dict")
self._data["ocp"] = request

@property
def media_type(self):
"""
Expand All @@ -434,7 +432,7 @@ def media_type(self):
elif self.audio_file:
return "audio_file"
return None

@property
def media_source(self):
"""
Expand All @@ -446,7 +444,7 @@ def media_source(self):
elif self.audio_file:
return self.audio_file
return None

# DAV properties
@property
def service(self) -> Optional[str]:
Expand Down Expand Up @@ -572,8 +570,8 @@ def _get_next_expiration_time(self, skip=False) -> Optional[dt.datetime]:
expiration += self.repeat_frequency
elif self.repeat_days:
while (
expiration <= now
or Weekdays(expiration.weekday()) not in self.repeat_days
expiration <= now
or Weekdays(expiration.weekday()) not in self.repeat_days
):
expiration += dt.timedelta(days=1)
elif self.until is not None:
Expand All @@ -589,7 +587,7 @@ def _get_next_expiration_time(self, skip=False) -> Optional[dt.datetime]:
LOG.debug(f"New expiration set for {self.ident}({self.alert_name}): {expiration}")
return expiration

# Constructors
# Constructors
@staticmethod
def from_dict(alert_data: dict):
"""
Expand Down Expand Up @@ -619,7 +617,7 @@ def to_ical(self) -> icalendar.Calendar:
"""
ical = icalendar.Calendar()
expiration = self.expiration

if self.dav_type == DAVType.VEVENT:
component = icalendar.Event()
alarm = icalendar.Alarm()
Expand Down Expand Up @@ -670,20 +668,20 @@ def deserialize(alert_str: str):

@staticmethod
def create(
expiration: Union[dt.date, dt.datetime, str] = None,
prenotification: int = None,
alert_name: str = None,
alert_type: AlertType = AlertType.UNKNOWN,
dav_type: DAVType = DAVType.VEVENT,
priority: int = AlertPriority.AVERAGE.value,
repeat_frequency: Union[int, dt.timedelta] = None,
repeat_days: Set[Weekdays] = None,
until: Union[dt.datetime, str] = None,
audio_file: str = None,
dav_calendar: str = None,
dav_service: str = None,
context: dict = None,
lang: str = None
expiration: Union[dt.date, dt.datetime, str] = None,
prenotification: int = None,
alert_name: str = None,
alert_type: AlertType = AlertType.UNKNOWN,
dav_type: DAVType = DAVType.VEVENT,
priority: int = AlertPriority.AVERAGE.value,
repeat_frequency: Union[int, dt.timedelta] = None,
repeat_days: Set[Weekdays] = None,
until: Union[dt.datetime, str] = None,
audio_file: str = None,
dav_calendar: str = None,
dav_service: str = None,
context: dict = None,
lang: str = None
):
"""
Object representing an arbitrary alert
Expand All @@ -707,8 +705,8 @@ def create(
expiration = dt.datetime.fromisoformat(expiration)
elif expiration.__class__ == dt.date:
data["all_day"] = True
expiration = dt.datetime.combine(expiration, dt.time.min)\
.replace(tzinfo=get_default_tz())
expiration = dt.datetime.combine(expiration, dt.time.min) \
.replace(tzinfo=get_default_tz())
if not expiration.tzinfo:
raise ValueError("expiration missing tzinfo")
# Round off any microseconds
Expand Down Expand Up @@ -753,8 +751,7 @@ def create(
context["ident"] = str(uuid4())

data.update({
"next_expiration_time": expiration.isoformat() if expiration \
else None,
"next_expiration_time": expiration.isoformat() if expiration else None,
"prenotification": prenotification,
"alert_type": alert_type.value,
"dav_type": dav_type.value,
Expand Down Expand Up @@ -782,7 +779,7 @@ def is_alert_type(alert: Alert, alert_type: AlertType) -> bool:
"""
if alert_type == AlertType.ALL:
return True

return alert.alert_type == alert_type.value


Expand Down Expand Up @@ -811,4 +808,3 @@ def properties_changed(local: Alert, dav: Alert) -> bool:
local.until != dav.until
]
)

2 changes: 1 addition & 1 deletion util/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def spoken_duration(alert_time: Union[dt.timedelta, dt.datetime],
return nice_duration(int(_seconds), lang=lang)


def get_abbreviation(wd: Weekdays, lang = None) -> str:
def get_abbreviation(wd: Weekdays, lang=None) -> str:
if wd == Weekdays.MON:
return translate("abbreviation_monday", lang=lang)
elif wd == Weekdays.TUE:
Expand Down
2 changes: 1 addition & 1 deletion util/parse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

from dateutil.relativedelta import relativedelta
from ovos_bus_client.message import Message, dig_for_message
from ovos_bus_client.util import get_message_lang
from ovos_config.locale import get_default_lang, get_default_tz
from ovos_date_parser import nice_time, nice_day, extract_datetime, extract_duration
from ovos_number_parser import extract_number
Expand All @@ -49,7 +50,6 @@
from ovos_utils.log import LOG
from ovos_utterance_normalizer import UtteranceNormalizerPlugin
from rapidfuzz import fuzz
from ovos_bus_client.util import get_message_lang


class Tokens(list):
Expand Down
Loading

0 comments on commit 27b18d5

Please sign in to comment.