Spaces:
Sleeping
Sleeping
File size: 12,595 Bytes
cd7bed1 | 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 | """
FocusTrack - Activity Tracker Engine
Detects active window, tracks idle time, logs heartbeats.
Cross-platform: Windows / macOS / Linux
"""
import time
import json
import logging
import platform
import threading
from datetime import datetime
from typing import Optional, Tuple
from pathlib import Path
logger = logging.getLogger("focustrack.tracker")
SYSTEM = platform.system() # 'Windows', 'Darwin', 'Linux'
# βββ Window Detection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_active_window() -> Tuple[str, str]:
"""
Returns (app_name, window_title) for the currently focused window.
Cross-platform with graceful fallbacks.
"""
try:
if SYSTEM == "Windows":
return _get_window_windows()
elif SYSTEM == "Darwin":
return _get_window_macos()
else:
return _get_window_linux()
except Exception as e:
logger.debug(f"Window detection error: {e}")
return ("unknown", "unknown")
def _get_window_windows() -> Tuple[str, str]:
import ctypes
import ctypes.wintypes
user32 = ctypes.windll.user32
hwnd = user32.GetForegroundWindow()
length = user32.GetWindowTextLengthW(hwnd)
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(hwnd, buf, length + 1)
title = buf.value or "unknown"
# Get process name
pid = ctypes.wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
try:
import psutil
proc = psutil.Process(pid.value)
app = proc.name().replace(".exe", "")
except Exception:
app = "unknown"
return (app, title)
def _get_window_macos() -> Tuple[str, str]:
try:
from AppKit import NSWorkspace
ws = NSWorkspace.sharedWorkspace()
app = ws.activeApplication()
app_name = app.get("NSApplicationName", "unknown") if app else "unknown"
title = "unknown"
try:
import subprocess
script = 'tell application "System Events" to get name of first window of (first process whose frontmost is true)'
result = subprocess.run(
["osascript", "-e", script], capture_output=True, text=True, timeout=2
)
if result.returncode == 0:
title = result.stdout.strip()
except Exception:
pass
return (app_name, title)
except ImportError:
# Fallback via subprocess
try:
import subprocess
script = """
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
set frontTitle to ""
try
set frontTitle to name of front window of (first process whose frontmost is true)
end try
return frontApp & "|" & frontTitle
end tell
"""
result = subprocess.run(
["osascript", "-e", script], capture_output=True, text=True, timeout=3
)
if result.returncode == 0:
parts = result.stdout.strip().split("|", 1)
return (parts[0], parts[1] if len(parts) > 1 else "")
except Exception:
pass
return ("unknown", "unknown")
def _get_window_linux() -> Tuple[str, str]:
try:
import subprocess
# Try xdotool
wid = subprocess.run(
["xdotool", "getactivewindow"], capture_output=True, text=True, timeout=2
)
if wid.returncode == 0:
wid_val = wid.stdout.strip()
name = subprocess.run(
["xdotool", "getwindowname", wid_val],
capture_output=True, text=True, timeout=2
)
pid_result = subprocess.run(
["xdotool", "getwindowpid", wid_val],
capture_output=True, text=True, timeout=2
)
title = name.stdout.strip() if name.returncode == 0 else "unknown"
app = "unknown"
if pid_result.returncode == 0:
try:
import psutil
proc = psutil.Process(int(pid_result.stdout.strip()))
app = proc.name()
except Exception:
pass
return (app, title)
except FileNotFoundError:
pass
try:
# Fallback: wmctrl
import subprocess
result = subprocess.run(
["wmctrl", "-a", ":ACTIVE:"], capture_output=True, text=True
)
except Exception:
pass
return ("unknown", "unknown")
# βββ Categorizer βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class Categorizer:
"""Rule-based app categorization using DB-defined rules."""
def __init__(self, db):
self.db = db
self._cache: dict = {}
self._reload_interval = 60 # seconds
self._last_reload = 0.0
self._load_rules()
def _load_rules(self):
cats = self.db.get_categories()
self._rules = []
for cat in cats:
self._rules.append({
"name": cat["name"],
"keywords": json.loads(cat["keywords"] or "[]"),
"apps": json.loads(cat["apps"] or "[]"),
})
self._last_reload = time.time()
def categorize(self, app_name: str, window_title: str, is_idle: bool) -> str:
if is_idle:
return "idle"
# Reload rules periodically
if time.time() - self._last_reload > self._reload_interval:
self._load_rules()
app_lower = app_name.lower()
title_lower = window_title.lower()
for rule in self._rules:
if rule["name"] == "idle":
continue
for app_kw in rule["apps"]:
if app_kw.lower() in app_lower:
return rule["name"]
for kw in rule["keywords"]:
if kw.lower() in title_lower or kw.lower() in app_lower:
return rule["name"]
return "uncategorized"
# βββ Idle Detector βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class IdleDetector:
"""Tracks mouse + keyboard activity to detect idle state."""
def __init__(self, threshold_seconds: int = 300):
self.threshold = threshold_seconds
self._last_event = time.time()
self._listener = None
self._running = False
def start(self):
self._running = True
try:
from pynput import mouse, keyboard
def on_activity(*args, **kwargs):
self._last_event = time.time()
self._mouse_listener = mouse.Listener(
on_move=on_activity, on_click=on_activity, on_scroll=on_activity
)
self._keyboard_listener = keyboard.Listener(on_press=on_activity)
self._mouse_listener.start()
self._keyboard_listener.start()
logger.info("Idle detector started (pynput)")
except Exception as e:
logger.warning(f"pynput unavailable ({e}), idle detection disabled")
def stop(self):
self._running = False
try:
if self._mouse_listener:
self._mouse_listener.stop()
if self._keyboard_listener:
self._keyboard_listener.stop()
except Exception:
pass
@property
def is_idle(self) -> bool:
return (time.time() - self._last_event) > self.threshold
@property
def idle_seconds(self) -> float:
elapsed = time.time() - self._last_event
return max(0.0, elapsed - self.threshold) if self.is_idle else 0.0
def update_threshold(self, seconds: int):
self.threshold = seconds
# βββ Main Tracker ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ActivityTracker:
"""
Background activity tracking service.
Logs heartbeats every N seconds to SQLite.
"""
def __init__(self, db):
self.db = db
self._running = False
self._paused = False
self._lock = threading.Lock()
idle_threshold = int(db.get_setting("idle_threshold_seconds", 300))
self.heartbeat_interval = int(db.get_setting("heartbeat_interval", 5))
self.idle_detector = IdleDetector(idle_threshold)
self.categorizer = Categorizer(db)
# Current session state
self.current_app = ""
self.current_title = ""
self.current_category = ""
self.session_start = datetime.now()
self.is_idle = False
def run(self):
"""Main tracking loop. Runs in a background thread."""
self._running = True
self.idle_detector.start()
logger.info(f"Tracker started (heartbeat: {self.heartbeat_interval}s)")
ignored_raw = self.db.get_setting("ignored_apps", "[]")
try:
ignored_apps = [a.lower() for a in json.loads(ignored_raw)]
except Exception:
ignored_apps = []
while self._running:
try:
if not self._paused:
self._tick(ignored_apps)
time.sleep(self.heartbeat_interval)
except Exception as e:
logger.error(f"Tracker error: {e}", exc_info=True)
time.sleep(self.heartbeat_interval)
def _tick(self, ignored_apps: list):
"""One heartbeat: detect window, log activity."""
app_name, window_title = get_active_window()
is_idle = self.idle_detector.is_idle
# Skip ignored apps
if any(ig in app_name.lower() for ig in ignored_apps):
return
category = self.categorizer.categorize(app_name, window_title, is_idle)
with self._lock:
self.current_app = app_name
self.current_title = window_title
self.current_category = category
self.is_idle = is_idle
# Check if session changed
if (app_name != self.current_app or
abs((datetime.now() - self.session_start).total_seconds()) > 30):
self.session_start = datetime.now()
self.db.log_activity(
timestamp=datetime.now(),
app_name=app_name,
window_title=window_title,
duration_seconds=self.heartbeat_interval,
category=category,
is_idle=is_idle,
)
# βββ Controls ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def pause(self):
self._paused = True
self.db.set_setting("tracker_running", "paused")
logger.info("Tracker paused")
def resume(self):
self._paused = False
self.db.set_setting("tracker_running", "true")
logger.info("Tracker resumed")
def stop(self):
self._running = False
self.idle_detector.stop()
self.db.set_setting("tracker_running", "false")
logger.info("Tracker stopped")
@property
def status(self) -> str:
if not self._running:
return "stopped"
if self._paused:
return "paused"
return "running"
def get_current_state(self) -> dict:
with self._lock:
return {
"app": self.current_app,
"title": self.current_title,
"category": self.current_category,
"is_idle": self.is_idle,
"status": self.status,
"session_start": self.session_start.isoformat(),
}
def reload_settings(self):
"""Reload settings from DB (called after settings change)."""
idle_threshold = int(self.db.get_setting("idle_threshold_seconds", 300))
self.heartbeat_interval = int(self.db.get_setting("heartbeat_interval", 5))
self.idle_detector.update_threshold(idle_threshold)
logger.info("Tracker settings reloaded")
|