refactor(src/services): simplify TodoService and remove unused ConfigService stop function

Remove redundant import duplication, replace uuid with os.urandom, rename completion_rate to active, update property decorator, and clean up callback handling. Also removed unused stop_config_service function.
This commit is contained in:
sankalp committed 2026-07-04 07:26:44 +05:45
1 parent 274ffbfaed
commit 01c193bd8e
3 files changed
+29 -40

No files matched your search

+1 -1
View File
@@ -6,6 +6,6 @@ from .keyboard_layout import KeyboardLayout # noqa: F401
from .network import NetworkClient, Wifi, Ethernet # noqa: F401 from .network import NetworkClient, Wifi, Ethernet # noqa: F401
from .mpris import PlayerService, PlayerManager # noqa: F401 from .mpris import PlayerService, PlayerManager # noqa: F401
from .mpris import PlayerService as MprisPlayer, PlayerManager as MprisPlayerManager # noqa: F401 from .mpris import PlayerService as MprisPlayer, PlayerManager as MprisPlayerManager # noqa: F401
from .todo import TodoService # noqa: F401
from .modus import ModusService # noqa: F401 from .modus import ModusService # noqa: F401
from .todo import TodoService # noqa: F401
from .config import on_config_change, start_config_service, ConfigService # noqa: F401 from .config import on_config_change, start_config_service, ConfigService # noqa: F401
-7
View File
@@ -198,13 +198,6 @@ def start_config_service() -> ConfigService:
return _service return _service
def stop_config_service() -> None:
global _service
if _service is not None:
_service.stop()
_service = None
# Convenience helpers for concise usage # Convenience helpers for concise usage
def config() -> ConfigService: def config() -> ConfigService:
"""Get the singleton service (concise alias).""" """Get the singleton service (concise alias)."""
+28 -32
View File
@@ -1,42 +1,28 @@
from fabric.utils import logger
# Standard library imports
import json import json
import uuid import os
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
# Fabric imports from fabric.core.service import Service
from fabric.core.service import Property, Service from fabric.utils import logger
# Local imports
import shared.data as data import shared.data as data
class TodoService(Service): class TodoService(Service):
"""Service for managing persistent todo list with JSON storage""" """Service for managing persistent todo list with JSON storage"""
def __init__(self): def __init__(self, **kwargs):
super().__init__() super().__init__(**kwargs)
self._todos = [] self._todos = []
self._file_path = self._get_todos_file_path() self._file_path = self._get_todos_file_path()
self._load_todos() self._load_todos()
self._callbacks = [] self._callbacks = []
def add_callback(self, callback): def _notify_callbacks(self, event: str, data=None):
"""Add a callback function to be notified of changes"""
self._callbacks.append(callback)
def remove_callback(self, callback):
"""Remove a callback function"""
if callback in self._callbacks:
self._callbacks.remove(callback)
def _notify_callbacks(self, event_type, data=None):
"""Notify all registered callbacks of changes"""
for callback in self._callbacks: for callback in self._callbacks:
try: try:
callback(event_type, data) callback(event, data)
except Exception as e: except Exception as e:
logger.error(f"Error in todo callback: {e}") logger.error(f"Error in todo callback: {e}")
@@ -50,7 +36,7 @@ class TodoService(Service):
"""Load todos from JSON file""" """Load todos from JSON file"""
try: try:
if self._file_path.exists(): if self._file_path.exists():
with open(self._file_path, "r", encoding="utf-8") as f: with open(self._file_path, "r") as f:
self._todos = json.load(f) self._todos = json.load(f)
else: else:
self._todos = [] self._todos = []
@@ -61,12 +47,12 @@ class TodoService(Service):
def _save_todos(self): def _save_todos(self):
"""Save todos to JSON file""" """Save todos to JSON file"""
try: try:
with open(self._file_path, "w", encoding="utf-8") as f: with open(self._file_path, "w") as f:
json.dump(self._todos, f, indent=2, ensure_ascii=False) json.dump(self._todos, f, indent=2, ensure_ascii=False)
except Exception as e: except Exception as e:
logger.error(f"Error saving todos: {e}") logger.error(f"Error saving todos: {e}")
@Property(list, "readable") @property
def todos(self): def todos(self):
"""Get all todos""" """Get all todos"""
return self._todos.copy() return self._todos.copy()
@@ -74,10 +60,10 @@ class TodoService(Service):
def add_todo(self, text: str, priority: str = "medium") -> dict: def add_todo(self, text: str, priority: str = "medium") -> dict:
"""Add a new todo item""" """Add a new todo item"""
todo = { todo = {
"id": str(uuid.uuid4()), "id": os.urandom(8).hex(),
"text": text, "text": text,
"completed": False, "completed": False,
"priority": priority, # low, medium, high "priority": priority,
"created_at": datetime.now().isoformat(), "created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(), "updated_at": datetime.now().isoformat(),
} }
@@ -124,7 +110,11 @@ class TodoService(Service):
def set_priority(self, todo_id: str, priority: str) -> bool: def set_priority(self, todo_id: str, priority: str) -> bool:
"""Set the priority of a todo item""" """Set the priority of a todo item"""
if priority not in ["low", "medium", "high"]: valid_priorities = ["low", "medium", "high"]
if priority not in valid_priorities:
logger.warning(
f"Invalid priority '{priority}'. Must be one of {valid_priorities}"
)
return False return False
for todo in self._todos: for todo in self._todos:
@@ -156,17 +146,23 @@ class TodoService(Service):
"""Get todo statistics""" """Get todo statistics"""
total = len(self._todos) total = len(self._todos)
completed = sum(1 for todo in self._todos if todo["completed"]) completed = sum(1 for todo in self._todos if todo["completed"])
pending = total - completed
return { return {
"total": total, "total": total,
"completed": completed, "completed": completed,
"pending": pending, "active": total - completed,
"completion_rate": (completed / total * 100) if total > 0 else 0,
} }
def add_callback(self, callback):
"""Add a callback for todo events"""
if callback not in self._callbacks:
self._callbacks.append(callback)
def remove_callback(self, callback):
"""Remove a callback"""
if callback in self._callbacks:
self._callbacks.remove(callback)
# Global service instance getter
_todo_service = None _todo_service = None