recipe links
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
# Home Assistant integration
|
||||
|
||||
This integration connects one user's TasksNest grocery list and, optionally, one planner task list to separate Home Assistant `todo.*` entities. The user configures the URL and long-lived access token at `/settings/home-assistant/`, tests the connection, discovers entities, chooses lists, and reviews signed previews before each list's first sync. A preview expires after ten minutes and is recalculated before writes. Later syncs can be manual or run every 5, 15, or 30 minutes after the grocery first sync is confirmed.
|
||||
|
||||
Home Assistant is reached through its REST API: `todo.get_items` uses `POST /api/services/todo/get_items?return_response`; `todo.add_item` and `todo.update_item` use the corresponding service paths. Responses are parsed from `service_response[entity_id].items`, and mappings use the returned item UID. The selected entity's `supported_features` controls whether create and update actions are offered. See the [REST API](https://developers.home-assistant.io/docs/api/rest/), [get-items action](https://www.home-assistant.io/actions/todo.get_items/), and [to-do feature flags](https://developers.home-assistant.io/docs/core/entity/todo/).
|
||||
|
||||
Grocery sync shares only item name and needed/purchased state. New Home Assistant items become one-piece groceries. TasksNest quantity, unit, category, notes, product, inventory link, and recipe provenance stay local. The optional task sync shares title, completion, description, and scheduled date when the chosen Home Assistant entity advertises support. Task exports require Home Assistant create and due-date support; imports without a due date are skipped because TasksNest tasks require a scheduled date. Only active, top-level, non-recurring planner tasks sync. Recurrence, subtasks, priority, weather rules, and deferrals stay in TasksNest. A missing item is reported; it is never deleted on the other side. Equal titles without a UID mapping are flagged for review and not merged automatically. The default conflict winner is Home Assistant when both mapped sides changed. One direction modes apply the chosen side's syncable fields.
|
||||
|
||||
The sync uses per-user and per-entity UID mappings with local and remote fingerprints. A database lease prevents concurrent runs; at most twenty changes are applied per run. Automatic retries back off and stop after five consecutive failures; the user can re-enable them after reviewing the error. If an outbound add may have succeeded but its UID cannot be confirmed, its mapping remains pending. The next preview attempts UID reconciliation from a unique matching name but never blindly sends another add. A still-uncertain add can be reset only after the user confirms they checked the remote list. Recent run history and failure backoff are stored per connection.
|
||||
|
||||
Tokens are encrypted at rest with a Fernet key derived from Django's deployment `SECRET_KEY`. Rotating that key requires users to replace their Home Assistant tokens. Requests validate the destination, pin a checked DNS result for the socket, verify TLS, reject redirects, and use five-second timeouts. Private-network HTTP is permitted; public destinations require HTTPS. No token value is rendered or logged.
|
||||
|
||||
Automatic sync runs through `manage.py sync_home_assistant`; install `main/deploy/systemd/tasknest-home-assistant-sync.service` and `.timer` on the host to check for due syncs every minute. Automatic syncing is off by default. A live Home Assistant instance was not available during implementation, so API behavior is covered by mocked tests and a targeted browser smoke test with a fake server.
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Bounded Home Assistant REST client with validated, pinned destinations."""
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import ipaddress
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
class ConnectionError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _cipher():
|
||||
# Derive a distinct encryption key from Django's deployment secret.
|
||||
key = hashlib.sha256(b'tasksnest-home-assistant-token-v1:' + settings.SECRET_KEY.encode()).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(key))
|
||||
|
||||
|
||||
def encrypt_token(token):
|
||||
return _cipher().encrypt(token.encode()).decode()
|
||||
|
||||
|
||||
def decrypt_token(value):
|
||||
try:
|
||||
return _cipher().decrypt(value.encode()).decode()
|
||||
except (InvalidToken, UnicodeError):
|
||||
raise ConnectionError('The saved Home Assistant token could not be read. Replace it in Settings.') from None
|
||||
|
||||
|
||||
def _addresses(host, port):
|
||||
addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
||||
if not addresses:
|
||||
raise ValueError
|
||||
ips = [ipaddress.ip_address(entry[4][0]) for entry in addresses]
|
||||
if any(ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved for ip in ips):
|
||||
raise ValueError
|
||||
return ips
|
||||
|
||||
|
||||
def normalize_url(raw):
|
||||
try:
|
||||
parts = urlsplit(raw.strip())
|
||||
if parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password:
|
||||
raise ValueError
|
||||
if parts.path not in {'', '/'} or parts.query or parts.fragment:
|
||||
raise ValueError
|
||||
port = parts.port
|
||||
ips = _addresses(parts.hostname, port or (443 if parts.scheme == 'https' else 80))
|
||||
if parts.scheme == 'http' and not all(ip.is_private for ip in ips):
|
||||
raise ConnectionError('HTTP is allowed only for private network addresses. Use HTTPS for public servers.')
|
||||
return urlunsplit((parts.scheme, parts.netloc.lower(), '', '', ''))
|
||||
except ConnectionError:
|
||||
raise
|
||||
except (ValueError, OverflowError, socket.gaierror):
|
||||
raise ConnectionError('Enter a reachable Home Assistant URL without a path, query, or credentials.') from None
|
||||
|
||||
|
||||
def _request_json(base_url, token, path, payload=None):
|
||||
# Connect to the validated IP while retaining the hostname for Host and TLS SNI.
|
||||
# This prevents a second DNS lookup from redirecting the socket to another address.
|
||||
base_url = normalize_url(base_url)
|
||||
parts = urlsplit(base_url)
|
||||
port = parts.port or (443 if parts.scheme == 'https' else 80)
|
||||
try:
|
||||
ips = _addresses(parts.hostname, port)
|
||||
if parts.scheme == 'http' and not all(address.is_private for address in ips):
|
||||
raise ValueError
|
||||
ip = str(ips[0])
|
||||
except (ValueError, socket.gaierror):
|
||||
raise ConnectionError('Home Assistant could not be reached.') from None
|
||||
connection_type = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection
|
||||
kwargs = {'timeout': 5}
|
||||
if parts.scheme == 'https':
|
||||
kwargs['context'] = ssl.create_default_context()
|
||||
connection = connection_type(parts.hostname, port, **kwargs)
|
||||
connection._create_connection = lambda _address, timeout, source_address=None: socket.create_connection(
|
||||
(ip, port), timeout, source_address)
|
||||
try:
|
||||
body = json.dumps(payload).encode() if payload is not None else None
|
||||
headers = {'Authorization': 'Bearer ' + token, 'Accept': 'application/json', 'Host': parts.netloc}
|
||||
if body is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
connection.request('POST' if body is not None else 'GET', path, body=body, headers=headers)
|
||||
response = connection.getresponse()
|
||||
if response.status == 401:
|
||||
raise ConnectionError('Token rejected (401). Check the long-lived access token.') from None
|
||||
if response.status in {301, 302, 303, 307, 308}:
|
||||
raise ConnectionError('The server redirected the request. Enter its final URL instead.')
|
||||
if response.status != 200:
|
||||
error_body = response.read(4096).decode('utf-8', 'replace').lower()
|
||||
if response.status >= 500 and 'did not match any entities' in error_body:
|
||||
raise ConnectionError(
|
||||
'The selected Home Assistant to-do list is unavailable. Refresh the discovered lists '
|
||||
'and choose an available list in Home Assistant settings.'
|
||||
) from None
|
||||
raise ConnectionError(f'Home Assistant returned HTTP {response.status}.')
|
||||
response_body = response.read(1024 * 1024 + 1)
|
||||
if len(response_body) > 1024 * 1024:
|
||||
raise ConnectionError('Home Assistant returned too much data.')
|
||||
return json.loads(response_body)
|
||||
except (TimeoutError, OSError, ssl.SSLError) as exc:
|
||||
reason = str(exc).lower()
|
||||
if 'certificate' in reason or 'ssl' in reason:
|
||||
raise ConnectionError('TLS certificate verification failed.') from None
|
||||
if 'timed out' in reason:
|
||||
raise ConnectionError('Connection timed out after five seconds.') from None
|
||||
raise ConnectionError('Home Assistant could not be reached.') from None
|
||||
except ConnectionError:
|
||||
raise
|
||||
except (ValueError, UnicodeError):
|
||||
raise ConnectionError('Home Assistant returned invalid JSON.') from None
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _get_json(base_url, token, path):
|
||||
return _request_json(base_url, token, path)
|
||||
|
||||
|
||||
def test_connection(base_url, token):
|
||||
data = _get_json(base_url, token, '/api/config')
|
||||
if not isinstance(data, dict) or not data.get('version'):
|
||||
raise ConnectionError('This does not look like a Home Assistant server.')
|
||||
return str(data['version'])[:100]
|
||||
|
||||
|
||||
def discover_entities(base_url, token):
|
||||
data = _get_json(base_url, token, '/api/states')
|
||||
if not isinstance(data, list):
|
||||
raise ConnectionError('Home Assistant returned an invalid entity list.')
|
||||
entities = []
|
||||
for state in data:
|
||||
if not isinstance(state, dict) or not str(state.get('entity_id', '')).startswith('todo.'):
|
||||
continue
|
||||
entity_id = str(state['entity_id'])[:255]
|
||||
attrs = state.get('attributes') or {}
|
||||
name = str(attrs.get('friendly_name') or entity_id)[:255] if isinstance(attrs, dict) else entity_id
|
||||
try:
|
||||
features = int(attrs.get('supported_features', 0)) if isinstance(attrs, dict) else 0
|
||||
except (TypeError, ValueError):
|
||||
features = 0
|
||||
entities.append({'id': entity_id, 'name': name, 'features': max(0, features),
|
||||
'available': isinstance(state.get('state'), str) and state['state'] != 'unavailable'})
|
||||
return sorted(entities, key=lambda entity: entity['name'].lower())
|
||||
|
||||
|
||||
def get_items(base_url, token, entity_id):
|
||||
if not entity_id.startswith('todo.'):
|
||||
raise ConnectionError('Choose a valid to-do list.')
|
||||
response = _request_json(base_url, token, '/api/services/todo/get_items?return_response',
|
||||
{'entity_id': entity_id, 'status': ['needs_action', 'completed']})
|
||||
try:
|
||||
items = response['service_response'][entity_id]['items']
|
||||
if not isinstance(items, list):
|
||||
raise KeyError
|
||||
result = {}
|
||||
for item in items:
|
||||
uid = item['uid']
|
||||
summary = item['summary']
|
||||
status = item['status']
|
||||
if not isinstance(uid, str) or not uid or len(uid) > 255 or not isinstance(summary, str) or not summary.strip() or len(summary.strip()) > 180 or status not in {'needs_action', 'completed'} or uid in result:
|
||||
raise KeyError
|
||||
due = item.get('due')
|
||||
if due is not None and (not isinstance(due, str) or len(due) > 64):
|
||||
raise KeyError
|
||||
description = item.get('description') or ''
|
||||
if not isinstance(description, str) or len(description) > 10000:
|
||||
raise KeyError
|
||||
result[uid] = {'uid': uid, 'name': summary.strip(), 'status': status,
|
||||
'due': due, 'description': description}
|
||||
return result
|
||||
except (KeyError, TypeError, AttributeError):
|
||||
raise ConnectionError('Home Assistant returned an incomplete to-do list. No changes were made.') from None
|
||||
|
||||
|
||||
def add_item(base_url, token, entity_id, name, *, due_date=None, description=None):
|
||||
data = {'entity_id': entity_id, 'item': name}
|
||||
if due_date is not None:
|
||||
data['due_date'] = due_date
|
||||
if description:
|
||||
data['description'] = description
|
||||
return _request_json(base_url, token, '/api/services/todo/add_item', data)
|
||||
|
||||
|
||||
def update_item(base_url, token, entity_id, uid, *, name=None, status=None, due_date=None,
|
||||
description=None):
|
||||
data = {'entity_id': entity_id, 'item': uid}
|
||||
if name is not None:
|
||||
data['rename'] = name
|
||||
if status is not None:
|
||||
data['status'] = status
|
||||
if due_date is not None:
|
||||
data['due_date'] = due_date
|
||||
if description is not None:
|
||||
data['description'] = description
|
||||
return _request_json(base_url, token, '/api/services/todo/update_item', data)
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from home_assistant.sync import run_due_syncs
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Run due Home Assistant grocery syncs.'
|
||||
|
||||
def handle(self, *args, **options):
|
||||
result = run_due_syncs()
|
||||
self.stdout.write(
|
||||
f"Home Assistant syncs: {result['succeeded']} succeeded, "
|
||||
f"{result['failed']} failed, {result['attempted']} attempted."
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
initial = True
|
||||
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='HomeAssistantConnection',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('base_url', models.URLField(max_length=500)),
|
||||
('encrypted_token', models.TextField()),
|
||||
('grocery_entity_id', models.CharField(blank=True, max_length=255)),
|
||||
('entities', models.JSONField(blank=True, default=list)),
|
||||
('version', models.CharField(blank=True, max_length=100)),
|
||||
('last_tested_at', models.DateTimeField(blank=True, null=True)),
|
||||
('last_error', models.CharField(blank=True, max_length=255)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='home_assistant_connection', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('home_assistant', '0001_initial'), ('groceries', '0003_groceryitem_inventory_transfer_and_more')]
|
||||
operations = [
|
||||
migrations.AddField(model_name='homeassistantconnection', name='direction', field=models.CharField(choices=[('both', 'Two-way'), ('from_ha', 'Home Assistant to TasksNest'), ('to_ha', 'TasksNest to Home Assistant')], default='both', max_length=10)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='conflict_winner', field=models.CharField(choices=[('ha', 'Home Assistant'), ('tasksnest', 'TasksNest')], default='ha', max_length=10)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='initial_sync_confirmed', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='sync_lock_until', field=models.DateTimeField(blank=True, null=True)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='last_synced_at', field=models.DateTimeField(blank=True, null=True)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='last_sync_error', field=models.CharField(blank=True, max_length=255)),
|
||||
migrations.CreateModel(name='HomeAssistantItemMap', fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('entity_id', models.CharField(max_length=255)),
|
||||
('ha_uid', models.CharField(blank=True, max_length=255)),
|
||||
('last_local_hash', models.CharField(blank=True, max_length=64)),
|
||||
('last_remote_hash', models.CharField(blank=True, max_length=64)),
|
||||
('pending_create', models.BooleanField(default=False)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('connection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_maps', to='home_assistant.homeassistantconnection')),
|
||||
('grocery', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='groceries.groceryitem')),
|
||||
], options={'constraints': [
|
||||
models.UniqueConstraint(fields=('connection', 'entity_id', 'grocery'), name='ha_unique_grocery_mapping'),
|
||||
models.UniqueConstraint(condition=~models.Q(ha_uid=''), fields=('connection', 'entity_id', 'ha_uid'), name='ha_unique_uid_mapping'),
|
||||
]}),
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('home_assistant', '0002_sync')]
|
||||
operations = [
|
||||
migrations.AddField(model_name='homeassistantconnection', name='auto_sync_enabled', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='sync_interval_minutes', field=models.CharField(choices=[('manual', 'Manual only'), ('5', 'Every 5 minutes'), ('15', 'Every 15 minutes'), ('30', 'Every 30 minutes')], default='15', max_length=6)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='next_sync_at', field=models.DateTimeField(blank=True, null=True)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='consecutive_sync_failures', field=models.PositiveSmallIntegerField(default=0)),
|
||||
migrations.CreateModel(name='HomeAssistantSyncRun', fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('succeeded', models.BooleanField(default=False)),
|
||||
('automatic', models.BooleanField(default=False)),
|
||||
('changes_applied', models.PositiveSmallIntegerField(default=0)),
|
||||
('summary', models.CharField(blank=True, max_length=255)),
|
||||
('error', models.CharField(blank=True, max_length=255)),
|
||||
('connection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sync_runs', to='home_assistant.homeassistantconnection')),
|
||||
], options={'ordering': ('-created_at', '-pk')}),
|
||||
]
|
||||
@@ -0,0 +1,20 @@
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
('home_assistant', '0003_background_history'),
|
||||
('planner', '0006_assign_unambiguous_legacy_task_owners'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='homeassistantconnection', name='task_entity_id',
|
||||
field=models.CharField(blank=True, max_length=255)),
|
||||
migrations.AddField(model_name='homeassistantconnection', name='task_initial_sync_confirmed',
|
||||
field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='homeassistantitemmap', name='task', field=models.ForeignKey(
|
||||
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='planner.task')),
|
||||
migrations.AddConstraint(model_name='homeassistantitemmap', constraint=models.UniqueConstraint(
|
||||
fields=('connection', 'entity_id', 'task'), name='ha_unique_task_mapping')),
|
||||
]
|
||||
@@ -0,0 +1,80 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class HomeAssistantConnection(models.Model):
|
||||
class Direction(models.TextChoices):
|
||||
BOTH = 'both', 'Two-way'
|
||||
FROM_HA = 'from_ha', 'Home Assistant to TasksNest'
|
||||
TO_HA = 'to_ha', 'TasksNest to Home Assistant'
|
||||
|
||||
class ConflictWinner(models.TextChoices):
|
||||
HA = 'ha', 'Home Assistant'
|
||||
TASKSNEST = 'tasksnest', 'TasksNest'
|
||||
|
||||
class SyncInterval(models.TextChoices):
|
||||
MANUAL = 'manual', 'Manual only'
|
||||
FIVE = '5', 'Every 5 minutes'
|
||||
FIFTEEN = '15', 'Every 15 minutes'
|
||||
THIRTY = '30', 'Every 30 minutes'
|
||||
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
related_name='home_assistant_connection')
|
||||
base_url = models.URLField(max_length=500)
|
||||
encrypted_token = models.TextField()
|
||||
grocery_entity_id = models.CharField(max_length=255, blank=True)
|
||||
task_entity_id = models.CharField(max_length=255, blank=True)
|
||||
task_initial_sync_confirmed = models.BooleanField(default=False)
|
||||
direction = models.CharField(max_length=10, choices=Direction.choices, default=Direction.BOTH)
|
||||
conflict_winner = models.CharField(max_length=10, choices=ConflictWinner.choices, default=ConflictWinner.HA)
|
||||
auto_sync_enabled = models.BooleanField(default=False)
|
||||
sync_interval_minutes = models.CharField(max_length=6, choices=SyncInterval.choices, default=SyncInterval.FIFTEEN)
|
||||
initial_sync_confirmed = models.BooleanField(default=False)
|
||||
sync_lock_until = models.DateTimeField(null=True, blank=True)
|
||||
last_synced_at = models.DateTimeField(null=True, blank=True)
|
||||
last_sync_error = models.CharField(max_length=255, blank=True)
|
||||
next_sync_at = models.DateTimeField(null=True, blank=True)
|
||||
consecutive_sync_failures = models.PositiveSmallIntegerField(default=0)
|
||||
entities = models.JSONField(default=list, blank=True)
|
||||
version = models.CharField(max_length=100, blank=True)
|
||||
last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
last_error = models.CharField(max_length=255, blank=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def __str__(self):
|
||||
return f'Home Assistant connection for user {self.user_id}'
|
||||
|
||||
|
||||
class HomeAssistantSyncRun(models.Model):
|
||||
connection = models.ForeignKey(HomeAssistantConnection, on_delete=models.CASCADE, related_name='sync_runs')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
succeeded = models.BooleanField(default=False)
|
||||
automatic = models.BooleanField(default=False)
|
||||
changes_applied = models.PositiveSmallIntegerField(default=0)
|
||||
summary = models.CharField(max_length=255, blank=True)
|
||||
error = models.CharField(max_length=255, blank=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-created_at', '-pk')
|
||||
|
||||
|
||||
class HomeAssistantItemMap(models.Model):
|
||||
connection = models.ForeignKey(HomeAssistantConnection, on_delete=models.CASCADE, related_name='item_maps')
|
||||
entity_id = models.CharField(max_length=255)
|
||||
grocery = models.ForeignKey('groceries.GroceryItem', on_delete=models.SET_NULL, null=True, blank=True)
|
||||
task = models.ForeignKey('planner.Task', on_delete=models.SET_NULL, null=True, blank=True)
|
||||
ha_uid = models.CharField(max_length=255, blank=True)
|
||||
last_local_hash = models.CharField(max_length=64, blank=True)
|
||||
last_remote_hash = models.CharField(max_length=64, blank=True)
|
||||
pending_create = models.BooleanField(default=False)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=['connection', 'entity_id', 'grocery'],
|
||||
name='ha_unique_grocery_mapping'),
|
||||
models.UniqueConstraint(fields=['connection', 'entity_id', 'task'],
|
||||
name='ha_unique_task_mapping'),
|
||||
models.UniqueConstraint(fields=['connection', 'entity_id', 'ha_uid'],
|
||||
condition=~models.Q(ha_uid=''), name='ha_unique_uid_mapping'),
|
||||
]
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Conservative UID-based grocery reconciliation. Never deletes on either side."""
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import timedelta
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
|
||||
from groceries.models import GroceryItem
|
||||
from groceries.services import add as add_grocery, edit as edit_grocery
|
||||
|
||||
from .client import ConnectionError, add_item, decrypt_token, get_items, update_item
|
||||
from .models import HomeAssistantConnection, HomeAssistantItemMap, HomeAssistantSyncRun
|
||||
|
||||
|
||||
def _fingerprint(name, status):
|
||||
return hashlib.sha256(json.dumps([name, status], ensure_ascii=False).encode()).hexdigest()
|
||||
|
||||
|
||||
def _local_state(item):
|
||||
return {'name': item.name, 'status': 'completed' if item.status == GroceryItem.Status.PURCHASED else 'needs_action'}
|
||||
|
||||
|
||||
def _hash_state(state):
|
||||
return _fingerprint(state['name'], state['status'])
|
||||
|
||||
|
||||
def _snapshot(connection):
|
||||
if not connection.grocery_entity_id:
|
||||
raise ConnectionError('Choose a Home Assistant grocery list first.')
|
||||
token = decrypt_token(connection.encrypted_token)
|
||||
remote = get_items(connection.base_url, token, connection.grocery_entity_id)
|
||||
local = {str(item.pk): item for item in GroceryItem.objects.filter(user=connection.user)}
|
||||
maps = list(HomeAssistantItemMap.objects.filter(connection=connection,
|
||||
entity_id=connection.grocery_entity_id).select_related('grocery'))
|
||||
return token, local, remote, maps
|
||||
|
||||
|
||||
def build_plan(connection, local, remote, maps):
|
||||
operations = []
|
||||
issues = []
|
||||
pending_recoveries = []
|
||||
mapped_local = {str(link.grocery_id) for link in maps if link.grocery_id}
|
||||
mapped_remote = {link.ha_uid for link in maps if link.ha_uid}
|
||||
can_pull = connection.direction in {'both', 'from_ha'}
|
||||
can_push = connection.direction in {'both', 'to_ha'}
|
||||
entity = next((entry for entry in connection.entities if entry.get('id') == connection.grocery_entity_id), {})
|
||||
features = int(entity.get('features') or 0)
|
||||
can_create = bool(features & 1)
|
||||
can_update = bool(features & 4)
|
||||
|
||||
for link in sorted(maps, key=lambda item: item.pk):
|
||||
item = local.get(str(link.grocery_id)) if link.grocery_id else None
|
||||
ha = remote.get(link.ha_uid) if link.ha_uid else None
|
||||
if link.pending_create:
|
||||
if not item:
|
||||
issues.append('An unfinished Home Assistant addition lost its TasksNest item; review it manually.')
|
||||
continue
|
||||
candidates = [value for uid, value in remote.items() if uid not in mapped_remote and value['name'].casefold() == item.name.casefold()]
|
||||
if len(candidates) == 1:
|
||||
operations.append({'kind': 'reconcile', 'local_id': str(item.pk), 'uid': candidates[0]['uid'], 'label': item.name})
|
||||
else:
|
||||
issues.append(f'Addition of “{item.name}” is uncertain; review Home Assistant before retrying.')
|
||||
if not candidates:
|
||||
pending_recoveries.append({'mapping_id': link.pk, 'label': item.name})
|
||||
continue
|
||||
if not item or not ha:
|
||||
issues.append(f'Mapped item {link.ha_uid or "unknown"} is missing on one side; no deletion will occur.')
|
||||
continue
|
||||
local_state = _local_state(item)
|
||||
local_hash = _hash_state(local_state)
|
||||
remote_hash = _hash_state(ha)
|
||||
if local_hash == remote_hash:
|
||||
if link.last_local_hash != local_hash or link.last_remote_hash != remote_hash:
|
||||
operations.append({'kind': 'baseline', 'local_id': str(item.pk), 'uid': link.ha_uid, 'label': item.name})
|
||||
continue
|
||||
local_changed = local_hash != link.last_local_hash
|
||||
remote_changed = remote_hash != link.last_remote_hash
|
||||
if connection.direction == 'from_ha':
|
||||
winner = 'ha'
|
||||
elif connection.direction == 'to_ha':
|
||||
winner = 'tasksnest'
|
||||
elif local_changed and remote_changed:
|
||||
winner = connection.conflict_winner
|
||||
elif remote_changed:
|
||||
winner = 'ha'
|
||||
elif local_changed:
|
||||
winner = 'tasksnest'
|
||||
else:
|
||||
# Inconsistent prior snapshots must be reviewed, not guessed.
|
||||
issues.append(f'“{item.name}” has inconsistent sync history; no change was made.')
|
||||
continue
|
||||
if winner == 'ha' and can_pull:
|
||||
operations.append({'kind': 'pull', 'local_id': str(item.pk), 'uid': link.ha_uid, 'label': ha['name']})
|
||||
elif winner == 'tasksnest' and can_push:
|
||||
if can_update:
|
||||
operations.append({'kind': 'push', 'local_id': str(item.pk), 'uid': link.ha_uid, 'label': item.name})
|
||||
else:
|
||||
issues.append(f'“{item.name}” cannot be updated: this Home Assistant list is read-only.')
|
||||
|
||||
reconciled_uids = {action['uid'] for action in operations if action['kind'] == 'reconcile'}
|
||||
unmatched_local = [item for key, item in local.items() if key not in mapped_local]
|
||||
unmatched_remote = [item for uid, item in remote.items() if uid not in mapped_remote and uid not in reconciled_uids]
|
||||
local_names = {item.name.casefold() for item in local.values()}
|
||||
remote_names = {item['name'].casefold() for item in remote.values()}
|
||||
collisions = ({item.name.casefold() for item in unmatched_local} & remote_names) | (
|
||||
{item['name'].casefold() for item in unmatched_remote} & local_names)
|
||||
for name in sorted(collisions):
|
||||
issues.append(f'“{name}” exists on both lists without a UID mapping; review duplicates before syncing it.')
|
||||
if can_push:
|
||||
for item in sorted(unmatched_local, key=lambda row: str(row.pk)):
|
||||
if item.name.casefold() not in collisions:
|
||||
if can_create and (item.status == GroceryItem.Status.NEEDED or can_update):
|
||||
operations.append({'kind': 'export', 'local_id': str(item.pk), 'label': item.name})
|
||||
else:
|
||||
issues.append(f'“{item.name}” cannot be added: this Home Assistant list lacks create or update support.')
|
||||
if can_pull:
|
||||
for uid, item in sorted(remote.items()):
|
||||
if uid not in mapped_remote and uid not in reconciled_uids and item['name'].casefold() not in collisions:
|
||||
operations.append({'kind': 'import', 'uid': uid, 'label': item['name']})
|
||||
|
||||
state = {
|
||||
'connection': connection.pk, 'entity': connection.grocery_entity_id,
|
||||
'direction': connection.direction, 'winner': connection.conflict_winner,
|
||||
'features': features,
|
||||
'local': sorted((key, _hash_state(_local_state(item))) for key, item in local.items()),
|
||||
'remote': sorted((uid, _hash_state(item)) for uid, item in remote.items()),
|
||||
'maps': sorted((link.pk, str(link.grocery_id), link.ha_uid, link.last_local_hash,
|
||||
link.last_remote_hash, link.pending_create) for link in maps),
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(state, sort_keys=True).encode()).hexdigest()
|
||||
return {'operations': operations, 'issues': issues, 'pending_recoveries': pending_recoveries, 'digest': digest,
|
||||
'limited': len(operations) > 20}
|
||||
|
||||
|
||||
def preview(connection):
|
||||
_, local, remote, maps = _snapshot(connection)
|
||||
return build_plan(connection, local, remote, maps)
|
||||
|
||||
|
||||
def _mapping(connection, item, uid='', *, pending=False, local_hash='', remote_hash=''):
|
||||
return HomeAssistantItemMap.objects.create(
|
||||
connection=connection, entity_id=connection.grocery_entity_id, grocery=item,
|
||||
ha_uid=uid, pending_create=pending, last_local_hash=local_hash,
|
||||
last_remote_hash=remote_hash)
|
||||
|
||||
|
||||
def _record_run(connection, *, succeeded, automatic, changes=0, summary='', error=''):
|
||||
HomeAssistantSyncRun.objects.create(connection=connection, succeeded=succeeded,
|
||||
automatic=automatic, changes_applied=changes, summary=str(summary)[:255], error=str(error)[:255])
|
||||
old_ids = list(connection.sync_runs.order_by('-created_at', '-pk').values_list('pk', flat=True)[20:])
|
||||
if old_ids:
|
||||
HomeAssistantSyncRun.objects.filter(pk__in=old_ids).delete()
|
||||
|
||||
|
||||
def _schedule_after_success(connection, now):
|
||||
connection.consecutive_sync_failures = 0
|
||||
connection.last_synced_at = now
|
||||
connection.last_sync_error = ''
|
||||
if connection.auto_sync_enabled and connection.sync_interval_minutes != 'manual':
|
||||
connection.next_sync_at = now + timedelta(minutes=int(connection.sync_interval_minutes))
|
||||
else:
|
||||
connection.next_sync_at = None
|
||||
|
||||
|
||||
def _schedule_after_failure(connection, error, automatic):
|
||||
connection.last_sync_error = str(error)[:255]
|
||||
connection.consecutive_sync_failures = min(connection.consecutive_sync_failures + 1, 16)
|
||||
exhausted = connection.consecutive_sync_failures >= 5
|
||||
if exhausted:
|
||||
connection.auto_sync_enabled = False
|
||||
connection.next_sync_at = None
|
||||
elif connection.auto_sync_enabled and connection.sync_interval_minutes != 'manual':
|
||||
backoff = min(60, 5 * (2 ** min(connection.consecutive_sync_failures - 1, 4)))
|
||||
connection.next_sync_at = timezone.now() + timedelta(minutes=backoff)
|
||||
connection.save(update_fields=['last_sync_error', 'consecutive_sync_failures', 'next_sync_at',
|
||||
'auto_sync_enabled', 'updated_at'])
|
||||
_record_run(connection, succeeded=False, automatic=automatic, error=error,
|
||||
summary=('Automatic sync disabled after five consecutive failures.' if exhausted else
|
||||
'Automatic sync failed.' if automatic else 'Sync stopped after an error.'))
|
||||
|
||||
|
||||
def _apply(connection, token, action, local, remote):
|
||||
kind = action['kind']
|
||||
item = local.get(action.get('local_id'))
|
||||
uid = action.get('uid', '')
|
||||
ha = remote.get(uid)
|
||||
link = HomeAssistantItemMap.objects.filter(connection=connection,
|
||||
entity_id=connection.grocery_entity_id, grocery=item).first() if item else None
|
||||
if kind == 'import':
|
||||
if not ha:
|
||||
raise ConnectionError('The Home Assistant list changed. Preview again.')
|
||||
key = 'ha:' + hashlib.sha256(f'{connection.pk}:{connection.grocery_entity_id}:{uid}'.encode()).hexdigest()[:64]
|
||||
with transaction.atomic():
|
||||
item = add_grocery(connection.user, name=ha['name'], quantity=1, unit='pieces', idempotency_key=key)
|
||||
if ha['status'] == 'completed' and item.status != GroceryItem.Status.PURCHASED:
|
||||
edit_grocery(connection.user, item.pk, {'status': GroceryItem.Status.PURCHASED})
|
||||
_mapping(connection, item, uid, local_hash=_hash_state(ha), remote_hash=_hash_state(ha))
|
||||
return
|
||||
if not item:
|
||||
raise ConnectionError('A TasksNest item changed. Preview again.')
|
||||
local_state = _local_state(item)
|
||||
if kind == 'export':
|
||||
link = _mapping(connection, item, pending=True)
|
||||
add_item(connection.base_url, token, connection.grocery_entity_id, item.name)
|
||||
latest = get_items(connection.base_url, token, connection.grocery_entity_id)
|
||||
candidates = [value for candidate_uid, value in latest.items()
|
||||
if candidate_uid not in remote and value['name'] == item.name]
|
||||
if len(candidates) != 1:
|
||||
raise ConnectionError(f'Added “{item.name}”, but its new UID could not be identified. Review the list before retrying.')
|
||||
uid = candidates[0]['uid']
|
||||
link.ha_uid = uid
|
||||
link.pending_create = False
|
||||
link.last_remote_hash = _hash_state(candidates[0])
|
||||
link.last_local_hash = _hash_state(candidates[0])
|
||||
link.save()
|
||||
if local_state['status'] == 'completed':
|
||||
update_item(connection.base_url, token, connection.grocery_entity_id, uid, status='completed')
|
||||
verified = get_items(connection.base_url, token, connection.grocery_entity_id).get(uid)
|
||||
if not verified or verified['status'] != 'completed':
|
||||
raise ConnectionError(f'“{item.name}” was added but its completed state was not confirmed.')
|
||||
link.last_local_hash = _hash_state(local_state)
|
||||
link.last_remote_hash = _hash_state(verified)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
return
|
||||
if not link or not ha:
|
||||
raise ConnectionError('A mapped item changed. Preview again.')
|
||||
if kind == 'reconcile':
|
||||
link.ha_uid = uid
|
||||
link.pending_create = False
|
||||
link.last_local_hash = _hash_state(ha)
|
||||
link.last_remote_hash = _hash_state(ha)
|
||||
link.save()
|
||||
elif kind == 'pull':
|
||||
changes = {}
|
||||
if item.name != ha['name']:
|
||||
changes['name'] = ha['name']
|
||||
new_status = GroceryItem.Status.PURCHASED if ha['status'] == 'completed' else GroceryItem.Status.NEEDED
|
||||
if item.status != new_status:
|
||||
changes['status'] = new_status
|
||||
if changes:
|
||||
edit_grocery(connection.user, item.pk, changes)
|
||||
link.last_local_hash = _hash_state(ha)
|
||||
link.last_remote_hash = _hash_state(ha)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
elif kind == 'push':
|
||||
update_item(connection.base_url, token, connection.grocery_entity_id, uid,
|
||||
name=item.name if item.name != ha['name'] else None,
|
||||
status=local_state['status'] if local_state['status'] != ha['status'] else None)
|
||||
verified = get_items(connection.base_url, token, connection.grocery_entity_id).get(uid)
|
||||
if not verified or _hash_state(verified) != _hash_state(local_state):
|
||||
raise ConnectionError(f'Home Assistant did not confirm the update to “{item.name}”.')
|
||||
link.last_local_hash = _hash_state(local_state)
|
||||
link.last_remote_hash = _hash_state(verified)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
elif kind == 'baseline':
|
||||
link.last_local_hash = _hash_state(local_state)
|
||||
link.last_remote_hash = _hash_state(ha)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
|
||||
|
||||
def confirm_and_sync(connection, expected_digest, *, automatic=False):
|
||||
now = timezone.now()
|
||||
claimed = HomeAssistantConnection.objects.filter(pk=connection.pk).filter(
|
||||
Q(sync_lock_until__isnull=True) | Q(sync_lock_until__lt=now)).update(
|
||||
sync_lock_until=now + timedelta(minutes=3))
|
||||
if not claimed:
|
||||
raise ConnectionError('A sync is already running. Try again shortly.')
|
||||
try:
|
||||
connection.refresh_from_db()
|
||||
token, local, remote, maps = _snapshot(connection)
|
||||
plan = build_plan(connection, local, remote, maps)
|
||||
if plan['digest'] != expected_digest:
|
||||
raise ConnectionError('The lists changed after the preview. Review a fresh preview before syncing.')
|
||||
connection.initial_sync_confirmed = True
|
||||
connection.save(update_fields=['initial_sync_confirmed', 'updated_at'])
|
||||
done = 0
|
||||
for action in plan['operations'][:20]:
|
||||
_apply(connection, token, action, local, remote)
|
||||
done += 1
|
||||
# Refresh state so later actions see UIDs and items created in this run.
|
||||
token, local, remote, _ = _snapshot(connection)
|
||||
_schedule_after_success(connection, timezone.now())
|
||||
connection.save(update_fields=['last_synced_at', 'last_sync_error', 'next_sync_at',
|
||||
'consecutive_sync_failures', 'updated_at'])
|
||||
_record_run(connection, succeeded=True, automatic=automatic, changes=done,
|
||||
summary=f'Applied {done} change(s); {len(plan["issues"])} item(s) need review.')
|
||||
return done, plan
|
||||
except ConnectionError as exc:
|
||||
_schedule_after_failure(connection, exc, automatic)
|
||||
raise
|
||||
finally:
|
||||
HomeAssistantConnection.objects.filter(pk=connection.pk).update(sync_lock_until=None)
|
||||
|
||||
|
||||
def reset_pending_create(connection, expected_digest, mapping_id):
|
||||
now = timezone.now()
|
||||
claimed = HomeAssistantConnection.objects.filter(pk=connection.pk).filter(
|
||||
Q(sync_lock_until__isnull=True) | Q(sync_lock_until__lt=now)).update(
|
||||
sync_lock_until=now + timedelta(minutes=3))
|
||||
if not claimed:
|
||||
raise ConnectionError('A sync is already running. Try again shortly.')
|
||||
try:
|
||||
connection.refresh_from_db()
|
||||
_, local, remote, maps = _snapshot(connection)
|
||||
plan = build_plan(connection, local, remote, maps)
|
||||
if plan['digest'] != expected_digest:
|
||||
raise ConnectionError('The lists changed after the preview. Review a fresh preview.')
|
||||
mapping = HomeAssistantItemMap.objects.filter(pk=mapping_id, connection=connection,
|
||||
entity_id=connection.grocery_entity_id, pending_create=True).select_related('grocery').first()
|
||||
if not mapping or not mapping.grocery_id:
|
||||
raise ConnectionError('This pending addition can no longer be reset.')
|
||||
if any(item['name'].casefold() == mapping.grocery.name.casefold() for item in remote.values()):
|
||||
raise ConnectionError('A matching item is now visible in Home Assistant. Preview again to reconcile it.')
|
||||
mapping.delete()
|
||||
_record_run(connection, succeeded=True, automatic=False,
|
||||
summary=f'Reset uncertain addition for “{mapping.grocery.name}”.')
|
||||
finally:
|
||||
HomeAssistantConnection.objects.filter(pk=connection.pk).update(sync_lock_until=None)
|
||||
|
||||
|
||||
def run_due_syncs():
|
||||
now = timezone.now()
|
||||
due = HomeAssistantConnection.objects.filter(auto_sync_enabled=True,
|
||||
initial_sync_confirmed=True).exclude(sync_interval_minutes='manual').filter(
|
||||
Q(next_sync_at__isnull=True) | Q(next_sync_at__lte=now)).order_by('next_sync_at', 'pk')
|
||||
attempted = succeeded = failed = 0
|
||||
for connection in due.iterator():
|
||||
if connection.sync_lock_until and connection.sync_lock_until > now:
|
||||
continue
|
||||
attempted += 1
|
||||
grocery_failed = False
|
||||
try:
|
||||
plan = preview(connection)
|
||||
confirm_and_sync(connection, plan['digest'], automatic=True)
|
||||
succeeded += 1
|
||||
except ConnectionError as exc:
|
||||
grocery_failed = True
|
||||
failed += 1
|
||||
connection.refresh_from_db()
|
||||
# Preview can fail before confirm_and_sync claims a lock and records history.
|
||||
recent = connection.sync_runs.filter(created_at__gte=now).exists()
|
||||
if not recent:
|
||||
_schedule_after_failure(connection, exc, automatic=True)
|
||||
# Optional task sync shares the connection's scheduler and lease, but has
|
||||
# its own first-sync confirmation and item mapping namespace.
|
||||
connection.refresh_from_db()
|
||||
if not grocery_failed and connection.task_entity_id and connection.task_initial_sync_confirmed:
|
||||
runs_before = connection.sync_runs.count()
|
||||
try:
|
||||
from .task_sync import confirm_task_sync, preview_tasks
|
||||
task_plan = preview_tasks(connection)
|
||||
confirm_task_sync(connection, task_plan['digest'], automatic=True)
|
||||
succeeded += 1
|
||||
attempted += 1
|
||||
except ConnectionError as exc:
|
||||
failed += 1
|
||||
connection.refresh_from_db()
|
||||
if connection.sync_runs.count() == runs_before:
|
||||
_schedule_after_failure(connection, exc, automatic=True)
|
||||
return {'attempted': attempted, 'succeeded': succeeded, 'failed': failed}
|
||||
@@ -0,0 +1,357 @@
|
||||
"""Optional synchronization for simple, top-level TasksNest planner tasks."""
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import Task
|
||||
|
||||
from .client import ConnectionError, add_item, decrypt_token, get_items, update_item
|
||||
from .models import HomeAssistantConnection, HomeAssistantItemMap
|
||||
from .sync import _record_run, _schedule_after_failure, _schedule_after_success
|
||||
|
||||
FEATURE_CREATE = 1
|
||||
FEATURE_UPDATE = 4
|
||||
FEATURE_DUE_DATE = 16
|
||||
FEATURE_DESCRIPTION = 64
|
||||
|
||||
|
||||
def _due_date(value):
|
||||
if not value:
|
||||
return ''
|
||||
try:
|
||||
return date.fromisoformat(value[:10]).isoformat()
|
||||
except (TypeError, ValueError):
|
||||
raise ConnectionError('Home Assistant returned an invalid task due date.') from None
|
||||
|
||||
|
||||
def _local_state(task):
|
||||
return {
|
||||
'name': task.title,
|
||||
'status': 'completed' if task.is_completed else 'needs_action',
|
||||
'description': task.description,
|
||||
'due': task.scheduled_for.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _remote_state(item):
|
||||
return {
|
||||
'name': item['name'],
|
||||
'status': item['status'],
|
||||
'description': item.get('description', ''),
|
||||
'due': _due_date(item.get('due')),
|
||||
}
|
||||
|
||||
|
||||
def _hash(state):
|
||||
raw = json.dumps(state, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(raw.encode()).hexdigest()
|
||||
|
||||
|
||||
def _snapshot(connection):
|
||||
if not connection.task_entity_id:
|
||||
raise ConnectionError('Choose a Home Assistant task list first.')
|
||||
token = decrypt_token(connection.encrypted_token)
|
||||
remote = get_items(connection.base_url, token, connection.task_entity_id)
|
||||
tasks = list(Task.objects.filter(owner=connection.user))
|
||||
eligible = {str(task.pk): task for task in tasks
|
||||
if task.parent_task_id is None and task.is_active and not task.is_recurring}
|
||||
maps = list(HomeAssistantItemMap.objects.filter(connection=connection,
|
||||
entity_id=connection.task_entity_id).select_related('task'))
|
||||
return token, tasks, eligible, remote, maps
|
||||
|
||||
|
||||
def build_task_plan(connection, tasks, eligible, remote, maps):
|
||||
operations, issues, recoveries = [], [], []
|
||||
features = next((int(e.get('features') or 0) for e in connection.entities
|
||||
if e.get('id') == connection.task_entity_id), 0)
|
||||
can_create = bool(features & FEATURE_CREATE)
|
||||
can_update = bool(features & FEATURE_UPDATE)
|
||||
can_due = bool(features & FEATURE_DUE_DATE)
|
||||
can_description = bool(features & FEATURE_DESCRIPTION)
|
||||
mapped_local = {str(link.task_id) for link in maps if link.task_id}
|
||||
mapped_remote = {link.ha_uid for link in maps if link.ha_uid}
|
||||
|
||||
for task in tasks:
|
||||
if task.parent_task_id is not None:
|
||||
issues.append(f'“{task.title}” is a subtask and is not synced as a separate item.')
|
||||
elif not task.is_active:
|
||||
issues.append(f'“{task.title}” is inactive and is not synced.')
|
||||
elif task.is_recurring:
|
||||
issues.append(f'“{task.title}” recurs; recurring tasks are not synced as single list items.')
|
||||
|
||||
for link in sorted(maps, key=lambda row: row.pk):
|
||||
task = eligible.get(str(link.task_id)) if link.task_id else None
|
||||
ha = remote.get(link.ha_uid) if link.ha_uid else None
|
||||
if link.pending_create:
|
||||
if not task:
|
||||
issues.append('An unfinished Home Assistant task addition lost its TasksNest task; review it manually.')
|
||||
continue
|
||||
candidates = [row for uid, row in remote.items()
|
||||
if uid not in mapped_remote and row['name'].casefold() == task.title.casefold()]
|
||||
if len(candidates) == 1:
|
||||
operations.append({'kind': 'task_reconcile', 'local_id': str(task.pk),
|
||||
'uid': candidates[0]['uid'], 'label': task.title})
|
||||
else:
|
||||
issues.append(f'Addition of “{task.title}” is uncertain; review Home Assistant before retrying.')
|
||||
if not candidates:
|
||||
recoveries.append({'mapping_id': link.pk, 'label': task.title})
|
||||
continue
|
||||
if not task or not ha:
|
||||
issues.append(f'Mapped task {link.ha_uid or "unknown"} is missing on one side; no deletion will occur.')
|
||||
continue
|
||||
local_state, remote_state = _local_state(task), _remote_state(ha)
|
||||
local_hash, remote_hash = _hash(local_state), _hash(remote_state)
|
||||
if local_hash == remote_hash:
|
||||
if link.last_local_hash != local_hash or link.last_remote_hash != remote_hash:
|
||||
operations.append({'kind': 'task_baseline', 'local_id': str(task.pk),
|
||||
'uid': link.ha_uid, 'label': task.title})
|
||||
continue
|
||||
local_changed, remote_changed = local_hash != link.last_local_hash, remote_hash != link.last_remote_hash
|
||||
if connection.direction == 'from_ha':
|
||||
winner = 'ha'
|
||||
elif connection.direction == 'to_ha':
|
||||
winner = 'tasksnest'
|
||||
elif local_changed and remote_changed:
|
||||
winner = connection.conflict_winner
|
||||
elif remote_changed:
|
||||
winner = 'ha'
|
||||
elif local_changed:
|
||||
winner = 'tasksnest'
|
||||
else:
|
||||
issues.append(f'“{task.title}” has inconsistent sync history; no change was made.')
|
||||
continue
|
||||
if winner == 'ha' and connection.direction != 'to_ha':
|
||||
if not remote_state['due'] and local_state['due']:
|
||||
issues.append(f'“{task.title}” has no Home Assistant due date; TasksNest requires a scheduled date, so it was left unchanged.')
|
||||
elif remote_state['due'] and not can_due and remote_state['due'] != local_state['due']:
|
||||
issues.append(f'“{task.title}” has a due date this Home Assistant list cannot edit; review it manually.')
|
||||
elif remote_state['description'] and not can_description and remote_state['description'] != local_state['description']:
|
||||
issues.append(f'“{task.title}” has a description this Home Assistant list cannot edit; review it manually.')
|
||||
else:
|
||||
operations.append({'kind': 'task_pull', 'local_id': str(task.pk), 'uid': link.ha_uid,
|
||||
'label': ha['name']})
|
||||
elif winner == 'tasksnest' and connection.direction != 'from_ha':
|
||||
unsupported = ((local_state['due'] != remote_state['due'] and not can_due)
|
||||
or (local_state['description'] != remote_state['description'] and not can_description))
|
||||
if not can_update:
|
||||
issues.append(f'“{task.title}” cannot be updated: this Home Assistant list is read-only.')
|
||||
elif unsupported:
|
||||
issues.append(f'“{task.title}” has fields this Home Assistant list cannot update; no fields were changed.')
|
||||
else:
|
||||
operations.append({'kind': 'task_push', 'local_id': str(task.pk), 'uid': link.ha_uid,
|
||||
'label': task.title})
|
||||
|
||||
unmatched = [task for key, task in eligible.items() if key not in mapped_local]
|
||||
unmatched_remote = [row for uid, row in remote.items() if uid not in mapped_remote]
|
||||
local_names = {task.title.casefold() for task in eligible.values()}
|
||||
remote_names = {row['name'].casefold() for row in remote.values()}
|
||||
collisions = ({task.title.casefold() for task in unmatched} & remote_names) | (
|
||||
{row['name'].casefold() for row in unmatched_remote} & local_names)
|
||||
for title in sorted(collisions):
|
||||
issues.append(f'“{title}” exists on both lists without a UID mapping; review duplicates before syncing it.')
|
||||
if connection.direction in {'both', 'to_ha'}:
|
||||
for task in sorted(unmatched, key=lambda row: str(row.pk)):
|
||||
state = _local_state(task)
|
||||
if len(task.title) > 180:
|
||||
issues.append(f'“{task.title[:80]}…” is longer than Home Assistant supports and was not exported.')
|
||||
continue
|
||||
unsupported = (not can_create or (task.is_completed and not can_update)
|
||||
or (state['due'] and not can_due)
|
||||
or (state['description'] and not can_description))
|
||||
if task.title.casefold() in collisions:
|
||||
continue
|
||||
if unsupported:
|
||||
issues.append(f'“{task.title}” needs create, update, due-date, and description support on the selected list.')
|
||||
else:
|
||||
operations.append({'kind': 'task_export', 'local_id': str(task.pk), 'label': task.title})
|
||||
if connection.direction in {'both', 'from_ha'}:
|
||||
for uid, item in sorted(remote.items()):
|
||||
if uid in mapped_remote or item['name'].casefold() in collisions:
|
||||
continue
|
||||
state = _remote_state(item)
|
||||
if not state['due']:
|
||||
issues.append(f'“{item["name"]}” has no due date; TasksNest requires a scheduled date, so it was not imported.')
|
||||
continue
|
||||
if (state['due'] and not can_due) or (state['description'] and not can_description):
|
||||
issues.append(f'“{item["name"]}” has fields this list cannot preserve in TasksNest; it was not imported.')
|
||||
continue
|
||||
operations.append({'kind': 'task_import', 'uid': uid, 'label': item['name']})
|
||||
|
||||
snapshot = {
|
||||
'connection': connection.pk, 'entity': connection.task_entity_id,
|
||||
'direction': connection.direction, 'winner': connection.conflict_winner, 'features': features,
|
||||
'local': sorted((key, _hash(_local_state(task))) for key, task in eligible.items()),
|
||||
'remote': sorted((uid, _hash(_remote_state(item))) for uid, item in remote.items()),
|
||||
'maps': sorted((row.pk, str(row.task_id), row.ha_uid, row.last_local_hash,
|
||||
row.last_remote_hash, row.pending_create) for row in maps),
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(snapshot, sort_keys=True).encode()).hexdigest()
|
||||
return {'operations': operations, 'issues': issues, 'pending_recoveries': recoveries,
|
||||
'digest': digest, 'limited': len(operations) > 20}
|
||||
|
||||
|
||||
def preview_tasks(connection):
|
||||
_, tasks, eligible, remote, maps = _snapshot(connection)
|
||||
return build_task_plan(connection, tasks, eligible, remote, maps)
|
||||
|
||||
|
||||
def _task_map(connection, task, uid='', *, pending=False, local_hash='', remote_hash=''):
|
||||
return HomeAssistantItemMap.objects.create(connection=connection, entity_id=connection.task_entity_id,
|
||||
task=task, ha_uid=uid, pending_create=pending, last_local_hash=local_hash,
|
||||
last_remote_hash=remote_hash)
|
||||
|
||||
|
||||
def _apply_task(connection, token, action, eligible, remote, features):
|
||||
kind, uid = action['kind'], action.get('uid', '')
|
||||
task = eligible.get(action.get('local_id'))
|
||||
ha = remote.get(uid)
|
||||
link = HomeAssistantItemMap.objects.filter(connection=connection,
|
||||
entity_id=connection.task_entity_id, task=task).first() if task else None
|
||||
if kind == 'task_import':
|
||||
if not ha:
|
||||
raise ConnectionError('The Home Assistant list changed. Preview again.')
|
||||
state = _remote_state(ha)
|
||||
with transaction.atomic():
|
||||
task = Task.objects.create(owner=connection.user, title=state['name'],
|
||||
description=state['description'], scheduled_for=date.fromisoformat(state['due']) if state['due'] else timezone.localdate(),
|
||||
is_completed=state['status'] == 'completed')
|
||||
_task_map(connection, task, uid, local_hash=_hash(state), remote_hash=_hash(state))
|
||||
return
|
||||
if not task:
|
||||
raise ConnectionError('A TasksNest task changed. Preview again.')
|
||||
state = _local_state(task)
|
||||
if kind == 'task_export':
|
||||
link = _task_map(connection, task, pending=True)
|
||||
add_item(connection.base_url, token, connection.task_entity_id, task.title,
|
||||
due_date=state['due'] if features & FEATURE_DUE_DATE else None,
|
||||
description=state['description'] if features & FEATURE_DESCRIPTION else None)
|
||||
latest = get_items(connection.base_url, token, connection.task_entity_id)
|
||||
candidates = [row for candidate_uid, row in latest.items()
|
||||
if candidate_uid not in remote and row['name'] == task.title]
|
||||
if len(candidates) != 1:
|
||||
raise ConnectionError(f'Added “{task.title}”, but its new UID could not be identified. Review the list before retrying.')
|
||||
item = candidates[0]
|
||||
uid = item['uid']
|
||||
link.ha_uid, link.pending_create = uid, False
|
||||
link.last_local_hash = link.last_remote_hash = _hash(_remote_state(item))
|
||||
link.save()
|
||||
if state['status'] == 'completed':
|
||||
update_item(connection.base_url, token, connection.task_entity_id, uid, status='completed')
|
||||
item = get_items(connection.base_url, token, connection.task_entity_id).get(uid)
|
||||
if not item or item['status'] != 'completed':
|
||||
raise ConnectionError(f'“{task.title}” was added but its completed state was not confirmed.')
|
||||
remote_state = _remote_state(item)
|
||||
link.last_local_hash = _hash(state)
|
||||
link.last_remote_hash = _hash(remote_state)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
return
|
||||
if not link or not ha:
|
||||
raise ConnectionError('A mapped task changed. Preview again.')
|
||||
if kind == 'task_reconcile':
|
||||
item = remote.get(uid)
|
||||
if not item:
|
||||
raise ConnectionError('The Home Assistant list changed. Preview again.')
|
||||
remote_state = _remote_state(item)
|
||||
link.ha_uid, link.pending_create = uid, False
|
||||
link.last_local_hash = link.last_remote_hash = _hash(remote_state)
|
||||
link.save()
|
||||
elif kind == 'task_baseline':
|
||||
task.refresh_from_db()
|
||||
local_state, remote_state = _local_state(task), _remote_state(ha)
|
||||
link.last_local_hash, link.last_remote_hash = _hash(local_state), _hash(remote_state)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
elif kind == 'task_pull':
|
||||
remote_state = _remote_state(ha)
|
||||
if not remote_state['due']:
|
||||
raise ConnectionError('Home Assistant removed a due date TasksNest requires. Review the task before syncing again.')
|
||||
task.title = remote_state['name']
|
||||
task.is_completed = remote_state['status'] == 'completed'
|
||||
task.description = remote_state['description']
|
||||
fields = ['title', 'is_completed', 'description', 'updated_at']
|
||||
if remote_state['due']:
|
||||
task.scheduled_for = date.fromisoformat(remote_state['due'])
|
||||
fields.append('scheduled_for')
|
||||
task.save(update_fields=fields)
|
||||
link.last_local_hash = link.last_remote_hash = _hash(remote_state)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
elif kind == 'task_push':
|
||||
remote_state = _remote_state(ha)
|
||||
update_item(connection.base_url, token, connection.task_entity_id, uid,
|
||||
name=state['name'] if state['name'] != remote_state['name'] else None,
|
||||
status=state['status'] if state['status'] != remote_state['status'] else None,
|
||||
due_date=state['due'] if state['due'] != remote_state['due'] else None,
|
||||
description=state['description'] if state['description'] != remote_state['description'] else None)
|
||||
item = get_items(connection.base_url, token, connection.task_entity_id).get(uid)
|
||||
if not item or _hash(_remote_state(item)) != _hash(state):
|
||||
raise ConnectionError(f'Home Assistant did not confirm the update to “{task.title}”.')
|
||||
link.last_local_hash = link.last_remote_hash = _hash(state)
|
||||
link.save(update_fields=['last_local_hash', 'last_remote_hash', 'updated_at'])
|
||||
|
||||
|
||||
def confirm_task_sync(connection, expected_digest, *, automatic=False):
|
||||
from datetime import timedelta
|
||||
from django.db import transaction
|
||||
now = timezone.now()
|
||||
claimed = HomeAssistantConnection.objects.filter(pk=connection.pk).filter(
|
||||
Q(sync_lock_until__isnull=True) | Q(sync_lock_until__lt=now)).update(
|
||||
sync_lock_until=now + timedelta(minutes=3))
|
||||
if not claimed:
|
||||
raise ConnectionError('A sync is already running. Try again shortly.')
|
||||
try:
|
||||
connection.refresh_from_db()
|
||||
token, tasks, eligible, remote, maps = _snapshot(connection)
|
||||
plan = build_task_plan(connection, tasks, eligible, remote, maps)
|
||||
if plan['digest'] != expected_digest:
|
||||
raise ConnectionError('The lists changed after the preview. Review a fresh preview before syncing.')
|
||||
connection.task_initial_sync_confirmed = True
|
||||
connection.save(update_fields=['task_initial_sync_confirmed', 'updated_at'])
|
||||
done = 0
|
||||
features = next((int(e.get('features') or 0) for e in connection.entities
|
||||
if e.get('id') == connection.task_entity_id), 0)
|
||||
for action in plan['operations'][:20]:
|
||||
_apply_task(connection, token, action, eligible, remote, features)
|
||||
done += 1
|
||||
token, tasks, eligible, remote, maps = _snapshot(connection)
|
||||
_schedule_after_success(connection, timezone.now())
|
||||
connection.save(update_fields=['last_synced_at', 'last_sync_error', 'next_sync_at',
|
||||
'consecutive_sync_failures', 'updated_at'])
|
||||
_record_run(connection, succeeded=True, automatic=automatic, changes=done,
|
||||
summary=f'Task sync applied {done} change(s); {len(plan["issues"])} item(s) need review.')
|
||||
return done, plan
|
||||
except ConnectionError as exc:
|
||||
_schedule_after_failure(connection, exc, automatic)
|
||||
raise
|
||||
finally:
|
||||
HomeAssistantConnection.objects.filter(pk=connection.pk).update(sync_lock_until=None)
|
||||
|
||||
|
||||
def reset_task_pending(connection, expected_digest, mapping_id):
|
||||
from datetime import timedelta
|
||||
now = timezone.now()
|
||||
claimed = HomeAssistantConnection.objects.filter(pk=connection.pk).filter(
|
||||
Q(sync_lock_until__isnull=True) | Q(sync_lock_until__lt=now)).update(
|
||||
sync_lock_until=now + timedelta(minutes=3))
|
||||
if not claimed:
|
||||
raise ConnectionError('A sync is already running. Try again shortly.')
|
||||
try:
|
||||
connection.refresh_from_db()
|
||||
_, tasks, eligible, remote, maps = _snapshot(connection)
|
||||
plan = build_task_plan(connection, tasks, eligible, remote, maps)
|
||||
if plan['digest'] != expected_digest:
|
||||
raise ConnectionError('The lists changed after the preview. Review a fresh preview.')
|
||||
mapping = HomeAssistantItemMap.objects.filter(pk=mapping_id, connection=connection,
|
||||
entity_id=connection.task_entity_id, pending_create=True).select_related('task').first()
|
||||
if not mapping or not mapping.task_id:
|
||||
raise ConnectionError('This pending task addition can no longer be reset.')
|
||||
if any(row['name'].casefold() == mapping.task.title.casefold() for row in remote.values()):
|
||||
raise ConnectionError('A matching item is now visible in Home Assistant. Preview again to reconcile it.')
|
||||
title = mapping.task.title
|
||||
mapping.delete()
|
||||
_record_run(connection, succeeded=True, automatic=False,
|
||||
summary=f'Reset uncertain task addition for “{title}”.')
|
||||
finally:
|
||||
HomeAssistantConnection.objects.filter(pk=connection.pk).update(sync_lock_until=None)
|
||||
@@ -0,0 +1,17 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Preview grocery sync · TasksNest{% endblock %}
|
||||
{% block content %}
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Home Assistant</p><h1>Preview grocery sync</h1>
|
||||
<p><a href="{% url 'home_assistant:settings' %}">← Home Assistant settings</a></p>
|
||||
<section class="settings-card">
|
||||
<h2>{% if first_sync %}First sync review{% else %}Changes to sync{% endif %}</h2>
|
||||
<p>Review these changes before anything is written. This preview expires after 10 minutes and is checked again when you confirm. At most 20 changes run at once.</p>
|
||||
{% if plan.operations %}<ul>{% for action in plan.operations %}<li><strong>{% if action.kind == 'export' %}Add to Home Assistant{% elif action.kind == 'import' %}Add to TasksNest{% elif action.kind == 'push' %}Update Home Assistant{% elif action.kind == 'pull' %}Update TasksNest{% elif action.kind == 'reconcile' %}Reconnect by UID{% else %}Record matching state{% endif %}:</strong> {{ action.label }}</li>{% endfor %}</ul>{% else %}<p>No changes are ready to sync.</p>{% endif %}
|
||||
{% if plan.limited %}<p>Only the first 20 changes will run. Preview again for the rest.</p>{% endif %}
|
||||
{% if plan.issues %}<h3>Needs review</h3><ul>{% for issue in plan.issues %}<li>{{ issue }}</li>{% endfor %}</ul>{% endif %}
|
||||
{% if plan.pending_recoveries %}<h3>Uncertain additions</h3><p>Check the Home Assistant list first. Reset only if the item is absent; if it appears, preview again so it can be matched.</p>{% for recovery in plan.pending_recoveries %}<form method="post">{% csrf_token %}<input type="hidden" name="preview_token" value="{{ preview_token }}"><input type="hidden" name="action" value="reset-pending"><input type="hidden" name="mapping_id" value="{{ recovery.mapping_id }}"><label><input type="checkbox" name="checked_absent" value="yes" required> I checked Home Assistant; “{{ recovery.label }}” is not there.</label> <button class="button button--secondary" type="submit">Reset pending addition</button></form>{% endfor %}{% endif %}
|
||||
{% if plan.operations or first_sync %}<form method="post">{% csrf_token %}<input type="hidden" name="preview_token" value="{{ preview_token }}"><button class="button" type="submit">{% if first_sync %}Confirm first sync{% else %}Sync these changes{% endif %}</button></form>{% endif %}
|
||||
</section>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,47 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Home Assistant · TasksNest{% endblock %}
|
||||
{% block content %}
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Integrations</p><h1>Home Assistant</h1>
|
||||
<p><a href="{% url 'planner:user-settings' %}">← Settings</a></p>
|
||||
<section class="settings-card" aria-labelledby="ha-connect-title">
|
||||
<h2 id="ha-connect-title">Connection</h2>
|
||||
<p>In Home Assistant, open your profile → Security → Long-Lived Access Tokens. Create a token and paste it here. For private network addresses, HTTP is allowed; use HTTPS for public servers.</p>
|
||||
<form method="post">{% csrf_token %}<input type="hidden" name="action" value="save"><input type="hidden" name="username" autocomplete="username" value="{{ request.user.username }}">
|
||||
<div class="form-field"><label for="ha-url">Instance URL</label><input id="ha-url" name="base_url" type="url" maxlength="500" required value="{% if connection %}{{ connection.base_url }}{% endif %}" placeholder="https://home.example.nl"></div>
|
||||
<div class="form-field"><label for="ha-token">Long-lived access token</label><input id="ha-token" name="token" type="password" maxlength="4096" autocomplete="new-password" {% if not connection %}required{% endif %} aria-describedby="ha-token-help"><small id="ha-token-help">{% if connection %}A token is saved. Leave blank to keep it; enter a new one to replace it.{% else %}The token is stored encrypted and is never shown again.{% endif %}</small></div>
|
||||
<button class="button" type="submit">Save connection</button>
|
||||
</form>
|
||||
{% if connection %}<p>Connection: {% if connection.last_tested_at %}Tested {{ connection.last_tested_at }} · Home Assistant {{ connection.version }}{% else %}Not tested{% endif %}</p>
|
||||
{% if connection.last_error %}<p role="alert">Last test: {{ connection.last_error }}</p>{% endif %}
|
||||
<form method="post">{% csrf_token %}<button class="button button--secondary" name="action" value="test">Test connection</button> <button class="button button--secondary" name="action" value="discover">Discover to-do lists</button></form>
|
||||
<form method="post">{% csrf_token %}<button class="button button--secondary" type="submit" name="action" value="disconnect">Disconnect and remove token</button></form>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% if connection and connection.entities %}<section class="settings-card" aria-labelledby="ha-lists-title">
|
||||
<h2 id="ha-lists-title">Grocery list</h2><p>Choose the Home Assistant to-do entity for your TasksNest groceries. Selecting a list does not sync or change any items.</p>
|
||||
<form method="post">{% csrf_token %}<div class="form-field"><label for="ha-grocery-list">Home Assistant list</label><select id="ha-grocery-list" name="grocery_entity_id" required><option value="">Choose a list</option>{% for entity in connection.entities %}<option value="{{ entity.id }}" {% if entity.id == connection.grocery_entity_id %}selected{% endif %} {% if entity.available == False %}disabled{% endif %}>{{ entity.name }} ({{ entity.id }}){% if entity.available == False %} — unavailable{% endif %}</option>{% endfor %}</select></div><button class="button" name="action" value="select">Save list</button></form>
|
||||
</section>{% endif %}
|
||||
{% if connection and connection.entities %}<section class="settings-card" aria-labelledby="ha-task-list-title">
|
||||
<h2 id="ha-task-list-title">Optional task list</h2>
|
||||
<p>Syncs only top-level, active, non-recurring tasks. Titles, completion, descriptions, and scheduled dates are shared when the selected Home Assistant list supports those fields. Recurrence, subtasks, priority, weather rules, and deferrals stay in TasksNest. If you also use Apple Reminders through the Home Assistant Companion app, set its list sync direction to “Beide kanten op” and its conflict preference to Home Assistant; iOS background sync may be delayed.</p>
|
||||
<form method="post">{% csrf_token %}<div class="form-field"><label for="ha-task-list">Home Assistant task list</label><select id="ha-task-list" name="task_entity_id"><option value="">Not connected</option>{% for entity in connection.entities %}{% if entity.id != connection.grocery_entity_id %}<option value="{{ entity.id }}" {% if entity.id == connection.task_entity_id %}selected{% endif %} {% if entity.available == False %}disabled{% endif %}>{{ entity.name }} ({{ entity.id }}){% if entity.available == False %} — unavailable{% endif %}</option>{% endif %}{% endfor %}</select></div><button class="button button--secondary" name="action" value="select-task">Save task list</button></form>
|
||||
{% if connection.task_entity_id %}<p>{% if connection.task_initial_sync_confirmed %}Task sync is enabled.{% else %}First task sync needs review and confirmation.{% endif %}</p><a class="button" href="{% url 'home_assistant:task-preview' %}">Preview task changes</a>{% endif %}
|
||||
</section>{% endif %}
|
||||
{% if connection and connection.grocery_entity_id %}<section class="settings-card" aria-labelledby="ha-sync-title">
|
||||
<h2 id="ha-sync-title">Grocery sync</h2>
|
||||
<p>TasksNest syncs item names and purchased status. Quantities, units, categories, product links, and inventory stay in TasksNest. Items absent from either list are never deleted automatically.</p>
|
||||
<form method="post">{% csrf_token %}<input type="hidden" name="action" value="sync-options">
|
||||
<div class="form-field"><label for="ha-direction">Direction</label><select id="ha-direction" name="direction"><option value="both" {% if connection.direction == 'both' %}selected{% endif %}>Two-way (recommended)</option><option value="from_ha" {% if connection.direction == 'from_ha' %}selected{% endif %}>Home Assistant → TasksNest</option><option value="to_ha" {% if connection.direction == 'to_ha' %}selected{% endif %}>TasksNest → Home Assistant</option></select></div>
|
||||
<div class="form-field"><label for="ha-winner">If both sides changed</label><select id="ha-winner" name="conflict_winner"><option value="ha" {% if connection.conflict_winner == 'ha' %}selected{% endif %}>Home Assistant wins (recommended)</option><option value="tasksnest" {% if connection.conflict_winner == 'tasksnest' %}selected{% endif %}>TasksNest wins</option></select></div>
|
||||
<div class="form-field"><label for="ha-interval">Automatic sync</label><select id="ha-interval" name="sync_interval_minutes"><option value="manual" {% if connection.sync_interval_minutes == 'manual' %}selected{% endif %}>Manual only</option><option value="5" {% if connection.sync_interval_minutes == '5' %}selected{% endif %}>Every 5 minutes</option><option value="15" {% if connection.sync_interval_minutes == '15' %}selected{% endif %}>Every 15 minutes</option><option value="30" {% if connection.sync_interval_minutes == '30' %}selected{% endif %}>Every 30 minutes</option></select></div>
|
||||
<div class="form-field"><label><input type="checkbox" name="auto_sync_enabled" {% if connection.auto_sync_enabled %}checked{% endif %} {% if not connection.initial_sync_confirmed %}disabled{% endif %}> Enable automatic sync</label>{% if not connection.initial_sync_confirmed %}<small>Confirm the first sync before enabling automatic sync.</small>{% endif %}</div>
|
||||
<button class="button button--secondary" type="submit">Save sync preferences</button>
|
||||
</form>
|
||||
<p>{% if connection.last_synced_at %}Last successful sync: {{ connection.last_synced_at }}{% else %}No sync has run yet.{% endif %}</p>
|
||||
{% if connection.last_sync_error %}<p role="alert">Last sync: {{ connection.last_sync_error }}</p>{% endif %}
|
||||
{% if history %}<h3>Recent sync activity</h3><ul>{% for run in history %}<li>{{ run.created_at }} · {% if run.succeeded %}Succeeded{% else %}Failed{% endif %}{% if run.automatic %} (automatic){% else %} (manual){% endif %} · {{ run.summary }}{% if run.error %}: {{ run.error }}{% endif %}</li>{% endfor %}</ul>{% endif %}
|
||||
<a class="button" href="{% url 'home_assistant:preview' %}">Preview changes</a>
|
||||
</section>{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,17 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Preview task sync · TasksNest{% endblock %}
|
||||
{% block content %}
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Home Assistant</p><h1>Preview task sync</h1>
|
||||
<p><a href="{% url 'home_assistant:settings' %}">← Home Assistant settings</a></p>
|
||||
<section class="settings-card">
|
||||
<h2>{% if first_sync %}First task sync review{% else %}Task changes to sync{% endif %}</h2>
|
||||
<p>Review changes before writing. The preview expires after 10 minutes and is checked again at confirmation. At most 20 changes run at once.</p>
|
||||
{% if plan.operations %}<ul>{% for action in plan.operations %}<li><strong>{% if action.kind == 'task_export' %}Add to Home Assistant{% elif action.kind == 'task_import' %}Add to TasksNest{% elif action.kind == 'task_push' %}Update Home Assistant{% elif action.kind == 'task_pull' %}Update TasksNest{% elif action.kind == 'task_reconcile' %}Reconnect by UID{% else %}Record matching state{% endif %}:</strong> {{ action.label }}</li>{% endfor %}</ul>{% else %}<p>No changes are ready to sync.</p>{% endif %}
|
||||
{% if plan.limited %}<p>Only the first 20 changes will run. Preview again for the rest.</p>{% endif %}
|
||||
{% if plan.issues %}<h3>Needs review</h3><ul>{% for issue in plan.issues %}<li>{{ issue }}</li>{% endfor %}</ul>{% endif %}
|
||||
{% if plan.pending_recoveries %}<h3>Uncertain additions</h3><p>Check the Home Assistant list first. Reset only if the task is absent; if it appears, preview again so it can be matched.</p>{% for recovery in plan.pending_recoveries %}<form method="post">{% csrf_token %}<input type="hidden" name="preview_token" value="{{ preview_token }}"><input type="hidden" name="action" value="reset-pending"><input type="hidden" name="mapping_id" value="{{ recovery.mapping_id }}"><label><input type="checkbox" name="checked_absent" value="yes" required> I checked Home Assistant; “{{ recovery.label }}” is not there.</label> <button class="button button--secondary" type="submit">Reset pending task addition</button></form>{% endfor %}{% endif %}
|
||||
{% if plan.operations or first_sync %}<form method="post">{% csrf_token %}<input type="hidden" name="preview_token" value="{{ preview_token }}"><button class="button" type="submit">{% if first_sync %}Confirm first task sync{% else %}Sync these task changes{% endif %}</button></form>{% endif %}
|
||||
</section>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,490 @@
|
||||
import hashlib
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
|
||||
from groceries.models import GroceryItem
|
||||
from planner.models import Task
|
||||
from .client import ConnectionError, _get_json, _request_json, decrypt_token, encrypt_token, get_items, normalize_url
|
||||
from .models import HomeAssistantConnection, HomeAssistantItemMap, HomeAssistantSyncRun
|
||||
from .sync import _schedule_after_failure, build_plan, confirm_and_sync, preview, run_due_syncs
|
||||
from .task_sync import confirm_task_sync, preview_tasks
|
||||
|
||||
|
||||
def dns_for(address):
|
||||
return [(2, 1, 6, '', (address, 8123))]
|
||||
|
||||
|
||||
@override_settings(SECURE_SSL_REDIRECT=False)
|
||||
class ConnectionTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='ha-user', password='example-password')
|
||||
self.other = get_user_model().objects.create_user(username='other-user', password='example-password')
|
||||
self.client.force_login(self.user)
|
||||
self.url = reverse('home_assistant:settings')
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
def test_token_is_encrypted_and_never_rendered(self, _dns):
|
||||
response = self.client.post(self.url, {'action': 'save', 'base_url': 'http://ha.local:8123/', 'token': 'private-token'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
connection = HomeAssistantConnection.objects.get(user=self.user)
|
||||
self.assertEqual(connection.base_url, 'http://ha.local:8123')
|
||||
self.assertNotIn('private-token', connection.encrypted_token)
|
||||
self.assertEqual(decrypt_token(connection.encrypted_token), 'private-token')
|
||||
self.assertNotContains(self.client.get(self.url), 'private-token')
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
def test_blank_token_keeps_previous_value_and_owner_isolation(self, _dns):
|
||||
HomeAssistantConnection.objects.create(user=self.user, base_url='http://ha.local:8123', encrypted_token=encrypt_token('old'))
|
||||
HomeAssistantConnection.objects.create(user=self.other, base_url='https://other.example', encrypted_token=encrypt_token('other'))
|
||||
self.client.post(self.url, {'action': 'save', 'base_url': 'http://ha.local:8123', 'token': ''})
|
||||
self.assertEqual(decrypt_token(HomeAssistantConnection.objects.get(user=self.user).encrypted_token), 'old')
|
||||
self.assertEqual(decrypt_token(HomeAssistantConnection.objects.get(user=self.other).encrypted_token), 'other')
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
@patch('home_assistant.views.test_connection', return_value='2026.10.0')
|
||||
@patch('home_assistant.views.discover_entities', return_value=[{'id': 'todo.shopping', 'name': 'Shopping'}])
|
||||
def test_discover_and_select_only_known_entity(self, _discover, _test, _dns):
|
||||
HomeAssistantConnection.objects.create(user=self.user, base_url='http://ha.local:8123', encrypted_token=encrypt_token('secret'))
|
||||
self.client.post(self.url, {'action': 'discover'})
|
||||
connection = HomeAssistantConnection.objects.get(user=self.user)
|
||||
self.assertEqual(connection.version, '2026.10.0')
|
||||
self.assertEqual(connection.entities[0]['id'], 'todo.shopping')
|
||||
self.client.post(self.url, {'action': 'select', 'grocery_entity_id': 'todo.foreign'})
|
||||
connection.refresh_from_db()
|
||||
self.assertEqual(connection.grocery_entity_id, '')
|
||||
self.client.post(self.url, {'action': 'select', 'grocery_entity_id': 'todo.shopping'})
|
||||
connection.refresh_from_db()
|
||||
self.assertEqual(connection.grocery_entity_id, 'todo.shopping')
|
||||
|
||||
def test_optional_task_entity_requires_discovery_and_can_be_disconnected(self):
|
||||
connection = HomeAssistantConnection.objects.create(user=self.user,
|
||||
base_url='https://ha.example', encrypted_token=encrypt_token('secret'),
|
||||
grocery_entity_id='todo.shopping', entities=[
|
||||
{'id': 'todo.shopping', 'name': 'Shopping'},
|
||||
{'id': 'todo.tasks', 'name': 'Tasks'},
|
||||
])
|
||||
self.client.post(self.url, {'action': 'select-task', 'task_entity_id': 'todo.unknown'})
|
||||
connection.refresh_from_db()
|
||||
self.assertEqual(connection.task_entity_id, '')
|
||||
self.client.post(self.url, {'action': 'select-task', 'task_entity_id': 'todo.tasks'})
|
||||
connection.refresh_from_db()
|
||||
self.assertEqual(connection.task_entity_id, 'todo.tasks')
|
||||
self.client.post(self.url, {'action': 'select-task', 'task_entity_id': ''})
|
||||
connection.refresh_from_db()
|
||||
self.assertEqual(connection.task_entity_id, '')
|
||||
self.assertEqual(connection.grocery_entity_id, 'todo.shopping')
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('8.8.8.8'))
|
||||
def test_public_http_rejected(self, _dns):
|
||||
with self.assertRaises(ConnectionError):
|
||||
normalize_url('http://example.com:8123')
|
||||
|
||||
def test_url_credentials_and_paths_rejected(self):
|
||||
for value in ('https://user:secret@example.com', 'https://example.com/api', 'file:///etc/passwd'):
|
||||
with self.subTest(value=value), self.assertRaises(ConnectionError):
|
||||
normalize_url(value)
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
def test_changing_host_requires_new_token(self, _dns):
|
||||
HomeAssistantConnection.objects.create(user=self.user, base_url='http://old.local:8123', encrypted_token=encrypt_token('old'))
|
||||
self.client.post(self.url, {'action': 'save', 'base_url': 'http://new.local:8123', 'token': ''})
|
||||
connection = HomeAssistantConnection.objects.get(user=self.user)
|
||||
self.assertEqual(connection.base_url, 'http://old.local:8123')
|
||||
|
||||
@patch('home_assistant.views.test_connection', side_effect=ConnectionError('Token rejected (401).'))
|
||||
def test_test_failure_is_sanitized_and_saved(self, _test):
|
||||
HomeAssistantConnection.objects.create(user=self.user, base_url='https://ha.example', encrypted_token=encrypt_token('secret'))
|
||||
self.client.post(self.url, {'action': 'test'})
|
||||
connection = HomeAssistantConnection.objects.get(user=self.user)
|
||||
self.assertEqual(connection.last_error, 'Token rejected (401).')
|
||||
self.assertNotIn('secret', connection.last_error)
|
||||
self.assertIsNone(connection.last_tested_at)
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
@patch('home_assistant.client.http.client.HTTPConnection')
|
||||
def test_api_rejects_redirect_and_unauthorized(self, connection_class, _dns):
|
||||
connection = connection_class.return_value
|
||||
response = MagicMock()
|
||||
connection.getresponse.return_value = response
|
||||
for status, expected in ((302, 'redirected'), (401, 'Token rejected')):
|
||||
response.status = status
|
||||
with self.subTest(status=status), self.assertRaisesRegex(ConnectionError, expected):
|
||||
_get_json('http://ha.local:8123', 'secret', '/api/config')
|
||||
self.assertEqual(connection.request.call_count, 2)
|
||||
self.assertEqual(connection.request.call_args.args[:2], ('GET', '/api/config'))
|
||||
|
||||
@patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10'))
|
||||
@patch('home_assistant.client.http.client.HTTPConnection')
|
||||
def test_unavailable_entity_error_is_actionable(self, connection_class, _dns):
|
||||
response = connection_class.return_value.getresponse.return_value
|
||||
response.status = 500
|
||||
response.read.return_value = b'{"message":"Service call requested response data but did not match any entities"}'
|
||||
with self.assertRaisesRegex(ConnectionError, 'selected Home Assistant to-do list is unavailable'):
|
||||
_request_json('http://ha.local:8123', 'secret', '/api/services/todo/get_items?return_response', {})
|
||||
|
||||
@patch('home_assistant.client._get_json', return_value=[
|
||||
{'entity_id': 'todo.active', 'state': '0', 'attributes': {'friendly_name': 'Active'}},
|
||||
{'entity_id': 'todo.offline', 'state': 'unavailable', 'attributes': {'friendly_name': 'Offline'}},
|
||||
])
|
||||
def test_discovery_marks_unavailable_entities(self, _get):
|
||||
from .client import discover_entities
|
||||
found = discover_entities('https://ha.example', 'token')
|
||||
self.assertTrue(next(entity for entity in found if entity['id'] == 'todo.active')['available'])
|
||||
self.assertFalse(next(entity for entity in found if entity['id'] == 'todo.offline')['available'])
|
||||
|
||||
@patch('home_assistant.client._request_json')
|
||||
def test_get_items_parses_service_response_and_rejects_duplicate_uids(self, request):
|
||||
request.return_value = {'changed_states': [], 'service_response': {'todo.shopping': {'items': [
|
||||
{'uid': 'one', 'summary': 'Milk', 'status': 'needs_action'},
|
||||
{'uid': 'two', 'summary': 'Bread', 'status': 'completed'},
|
||||
]}}}
|
||||
result = get_items('https://ha.example', 'token', 'todo.shopping')
|
||||
self.assertEqual(set(result), {'one', 'two'})
|
||||
self.assertEqual(request.call_args.args[2], '/api/services/todo/get_items?return_response')
|
||||
request.return_value['service_response']['todo.shopping']['items'][1]['uid'] = 'one'
|
||||
with self.assertRaises(ConnectionError):
|
||||
get_items('https://ha.example', 'token', 'todo.shopping')
|
||||
|
||||
|
||||
class FakeHomeAssistant:
|
||||
def __init__(self, items=None):
|
||||
self.items = {item['uid']: item.copy() for item in (items or [])}
|
||||
self.calls = []
|
||||
self.next_id = 1
|
||||
|
||||
def get(self, *_args):
|
||||
return {uid: item.copy() for uid, item in self.items.items()}
|
||||
|
||||
def add(self, _url, _token, _entity, name):
|
||||
self.calls.append(('add', name))
|
||||
uid = f'new-{self.next_id}'
|
||||
self.next_id += 1
|
||||
self.items[uid] = {'uid': uid, 'name': name, 'status': 'needs_action'}
|
||||
|
||||
def update(self, _url, _token, _entity, uid, *, name=None, status=None):
|
||||
self.calls.append(('update', uid, name, status))
|
||||
if name is not None:
|
||||
self.items[uid]['name'] = name
|
||||
if status is not None:
|
||||
self.items[uid]['status'] = status
|
||||
|
||||
|
||||
class FakeTaskHomeAssistant:
|
||||
def __init__(self, items=None):
|
||||
self.items = {item['uid']: item.copy() for item in (items or [])}
|
||||
self.next_id = 1
|
||||
|
||||
def get(self, *_args):
|
||||
return {uid: item.copy() for uid, item in self.items.items()}
|
||||
|
||||
def add(self, _url, _token, _entity, name, *, due_date=None, description=None):
|
||||
uid = f'task-{self.next_id}'
|
||||
self.next_id += 1
|
||||
self.items[uid] = {'uid': uid, 'name': name, 'status': 'needs_action',
|
||||
'due': due_date, 'description': description or ''}
|
||||
|
||||
def update(self, _url, _token, _entity, uid, *, name=None, status=None,
|
||||
due_date=None, description=None):
|
||||
item = self.items[uid]
|
||||
if name is not None:
|
||||
item['name'] = name
|
||||
if status is not None:
|
||||
item['status'] = status
|
||||
if due_date is not None:
|
||||
item['due'] = due_date
|
||||
if description is not None:
|
||||
item['description'] = description
|
||||
|
||||
|
||||
@override_settings(SECURE_SSL_REDIRECT=False)
|
||||
class GrocerySyncTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='sync-user')
|
||||
self.other = get_user_model().objects.create_user(username='sync-other')
|
||||
self.connection = HomeAssistantConnection.objects.create(
|
||||
user=self.user, base_url='https://ha.example', encrypted_token=encrypt_token('secret'),
|
||||
grocery_entity_id='todo.shopping',
|
||||
entities=[{'id': 'todo.shopping', 'name': 'Shopping', 'features': 5}])
|
||||
|
||||
def local(self, name, status='needed', user=None):
|
||||
return GroceryItem.objects.create(user=user or self.user, name=name, quantity=1,
|
||||
unit='pieces', status=status)
|
||||
|
||||
def run_with(self, fake):
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get), \
|
||||
patch('home_assistant.sync.add_item', side_effect=fake.add), \
|
||||
patch('home_assistant.sync.update_item', side_effect=fake.update):
|
||||
plan = preview(self.connection)
|
||||
result = confirm_and_sync(self.connection, plan['digest'])
|
||||
return plan, result
|
||||
|
||||
def test_first_sync_import_export_and_repeat_is_duplicate_free(self):
|
||||
local = self.local('Milk', 'purchased')
|
||||
self.local('Private', user=self.other)
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Bread', 'status': 'completed'}])
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual({action['kind'] for action in plan['operations']}, {'import', 'export'})
|
||||
self.assertEqual(done, 2)
|
||||
self.assertEqual(fake.items['new-1']['status'], 'completed')
|
||||
self.assertEqual(HomeAssistantItemMap.objects.filter(connection=self.connection).count(), 2)
|
||||
self.assertEqual(GroceryItem.objects.get(user=self.user, name='Bread').status, 'purchased')
|
||||
self.assertEqual(GroceryItem.objects.get(pk=local.pk).name, 'Milk')
|
||||
second, (done_again, _) = self.run_with(fake)
|
||||
self.assertEqual(second['operations'], [])
|
||||
self.assertEqual(done_again, 0)
|
||||
self.assertEqual(fake.calls.count(('add', 'Milk')), 1)
|
||||
self.assertFalse(GroceryItem.objects.filter(user=self.user, name='Private').exists())
|
||||
|
||||
def test_ambiguous_same_title_is_not_merged_or_duplicated(self):
|
||||
self.local('Eggs')
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Eggs', 'status': 'needs_action'}])
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual(done, 0)
|
||||
self.assertEqual(plan['operations'], [])
|
||||
self.assertTrue(plan['issues'])
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_remote_edit_and_completion_pull_into_local(self):
|
||||
item = self.local('Tea')
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Tea', 'status': 'needs_action'}])
|
||||
self.run_with(fake)
|
||||
# Initial same-title items are deliberately not matched; create a known mapping.
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item,
|
||||
ha_uid='ha-1', last_local_hash='x', last_remote_hash='x')
|
||||
fake.items['ha-1'].update(name='Green tea', status='completed')
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get):
|
||||
plan = preview(self.connection)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'pull')
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get):
|
||||
confirm_and_sync(self.connection, plan['digest'])
|
||||
item.refresh_from_db()
|
||||
self.assertEqual((item.name, item.status), ('Green tea', 'purchased'))
|
||||
|
||||
def test_missing_remote_does_not_delete_local(self):
|
||||
item = self.local('Rice')
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item,
|
||||
ha_uid='gone', last_local_hash='x', last_remote_hash='x')
|
||||
fake = FakeHomeAssistant()
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual(done, 0)
|
||||
self.assertTrue(plan['issues'])
|
||||
self.assertTrue(GroceryItem.objects.filter(pk=item.pk).exists())
|
||||
|
||||
def test_outbound_failure_stays_pending_and_does_not_retry_blindly(self):
|
||||
self.local('Oats')
|
||||
fake = FakeHomeAssistant()
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get), \
|
||||
patch('home_assistant.sync.add_item', side_effect=ConnectionError('Connection timed out.')):
|
||||
plan = preview(self.connection)
|
||||
with self.assertRaises(ConnectionError):
|
||||
confirm_and_sync(self.connection, plan['digest'])
|
||||
mapping = HomeAssistantItemMap.objects.get(connection=self.connection)
|
||||
self.assertTrue(mapping.pending_create)
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get):
|
||||
next_plan = preview(self.connection)
|
||||
self.assertFalse(next_plan['operations'])
|
||||
self.assertTrue(next_plan['issues'])
|
||||
|
||||
def test_two_sided_conflict_defaults_to_home_assistant(self):
|
||||
item = self.local('Original')
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'completed'}])
|
||||
baseline = hashlib.sha256(json.dumps(['Original', 'needs_action'], ensure_ascii=False).encode()).hexdigest()
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item,
|
||||
ha_uid='ha-1', last_local_hash=baseline, last_remote_hash=baseline)
|
||||
item.name = 'TasksNest edit'
|
||||
item.save()
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'pull')
|
||||
self.assertEqual(done, 1)
|
||||
item.refresh_from_db()
|
||||
self.assertEqual((item.name, item.status), ('Home edit', 'purchased'))
|
||||
|
||||
def test_two_sided_conflict_can_choose_tasksnest(self):
|
||||
item = self.local('Local edit')
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'completed'}])
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item,
|
||||
ha_uid='ha-1', last_local_hash='old', last_remote_hash='old')
|
||||
self.connection.conflict_winner = 'tasksnest'
|
||||
self.connection.save()
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'push')
|
||||
self.assertEqual(done, 1)
|
||||
self.assertEqual(fake.items['ha-1']['name'], 'Local edit')
|
||||
self.assertEqual(fake.items['ha-1']['status'], 'needs_action')
|
||||
|
||||
def test_direction_to_ha_pushes_and_unsupported_update_is_blocked(self):
|
||||
item = self.local('Original')
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'needs_action'}])
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item,
|
||||
ha_uid='ha-1', last_local_hash='previous', last_remote_hash='previous')
|
||||
self.connection.direction = 'to_ha'
|
||||
self.connection.save()
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'push')
|
||||
self.assertEqual(done, 1)
|
||||
self.assertEqual(fake.items['ha-1']['name'], 'Original')
|
||||
self.connection.entities = [{'id': 'todo.shopping', 'features': 1}]
|
||||
self.connection.save()
|
||||
item.name = 'Another edit'
|
||||
item.save()
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get):
|
||||
blocked = preview(self.connection)
|
||||
self.assertFalse(blocked['operations'])
|
||||
self.assertTrue(blocked['issues'])
|
||||
|
||||
def test_stale_preview_cannot_write(self):
|
||||
item = self.local('Apples')
|
||||
fake = FakeHomeAssistant()
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get), \
|
||||
patch('home_assistant.sync.add_item', side_effect=fake.add):
|
||||
digest = preview(self.connection)['digest']
|
||||
item.name = 'Oranges'
|
||||
item.save()
|
||||
with self.assertRaisesRegex(ConnectionError, 'changed after the preview'):
|
||||
confirm_and_sync(self.connection, digest)
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_preview_page_requires_signed_confirmation(self):
|
||||
self.client.force_login(self.user)
|
||||
self.local('Bananas')
|
||||
fake = FakeHomeAssistant()
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get):
|
||||
response = self.client.get(reverse('home_assistant:preview'))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Bananas')
|
||||
bad = self.client.post(reverse('home_assistant:preview'), {'preview_token': 'invalid'})
|
||||
self.assertEqual(bad.status_code, 302)
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_pending_addition_can_only_be_reset_after_checked_absent(self):
|
||||
item = self.local('Oats')
|
||||
mapping = HomeAssistantItemMap.objects.create(connection=self.connection,
|
||||
entity_id='todo.shopping', grocery=item, pending_create=True)
|
||||
self.client.force_login(self.user)
|
||||
with patch('home_assistant.sync.get_items', return_value={}):
|
||||
response = self.client.get(reverse('home_assistant:preview'))
|
||||
token = response.context['preview_token']
|
||||
refused = self.client.post(reverse('home_assistant:preview'), {
|
||||
'action': 'reset-pending', 'mapping_id': mapping.pk, 'preview_token': token,
|
||||
})
|
||||
self.assertEqual(refused.status_code, 302)
|
||||
self.assertTrue(HomeAssistantItemMap.objects.filter(pk=mapping.pk).exists())
|
||||
reset = self.client.post(reverse('home_assistant:preview'), {
|
||||
'action': 'reset-pending', 'mapping_id': mapping.pk,
|
||||
'checked_absent': 'yes', 'preview_token': token,
|
||||
})
|
||||
self.assertEqual(reset.status_code, 302)
|
||||
self.assertFalse(HomeAssistantItemMap.objects.filter(pk=mapping.pk).exists())
|
||||
|
||||
def test_auto_sync_preferences_and_due_run_are_recorded(self):
|
||||
self.client.force_login(self.user)
|
||||
self.connection.initial_sync_confirmed = True
|
||||
self.connection.save(update_fields=['initial_sync_confirmed', 'updated_at'])
|
||||
self.client.post(reverse('home_assistant:settings'), {
|
||||
'action': 'sync-options', 'direction': 'both', 'conflict_winner': 'ha',
|
||||
'sync_interval_minutes': '5', 'auto_sync_enabled': 'on',
|
||||
})
|
||||
self.connection.refresh_from_db()
|
||||
self.assertTrue(self.connection.auto_sync_enabled)
|
||||
self.assertEqual(self.connection.sync_interval_minutes, '5')
|
||||
self.connection.task_entity_id = 'todo.tasks'
|
||||
self.connection.task_initial_sync_confirmed = True
|
||||
self.connection.entities.append({'id': 'todo.tasks', 'features': 85})
|
||||
self.connection.save(update_fields=['task_entity_id', 'task_initial_sync_confirmed', 'entities', 'updated_at'])
|
||||
fake = FakeHomeAssistant()
|
||||
with patch('home_assistant.sync.get_items', side_effect=fake.get), \
|
||||
patch('home_assistant.task_sync.get_items', side_effect=fake.get):
|
||||
result = run_due_syncs()
|
||||
self.assertEqual(result, {'attempted': 2, 'succeeded': 2, 'failed': 0})
|
||||
runs = HomeAssistantSyncRun.objects.filter(connection=self.connection)
|
||||
self.assertEqual(runs.count(), 2)
|
||||
self.assertTrue(all(run.succeeded and run.automatic for run in runs))
|
||||
self.connection.refresh_from_db()
|
||||
self.assertIsNotNone(self.connection.next_sync_at)
|
||||
self.assertEqual(self.connection.consecutive_sync_failures, 0)
|
||||
|
||||
def test_automatic_retries_stop_after_five_consecutive_failures(self):
|
||||
self.connection.auto_sync_enabled = True
|
||||
self.connection.sync_interval_minutes = '5'
|
||||
self.connection.consecutive_sync_failures = 4
|
||||
self.connection.save()
|
||||
_schedule_after_failure(self.connection, ConnectionError('Home Assistant is unreachable.'), True)
|
||||
self.connection.refresh_from_db()
|
||||
self.assertFalse(self.connection.auto_sync_enabled)
|
||||
self.assertIsNone(self.connection.next_sync_at)
|
||||
self.assertEqual(self.connection.consecutive_sync_failures, 5)
|
||||
run = self.connection.sync_runs.first()
|
||||
self.assertIn('disabled after five', run.summary)
|
||||
|
||||
def test_task_sync_maps_due_description_and_completion_without_losing_planner_fields(self):
|
||||
local = Task.objects.create(owner=self.user, title='Read a book', description='Chapter 4',
|
||||
scheduled_for='2026-11-02', priority=Task.Priority.HIGH, is_completed=True,
|
||||
is_outdoor=True, weather_profile=Task.WeatherProfile.SUNNY)
|
||||
self.connection.task_entity_id = 'todo.tasks'
|
||||
self.connection.entities.append({'id': 'todo.tasks', 'features': 85})
|
||||
self.connection.save()
|
||||
remote = FakeTaskHomeAssistant([{'uid': 'remote-1', 'name': 'Pay a bill',
|
||||
'status': 'completed', 'due': '2026-11-03', 'description': 'Online'}])
|
||||
with patch('home_assistant.task_sync.get_items', side_effect=remote.get), \
|
||||
patch('home_assistant.task_sync.add_item', side_effect=remote.add), \
|
||||
patch('home_assistant.task_sync.update_item', side_effect=remote.update):
|
||||
plan = preview_tasks(self.connection)
|
||||
self.assertEqual({item['kind'] for item in plan['operations']}, {'task_export', 'task_import'})
|
||||
done, _ = confirm_task_sync(self.connection, plan['digest'])
|
||||
self.assertEqual(done, 2)
|
||||
next_plan = preview_tasks(self.connection)
|
||||
self.assertFalse(next_plan['operations'])
|
||||
local.refresh_from_db()
|
||||
self.assertEqual((local.title, local.description, local.priority, local.is_outdoor,
|
||||
local.weather_profile, local.is_completed),
|
||||
('Read a book', 'Chapter 4', Task.Priority.HIGH, True,
|
||||
Task.WeatherProfile.SUNNY, True))
|
||||
imported = Task.objects.get(owner=self.user, title='Pay a bill')
|
||||
self.assertEqual((imported.description, imported.scheduled_for.isoformat(), imported.is_completed),
|
||||
('Online', '2026-11-03', True))
|
||||
self.assertEqual(remote.items['task-1']['status'], 'completed')
|
||||
|
||||
def test_task_sync_skips_recurring_and_remote_tasks_without_due_dates(self):
|
||||
Task.objects.create(owner=self.user, title='Daily journal', scheduled_for='2026-10-22', is_recurring=True)
|
||||
self.connection.task_entity_id = 'todo.tasks'
|
||||
self.connection.entities.append({'id': 'todo.tasks', 'features': 85})
|
||||
self.connection.save()
|
||||
remote = FakeTaskHomeAssistant([{'uid': 'remote-1', 'name': 'Unscheduled',
|
||||
'status': 'needs_action', 'due': None, 'description': ''}])
|
||||
with patch('home_assistant.task_sync.get_items', side_effect=remote.get):
|
||||
plan = preview_tasks(self.connection)
|
||||
self.assertFalse(plan['operations'])
|
||||
self.assertTrue(any('recurs' in issue for issue in plan['issues']))
|
||||
self.assertTrue(any('requires a scheduled date' in issue for issue in plan['issues']))
|
||||
|
||||
def test_reopening_and_local_completion_both_propagate(self):
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Coffee', 'status': 'completed'}])
|
||||
self.run_with(fake)
|
||||
item = GroceryItem.objects.get(user=self.user, name='Coffee')
|
||||
self.assertEqual(item.status, 'purchased')
|
||||
fake.items['ha-1']['status'] = 'needs_action'
|
||||
plan, _ = self.run_with(fake)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'pull')
|
||||
item.refresh_from_db()
|
||||
self.assertEqual(item.status, 'needed')
|
||||
item.status = 'purchased'
|
||||
item.save()
|
||||
plan, _ = self.run_with(fake)
|
||||
self.assertEqual(plan['operations'][0]['kind'], 'push')
|
||||
self.assertEqual(fake.items['ha-1']['status'], 'completed')
|
||||
|
||||
def test_uncertain_addition_reconciles_uid_without_duplicate(self):
|
||||
item = self.local('Yoghurt')
|
||||
HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping',
|
||||
grocery=item, pending_create=True)
|
||||
fake = FakeHomeAssistant([{'uid': 'ha-created', 'name': 'Yoghurt', 'status': 'needs_action'}])
|
||||
plan, (done, _) = self.run_with(fake)
|
||||
self.assertEqual([action['kind'] for action in plan['operations']], ['reconcile'])
|
||||
self.assertEqual(done, 1)
|
||||
mapping = HomeAssistantItemMap.objects.get(connection=self.connection)
|
||||
self.assertEqual(mapping.ha_uid, 'ha-created')
|
||||
self.assertEqual(fake.calls, [])
|
||||
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'home_assistant'
|
||||
urlpatterns = [
|
||||
path('', views.connection_settings, name='settings'),
|
||||
path('preview/', views.grocery_preview, name='preview'),
|
||||
path('tasks/preview/', views.task_preview, name='task-preview'),
|
||||
]
|
||||
@@ -0,0 +1,219 @@
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core import signing
|
||||
from django.shortcuts import redirect, render
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from planner.demo_policy import is_demo_user
|
||||
from .client import ConnectionError, decrypt_token, discover_entities, encrypt_token, normalize_url, test_connection
|
||||
from .models import HomeAssistantConnection
|
||||
from .sync import confirm_and_sync, preview, reset_pending_create
|
||||
from .task_sync import confirm_task_sync, preview_tasks, reset_task_pending
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def connection_settings(request):
|
||||
if is_demo_user(request.user):
|
||||
from django.http import HttpResponseForbidden
|
||||
return HttpResponseForbidden('This action is unavailable in the demo account.')
|
||||
connection = HomeAssistantConnection.objects.filter(user=request.user).first()
|
||||
if request.method == 'POST':
|
||||
action = request.POST.get('action')
|
||||
if action == 'save':
|
||||
raw_token = request.POST.get('token', '').strip()
|
||||
try:
|
||||
url = normalize_url(request.POST.get('base_url', ''))
|
||||
if not raw_token and not connection:
|
||||
raise ConnectionError('Enter a long-lived access token.')
|
||||
if connection and url != connection.base_url and not raw_token:
|
||||
raise ConnectionError('Enter a new token when changing the Home Assistant URL.')
|
||||
if len(raw_token) > 4096:
|
||||
raise ConnectionError('The access token is too long.')
|
||||
connection = connection or HomeAssistantConnection(user=request.user)
|
||||
if url != connection.base_url:
|
||||
if connection.pk:
|
||||
connection.item_maps.all().delete()
|
||||
connection.entities = []
|
||||
connection.grocery_entity_id = ''
|
||||
connection.task_entity_id = ''
|
||||
connection.initial_sync_confirmed = False
|
||||
connection.task_initial_sync_confirmed = False
|
||||
connection.base_url = url
|
||||
if raw_token:
|
||||
connection.encrypted_token = encrypt_token(raw_token)
|
||||
connection.last_tested_at = None
|
||||
connection.last_error = ''
|
||||
connection.version = ''
|
||||
connection.save()
|
||||
messages.success(request, 'Connection details saved. Test the connection before choosing a list.')
|
||||
return redirect('home_assistant:settings')
|
||||
except ConnectionError as exc:
|
||||
messages.error(request, str(exc))
|
||||
elif action == 'disconnect' and connection:
|
||||
connection.delete()
|
||||
messages.success(request, 'Home Assistant disconnected. Your TasksNest groceries were kept.')
|
||||
return redirect('home_assistant:settings')
|
||||
elif connection and action in {'test', 'discover'}:
|
||||
try:
|
||||
token = decrypt_token(connection.encrypted_token)
|
||||
version = test_connection(connection.base_url, token)
|
||||
connection.version = version
|
||||
connection.last_tested_at = timezone.now()
|
||||
connection.last_error = ''
|
||||
if action == 'discover':
|
||||
connection.entities = discover_entities(connection.base_url, token)
|
||||
if connection.grocery_entity_id not in {item['id'] for item in connection.entities}:
|
||||
connection.grocery_entity_id = ''
|
||||
connection.initial_sync_confirmed = False
|
||||
if connection.task_entity_id not in {item['id'] for item in connection.entities}:
|
||||
connection.task_entity_id = ''
|
||||
connection.task_initial_sync_confirmed = False
|
||||
messages.success(request, f'Found {len(connection.entities)} to-do lists.')
|
||||
else:
|
||||
messages.success(request, f'Connected to Home Assistant {version}.')
|
||||
connection.save()
|
||||
except ConnectionError as exc:
|
||||
connection.last_error = str(exc)
|
||||
connection.save(update_fields=['last_error', 'updated_at'])
|
||||
messages.error(request, str(exc))
|
||||
return redirect('home_assistant:settings')
|
||||
elif connection and action == 'select':
|
||||
entity_id = request.POST.get('grocery_entity_id', '')
|
||||
known_entities = {item['id']: item for item in connection.entities}
|
||||
if (entity_id and entity_id != connection.task_entity_id and entity_id in known_entities
|
||||
and known_entities[entity_id].get('available', True)):
|
||||
if entity_id != connection.grocery_entity_id:
|
||||
connection.initial_sync_confirmed = False
|
||||
connection.grocery_entity_id = entity_id
|
||||
connection.save(update_fields=['grocery_entity_id', 'initial_sync_confirmed', 'updated_at'])
|
||||
messages.success(request, 'Grocery list selected. Preview changes before syncing.')
|
||||
else:
|
||||
messages.error(request, 'Choose a discovered to-do list different from the selected task list.')
|
||||
return redirect('home_assistant:settings')
|
||||
elif connection and action == 'select-task':
|
||||
entity_id = request.POST.get('task_entity_id', '')
|
||||
if not entity_id:
|
||||
connection.task_entity_id = ''
|
||||
connection.task_initial_sync_confirmed = False
|
||||
connection.save(update_fields=['task_entity_id', 'task_initial_sync_confirmed', 'updated_at'])
|
||||
messages.success(request, 'Optional task list disconnected. TasksNest tasks were kept.')
|
||||
elif (entity_id != connection.grocery_entity_id
|
||||
and entity_id in {item['id'] for item in connection.entities}
|
||||
and next(item for item in connection.entities if item['id'] == entity_id).get('available', True)):
|
||||
if entity_id != connection.task_entity_id:
|
||||
connection.task_initial_sync_confirmed = False
|
||||
connection.task_entity_id = entity_id
|
||||
connection.save(update_fields=['task_entity_id', 'task_initial_sync_confirmed', 'updated_at'])
|
||||
messages.success(request, 'Task list selected. Review a preview before its first sync.')
|
||||
else:
|
||||
messages.error(request, 'Choose a discovered to-do list different from your grocery list.')
|
||||
return redirect('home_assistant:settings')
|
||||
elif connection and action == 'sync-options':
|
||||
direction = request.POST.get('direction')
|
||||
winner = request.POST.get('conflict_winner')
|
||||
interval = request.POST.get('sync_interval_minutes')
|
||||
auto_enabled = request.POST.get('auto_sync_enabled') == 'on'
|
||||
if (direction in HomeAssistantConnection.Direction.values
|
||||
and winner in HomeAssistantConnection.ConflictWinner.values
|
||||
and interval in HomeAssistantConnection.SyncInterval.values
|
||||
and (not auto_enabled or connection.initial_sync_confirmed)):
|
||||
connection.direction = direction
|
||||
connection.conflict_winner = winner
|
||||
connection.sync_interval_minutes = interval
|
||||
connection.auto_sync_enabled = auto_enabled and interval != HomeAssistantConnection.SyncInterval.MANUAL
|
||||
connection.next_sync_at = timezone.now() if connection.auto_sync_enabled else None
|
||||
connection.save(update_fields=['direction', 'conflict_winner', 'sync_interval_minutes',
|
||||
'auto_sync_enabled', 'next_sync_at', 'updated_at'])
|
||||
messages.success(request, 'Sync preferences saved. Preview before syncing.')
|
||||
else:
|
||||
messages.error(request, 'Choose valid sync preferences and confirm the first sync before enabling automatic sync.')
|
||||
return redirect('home_assistant:settings')
|
||||
else:
|
||||
messages.error(request, 'Save a connection before using that action.')
|
||||
history = connection.sync_runs.all()[:10] if connection else []
|
||||
return render(request, 'home_assistant/settings.html', {'connection': connection, 'history': history})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def grocery_preview(request):
|
||||
if is_demo_user(request.user):
|
||||
from django.http import HttpResponseForbidden
|
||||
return HttpResponseForbidden('This action is unavailable in the demo account.')
|
||||
connection = HomeAssistantConnection.objects.filter(user=request.user).first()
|
||||
if not connection or not connection.grocery_entity_id:
|
||||
messages.error(request, 'Connect Home Assistant and choose a to-do list first.')
|
||||
return redirect('home_assistant:settings')
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
digest = signing.loads(request.POST.get('preview_token', ''), salt='ha-grocery-sync', max_age=600)
|
||||
if request.POST.get('action') == 'reset-pending':
|
||||
if request.POST.get('checked_absent') != 'yes':
|
||||
raise ConnectionError('Confirm that you checked Home Assistant before resetting this addition.')
|
||||
reset_pending_create(connection, digest, request.POST.get('mapping_id'))
|
||||
messages.success(request, 'Pending addition reset. Preview again before syncing.')
|
||||
return redirect('home_assistant:preview')
|
||||
done, plan = confirm_and_sync(connection, digest)
|
||||
remaining = max(0, len(plan['operations']) - done)
|
||||
messages.success(request, f'Synced {done} changes.' + (f' Preview again for {remaining} more.' if remaining else ''))
|
||||
return redirect('home_assistant:settings')
|
||||
except signing.BadSignature:
|
||||
messages.error(request, 'The preview expired or was invalid. Review it again.')
|
||||
return redirect('home_assistant:preview')
|
||||
except ConnectionError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('home_assistant:preview')
|
||||
try:
|
||||
plan = preview(connection)
|
||||
token = signing.dumps(plan['digest'], salt='ha-grocery-sync')
|
||||
except ConnectionError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('home_assistant:settings')
|
||||
return render(request, 'home_assistant/preview.html', {
|
||||
'connection': connection, 'plan': plan, 'preview_token': token,
|
||||
'first_sync': not connection.initial_sync_confirmed,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def task_preview(request):
|
||||
if is_demo_user(request.user):
|
||||
from django.http import HttpResponseForbidden
|
||||
return HttpResponseForbidden('This action is unavailable in the demo account.')
|
||||
connection = HomeAssistantConnection.objects.filter(user=request.user).first()
|
||||
if not connection or not connection.task_entity_id:
|
||||
messages.error(request, 'Connect Home Assistant and choose a task list first.')
|
||||
return redirect('home_assistant:settings')
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
digest = signing.loads(request.POST.get('preview_token', ''), salt='ha-task-sync', max_age=600)
|
||||
if request.POST.get('action') == 'reset-pending':
|
||||
if request.POST.get('checked_absent') != 'yes':
|
||||
raise ConnectionError('Confirm that you checked Home Assistant before resetting this addition.')
|
||||
reset_task_pending(connection, digest, request.POST.get('mapping_id'))
|
||||
messages.success(request, 'Pending task addition reset. Preview again before syncing.')
|
||||
return redirect('home_assistant:task-preview')
|
||||
done, plan = confirm_task_sync(connection, digest)
|
||||
remaining = max(0, len(plan['operations']) - done)
|
||||
messages.success(request, f'Synced {done} task changes.' +
|
||||
(f' Preview again for {remaining} more.' if remaining else ''))
|
||||
return redirect('home_assistant:settings')
|
||||
except signing.BadSignature:
|
||||
messages.error(request, 'The preview expired or was invalid. Review it again.')
|
||||
return redirect('home_assistant:task-preview')
|
||||
except ConnectionError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('home_assistant:task-preview')
|
||||
try:
|
||||
plan = preview_tasks(connection)
|
||||
token = signing.dumps(plan['digest'], salt='ha-task-sync')
|
||||
except ConnectionError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('home_assistant:settings')
|
||||
return render(request, 'home_assistant/task_preview.html', {
|
||||
'connection': connection, 'plan': plan, 'preview_token': token,
|
||||
'first_sync': not connection.task_initial_sync_confirmed,
|
||||
})
|
||||
Reference in New Issue
Block a user