Files
Django_TasksApp/main/dreams/api.py
T
2026-10-19 16:51:53 +02:00

150 lines
7.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Private dream journal API for the authenticated user's MCP tools."""
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime
from food.api import api_view, error, _json, _idempotent
from planner.timezones import timezone_for_user
from .forms import normalize_terms
from .models import DreamEntry
FIELDS = {'wake_up_date', 'dreamed_at', 'title', 'narrative', 'interpretation',
'tags', 'emotions', 'vividness', 'is_nightmare', 'after_waking_notes'}
APPEND_FIELDS = {'append_narrative': 'narrative', 'append_after_waking_notes': 'after_waking_notes'}
def serialize(entry):
return {'id': str(entry.pk), 'wake_up_date': entry.wake_up_date.isoformat(),
'dreamed_at': entry.dreamed_at.isoformat() if entry.dreamed_at else None,
'title': entry.title, 'narrative': entry.narrative, 'interpretation': entry.interpretation,
'tags': entry.tags, 'emotions': entry.emotions, 'vividness': entry.vividness,
'is_nightmare': entry.is_nightmare, 'after_waking_notes': entry.after_waking_notes,
'created_at': entry.created_at.isoformat(), 'updated_at': entry.updated_at.isoformat()}
def validate(data, user, *, updating=False):
if not isinstance(data, dict):
raise ValueError('Expected a JSON object.')
unknown = set(data) - FIELDS - (set(APPEND_FIELDS) if updating else set())
if unknown:
raise ValueError('Unknown fields: ' + ', '.join(sorted(unknown)))
if 'narrative' in data and 'append_narrative' in data:
raise ValueError('Choose narrative or append_narrative, not both.')
if 'after_waking_notes' in data and 'append_after_waking_notes' in data:
raise ValueError('Choose after_waking_notes or append_after_waking_notes, not both.')
result = {}
if 'wake_up_date' in data:
value = data['wake_up_date']
day = parse_date(value) if isinstance(value, str) else None
if day is None or day.isoformat() != value:
raise ValueError('Use YYYY-MM-DD for wake_up_date.')
result['wake_up_date'] = day
if 'dreamed_at' in data:
value = data['dreamed_at']
if value is None:
result['dreamed_at'] = None
else:
moment = parse_datetime(value) if isinstance(value, str) else None
if moment is None:
raise ValueError('Use an ISO date and time for dreamed_at.')
result['dreamed_at'] = timezone.make_aware(moment, timezone_for_user(user)) if timezone.is_naive(moment) else moment
for name, limit in [('title', 160), ('narrative', 20000), ('interpretation', 4000),
('after_waking_notes', 4000)]:
if name in data:
value = data[name]
if not isinstance(value, str) or len(value) > limit or (name in {'title', 'narrative'} and not value.strip()):
raise ValueError(f'{name} must be non-empty text within {limit} characters.' if name in {'title', 'narrative'} else f'{name} must be text within {limit} characters.')
result[name] = value
for name in ('tags', 'emotions'):
if name in data:
result[name] = normalize_terms(data[name])
if 'vividness' in data:
score = data['vividness']
if score is not None and (isinstance(score, bool) or not isinstance(score, int) or not 0 <= score <= 10):
raise ValueError('Vividness must be 0–10 or null.')
result['vividness'] = score
if 'is_nightmare' in data:
if not isinstance(data['is_nightmare'], bool):
raise ValueError('is_nightmare must be true or false.')
result['is_nightmare'] = data['is_nightmare']
for append_name in APPEND_FIELDS:
if append_name in data:
value = data[append_name]
if not isinstance(value, str) or not value.strip():
raise ValueError(f'{append_name} must be non-empty text.')
result[append_name] = value.strip()
return result
@api_view({'GET': 'journal:read', 'POST': 'journal:write'}, ('GET', 'POST'))
def collection(request):
if request.method == 'GET':
entries = DreamEntry.objects.filter(user=request.api_user)
query = request.GET.get('query', '').strip()[:100]
if query:
entries = entries.filter(Q(title__icontains=query) | Q(narrative__icontains=query) |
Q(tags__icontains=query) | Q(emotions__icontains=query))
tag = request.GET.get('tag', '').strip()[:40]
if tag:
entries = entries.filter(tags__icontains=tag)
for key, lookup in (('date', 'wake_up_date'), ('date_from', 'wake_up_date__gte'),
('date_to', 'wake_up_date__lte')):
if text := request.GET.get(key):
day = parse_date(text)
if day is None or day.isoformat() != text:
return error('invalid_date', f'Use YYYY-MM-DD for {key}.')
entries = entries.filter(**{lookup: day})
try:
limit = min(max(int(request.GET.get('limit', 30)), 1), 100)
offset = max(int(request.GET.get('offset', 0)), 0)
except ValueError:
return error('invalid_pagination', 'Limit and offset must be integers.')
return JsonResponse({'items': [serialize(entry) for entry in entries[offset:offset + limit]],
'total': entries.count()})
data = _json(request)
cleaned = validate(data, request.api_user)
if not {'wake_up_date', 'title', 'narrative'} <= cleaned.keys():
return error('missing_fields', 'wake_up_date, title, and narrative are required.')
def action():
entry = DreamEntry(user=request.api_user, **cleaned)
entry.full_clean()
entry.save()
return JsonResponse(serialize(entry), status=201)
return _idempotent(request, data, action)
@api_view({'GET': 'journal:read', 'PATCH': 'journal:write', 'DELETE': 'journal:write'},
('GET', 'PATCH', 'DELETE'))
def item(request, identifier):
entry = DreamEntry.objects.filter(pk=identifier, user=request.api_user).first()
if entry is None:
return error('not_found', 'Dream entry not found.', 404)
if request.method == 'GET':
return JsonResponse(serialize(entry))
if request.method == 'DELETE':
entry.delete()
return JsonResponse({'deleted': True})
data = _json(request)
cleaned = validate(data, request.api_user, updating=True)
if any(name in cleaned for name in APPEND_FIELDS) and not request.headers.get('Idempotency-Key'):
return error('idempotency_required', 'Use an Idempotency-Key when appending dream details.')
def action():
for name, value in cleaned.items():
if name in APPEND_FIELDS:
field = APPEND_FIELDS[name]
current = getattr(entry, field)
combined = f'{current}\n\n{value}' if current else value
if len(combined) > (20000 if field == 'narrative' else 4000):
return error('too_long', f'{field} is too long.')
setattr(entry, field, combined)
else:
setattr(entry, name, value)
entry.full_clean()
entry.save()
return JsonResponse(serialize(entry))
return _idempotent(request, data, action) if request.headers.get('Idempotency-Key') else action()