activity.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # -*- coding: utf-8 -*-
  2. """
  3. Activity Conditions - Aktivitätsbasierte Bedingungen.
  4. """
  5. from datetime import datetime, timedelta
  6. from typing import Any
  7. from trixy_core.scheduler.condition.base import Condition
  8. class RecentActivityCondition(Condition):
  9. """
  10. Prüft ob kürzlich Aktivität stattfand.
  11. Beispiel:
  12. - RecentActivityCondition("last_voice_input", minutes=10)
  13. → Nur wenn in letzten 10 Min. Voice-Input war
  14. - RecentActivityCondition("last_motion", seconds=30)
  15. → Nur wenn in letzten 30 Sek. Bewegung war
  16. """
  17. def __init__(
  18. self,
  19. activity_key: str,
  20. seconds: int = 0,
  21. minutes: int = 0,
  22. hours: int = 0,
  23. name: str | None = None,
  24. invert: bool = False,
  25. ):
  26. """
  27. Initialisiert die Condition.
  28. Args:
  29. activity_key: Schlüssel für Aktivitäts-Timestamp im Kontext
  30. seconds: Zeitfenster in Sekunden
  31. minutes: Zeitfenster in Minuten
  32. hours: Zeitfenster in Stunden
  33. name: Condition-Name
  34. invert: Ergebnis invertieren
  35. """
  36. super().__init__(name, invert)
  37. self._activity_key = activity_key
  38. self._window = timedelta(seconds=seconds, minutes=minutes, hours=hours)
  39. if self._window.total_seconds() <= 0:
  40. raise ValueError("Zeitfenster muss größer als 0 sein")
  41. @property
  42. def activity_key(self) -> str:
  43. """Aktivitäts-Schlüssel."""
  44. return self._activity_key
  45. @property
  46. def window(self) -> timedelta:
  47. """Zeitfenster."""
  48. return self._window
  49. def _evaluate(self, context: dict) -> bool:
  50. """Prüft ob Aktivität kürzlich war."""
  51. last_activity = context.get(self._activity_key)
  52. if not last_activity:
  53. return False
  54. # Timestamp parsen
  55. if isinstance(last_activity, str):
  56. try:
  57. last_activity = datetime.fromisoformat(last_activity)
  58. except ValueError:
  59. return False
  60. elif not isinstance(last_activity, datetime):
  61. return False
  62. now = context.get("current_time", datetime.now())
  63. if isinstance(now, str):
  64. now = datetime.fromisoformat(now)
  65. elapsed = now - last_activity
  66. return elapsed <= self._window
  67. def to_dict(self) -> dict:
  68. """Konvertiert zu Dictionary."""
  69. return {
  70. **self._base_dict(),
  71. "activity_key": self._activity_key,
  72. "window_seconds": self._window.total_seconds(),
  73. }
  74. @classmethod
  75. def from_dict(cls, data: dict) -> "RecentActivityCondition":
  76. """Erstellt Condition aus Dictionary."""
  77. return cls(
  78. activity_key=data["activity_key"],
  79. seconds=int(data.get("window_seconds", 0)),
  80. name=data.get("name"),
  81. invert=data.get("invert", False),
  82. )
  83. class ActivityCountCondition(Condition):
  84. """
  85. Prüft ob Aktivitäts-Zähler einen Schwellenwert erreicht.
  86. Beispiel:
  87. - ActivityCountCondition("error_count", min_count=5)
  88. → Nur wenn mindestens 5 Fehler
  89. - ActivityCountCondition("login_attempts", max_count=3)
  90. → Nur wenn max. 3 Login-Versuche
  91. """
  92. def __init__(
  93. self,
  94. count_key: str,
  95. min_count: int | None = None,
  96. max_count: int | None = None,
  97. name: str | None = None,
  98. invert: bool = False,
  99. ):
  100. """
  101. Initialisiert die Condition.
  102. Args:
  103. count_key: Schlüssel für Zähler im Kontext
  104. min_count: Mindestanzahl (optional)
  105. max_count: Maximalanzahl (optional)
  106. name: Condition-Name
  107. invert: Ergebnis invertieren
  108. """
  109. super().__init__(name, invert)
  110. self._count_key = count_key
  111. self._min_count = min_count
  112. self._max_count = max_count
  113. if min_count is None and max_count is None:
  114. raise ValueError("min_count oder max_count muss gesetzt sein")
  115. @property
  116. def count_key(self) -> str:
  117. """Zähler-Schlüssel."""
  118. return self._count_key
  119. @property
  120. def min_count(self) -> int | None:
  121. """Mindestanzahl."""
  122. return self._min_count
  123. @property
  124. def max_count(self) -> int | None:
  125. """Maximalanzahl."""
  126. return self._max_count
  127. def _evaluate(self, context: dict) -> bool:
  128. """Prüft ob Zähler Bedingung erfüllt."""
  129. count = context.get(self._count_key, 0)
  130. try:
  131. count = int(count)
  132. except (TypeError, ValueError):
  133. return False
  134. if self._min_count is not None and count < self._min_count:
  135. return False
  136. if self._max_count is not None and count > self._max_count:
  137. return False
  138. return True
  139. def to_dict(self) -> dict:
  140. """Konvertiert zu Dictionary."""
  141. return {
  142. **self._base_dict(),
  143. "count_key": self._count_key,
  144. "min_count": self._min_count,
  145. "max_count": self._max_count,
  146. }
  147. @classmethod
  148. def from_dict(cls, data: dict) -> "ActivityCountCondition":
  149. """Erstellt Condition aus Dictionary."""
  150. return cls(
  151. count_key=data["count_key"],
  152. min_count=data.get("min_count"),
  153. max_count=data.get("max_count"),
  154. name=data.get("name"),
  155. invert=data.get("invert", False),
  156. )