Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
narrow: Move python-only implemenation into its own file.
Alex Vandiver823f732132ed
diff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex d62aeb100b5..745537e3e78 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -38,8 +38,8 @@ from zerver.lib.message import (remove_message_id_from_unread_mgs,)from zerver.lib.muted_users import get_user_mutes-from zerver.lib.narrow import check_narrow_for_events, read_stop_words-from zerver.lib.narrow_helpers import NarrowTerm+from zerver.lib.narrow_helpers import NarrowTerm, read_stop_words+from zerver.lib.narrow_predicate import check_narrow_for_eventsfrom zerver.lib.presence import get_presence_for_user, get_presences_for_realmfrom zerver.lib.realm_icon import realm_icon_urlfrom zerver.lib.realm_logo import get_realm_logo_source, get_realm_logo_urldiff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 4970cfc4ecc..b5178fb6b6c 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -1,16 +1,13 @@-import osimport refrom dataclasses import dataclassfrom typing import (Any,Callable,- Collection,Dict,Generic,Iterable,List,Optional,- Protocol,Sequence,Set,Tuple,@@ -48,7 +45,7 @@ from typing_extensions import TypeAlias, overridefrom zerver.lib.addressee import get_user_profiles, get_user_profiles_by_idsfrom zerver.lib.exceptions import ErrorCode, JsonableErrorfrom zerver.lib.message import get_first_visible_message_id-from zerver.lib.narrow_helpers import NarrowTerm+from zerver.lib.narrow_predicate import channel_operators, channels_operatorsfrom zerver.lib.recipient_users import recipient_for_user_profilesfrom zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.streams import (@@ -58,7 +55,6 @@ from zerver.lib.streams import (get_stream_by_narrow_operand_access_unchecked,get_web_public_streams_queryset,)-from zerver.lib.topic import RESOLVED_TOPIC_PREFIX, get_topic_from_message_infofrom zerver.lib.topic_sqlalchemy import (get_resolved_topic_condition_sa,topic_column_sa,@@ -81,34 +77,6 @@ from zerver.models.users import (get_user_including_cross_realm,)-stop_words_list: Optional[List[str]] = None---def read_stop_words() -> List[str]:- global stop_words_list- if stop_words_list is None:- file_path = os.path.join(- settings.DEPLOY_ROOT, "puppet/zulip/files/postgresql/zulip_english.stop"- )- with open(file_path) as f:- stop_words_list = f.read().splitlines()-- return stop_words_list---# "stream" is a legacy alias for "channel"-channel_operators: List[str] = ["channel", "stream"]-# "streams" is a legacy alias for "channels"-channels_operators: List[str] = ["channels", "streams"]---def check_narrow_for_events(narrow: Collection[NarrowTerm]) -> None:- supported_operators = [*channel_operators, "topic", "sender", "is"]- for narrow_term in narrow:- operator = narrow_term.operator- if operator not in supported_operators:- raise JsonableError(_("Operator {operator} not supported.").format(operator=operator))-def is_spectator_compatible(narrow: Iterable[Dict[str, Any]]) -> bool:# This implementation should agree with is_spectator_compatible in hash_parser.ts.@@ -146,64 +114,6 @@ def is_web_public_narrow(narrow: Optional[Iterable[Dict[str, Any]]]) -> bool:)-class NarrowPredicate(Protocol):- def __call__(self, *, message: Dict[str, Any], flags: List[str]) -> bool: ...---def build_narrow_predicate(- narrow: Collection[NarrowTerm],-) -> NarrowPredicate:- """Changes to this function should come with corresponding changes to- NarrowLibraryTest."""- check_narrow_for_events(narrow)-- def narrow_predicate(*, message: Dict[str, Any], flags: List[str]) -> bool:- def satisfies_operator(*, operator: str, operand: str) -> bool:- if operator in channel_operators:- if message["type"] != "stream":- return False- if operand.lower() != message["display_recipient"].lower():- return False- elif operator == "topic":- if message["type"] != "stream":- return False- topic_name = get_topic_from_message_info(message)- if operand.lower() != topic_name.lower():- return False- elif operator == "sender":- if operand.lower() != message["sender_email"].lower():- return False- elif operator == "is" and operand in ["dm", "private"]:- # "is:private" is a legacy alias for "is:dm"- if message["type"] != "private":- return False- elif operator == "is" and operand in ["starred"]:- if operand not in flags:- return False- elif operator == "is" and operand == "unread":- if "read" in flags:- return False- elif operator == "is" and operand in ["alerted", "mentioned"]:- if "mentioned" not in flags:- return False- elif operator == "is" and operand == "resolved":- if message["type"] != "stream":- return False- topic_name = get_topic_from_message_info(message)- if not topic_name.startswith(RESOLVED_TOPIC_PREFIX):- return False- return True-- for narrow_term in narrow:- # TODO: Eventually handle negated narrow terms.- if not satisfies_operator(operator=narrow_term.operator, operand=narrow_term.operand):- return False-- return True-- return narrow_predicate--LARGER_THAN_MAX_MESSAGE_ID = 10000000000000000diff --git a/zerver/lib/narrow_helpers.py b/zerver/lib/narrow_helpers.pyindex 1c7e0df5b8a..404cc276a06 100644--- a/zerver/lib/narrow_helpers.py+++ b/zerver/lib/narrow_helpers.py@@ -18,8 +18,11 @@ from users:specification internally as dataclasses."""+import osfrom dataclasses import dataclass-from typing import Collection, Sequence+from typing import Collection, List, Optional, Sequence++from django.conf import settings@dataclass@@ -35,3 +38,18 @@ def narrow_dataclasses_from_tuples(tups: Collection[Sequence[str]]) -> Collectiotherefore as of summer 2023, they do not yet support the "negated" flag."""return [NarrowTerm(operator=tup[0], operand=tup[1]) for tup in tups]+++stop_words_list: Optional[List[str]] = None+++def read_stop_words() -> List[str]:+ global stop_words_list+ if stop_words_list is None:+ file_path = os.path.join(+ settings.DEPLOY_ROOT, "puppet/zulip/files/postgresql/zulip_english.stop"+ )+ with open(file_path) as f:+ stop_words_list = f.read().splitlines()++ return stop_words_listdiff --git a/zerver/lib/narrow_predicate.py b/zerver/lib/narrow_predicate.pynew file mode 100644index 00000000000..948e793eecc--- /dev/null+++ b/zerver/lib/narrow_predicate.py@@ -0,0 +1,78 @@+from typing import Any, Collection, Dict, List, Protocol++from django.utils.translation import gettext as _++from zerver.lib.exceptions import JsonableError+from zerver.lib.narrow_helpers import NarrowTerm+from zerver.lib.topic import RESOLVED_TOPIC_PREFIX, get_topic_from_message_info++# "stream" is a legacy alias for "channel"+channel_operators: List[str] = ["channel", "stream"]+# "streams" is a legacy alias for "channels"+channels_operators: List[str] = ["channels", "streams"]+++def check_narrow_for_events(narrow: Collection[NarrowTerm]) -> None:+ supported_operators = [*channel_operators, "topic", "sender", "is"]+ for narrow_term in narrow:+ operator = narrow_term.operator+ if operator not in supported_operators:+ raise JsonableError(_("Operator {operator} not supported.").format(operator=operator))+++class NarrowPredicate(Protocol):+ def __call__(self, *, message: Dict[str, Any], flags: List[str]) -> bool: ...+++def build_narrow_predicate(+ narrow: Collection[NarrowTerm],+) -> NarrowPredicate:+ """Changes to this function should come with corresponding changes to+ NarrowLibraryTest."""+ check_narrow_for_events(narrow)++ def narrow_predicate(*, message: Dict[str, Any], flags: List[str]) -> bool:+ def satisfies_operator(*, operator: str, operand: str) -> bool:+ if operator in channel_operators:+ if message["type"] != "stream":+ return False+ if operand.lower() != message["display_recipient"].lower():+ return False+ elif operator == "topic":+ if message["type"] != "stream":+ return False+ topic_name = get_topic_from_message_info(message)+ if operand.lower() != topic_name.lower():+ return False+ elif operator == "sender":+ if operand.lower() != message["sender_email"].lower():+ return False+ elif operator == "is" and operand in ["dm", "private"]:+ # "is:private" is a legacy alias for "is:dm"+ if message["type"] != "private":+ return False+ elif operator == "is" and operand in ["starred"]:+ if operand not in flags:+ return False+ elif operator == "is" and operand == "unread":+ if "read" in flags:+ return False+ elif operator == "is" and operand in ["alerted", "mentioned"]:+ if "mentioned" not in flags:+ return False+ elif operator == "is" and operand == "resolved":+ if message["type"] != "stream":+ return False+ topic_name = get_topic_from_message_info(message)+ if not topic_name.startswith(RESOLVED_TOPIC_PREFIX):+ return False+ return True++ for narrow_term in narrow:+ # TODO: Eventually handle negated narrow terms.+ if not satisfies_operator(operator=narrow_term.operator, operand=narrow_term.operand):+ return False++ return True++ return narrow_predicatediff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex a7d110bd7e2..f7ddc501de8 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -33,7 +33,6 @@ from zerver.lib.narrow import (LARGER_THAN_MAX_MESSAGE_ID,BadNarrowOperatorError,NarrowBuilder,- build_narrow_predicate,exclude_muting_conditions,find_first_unread_anchor,is_spectator_compatible,@@ -41,6 +40,7 @@ from zerver.lib.narrow import (post_process_limited_query,)from zerver.lib.narrow_helpers import NarrowTerm+from zerver.lib.narrow_predicate import build_narrow_predicatefrom zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.streams import StreamDict, create_streams_if_needed, get_public_streams_querysetfrom zerver.lib.test_classes import ZulipTestCasediff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.pyindex 601b918d728..26f4fe0d244 100644--- a/zerver/tornado/event_queue.py+++ b/zerver/tornado/event_queue.py@@ -41,8 +41,8 @@ from typing_extensions import overridefrom version import API_FEATURE_LEVEL, ZULIP_MERGE_BASE, ZULIP_VERSIONfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.message_cache import MessageDict-from zerver.lib.narrow import build_narrow_predicatefrom zerver.lib.narrow_helpers import narrow_dataclasses_from_tuples+from zerver.lib.narrow_predicate import build_narrow_predicatefrom zerver.lib.notification_data import UserMessageNotificationsDatafrom zerver.lib.queue import queue_json_publish, retry_eventfrom zerver.middleware import async_request_timer_restart