Files
2026-11-23 16:35:53 +03:00

560 lines
21 KiB
Python

"""Asynchronous Todoist REST API v2 and Sync API v9 Client."""
import json
import logging
from typing import Any, Optional
import uuid
import httpx
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class TodoistClient:
"""Async Client for Todoist REST API v2 and Sync API v9."""
def __init__(
self,
token: Optional[str] = None,
api_url: Optional[str] = None,
sync_url: Optional[str] = None,
) -> None:
settings = get_settings()
self.token = (
token
or (settings.TODOIST_API_TOKEN.get_secret_value() if settings.TODOIST_API_TOKEN else "")
)
self.api_url = (api_url or settings.TODOIST_API_URL or "https://api.todoist.com/rest/v2").rstrip("/")
self.sync_url = (sync_url or settings.TODOIST_SYNC_URL or "https://api.todoist.com/sync/v9").rstrip("/")
def is_configured(self) -> bool:
return bool(self.token)
def _get_headers(self, request_id: Optional[str] = None) -> dict[str, str]:
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
if request_id:
headers["X-Request-Id"] = request_id
return headers
async def _request(
self,
method: str,
endpoint: str,
params: Optional[dict[str, Any]] = None,
json_data: Optional[dict[str, Any]] = None,
use_sync: bool = False,
) -> Any:
base = self.sync_url if use_sync else self.api_url
url = f"{base}/{endpoint.lstrip('/')}"
req_id = str(uuid.uuid4()) if method.upper() in ("POST", "PUT", "DELETE") else None
headers = self._get_headers(request_id=req_id)
async with httpx.AsyncClient(timeout=25.0) as client:
response = await client.request(
method=method,
url=url,
headers=headers,
params=params,
json=json_data,
)
if response.status_code == 204 or not response.content:
return None
if response.is_error:
error_body = response.text
logger.error("Todoist API error %d on %s: %s", response.status_code, url, error_body)
raise RuntimeError(f"Todoist API error ({response.status_code}): {error_body}")
return response.json()
async def _sync_command(
self,
cmd_type: str,
args: dict[str, Any],
temp_id: Optional[str] = None,
) -> dict[str, Any]:
"""Execute a Sync API v9 command (e.g. item_move)."""
cmd_uuid = str(uuid.uuid4())
cmd: dict[str, Any] = {
"type": cmd_type,
"uuid": cmd_uuid,
"args": args,
}
if temp_id:
cmd["temp_id"] = temp_id
data = await self._request(
"POST",
"sync",
json_data={"commands": [cmd]},
use_sync=True,
)
sync_status = (data or {}).get("sync_status", {}).get(cmd_uuid)
if isinstance(sync_status, dict) and sync_status.get("error"):
err_msg = sync_status.get("error", "Unknown sync error")
err_code = sync_status.get("error_code", "")
raise RuntimeError(f"Todoist Sync error ({err_code}): {err_msg}")
return data or {}
# -------------------------------------------------------------------------
# Projects
# -------------------------------------------------------------------------
async def list_projects(self) -> list[dict[str, Any]]:
"""Get all user projects."""
res = await self._request("GET", "projects")
return res if isinstance(res, list) else []
async def get_project(self, project_id: str) -> dict[str, Any]:
"""Get a project by ID."""
return await self._request("GET", f"projects/{project_id}")
async def create_project(
self,
name: str,
parent_id: Optional[str] = None,
color: Optional[str] = None,
is_favorite: Optional[bool] = None,
view_style: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new project."""
payload: dict[str, Any] = {"name": name}
if parent_id:
payload["parent_id"] = parent_id
if color:
payload["color"] = color
if is_favorite is not None:
payload["is_favorite"] = is_favorite
if view_style:
payload["view_style"] = view_style
return await self._request("POST", "projects", json_data=payload)
async def update_project(
self,
project_id: str,
name: Optional[str] = None,
color: Optional[str] = None,
is_favorite: Optional[bool] = None,
view_style: Optional[str] = None,
) -> dict[str, Any]:
"""Update an existing project."""
payload: dict[str, Any] = {}
if name is not None:
payload["name"] = name
if color is not None:
payload["color"] = color
if is_favorite is not None:
payload["is_favorite"] = is_favorite
if view_style is not None:
payload["view_style"] = view_style
return await self._request("POST", f"projects/{project_id}", json_data=payload)
async def delete_project(self, project_id: str) -> None:
"""Delete a project."""
await self._request("DELETE", f"projects/{project_id}")
async def get_project_collaborators(self, project_id: str) -> list[dict[str, Any]]:
"""Get all collaborators for a shared project."""
res = await self._request("GET", f"projects/{project_id}/collaborators")
return res if isinstance(res, list) else []
async def resolve_project_id(self, project_name_or_id: str) -> Optional[str]:
"""Resolve a project name or ID to its actual ID."""
clean = str(project_name_or_id).strip()
if not clean:
return None
projects = await self.list_projects()
# Exact ID match
for p in projects:
if str(p.get("id")) == clean:
return str(p["id"])
# Exact case-insensitive name match
clean_lower = clean.lower()
for p in projects:
if str(p.get("name", "")).strip().lower() == clean_lower:
return str(p["id"])
# Substring match
for p in projects:
if clean_lower in str(p.get("name", "")).strip().lower():
return str(p["id"])
return None
# -------------------------------------------------------------------------
# Sections
# -------------------------------------------------------------------------
async def list_sections(self, project_id: Optional[str] = None) -> list[dict[str, Any]]:
"""Get sections (optionally filtered by project_id)."""
params: dict[str, Any] = {}
if project_id:
params["project_id"] = project_id
res = await self._request("GET", "sections", params=params or None)
return res if isinstance(res, list) else []
async def get_section(self, section_id: str) -> dict[str, Any]:
"""Get a single section by ID."""
return await self._request("GET", f"sections/{section_id}")
async def create_section(
self,
name: str,
project_id: str,
order: Optional[int] = None,
) -> dict[str, Any]:
"""Create a new section in a project."""
payload: dict[str, Any] = {"name": name, "project_id": project_id}
if order is not None:
payload["order"] = order
return await self._request("POST", "sections", json_data=payload)
async def update_section(self, section_id: str, name: str) -> dict[str, Any]:
"""Rename a section."""
return await self._request("POST", f"sections/{section_id}", json_data={"name": name})
async def delete_section(self, section_id: str) -> None:
"""Delete a section and all its tasks."""
await self._request("DELETE", f"sections/{section_id}")
async def resolve_section_id(
self,
section_name_or_id: str,
project_id: Optional[str] = None,
) -> Optional[str]:
"""Resolve a section name or ID to its actual ID."""
clean = str(section_name_or_id).strip()
if not clean:
return None
sections = await self.list_sections(project_id=project_id)
for s in sections:
if str(s.get("id")) == clean:
return str(s["id"])
clean_lower = clean.lower()
for s in sections:
if str(s.get("name", "")).strip().lower() == clean_lower:
return str(s["id"])
for s in sections:
if clean_lower in str(s.get("name", "")).strip().lower():
return str(s["id"])
return None
# -------------------------------------------------------------------------
# Tasks
# -------------------------------------------------------------------------
async def list_tasks(
self,
project_id: Optional[str] = None,
section_id: Optional[str] = None,
label: Optional[str] = None,
filter_query: Optional[str] = None,
lang: str = "ru",
ids: Optional[list[str]] = None,
) -> list[dict[str, Any]]:
"""Get active tasks across the account or with filters."""
params: dict[str, Any] = {}
if project_id:
params["project_id"] = project_id
if section_id:
params["section_id"] = section_id
if label:
params["label"] = label
if filter_query:
params["filter"] = filter_query
params["lang"] = lang
if ids:
params["ids"] = ",".join(str(i) for i in ids)
res = await self._request("GET", "tasks", params=params or None)
return res if isinstance(res, list) else []
async def get_task(self, task_id: str) -> dict[str, Any]:
"""Get an active task by ID."""
return await self._request("GET", f"tasks/{task_id}")
async def create_task(
self,
content: str,
description: Optional[str] = None,
project_id: Optional[str] = None,
section_id: Optional[str] = None,
parent_id: Optional[str] = None,
order: Optional[int] = None,
labels: Optional[list[str]] = None,
priority: Optional[int] = None,
due_string: Optional[str] = None,
due_date: Optional[str] = None,
due_datetime: Optional[str] = None,
due_lang: str = "ru",
assignee_id: Optional[str] = None,
duration: Optional[int] = None,
duration_unit: Optional[str] = None,
deadline_date: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new task."""
payload: dict[str, Any] = {"content": content}
if description is not None:
payload["description"] = description
if project_id:
payload["project_id"] = project_id
if section_id:
payload["section_id"] = section_id
if parent_id:
payload["parent_id"] = parent_id
if order is not None:
payload["order"] = order
if labels is not None:
payload["labels"] = labels
if priority is not None:
payload["priority"] = priority
if due_datetime:
payload["due_datetime"] = due_datetime
elif due_date:
payload["due_date"] = due_date
elif due_string:
payload["due_string"] = due_string
payload["due_lang"] = due_lang
if assignee_id:
payload["assignee_id"] = assignee_id
if duration is not None and duration_unit:
payload["duration"] = duration
payload["duration_unit"] = duration_unit
if deadline_date:
payload["deadline_date"] = deadline_date
return await self._request("POST", "tasks", json_data=payload)
async def quick_add_task(
self,
text: str,
note: Optional[str] = None,
reminder: Optional[str] = None,
auto_reminder: bool = False,
) -> dict[str, Any]:
"""Quick add a task using Todoist natural language parsing (Sync API v9 quick/add)."""
payload: dict[str, Any] = {"text": text}
if note:
payload["note"] = note
if reminder:
payload["reminder"] = reminder
if auto_reminder:
payload["auto_reminder"] = True
return await self._request("POST", "quick/add", json_data=payload, use_sync=True)
async def update_task(
self,
task_id: str,
content: Optional[str] = None,
description: Optional[str] = None,
labels: Optional[list[str]] = None,
priority: Optional[int] = None,
due_string: Optional[str] = None,
due_date: Optional[str] = None,
due_datetime: Optional[str] = None,
due_lang: str = "ru",
assignee_id: Optional[str] = None,
duration: Optional[int] = None,
duration_unit: Optional[str] = None,
deadline_date: Optional[str] = None,
) -> dict[str, Any]:
"""Update an existing task's properties via REST API v2."""
payload: dict[str, Any] = {}
if content is not None:
payload["content"] = content
if description is not None:
payload["description"] = description
if labels is not None:
payload["labels"] = labels
if priority is not None:
payload["priority"] = priority
if due_datetime:
payload["due_datetime"] = due_datetime
elif due_date:
payload["due_date"] = due_date
elif due_string is not None:
payload["due_string"] = due_string
payload["due_lang"] = due_lang
if assignee_id is not None:
payload["assignee_id"] = assignee_id if assignee_id else None
if duration is not None and duration_unit:
payload["duration"] = duration
payload["duration_unit"] = duration_unit
if deadline_date is not None:
payload["deadline_date"] = deadline_date if deadline_date else None
return await self._request("POST", f"tasks/{task_id}", json_data=payload)
async def move_task(
self,
task_id: str,
project_id: Optional[str] = None,
section_id: Optional[str] = None,
parent_id: Optional[str] = None,
) -> dict[str, Any]:
"""Move a task to another project, section, or parent task via Sync API v9 item_move."""
args: dict[str, Any] = {"id": str(task_id)}
# Todoist item_move accepts exactly one destination parameter: parent_id, section_id, or project_id
if parent_id:
args["parent_id"] = str(parent_id)
elif section_id:
args["section_id"] = str(section_id)
elif project_id:
args["project_id"] = str(project_id)
else:
raise ValueError("One of project_id, section_id, or parent_id must be specified to move a task.")
return await self._sync_command("item_move", args)
async def close_task(self, task_id: str) -> None:
"""Close (complete) a task."""
await self._request("POST", f"tasks/{task_id}/close")
async def reopen_task(self, task_id: str) -> None:
"""Reopen a completed task."""
await self._request("POST", f"tasks/{task_id}/reopen")
async def delete_task(self, task_id: str) -> None:
"""Delete a task permanently."""
await self._request("DELETE", f"tasks/{task_id}")
async def list_completed_tasks(
self,
project_id: Optional[str] = None,
section_id: Optional[str] = None,
since: Optional[str] = None,
until: Optional[str] = None,
limit: int = 30,
offset: int = 0,
) -> list[dict[str, Any]]:
"""List completed tasks from Todoist Sync API v9."""
params: dict[str, Any] = {"limit": limit, "offset": offset}
if project_id:
params["project_id"] = project_id
if section_id:
params["section_id"] = section_id
if since:
params["since"] = since
if until:
params["until"] = until
data = await self._request("GET", "completed/get_all", params=params, use_sync=True)
if isinstance(data, dict):
return data.get("items", [])
return []
# -------------------------------------------------------------------------
# Labels
# -------------------------------------------------------------------------
async def list_labels(self) -> list[dict[str, Any]]:
"""Get all personal labels."""
res = await self._request("GET", "labels")
return res if isinstance(res, list) else []
async def get_label(self, label_id: str) -> dict[str, Any]:
"""Get a personal label by ID."""
return await self._request("GET", f"labels/{label_id}")
async def create_label(
self,
name: str,
color: Optional[str] = None,
order: Optional[int] = None,
is_favorite: Optional[bool] = None,
) -> dict[str, Any]:
"""Create a new personal label."""
payload: dict[str, Any] = {"name": name}
if color:
payload["color"] = color
if order is not None:
payload["order"] = order
if is_favorite is not None:
payload["is_favorite"] = is_favorite
return await self._request("POST", "labels", json_data=payload)
async def update_label(
self,
label_id: str,
name: Optional[str] = None,
color: Optional[str] = None,
order: Optional[int] = None,
is_favorite: Optional[bool] = None,
) -> dict[str, Any]:
"""Update a personal label."""
payload: dict[str, Any] = {}
if name is not None:
payload["name"] = name
if color is not None:
payload["color"] = color
if order is not None:
payload["order"] = order
if is_favorite is not None:
payload["is_favorite"] = is_favorite
return await self._request("POST", f"labels/{label_id}", json_data=payload)
async def delete_label(self, label_id: str) -> None:
"""Delete a personal label."""
await self._request("DELETE", f"labels/{label_id}")
async def list_shared_labels(self, omit_personal: bool = False) -> list[str]:
"""List all shared labels across active tasks."""
res = await self._request("GET", "labels/shared", params={"omit_personal": omit_personal})
return res if isinstance(res, list) else []
async def rename_shared_label(self, name: str, new_name: str) -> None:
"""Rename a shared label across all tasks."""
await self._request("POST", "labels/shared/rename", json_data={"name": name, "new_name": new_name})
async def remove_shared_label(self, name: str) -> None:
"""Remove a shared label from all active tasks."""
await self._request("POST", "labels/shared/remove", json_data={"name": name})
# -------------------------------------------------------------------------
# Comments
# -------------------------------------------------------------------------
async def list_comments(
self,
task_id: Optional[str] = None,
project_id: Optional[str] = None,
) -> list[dict[str, Any]]:
"""Get comments for a task or project."""
if not task_id and not project_id:
raise ValueError("Either task_id or project_id is required to list comments.")
params: dict[str, Any] = {}
if task_id:
params["task_id"] = task_id
elif project_id:
params["project_id"] = project_id
res = await self._request("GET", "comments", params=params)
return res if isinstance(res, list) else []
async def get_comment(self, comment_id: str) -> dict[str, Any]:
"""Get a single comment by ID."""
return await self._request("GET", f"comments/{comment_id}")
async def create_comment(
self,
content: str,
task_id: Optional[str] = None,
project_id: Optional[str] = None,
) -> dict[str, Any]:
"""Create a comment on a task or project."""
if not task_id and not project_id:
raise ValueError("Either task_id or project_id is required to create a comment.")
payload: dict[str, Any] = {"content": content}
if task_id:
payload["task_id"] = task_id
elif project_id:
payload["project_id"] = project_id
return await self._request("POST", "comments", json_data=payload)
async def update_comment(self, comment_id: str, content: str) -> dict[str, Any]:
"""Update a comment."""
return await self._request("POST", f"comments/{comment_id}", json_data={"content": content})
async def delete_comment(self, comment_id: str) -> None:
"""Delete a comment."""
await self._request("DELETE", f"comments/{comment_id}")