Files
Evection/apps/reader/views.py
T
ksmithandClaude Sonnet 5 0e132e9ab9 Remove folders; feeds are organized by tags now
Folders are gone — organization is tags-only, via the SubscriptionTag
model added last commit. A migration converts every existing Folder into
a same-named Tag applied to its feeds, and every folder-scoped FilterRule
into an equivalent tag-scoped one, before the Folder table is dropped, so
upgrading an existing instance loses nothing (verified by seeding the
pre-removal schema directly and running the migration chain against it).

Unlike folders, a feed can carry more than one tag, so:
- apps.articles.tasks.apply_filter_rules_for_feed and apps.rules.tasks's
  backlog re-apply now scope by "does this feed carry tag X" rather than
  "does this feed belong to folder X".
- apps.feeds.opml: a feed's tags export as a comma-separated "category"
  attribute (the standard OPML way to represent multiple categories)
  instead of nesting under one folder outline. Import reads both that
  attribute and nested category outlines, turning each enclosing level
  into its own tag rather than collapsing to the nearest one.
- The sidebar groups feeds by tag instead of folder, so a feed with two
  tags now appears in both groups; untagged feeds fall into "Untagged".

AddFeedForm gained a comma-separated tag_names field for parity with the
old add-time folder picker. EditSubscriptionForm dropped its folder
field entirely — tagging a subscription happens through the tag editor
already on that page.

Verified end to end: the migration chain from empty, the data migration
against a seeded pre-removal schema (folder/subscription/rule all convert
correctly), and the running app's sidebar grouping, OPML export category
attributes, and tag editor.

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

250 lines
8.8 KiB
Python

from itertools import groupby
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.http import require_POST
from apps.articles.models import Article, Tag, UserArticleState
from apps.articles.queries import with_user_state
from apps.feeds.models import Feed
FILTER_CHOICES = [
("unread", "Unread"),
("all", "All"),
("starred", "Starred"),
("saved", "Saved"),
]
VALID_FILTERS = {key for key, _ in FILTER_CHOICES}
PAGE_SIZE = 30
def _base_queryset(user):
"""Articles from the user's subscriptions, with rule-hidden articles
excluded regardless of which filter tab is active."""
return (
Article.objects.filter(feed__subscriptions__user=user)
.exclude(user_states__user=user, user_states__is_hidden=True)
.select_related("feed")
)
def _get_or_create_state(user, article):
state, _ = UserArticleState.objects.get_or_create(user=user, article=article)
return state
def _apply_scope(request, queryset):
"""Narrows an already-base-scoped Article queryset by the optional
?tag=/?feed= params the sidebar links use. feed_id alone is enough to
scope by feed (the base queryset already restricts to the user's own
subscriptions)."""
active_tag = None
tag_id = request.GET.get("tag")
if tag_id:
active_tag = Tag.objects.filter(user=request.user, pk=tag_id).first()
if active_tag:
# A tag matches an article either directly (ArticleTag) or by
# the article's feed being tagged via the user's Subscription
# (SubscriptionTag) — tagging a whole feed surfaces all of its
# articles under that tag, not just individually-tagged ones.
queryset = queryset.filter(
Q(article_tags__user=request.user, article_tags__tag=active_tag)
| Q(
feed__subscriptions__user=request.user,
feed__subscriptions__subscription_tags__user=request.user,
feed__subscriptions__subscription_tags__tag=active_tag,
)
).distinct()
active_feed = None
feed_id = request.GET.get("feed")
if feed_id:
active_feed = Feed.objects.filter(pk=feed_id, subscriptions__user=request.user).first()
if active_feed:
queryset = queryset.filter(feed_id=active_feed.pk)
return queryset, active_tag, active_feed
def _date_label(day, today):
if day is None:
return "Undated"
diff = (today - day).days
if diff == 0:
return f"Received today — {day.strftime('%-d %B %Y')}"
if diff == 1:
return f"Received yesterday — {day.strftime('%-d %B %Y')}"
return f"Received {day.strftime('%-d %B %Y')}"
def _group_by_date(articles):
"""Articles are already ordered newest-first (Article.Meta.ordering),
so same-day articles are contiguous and groupby doesn't need a sort."""
today = timezone.localdate()
def day_of(article):
return timezone.localtime(article.published_at).date() if article.published_at else None
return [
{"label": _date_label(day, today), "articles": list(items)}
for day, items in groupby(articles, key=day_of)
]
@login_required
def stream(request):
requested_filter = request.GET.get("filter")
if requested_filter in VALID_FILTERS:
active_filter = requested_filter
else:
# No (valid) filter in the URL — e.g. a sidebar feed/folder/tag
# link, or just "/" — falls back to whatever the user last had
# selected, rather than always resetting to "unread".
active_filter = request.session.get("stream_filter", "unread")
request.session["stream_filter"] = active_filter
queryset = _base_queryset(request.user)
if active_filter == "unread":
queryset = queryset.exclude(user_states__user=request.user, user_states__is_read=True)
elif active_filter == "starred":
queryset = queryset.filter(user_states__user=request.user, user_states__is_starred=True)
elif active_filter == "saved":
queryset = queryset.filter(
user_states__user=request.user, user_states__is_saved_for_later=True
)
queryset, active_tag, active_feed = _apply_scope(request, queryset)
try:
page = max(int(request.GET.get("page", 1)), 1)
except ValueError:
page = 1
start, end = (page - 1) * PAGE_SIZE, page * PAGE_SIZE
total_count = queryset.count()
articles = with_user_state(queryset[start:end], request.user)
context = {
"date_groups": _group_by_date(articles),
"active_filter": active_filter,
"filters": FILTER_CHOICES,
"active_tag": active_tag,
"active_feed": active_feed,
"user_tags": Tag.objects.filter(user=request.user),
"page": page,
"has_next_page": end < total_count,
"has_previous_page": page > 1,
}
return render(request, "reader/stream.html", context)
@login_required
@require_POST
def mark_all_read(request):
"""Marks every unread article currently matching the stream's filter
scope (tag included, "unread"/"all" filter excluded since it's a no-op
choice here) as read — bulk, not one UserArticleState per article."""
queryset = _base_queryset(request.user)
queryset, _active_tag, _active_feed = _apply_scope(request, queryset)
unread_articles = queryset.exclude(user_states__user=request.user, user_states__is_read=True)
unread_ids = list(unread_articles.values_list("id", flat=True))
if unread_ids:
now = timezone.now()
existing_state_article_ids = set(
UserArticleState.objects.filter(
user=request.user, article_id__in=unread_ids
).values_list("article_id", flat=True)
)
UserArticleState.objects.filter(
user=request.user, article_id__in=existing_state_article_ids
).update(is_read=True, read_at=now)
new_article_ids = [aid for aid in unread_ids if aid not in existing_state_article_ids]
UserArticleState.objects.bulk_create(
[
UserArticleState(user=request.user, article_id=aid, is_read=True, read_at=now)
for aid in new_article_ids
]
)
stream_url = reverse("reader:stream")
query = request.GET.urlencode()
return redirect(f"{stream_url}?{query}" if query else stream_url)
def _load_article_and_mark_read(user, article_id):
article = get_object_or_404(_base_queryset(user), pk=article_id)
state = _get_or_create_state(user, article)
if not state.is_read:
state.is_read = True
state.read_at = timezone.now()
state.save(update_fields=["is_read", "read_at"])
article.is_read = state.is_read
article.is_starred = state.is_starred
article.is_saved_for_later = state.is_saved_for_later
return article
@login_required
def article_detail(request, article_id):
article = _load_article_and_mark_read(request.user, article_id)
return render(request, "reader/article_detail.html", {"article": article})
@login_required
def article_inline(request, article_id):
"""Fetched via htmx when a row in the stream is expanded in place —
mirrors article_detail's mark-read side effect, but renders just the
content fragment plus an out-of-band update of the row's own read/star
icons (see templates/reader/_article_inline.html)."""
article = _load_article_and_mark_read(request.user, article_id)
return render(request, "reader/_article_inline.html", {"article": article})
@login_required
@require_POST
def toggle_read(request, article_id):
return _toggle(request, article_id, "is_read", "read_at")
@login_required
@require_POST
def toggle_star(request, article_id):
return _toggle(request, article_id, "is_starred", "starred_at")
@login_required
@require_POST
def toggle_saved(request, article_id):
return _toggle(request, article_id, "is_saved_for_later", None)
def _toggle(request, article_id, flag_field, timestamp_field):
try:
article = _base_queryset(request.user).get(pk=article_id)
except Article.DoesNotExist:
raise Http404
state = _get_or_create_state(request.user, article)
new_value = not getattr(state, flag_field)
setattr(state, flag_field, new_value)
update_fields = [flag_field]
if timestamp_field:
setattr(state, timestamp_field, timezone.now() if new_value else None)
update_fields.append(timestamp_field)
state.save(update_fields=update_fields)
article.is_read = state.is_read
article.is_starred = state.is_starred
article.is_saved_for_later = state.is_saved_for_later
return render(request, "reader/_article_actions.html", {"article": article})