diff --git a/apps/articles/tasks.py b/apps/articles/tasks.py new file mode 100644 index 0000000..9951927 --- /dev/null +++ b/apps/articles/tasks.py @@ -0,0 +1,44 @@ +from celery import shared_task +from django.db.models import Q + +from apps.feeds.models import Subscription +from apps.rules.engine import evaluate_rules_for_article +from apps.rules.models import FilterRule + +from .models import Article + + +@shared_task +def apply_filter_rules_for_feed(feed_id: int, article_ids: list[int]): + """For every subscriber of ``feed_id``, evaluate their enabled + FilterRules (scoped to this feed/folder or unscoped) against the given + articles. Dispatched by the fetch pipeline after new/updated articles + are committed for a feed. + """ + if not article_ids: + return 0 + + articles = list(Article.objects.filter(pk__in=article_ids).select_related("feed")) + if not articles: + return 0 + + subscriptions = Subscription.objects.filter(feed_id=feed_id).select_related("user") + + evaluated = 0 + for subscription in subscriptions: + rules = FilterRule.objects.filter(user=subscription.user, is_enabled=True).filter( + Q(feed_id=feed_id) | Q(feed__isnull=True) + ) + if subscription.folder_id: + rules = rules.filter(Q(folder_id=subscription.folder_id) | Q(folder__isnull=True)) + else: + rules = rules.filter(folder__isnull=True) + rules = list(rules.order_by("priority", "id")) + if not rules: + continue + + for article in articles: + evaluate_rules_for_article(subscription.user, article, rules) + evaluated += 1 + + return evaluated diff --git a/apps/articles/test_rule_dispatch.py b/apps/articles/test_rule_dispatch.py new file mode 100644 index 0000000..bb075eb --- /dev/null +++ b/apps/articles/test_rule_dispatch.py @@ -0,0 +1,122 @@ +import pytest +from django.contrib.auth import get_user_model + +from apps.feeds.models import Feed, Folder, Subscription +from apps.rules.models import FilterRule + +from .models import Article, UserArticleState +from .tasks import apply_filter_rules_for_feed + +User = get_user_model() + + +@pytest.fixture +def feed(db): + return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example Feed") + + +@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.mark.django_db +def test_dispatch_applies_rules_only_for_subscribers_with_matching_rules(feed, alice, bob): + Subscription.objects.create(user=alice, feed=feed) + Subscription.objects.create(user=bob, feed=feed) + FilterRule.objects.create( + user=alice, + match_field=FilterRule.FIELD_TITLE, + match_type=FilterRule.MATCH_CONTAINS, + match_value="Python", + action=FilterRule.ACTION_STAR, + ) + article = Article.objects.create(feed=feed, guid="guid-1", title="Python 4 released") + + apply_filter_rules_for_feed(feed.id, [article.pk]) + + assert UserArticleState.objects.get(user=alice, article=article).is_starred is True + # Bob has no rules, so he should get no state row at all. + assert not UserArticleState.objects.filter(user=bob, article=article).exists() + + +@pytest.mark.django_db +def test_feed_scoped_rule_does_not_apply_to_other_feeds(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) + + 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, + ) + + article_a = Article.objects.create(feed=feed_a, guid="guid-1", title="Python news") + article_b = Article.objects.create(feed=feed_b, guid="guid-2", title="Python news too") + + apply_filter_rules_for_feed(feed_a.id, [article_a.pk]) + apply_filter_rules_for_feed(feed_b.id, [article_b.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() + + +@pytest.mark.django_db +def test_folder_scoped_rule_only_applies_within_that_folder(alice, feed): + other_feed = Feed.objects.create(feed_url="https://other.example.com/feed.xml") + folder = Folder.objects.create(user=alice, name="Tech") + Subscription.objects.create(user=alice, feed=feed, folder=folder) + Subscription.objects.create(user=alice, feed=other_feed, folder=None) + + FilterRule.objects.create( + user=alice, + folder=folder, + match_field=FilterRule.FIELD_TITLE, + match_type=FilterRule.MATCH_CONTAINS, + match_value="Python", + action=FilterRule.ACTION_STAR, + ) + + in_folder_article = Article.objects.create(feed=feed, guid="guid-1", title="Python in folder") + outside_folder_article = Article.objects.create( + feed=other_feed, guid="guid-2", title="Python outside folder" + ) + + apply_filter_rules_for_feed(feed.id, [in_folder_article.pk]) + apply_filter_rules_for_feed(other_feed.id, [outside_folder_article.pk]) + + assert UserArticleState.objects.get(user=alice, article=in_folder_article).is_starred is True + assert not UserArticleState.objects.filter(user=alice, article=outside_folder_article).exists() + + +@pytest.mark.django_db +def test_disabled_rule_does_not_apply(feed, alice): + Subscription.objects.create(user=alice, feed=feed) + FilterRule.objects.create( + user=alice, + match_field=FilterRule.FIELD_TITLE, + match_type=FilterRule.MATCH_CONTAINS, + match_value="Python", + action=FilterRule.ACTION_STAR, + is_enabled=False, + ) + article = Article.objects.create(feed=feed, guid="guid-1", title="Python 4 released") + + apply_filter_rules_for_feed(feed.id, [article.pk]) + + assert not UserArticleState.objects.filter(user=alice, article=article).exists() + + +@pytest.mark.django_db +def test_dispatch_with_empty_article_ids_is_a_noop(feed): + assert apply_filter_rules_for_feed(feed.id, []) == 0 diff --git a/apps/feeds/tasks.py b/apps/feeds/tasks.py index 2d0ff0c..fc6606b 100644 --- a/apps/feeds/tasks.py +++ b/apps/feeds/tasks.py @@ -4,6 +4,8 @@ from datetime import timedelta from celery import shared_task from django.utils import timezone +from apps.articles.tasks import apply_filter_rules_for_feed + from .models import Feed from .services.fetcher import effective_interval_minutes, fetch_and_ingest @@ -45,15 +47,15 @@ def fetch_feed(feed_id: int): result = fetch_and_ingest(feed) feed.save() - if result.new_article_ids: + changed_article_ids = result.new_article_ids + result.updated_article_ids + if changed_article_ids: logger.info( "Feed %s: %d new article(s), %d updated", feed.feed_url, len(result.new_article_ids), len(result.updated_article_ids), ) - # Rule application (tag/star/hide/mark_read on new articles for each - # subscriber) is wired in once apps.rules exists — see milestone 6. + apply_filter_rules_for_feed.delay(feed_id, changed_article_ids) return { "status": result.status, diff --git a/apps/rules/admin.py b/apps/rules/admin.py index 846f6b4..942aa21 100644 --- a/apps/rules/admin.py +++ b/apps/rules/admin.py @@ -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"] diff --git a/apps/rules/engine.py b/apps/rules/engine.py new file mode 100644 index 0000000..b2f22b5 --- /dev/null +++ b/apps/rules/engine.py @@ -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 diff --git a/apps/rules/forms.py b/apps/rules/forms.py new file mode 100644 index 0000000..8565541 --- /dev/null +++ b/apps/rules/forms.py @@ -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 diff --git a/apps/rules/migrations/0001_initial.py b/apps/rules/migrations/0001_initial.py new file mode 100644 index 0000000..1aecda4 --- /dev/null +++ b/apps/rules/migrations/0001_initial.py @@ -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"], + }, + ), + ] diff --git a/apps/rules/models.py b/apps/rules/models.py index 6b20219..f0c38ce 100644 --- a/apps/rules/models.py +++ b/apps/rules/models.py @@ -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()}" diff --git a/apps/rules/tasks.py b/apps/rules/tasks.py new file mode 100644 index 0000000..0f2ece2 --- /dev/null +++ b/apps/rules/tasks.py @@ -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) diff --git a/apps/rules/test_engine.py b/apps/rules/test_engine.py new file mode 100644 index 0000000..891fb20 --- /dev/null +++ b/apps/rules/test_engine.py @@ -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="
Lots of details about the release.
", + 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 diff --git a/apps/rules/test_views.py b/apps/rules/test_views.py new file mode 100644 index 0000000..39c8720 --- /dev/null +++ b/apps/rules/test_views.py @@ -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() diff --git a/apps/rules/urls.py b/apps/rules/urls.py new file mode 100644 index 0000000..19886f0 --- /dev/null +++ b/apps/rules/urls.py @@ -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/