Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions custom_components/yandex_station/core/yandex_quasar.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,50 @@ async def get_alarms(self, device: dict):
resp = await r.json()
return resp["alarms"]

async def get_notes(self) -> list[dict]:
"""Облачные заметки/списки Алисы (rpc.alice, cookie-сессия, без CSRF).

Обходит стриминговую Алису: локальный glagol на «Что в списке покупок»
теперь отдаёт is_streaming без текстовой карточки (issue #631).
"""
r = await self.session.post(
"https://rpc.alice.yandex.ru/gproxy/get_notes",
json={},
headers=NOTES_HEADERS,
)
resp = await r.json()
return resp.get("notes") or []

async def get_shopping_note(self) -> dict | None:
"""Облачная заметка «Список покупок» целиком (note_id + subtasks) или None."""
for note in await self.get_notes():
if note.get("title") == SHOPPING_LIST_TITLE:
return note
return None

@staticmethod
def note_active_items(note: dict) -> dict[str, str]:
"""{текст: subtask_id} для активных (не купленных) пунктов заметки."""
return {
s["text"]: s["subtask_id"]
for s in note.get("subtasks") or []
if s.get("text") and not s.get("done") and s.get("subtask_id")
}

async def add_shopping_item(self, note_id: str, text: str) -> None:
await self.session.post(
"https://rpc.alice.yandex.ru/gproxy/create_subtask",
json={"note_id": note_id, "subtask": {"text": text}},
headers=NOTES_HEADERS,
)

async def delete_shopping_item(self, note_id: str, subtask_id: str) -> None:
await self.session.post(
"https://rpc.alice.yandex.ru/gproxy/delete_subtask",
json={"note_id": note_id, "subtask_id": subtask_id},
headers=NOTES_HEADERS,
)

async def create_alarm(self, device: dict, alarm: dict) -> bool:
alarm["device_id"] = device["quasar_info"]["device_id"]
resp = await self.session.post(
Expand Down Expand Up @@ -672,6 +716,19 @@ async def cancel_alarms(self, device: dict, alarm_id: str) -> bool:
"x-ya-application": '{"app_id":"unknown","uuid":"unknown","lang":"ru"}',
}

# Заголовки веб-клиента «Заметки и списки» (yandex.ru/alice/shopping-list).
# Как ALARM_HEADERS, но x-ya-app-type "other" — cookie-only, без CSRF (rpc.alice.*).
NOTES_HEADERS = {
"accept": "application/json",
"content-type": "application/json",
"origin": "https://yandex.ru",
"x-ya-app-type": "other",
"x-ya-application": '{"app_id":"unknown","uuid":"unknown","lang":"ru"}',
}

# Заголовок облачного «Списка покупок» — единственная заметка с этим title.
SHOPPING_LIST_TITLE = "Список покупок"


BOOL_CONFIG = {"да": True, "нет": False}
ACCOUNT_CONFIG = {
Expand Down
4 changes: 2 additions & 2 deletions custom_components/yandex_station/core/yandex_station.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,9 +980,9 @@ async def async_play_media(
elif media_type == "shopping_list":
# media_id == "update" — легаси команда для интеграции Shopping List
coro = (
shopping_list.shopping_sync(self.hass, self.glagol)
shopping_list.shopping_sync(self.hass, self.quasar)
if media_id == "update"
else todo_list.shopping_sync(self.hass, self.glagol, media_id)
else todo_list.shopping_sync(self.hass, self.quasar, media_id)
)

await self.hass.async_create_background_task(coro, self.name)
Expand Down
74 changes: 34 additions & 40 deletions custom_components/yandex_station/hass/shopping_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from homeassistant.components.shopping_list import ShoppingData
from homeassistant.core import HomeAssistant

from ..core.yandex_glagol import YandexGlagol
from ..core.yandex_quasar import YandexQuasar

try:
from homeassistant.const import EVENT_SHOPPING_LIST_UPDATED
Expand All @@ -17,25 +17,9 @@
RE_SHOPPING = re.compile(r"^\d+\) (.+)$", re.MULTILINE)


def shopping_for_remove(shopping_data: ShoppingData, alice_data: str) -> list[str]:
alice_items = RE_SHOPPING.findall(alice_data)
for_remove = [
alice_items.index(item["name"])
for item in shopping_data.items
if item["complete"] and item["name"] in alice_items
]
return [str(i + 1) for i in sorted(for_remove)]


def shopping_for_add(shopping_data: ShoppingData, alice_data: str) -> list[str]:
alice_items = RE_SHOPPING.findall(alice_data)
return [
item["name"]
for item in shopping_data.items
if not item["complete"]
and item["name"] not in alice_items
and not item["id"].startswith("alice")
]
def alice_text(items: list[str]) -> str:
"""Собрать нумерованный текст в формате карточки Алисы (под RE_SHOPPING)."""
return "\n".join(f"{i + 1}) {name}" for i, name in enumerate(items))


def shopping_save(hass: HomeAssistant, shopping_data: ShoppingData, alice_data: str):
Expand Down Expand Up @@ -66,7 +50,7 @@ def shopping_save(hass: HomeAssistant, shopping_data: ShoppingData, alice_data:
)


async def shopping_sync(hass: HomeAssistant, glagol: YandexGlagol):
async def shopping_sync(hass: HomeAssistant, quasar: YandexQuasar):
entries = hass.config_entries.async_entries("shopping_list")
if not entries:
return
Expand All @@ -75,24 +59,34 @@ async def shopping_sync(hass: HomeAssistant, glagol: YandexGlagol):
# magic for support new version after HA 2026.5 and old version
data = getattr(entries[0], "runtime_data", hass.data.get("shopping_list"))

payload = {"command": "sendText", "text": "Что в списке покупок"}
card = await glagol.send(payload)

while for_remove := shopping_for_remove(data, card["text"]):
# не удаляет больше 5 элементов за раз
text = "Удали " + ", ".join(for_remove[:5])
await glagol.send({"command": "sendText", "text": text})
# обновим после изменений
card = await glagol.send(payload)

if for_add := shopping_for_add(data, card["text"]):
for item in for_add:
# плохо работает, если добавлять всё сразу через запятую
text = f"Добавь в список покупок {item}"
await glagol.send({"command": "sendText", "text": text})
# обновим после изменений
card = await glagol.send(payload)

shopping_save(hass, data, card["text"])
# Полностью облачный синк (стриминговая Алиса убила локальный glagol-путь,
# issue #631): читаем и пишем список через rpc.alice notes API.
note = await quasar.get_shopping_note()
if note is None:
_LOGGER.warning("shopping_sync: облачный «Список покупок» не найден")
return

note_id = note["note_id"]
alice = quasar.note_active_items(note) # {текст: subtask_id}

# Выполненные в HA → удалить у Алисы (галка = куплено = убрать из
# списка, как в исходном glagol-синке)
for item in data.items:
if item["complete"] and item["name"] in alice:
await quasar.delete_shopping_item(note_id, alice[item["name"]])

# Новые в HA (не из Алисы) — добавить Алисе
for item in data.items:
if (
not item["complete"]
and item["name"] not in alice
and not item["id"].startswith("alice")
):
await quasar.add_shopping_item(note_id, item["name"])

# Перечитать актуальный список Алисы и отразить его в HA
note = await quasar.get_shopping_note()
card_text = alice_text(list(quasar.note_active_items(note).keys()))
shopping_save(hass, data, card_text)
except Exception as e:
_LOGGER.error("shopping_sync", exc_info=e)
131 changes: 47 additions & 84 deletions custom_components/yandex_station/hass/todo_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from homeassistant.core import HomeAssistant
from homeassistant.helpers.storage import Store

from ..core.yandex_glagol import YandexGlagol
from ..core.yandex_quasar import YandexQuasar

_LOGGER = logging.getLogger(__package__)

Expand All @@ -14,6 +14,11 @@
STORE_KEY = "yandex_station.todo"


def alice_text(items: list[str]) -> str:
"""Собрать нумерованный текст в формате карточки Алисы (под RE_TODO)."""
return "\n".join(f"{i + 1}) {name}" for i, name in enumerate(items))


async def get_todo_items(hass: HomeAssistant, entity_id: str) -> list[dict]:
response = await hass.services.async_call(
"todo",
Expand All @@ -34,59 +39,6 @@ async def get_todo_items(hass: HomeAssistant, entity_id: str) -> list[dict]:
return data.get("items", [])


def todo_for_remove(
todo_items: list[dict], alice_data: str, previous_alice_items: set[str]
) -> list[str]:
alice_items = RE_TODO.findall(alice_data)

current_todo_items = {
item.get("summary") for item in todo_items if item.get("summary")
}

for_remove = []
alice_indexes = {item: i for i, item in enumerate(alice_items)}

# Помечены как завершенные
for item in todo_items:
summary = item.get("summary")
if summary and item.get("status") == "completed" and summary in alice_items:
for_remove.append(alice_indexes[summary])

# Удалены пользователем из ToDo
for summary in previous_alice_items - current_todo_items:
if summary in alice_items:
for_remove.append(alice_indexes[summary])

return [str(i + 1) for i in sorted(set(for_remove))]


async def todo_for_add(
todo_items: list[dict], alice_data: str, previous_alice_items: set[str]
) -> list[str]:
alice_items = set(RE_TODO.findall(alice_data))

result = []

for item in todo_items:
status = item.get("status", "needs_action")
summary = item.get("summary")

if status == "completed" or not summary:
continue

# Элемент уже есть у Алисы
if summary in alice_items:
continue

# Раньше был у Алисы, но пользователь удалил
if summary in previous_alice_items:
continue

result.append(summary)

return result


async def todo_save(hass: HomeAssistant, entity_id: str, alice_data: str) -> None:
alice_items = set(RE_TODO.findall(alice_data))

Expand Down Expand Up @@ -125,47 +77,58 @@ async def todo_save(hass: HomeAssistant, entity_id: str, alice_data: str) -> Non


async def shopping_sync(
hass: HomeAssistant, glagol: YandexGlagol, entity_id: str
hass: HomeAssistant, quasar: YandexQuasar, entity_id: str
) -> None:
try:
# Элементы из списка Home Assistant
items = await get_todo_items(hass, entity_id)

payload = {"command": "sendText", "text": "Что в списке покупок"}
card = await glagol.send(payload)
# Полностью облачный синк (стриминговая Алиса убила локальный glagol-путь,
# issue #631): читаем и пишем список Алисы через rpc.alice notes API.
note = await quasar.get_shopping_note()
if note is None:
_LOGGER.warning("todo_sync: облачный «Список покупок» не найден")
return

note_id = note["note_id"]
alice = quasar.note_active_items(note) # {текст: subtask_id}

store = Store(hass, STORE_VERSION, STORE_KEY)
store_data = await store.async_load() or {}

# Элементы ранее синхронизированные с алисой
previous_alice_items = set(store_data.get(entity_id) or [])

# Удаляем выполненные
while for_remove := todo_for_remove(items, card["text"], previous_alice_items):
# Не удаляет больше 2-х элементов за раз
await glagol.send(
{"command": "sendText", "text": "Удали " + ", ".join(for_remove[:2])}
)
card = await glagol.send(payload)

# Добавляем новые элементы в список по одному
if for_add := await todo_for_add(items, card["text"], previous_alice_items):
for item in for_add:
await glagol.send(
{"command": "sendText", "text": f"Добавь в список покупок {item}"}
)
card = await glagol.send(payload)

# Сохраняем изменения из Алисы в ToDo
await todo_save(hass, entity_id, card["text"])

# Обновляем Store
current_alice_items = set(RE_TODO.findall(card["text"]))
store_data[entity_id] = current_alice_items
current_todo = {item.get("summary") for item in items if item.get("summary")}

# Выполненные в ToDo → удалить у Алисы (галка = куплено = убрать из
# списка, как в исходном glagol-синке)
for item in items:
summary = item.get("summary")
if summary and item.get("status") == "completed" and summary in alice:
await quasar.delete_shopping_item(note_id, alice[summary])

# Удалённые пользователем из ToDo → удалить у Алисы
for summary in previous_alice_items - current_todo:
if summary in alice:
await quasar.delete_shopping_item(note_id, alice[summary])

# Добавляем Алисе новые активные элементы (которых нет у неё и которые
# пользователь ранее не удалял из Алисы)
for item in items:
status = item.get("status", "needs_action")
summary = item.get("summary")
if status == "completed" or not summary:
continue
if summary in alice or summary in previous_alice_items:
continue
await quasar.add_shopping_item(note_id, summary)

# Перечитать актуальный список Алисы, отразить в ToDo и обновить Store
note = await quasar.get_shopping_note()
card_text = alice_text(list(quasar.note_active_items(note).keys()))
await todo_save(hass, entity_id, card_text)

store_data[entity_id] = set(RE_TODO.findall(card_text))
await store.async_save(store_data)

# Остановим алису
await glagol.send({"command": "sendText", "text": "Стоп"})

except Exception as e:
_LOGGER.error("todo_sync", exc_info=e)