Files
Evection/apps/feeds/views.py
T
ksmithandClaude Sonnet 5 ea214dd9ce Add OPML import/export and a subscriptions management page
Implements OPML parsing with defusedxml (untrusted upload, XXE risk)
and export with the stdlib's plain ElementTree (trusted, app-generated
output). Nesting deeper than one level flattens into its nearest
enclosing folder, matching the app's flat-folder model. Import reuses
existing Feed/Subscription rows via get_or_create, so re-importing the
same file is idempotent and cross-user Feed dedup is preserved.

Large imports (>50 entries) dispatch to a Celery task instead of
blocking the request; newly imported feeds aren't fetched immediately
since they have no last_fetched_at, so the next poll_due_feeds beat
cycle picks them up naturally.

Adds a Subscriptions page (replacing the standalone "Add feed" link in
nav) listing current subscriptions with unsubscribe, plus Import/
Export OPML actions.

Verified live: imported a 2-feed/1-folder OPML file against the
running dev server (via an authenticated session, since this browser
tool has no file-picker automation), confirmed the resulting
subscriptions and folder in the UI, exported and inspected the
resulting OPML structure, and unsubscribed from one feed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 16:41:18 -06:00

108 lines
3.8 KiB
Python

from io import BytesIO
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
from .forms import AddFeedForm, OPMLImportForm
from .models import Feed, Subscription
from .opml import export_opml, import_opml, parse_opml
from .services.fetcher import fetch_and_ingest
from .tasks import import_opml_task
OPML_ASYNC_THRESHOLD = 50
@login_required
def add_feed(request):
form = AddFeedForm(request.POST or None, user=request.user)
if request.method == "POST" and form.is_valid():
feed_url = form.cleaned_data["feed_url"]
feed, _created = Feed.objects.get_or_create(feed_url=feed_url)
subscription, created = Subscription.objects.get_or_create(
user=request.user,
feed=feed,
defaults={"folder": form.cleaned_data["folder"]},
)
if not created:
messages.info(request, "You're already subscribed to that feed.")
return redirect("reader:stream")
# Fetch synchronously so the user sees results immediately; the
# periodic Celery poll takes over from here for subsequent fetches.
result = fetch_and_ingest(feed)
feed.save()
if result.status == Feed.STATUS_ERROR:
messages.warning(
request,
f"Subscribed to {feed_url}, but the initial fetch failed: {result.error_message}",
)
else:
article_count = len(result.new_article_ids)
messages.success(
request,
f"Subscribed to '{subscription.display_title}' — "
f"{article_count} article(s) fetched.",
)
return redirect("reader:stream")
return render(request, "feeds/add_feed.html", {"form": form})
@login_required
def subscription_list(request):
subscriptions = (
Subscription.objects.filter(user=request.user)
.select_related("feed", "folder")
.order_by("folder__name", "order", "id")
)
return render(request, "feeds/subscriptions.html", {"subscriptions": subscriptions})
@login_required
@require_POST
def unsubscribe(request, subscription_id):
subscription = get_object_or_404(Subscription, user=request.user, pk=subscription_id)
title = subscription.display_title
subscription.delete()
messages.success(request, f"Unsubscribed from '{title}'.")
return redirect("feeds:subscription_list")
@login_required
def import_opml_view(request):
form = OPMLImportForm(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
content = form.cleaned_data["opml_file"].read()
try:
entry_count = len(parse_opml(BytesIO(content)))
except Exception:
messages.error(request, "That file doesn't look like a valid OPML export.")
return redirect("feeds:import_opml")
if entry_count > OPML_ASYNC_THRESHOLD:
import_opml_task.delay(request.user.id, content.decode("utf-8"))
messages.success(request, f"Importing {entry_count} feeds in the background.")
else:
result = import_opml(request.user, BytesIO(content))
messages.success(
request,
f"Imported {result['created']} feed(s) "
f"({result['already_subscribed']} already subscribed).",
)
return redirect("feeds:subscription_list")
return render(request, "feeds/import_opml.html", {"form": form})
@login_required
def export_opml_view(request):
content = export_opml(request.user)
response = HttpResponse(content, content_type="text/x-opml")
response["Content-Disposition"] = 'attachment; filename="evection-subscriptions.opml"'
return response