Files
Evection/apps/rules/engine.py
T
ksmithandClaude Sonnet 5 753ae9efc7 Make Starred and Saved-for-later pre-configured system tags
UserArticleState.is_starred/is_saved_for_later/starred_at are gone —
starring and saving now add/remove an ArticleTag against a per-user
"Starred" / "Saved for later" Tag, created lazily on first use and marked
Tag.is_system=True. is_read/is_hidden stay on UserArticleState since
they're genuine reading state, not categorization, which is what made
these two candidates for unifying into the general tag mechanism.

System tags are excluded from the Manage Tags page and from delete_tag
(get_object_or_404 now requires is_system=False, so attempting to delete
one 404s) and from the subscription-tag autocomplete, since they
categorize articles, not feeds. The star/save icons are still exactly
where they were — this only changes what powers them.

apps.rules.engine's star action now does get_system_tag + ArticleTag.
get_or_create instead of setting a boolean field. A data migration
converts every existing is_starred=True/is_saved_for_later=True row into
its ArticleTag equivalent before the fields are dropped — verified by
seeding the pre-removal schema directly (including a row with both flags
set) and confirming the migration produces the right tags.

apps.articles.queries.with_user_state gained one more query (tag lookup
for the current page's articles) to stay in the same "fixed number of
queries regardless of article count" shape it already had.

Verified end to end against a running dev server: toggling star/saved,
the starred/saved filters, the sidebar's Favourites count, and that the
Starred tag doesn't appear on the Manage Tags page.

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

120 lines
3.8 KiB
Python

"""Evaluates FilterRules against Articles and applies their actions.
Kept as plain functions over model instances (no Celery here) so rule
logic can be unit-tested directly and reused both from the ingest-time
dispatch (apps.articles.tasks) and the retroactive "re-apply" task.
"""
from __future__ import annotations
import logging
import re
from django.utils import timezone
from apps.articles.models import (
STARRED_TAG_NAME,
Article,
ArticleTag,
Tag,
UserArticleState,
get_system_tag,
)
from .models import FilterRule
logger = logging.getLogger(__name__)
_TAG_RE = re.compile(r"<[^>]+>")
def _haystack(article: Article, match_field: str) -> str:
if match_field == FilterRule.FIELD_TITLE:
return article.title or ""
if match_field == FilterRule.FIELD_CONTENT:
return _TAG_RE.sub(" ", article.content_html or "")
if match_field == FilterRule.FIELD_AUTHOR:
return article.author or ""
if match_field == FilterRule.FIELD_FEED_TITLE:
return article.feed.title or ""
if match_field == FilterRule.FIELD_URL:
return article.link or ""
return ""
def rule_matches(rule: FilterRule, article: Article) -> bool:
raw_haystack = _haystack(article, rule.match_field)
if rule.match_type == FilterRule.MATCH_REGEX:
flags = 0 if rule.case_sensitive else re.IGNORECASE
try:
return re.search(rule.match_value, raw_haystack, flags) is not None
except re.error as exc:
logger.warning("Invalid regex in rule %s: %s", rule.pk, exc)
return False
haystack = raw_haystack
needle = rule.match_value
if not rule.case_sensitive:
haystack = haystack.casefold()
needle = needle.casefold()
if rule.match_type == FilterRule.MATCH_CONTAINS:
return needle in haystack
if rule.match_type == FilterRule.MATCH_NOT_CONTAINS:
return needle not in haystack
if rule.match_type == FilterRule.MATCH_EXACT:
return haystack == needle
return False
return False
def apply_rule_action(rule: FilterRule, user, article: Article, state: UserArticleState) -> bool:
"""Applies a matched rule's action to the given state. Returns True if
evaluation should stop for this article (the rule hid it)."""
now = timezone.now()
if rule.action == FilterRule.ACTION_HIDE:
state.is_hidden = True
state.is_read = True
state.read_at = state.read_at or now
state.save(update_fields=["is_hidden", "is_read", "read_at"])
return True
if rule.action == FilterRule.ACTION_STAR:
tag = get_system_tag(user, STARRED_TAG_NAME)
ArticleTag.objects.get_or_create(user=user, article=article, tag=tag)
return False
if rule.action == FilterRule.ACTION_MARK_READ:
state.is_read = True
state.read_at = state.read_at or now
state.save(update_fields=["is_read", "read_at"])
return False
if rule.action == FilterRule.ACTION_TAG and rule.action_value.strip():
tag, _ = Tag.objects.get_or_create(user=user, name=rule.action_value.strip())
ArticleTag.objects.get_or_create(user=user, article=article, tag=tag)
return False
return False
def evaluate_rules_for_article(user, article: Article, rules) -> None:
"""Evaluates an ordered iterable of rules (already scoped/enabled)
against one article for one user, applying actions as they match."""
matched_any = False
state = None
for rule in rules:
if not rule_matches(rule, article):
continue
if state is None:
state, _ = UserArticleState.objects.get_or_create(user=user, article=article)
matched_any = True
should_stop = apply_rule_action(rule, user, article, state)
if should_stop:
break
return matched_any