Add the filter/rules engine

Implements FilterRule (one condition -> action, scoped to a feed and/or
folder or global) with an evaluation engine applied at ingest time:
after the fetch pipeline commits new/updated articles, each affected
subscriber's enabled rules run in priority order against them, with
tag/star/mark_read actions stacking and hide short-circuiting further
evaluation for that article.

Adds rule management (create/edit/delete) and a "Re-apply" action that
re-evaluates a user's full ruleset against their unread backlog, scoped
by the triggering rule's own feed/folder — so a newly added rule can
retroactively affect already-ingested articles, not just future ones.

Verified live in-browser: created a "title contains 'Show HN' -> star"
rule scoped to the subscribed Hacker News feed, re-applied it against
the existing unread backlog, and confirmed both matching articles were
starred.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-30 16:31:33 -06:00
1 parent 579696efc0
commit 5ed0499845
18 files changed
+1072 -6

No files matched your search

+18 -1
View File
@@ -1 +1,18 @@
# Register your models here.
from django.contrib import admin
from .models import FilterRule
@admin.register(FilterRule)
class FilterRuleAdmin(admin.ModelAdmin):
list_display = [
"name",
"user",
"match_field",
"match_type",
"match_value",
"action",
"priority",
"is_enabled",
]
list_filter = ["is_enabled", "action", "match_field"]
+113
View File
@@ -0,0 +1,113 @@
"""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 Article, ArticleTag, Tag, UserArticleState
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:
state.is_starred = True
state.starred_at = state.starred_at or now
state.save(update_fields=["is_starred", "starred_at"])
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
+49
View File
@@ -0,0 +1,49 @@
from django import forms
from apps.feeds.models import Feed, Folder
from .models import FilterRule
class FilterRuleForm(forms.ModelForm):
class Meta:
model = FilterRule
fields = [
"name",
"feed",
"folder",
"match_field",
"match_type",
"match_value",
"case_sensitive",
"action",
"action_value",
"priority",
"is_enabled",
]
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self._user = user
if user is not None:
self.fields["feed"].queryset = Feed.objects.filter(subscriptions__user=user).distinct()
self.fields["folder"].queryset = Folder.objects.filter(user=user)
self.fields["feed"].required = False
self.fields["folder"].required = False
def clean(self):
cleaned_data = super().clean()
if (
cleaned_data.get("action") == FilterRule.ACTION_TAG
and not cleaned_data.get("action_value", "").strip()
):
self.add_error("action_value", "Required when the action is 'Add tag'.")
return cleaned_data
def save(self, commit=True):
rule = super().save(commit=False)
if self._user is not None:
rule.user = self._user
if commit:
rule.save()
return rule
+111
View File
@@ -0,0 +1,111 @@
# Generated by Django 5.2.18 on 2026-10-30 22:27
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("feeds", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="FilterRule",
fields=[
(
"id",
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("name", models.CharField(blank=True, max_length=255)),
(
"match_field",
models.CharField(
choices=[
("title", "Title"),
("content", "Content"),
("author", "Author"),
("feed_title", "Feed"),
("url", "URL"),
],
max_length=20,
),
),
(
"match_type",
models.CharField(
choices=[
("contains", "Contains"),
("not_contains", "Does not contain"),
("regex", "Regex"),
("exact", "Exact match"),
],
max_length=20,
),
),
("match_value", models.CharField(max_length=500)),
("case_sensitive", models.BooleanField(default=False)),
(
"action",
models.CharField(
choices=[
("tag", "Add tag"),
("star", "Star"),
("hide", "Hide"),
("mark_read", "Mark read"),
],
max_length=20,
),
),
(
"action_value",
models.CharField(
blank=True,
help_text="Tag name, only used when action is 'Add tag'.",
max_length=100,
),
),
(
"priority",
models.PositiveIntegerField(default=0, help_text="Lower numbers run first."),
),
("is_enabled", models.BooleanField(default=True)),
(
"feed",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="feeds.feed",
),
),
(
"folder",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="feeds.folder",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="filter_rules",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["priority", "id"],
},
),
]
+79 -1
View File
@@ -1 +1,79 @@
# Create your models here.
from django.conf import settings
from django.db import models
from apps.feeds.models import Feed, Folder
class FilterRule(models.Model):
"""A single condition -> action rule, evaluated at ingest time against
new/updated articles for every subscriber of the matching feed(s).
v1 supports one condition per rule; users combine effects by stacking
multiple rules (evaluated in ``priority`` order, ascending — lower
numbers run first). Compound AND/OR condition groups are deferred.
"""
FIELD_TITLE = "title"
FIELD_CONTENT = "content"
FIELD_AUTHOR = "author"
FIELD_FEED_TITLE = "feed_title"
FIELD_URL = "url"
MATCH_FIELD_CHOICES = [
(FIELD_TITLE, "Title"),
(FIELD_CONTENT, "Content"),
(FIELD_AUTHOR, "Author"),
(FIELD_FEED_TITLE, "Feed"),
(FIELD_URL, "URL"),
]
MATCH_CONTAINS = "contains"
MATCH_NOT_CONTAINS = "not_contains"
MATCH_REGEX = "regex"
MATCH_EXACT = "exact"
MATCH_TYPE_CHOICES = [
(MATCH_CONTAINS, "Contains"),
(MATCH_NOT_CONTAINS, "Does not contain"),
(MATCH_REGEX, "Regex"),
(MATCH_EXACT, "Exact match"),
]
ACTION_TAG = "tag"
ACTION_STAR = "star"
ACTION_HIDE = "hide"
ACTION_MARK_READ = "mark_read"
ACTION_CHOICES = [
(ACTION_TAG, "Add tag"),
(ACTION_STAR, "Star"),
(ACTION_HIDE, "Hide"),
(ACTION_MARK_READ, "Mark read"),
]
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="filter_rules"
)
name = models.CharField(max_length=255, blank=True)
# Scope: null means "every subscription", matching the plan's decision
# to keep folders flat and scoping simple.
feed = models.ForeignKey(Feed, null=True, blank=True, on_delete=models.CASCADE)
folder = models.ForeignKey(Folder, null=True, blank=True, on_delete=models.CASCADE)
match_field = models.CharField(max_length=20, choices=MATCH_FIELD_CHOICES)
match_type = models.CharField(max_length=20, choices=MATCH_TYPE_CHOICES)
match_value = models.CharField(max_length=500)
case_sensitive = models.BooleanField(default=False)
action = models.CharField(max_length=20, choices=ACTION_CHOICES)
action_value = models.CharField(
max_length=100, blank=True, help_text="Tag name, only used when action is 'Add tag'."
)
priority = models.PositiveIntegerField(default=0, help_text="Lower numbers run first.")
is_enabled = models.BooleanField(default=True)
class Meta:
ordering = ["priority", "id"]
def __str__(self):
label = self.name or f"{self.get_match_field_display()} {self.get_match_type_display()}"
return f"{label} -> {self.get_action_display()}"
+57
View File
@@ -0,0 +1,57 @@
from celery import shared_task
from apps.articles.models import Article
from apps.feeds.models import Subscription
from .engine import evaluate_rules_for_article
from .models import FilterRule
def reapply_rules_for_user_backlog(rule_id: int) -> int:
"""Re-evaluates a user's full enabled ruleset (not just the triggering
rule, so priority/short-circuit ordering stays correct) against their
unread backlog, scoped by the triggering rule's own feed/folder scope.
Exists as a plain function so it can be called synchronously for
immediate feedback (e.g. from a "Re-apply" view) or wrapped in a task
for background use — see reapply_rules_for_user below.
"""
try:
rule = FilterRule.objects.select_related("user").get(pk=rule_id)
except FilterRule.DoesNotExist:
return 0
user = rule.user
if rule.feed_id:
feed_ids = [rule.feed_id]
elif rule.folder_id:
feed_ids = list(
Subscription.objects.filter(user=user, folder_id=rule.folder_id).values_list(
"feed_id", flat=True
)
)
else:
feed_ids = list(Subscription.objects.filter(user=user).values_list("feed_id", flat=True))
if not feed_ids:
return 0
backlog = (
Article.objects.filter(feed_id__in=feed_ids)
.exclude(user_states__user=user, user_states__is_read=True)
.select_related("feed")
)
rules = list(FilterRule.objects.filter(user=user, is_enabled=True).order_by("priority", "id"))
count = 0
for article in backlog:
evaluate_rules_for_article(user, article, rules)
count += 1
return count
@shared_task
def reapply_rules_for_user(rule_id: int):
return reapply_rules_for_user_backlog(rule_id)
+169
View File
@@ -0,0 +1,169 @@
import pytest
from django.contrib.auth import get_user_model
from apps.articles.models import Article, ArticleTag, Tag, UserArticleState
from apps.feeds.models import Feed
from .engine import evaluate_rules_for_article, rule_matches
from .models import FilterRule
User = get_user_model()
@pytest.fixture
def user(db):
return User.objects.create_user("alice", password="pw-alice-123")
@pytest.fixture
def feed(db):
return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example Feed")
@pytest.fixture
def article(feed):
return Article.objects.create(
feed=feed,
guid="guid-1",
title="Breaking: Python 4 announced",
author="Jane Doe",
content_html="<p>Lots of details about the release.</p>",
link="https://example.com/python-4",
)
def make_rule(user, **overrides):
defaults = {
"match_field": FilterRule.FIELD_TITLE,
"match_type": FilterRule.MATCH_CONTAINS,
"match_value": "Python",
"action": FilterRule.ACTION_STAR,
}
defaults.update(overrides)
return FilterRule.objects.create(user=user, **defaults)
@pytest.mark.django_db
class TestRuleMatches:
def test_contains_case_insensitive_by_default(self, user, article):
rule = make_rule(user, match_value="python")
assert rule_matches(rule, article) is True
def test_contains_respects_case_sensitivity(self, user, article):
rule = make_rule(user, match_value="python", case_sensitive=True)
assert rule_matches(rule, article) is False
def test_not_contains(self, user, article):
rule = make_rule(user, match_type=FilterRule.MATCH_NOT_CONTAINS, match_value="golang")
assert rule_matches(rule, article) is True
def test_exact_match(self, user, article):
rule = make_rule(
user,
match_type=FilterRule.MATCH_EXACT,
match_value="breaking: python 4 announced",
)
assert rule_matches(rule, article) is True
article.title = "Something else"
assert rule_matches(rule, article) is False
def test_regex_match(self, user, article):
rule = make_rule(user, match_type=FilterRule.MATCH_REGEX, match_value=r"Python \d")
assert rule_matches(rule, article) is True
def test_invalid_regex_does_not_raise(self, user, article):
rule = make_rule(user, match_type=FilterRule.MATCH_REGEX, match_value="(unclosed")
assert rule_matches(rule, article) is False
def test_content_field_strips_html_tags(self, user, article):
rule = make_rule(user, match_field=FilterRule.FIELD_CONTENT, match_value="Lots of details")
assert rule_matches(rule, article) is True
def test_author_field(self, user, article):
rule = make_rule(user, match_field=FilterRule.FIELD_AUTHOR, match_value="Jane")
assert rule_matches(rule, article) is True
def test_feed_title_field(self, user, article):
rule = make_rule(user, match_field=FilterRule.FIELD_FEED_TITLE, match_value="Example")
assert rule_matches(rule, article) is True
def test_url_field(self, user, article):
rule = make_rule(user, match_field=FilterRule.FIELD_URL, match_value="python-4")
assert rule_matches(rule, article) is True
@pytest.mark.django_db
class TestApplyRuleAction:
def test_star_action(self, user, article):
rules = [make_rule(user, action=FilterRule.ACTION_STAR)]
evaluate_rules_for_article(user, article, rules)
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_starred is True
assert state.starred_at is not None
assert state.is_read is False
def test_mark_read_action(self, user, article):
rules = [make_rule(user, action=FilterRule.ACTION_MARK_READ)]
evaluate_rules_for_article(user, article, rules)
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_read is True
assert state.read_at is not None
def test_hide_action_marks_hidden_and_read(self, user, article):
rules = [make_rule(user, action=FilterRule.ACTION_HIDE)]
evaluate_rules_for_article(user, article, rules)
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_hidden is True
assert state.is_read is True
def test_tag_action_creates_and_assigns_tag(self, user, article):
rules = [make_rule(user, action=FilterRule.ACTION_TAG, action_value="python-news")]
evaluate_rules_for_article(user, article, rules)
tag = Tag.objects.get(user=user, name="python-news")
assert ArticleTag.objects.filter(user=user, article=article, tag=tag).exists()
def test_non_matching_rule_creates_no_state(self, user, article):
rules = [make_rule(user, match_value="golang", action=FilterRule.ACTION_STAR)]
evaluate_rules_for_article(user, article, rules)
assert not UserArticleState.objects.filter(user=user, article=article).exists()
@pytest.mark.django_db
class TestRulePriorityAndShortCircuit:
def test_rules_apply_in_priority_order(self, user, article):
tag_rule = make_rule(
user, priority=1, action=FilterRule.ACTION_TAG, action_value="early-tag"
)
star_rule = make_rule(user, priority=2, action=FilterRule.ACTION_STAR)
evaluate_rules_for_article(user, article, [tag_rule, star_rule])
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_starred is True
assert Tag.objects.filter(user=user, name="early-tag").exists()
def test_hide_short_circuits_later_rules(self, user, article):
hide_rule = make_rule(user, priority=1, action=FilterRule.ACTION_HIDE)
star_rule = make_rule(user, priority=2, action=FilterRule.ACTION_STAR)
evaluate_rules_for_article(user, article, [hide_rule, star_rule])
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_hidden is True
# The star rule never ran because hide short-circuited first.
assert state.is_starred is False
def test_non_hide_actions_stack_across_multiple_rules(self, user, article):
star_rule = make_rule(user, priority=1, action=FilterRule.ACTION_STAR)
read_rule = make_rule(user, priority=2, action=FilterRule.ACTION_MARK_READ)
evaluate_rules_for_article(user, article, [star_rule, read_rule])
state = UserArticleState.objects.get(user=user, article=article)
assert state.is_starred is True
assert state.is_read is True
+157
View File
@@ -0,0 +1,157 @@
import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
from apps.articles.models import Article, UserArticleState
from apps.feeds.models import Feed, Subscription
from .models import FilterRule
from .tasks import reapply_rules_for_user_backlog
User = get_user_model()
@pytest.fixture
def alice(db):
return User.objects.create_user("alice", password="pw-alice-123")
@pytest.fixture
def bob(db):
return User.objects.create_user("bob", password="pw-bob-123")
@pytest.fixture
def feed(db):
return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example Feed")
@pytest.mark.django_db
def test_create_rule(client, alice, feed):
Subscription.objects.create(user=alice, feed=feed)
client.login(username="alice", password="pw-alice-123")
response = client.post(
reverse("rules:create_rule"),
{
"match_field": FilterRule.FIELD_TITLE,
"match_type": FilterRule.MATCH_CONTAINS,
"match_value": "Python",
"action": FilterRule.ACTION_STAR,
"priority": 0,
"is_enabled": "on",
},
)
assert response.status_code == 302
assert FilterRule.objects.filter(user=alice, match_value="Python").exists()
@pytest.mark.django_db
def test_tag_action_requires_action_value(client, alice):
client.login(username="alice", password="pw-alice-123")
response = client.post(
reverse("rules:create_rule"),
{
"match_field": FilterRule.FIELD_TITLE,
"match_type": FilterRule.MATCH_CONTAINS,
"match_value": "Python",
"action": FilterRule.ACTION_TAG,
"action_value": "",
"priority": 0,
},
)
assert response.status_code == 200
assert not FilterRule.objects.exists()
@pytest.mark.django_db
def test_user_cannot_edit_another_users_rule(client, alice, bob):
rule = FilterRule.objects.create(
user=alice,
match_field=FilterRule.FIELD_TITLE,
match_type=FilterRule.MATCH_CONTAINS,
match_value="Python",
action=FilterRule.ACTION_STAR,
)
client.login(username="bob", password="pw-bob-123")
response = client.get(reverse("rules:edit_rule", args=[rule.pk]))
assert response.status_code == 404
@pytest.mark.django_db
def test_delete_rule(client, alice):
rule = FilterRule.objects.create(
user=alice,
match_field=FilterRule.FIELD_TITLE,
match_type=FilterRule.MATCH_CONTAINS,
match_value="Python",
action=FilterRule.ACTION_STAR,
)
client.login(username="alice", password="pw-alice-123")
response = client.post(reverse("rules:delete_rule", args=[rule.pk]))
assert response.status_code == 302
assert not FilterRule.objects.filter(pk=rule.pk).exists()
@pytest.mark.django_db
def test_reapply_rule_view_applies_to_unread_backlog(client, alice, feed):
Subscription.objects.create(user=alice, feed=feed)
article = Article.objects.create(feed=feed, guid="guid-1", title="Python 4 released")
rule = FilterRule.objects.create(
user=alice,
match_field=FilterRule.FIELD_TITLE,
match_type=FilterRule.MATCH_CONTAINS,
match_value="Python",
action=FilterRule.ACTION_STAR,
)
client.login(username="alice", password="pw-alice-123")
response = client.post(reverse("rules:reapply_rule", args=[rule.pk]))
assert response.status_code == 302
assert UserArticleState.objects.get(user=alice, article=article).is_starred is True
@pytest.mark.django_db
def test_reapply_skips_already_read_articles(alice, feed):
article = Article.objects.create(feed=feed, guid="guid-1", title="Python 4 released")
Subscription.objects.create(user=alice, feed=feed)
UserArticleState.objects.create(user=alice, article=article, is_read=True)
rule = FilterRule.objects.create(
user=alice,
match_field=FilterRule.FIELD_TITLE,
match_type=FilterRule.MATCH_CONTAINS,
match_value="Python",
action=FilterRule.ACTION_STAR,
)
count = reapply_rules_for_user_backlog(rule.pk)
assert count == 0
state = UserArticleState.objects.get(user=alice, article=article)
assert state.is_starred is False
@pytest.mark.django_db
def test_reapply_respects_feed_scope(alice):
feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml")
feed_b = Feed.objects.create(feed_url="https://b.example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed_a)
Subscription.objects.create(user=alice, feed=feed_b)
article_a = Article.objects.create(feed=feed_a, guid="guid-1", title="Python in A")
article_b = Article.objects.create(feed=feed_b, guid="guid-2", title="Python in B")
rule = FilterRule.objects.create(
user=alice,
feed=feed_a,
match_field=FilterRule.FIELD_TITLE,
match_type=FilterRule.MATCH_CONTAINS,
match_value="Python",
action=FilterRule.ACTION_STAR,
)
reapply_rules_for_user_backlog(rule.pk)
assert UserArticleState.objects.get(user=alice, article=article_a).is_starred is True
assert not UserArticleState.objects.filter(user=alice, article=article_b).exists()
+13
View File
@@ -0,0 +1,13 @@
from django.urls import path
from . import views
app_name = "rules"
urlpatterns = [
path("rules/", views.rule_list, name="rule_list"),
path("rules/new/", views.create_rule, name="create_rule"),
path("rules/<int:rule_id>/edit/", views.edit_rule, name="edit_rule"),
path("rules/<int:rule_id>/delete/", views.delete_rule, name="delete_rule"),
path("rules/<int:rule_id>/reapply/", views.reapply_rule, name="reapply_rule"),
]
+55 -1
View File
@@ -1 +1,55 @@
# Create your views here.
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
from .forms import FilterRuleForm
from .models import FilterRule
from .tasks import reapply_rules_for_user_backlog
@login_required
def rule_list(request):
rules = FilterRule.objects.filter(user=request.user).select_related("feed", "folder")
return render(request, "rules/rule_list.html", {"rules": rules})
@login_required
def create_rule(request):
form = FilterRuleForm(request.POST or None, user=request.user)
if request.method == "POST" and form.is_valid():
form.save()
messages.success(request, "Rule created.")
return redirect("rules:rule_list")
return render(request, "rules/rule_form.html", {"form": form})
@login_required
def edit_rule(request, rule_id):
rule = get_object_or_404(FilterRule, user=request.user, pk=rule_id)
form = FilterRuleForm(request.POST or None, instance=rule, user=request.user)
if request.method == "POST" and form.is_valid():
form.save()
messages.success(request, "Rule updated.")
return redirect("rules:rule_list")
return render(request, "rules/rule_form.html", {"form": form, "rule": rule})
@login_required
@require_POST
def delete_rule(request, rule_id):
rule = get_object_or_404(FilterRule, user=request.user, pk=rule_id)
rule.delete()
messages.success(request, "Rule deleted.")
return redirect("rules:rule_list")
@login_required
@require_POST
def reapply_rule(request, rule_id):
rule = get_object_or_404(FilterRule, user=request.user, pk=rule_id)
# Run synchronously for immediate feedback, same pattern as add_feed —
# a Celery worker isn't required for this to work.
count = reapply_rules_for_user_backlog(rule.pk)
messages.success(request, f"Re-applied your rules to {count} unread article(s).")
return redirect("rules:rule_list")