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, })