2020-06-11 00:54:34 +02:00
|
|
|
import re
|
2020-11-16 22:52:27 +01:00
|
|
|
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2020-08-07 01:09:47 +02:00
|
|
|
import orjson
|
2013-12-12 18:36:32 +01:00
|
|
|
from django.conf import settings
|
2020-08-04 19:33:43 +02:00
|
|
|
from django.contrib.auth.models import AnonymousUser
|
2013-12-12 18:36:32 +01:00
|
|
|
from django.core.exceptions import ValidationError
|
2020-06-22 22:57:01 +02:00
|
|
|
from django.db import connection
|
2016-06-06 00:32:39 +02:00
|
|
|
from django.http import HttpRequest, HttpResponse
|
2013-11-26 00:41:24 +01:00
|
|
|
from django.utils.html import escape as escape_html
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2020-06-11 00:54:34 +02:00
|
|
|
from sqlalchemy.dialects import postgresql
|
2021-08-21 01:07:28 +02:00
|
|
|
from sqlalchemy.engine import Connection, Row
|
2020-06-11 00:54:34 +02:00
|
|
|
from sqlalchemy.sql import (
|
2020-11-16 22:52:27 +01:00
|
|
|
ClauseElement,
|
2020-06-11 00:54:34 +02:00
|
|
|
ColumnElement,
|
2020-11-16 22:52:27 +01:00
|
|
|
Select,
|
2020-06-11 00:54:34 +02:00
|
|
|
and_,
|
|
|
|
column,
|
2021-08-21 01:07:28 +02:00
|
|
|
func,
|
2020-06-11 00:54:34 +02:00
|
|
|
join,
|
|
|
|
literal,
|
|
|
|
literal_column,
|
|
|
|
not_,
|
|
|
|
or_,
|
|
|
|
select,
|
|
|
|
table,
|
|
|
|
union_all,
|
|
|
|
)
|
2022-02-10 03:15:46 +01:00
|
|
|
from sqlalchemy.sql.selectable import SelectBase
|
2021-08-21 01:07:28 +02:00
|
|
|
from sqlalchemy.types import ARRAY, Boolean, Integer, Text
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2020-09-01 13:56:15 +02:00
|
|
|
from zerver.context_processors import get_valid_realm_from_request
|
2020-06-22 23:25:37 +02:00
|
|
|
from zerver.lib.actions import recipient_for_user_profiles
|
2019-06-28 21:05:58 +02:00
|
|
|
from zerver.lib.addressee import get_user_profiles, get_user_profiles_by_ids
|
2020-08-31 09:31:50 +02:00
|
|
|
from zerver.lib.exceptions import ErrorCode, JsonableError, MissingAuthenticationError
|
2020-06-22 23:25:37 +02:00
|
|
|
from zerver.lib.message import get_first_visible_message_id, messages_for_ids
|
2021-09-04 04:03:07 +02:00
|
|
|
from zerver.lib.narrow import is_spectator_compatible, is_web_public_narrow
|
2021-08-21 19:24:20 +02:00
|
|
|
from zerver.lib.request import REQ, RequestNotes, has_request_variables
|
2021-06-30 18:35:50 +02:00
|
|
|
from zerver.lib.response import json_success
|
2016-07-19 08:12:35 +02:00
|
|
|
from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.streams import (
|
|
|
|
can_access_stream_history_by_id,
|
|
|
|
can_access_stream_history_by_name,
|
|
|
|
get_public_streams_queryset,
|
|
|
|
get_stream_by_narrow_operand_access_unchecked,
|
2020-08-04 19:33:43 +02:00
|
|
|
get_web_public_streams_queryset,
|
2020-06-11 00:54:34 +02:00
|
|
|
)
|
2021-07-13 20:23:36 +02:00
|
|
|
from zerver.lib.topic import (
|
|
|
|
DB_TOPIC_NAME,
|
|
|
|
MATCH_TOPIC,
|
|
|
|
get_resolved_topic_condition_sa,
|
|
|
|
topic_column_sa,
|
|
|
|
topic_match_sa,
|
|
|
|
)
|
2017-08-29 17:16:53 +02:00
|
|
|
from zerver.lib.topic_mutes import exclude_topic_mutes
|
2020-06-22 22:37:00 +02:00
|
|
|
from zerver.lib.types import Validator
|
2013-12-12 18:36:32 +01:00
|
|
|
from zerver.lib.utils import statsd
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.validator import (
|
|
|
|
check_bool,
|
|
|
|
check_dict,
|
|
|
|
check_int,
|
|
|
|
check_list,
|
|
|
|
check_required_string,
|
|
|
|
check_string,
|
|
|
|
check_string_or_int,
|
|
|
|
check_string_or_int_list,
|
|
|
|
to_non_negative_int,
|
|
|
|
)
|
|
|
|
from zerver.models import (
|
|
|
|
Realm,
|
|
|
|
Recipient,
|
|
|
|
Stream,
|
|
|
|
Subscription,
|
|
|
|
UserMessage,
|
|
|
|
UserProfile,
|
|
|
|
get_active_streams,
|
|
|
|
get_user_by_id_in_realm_including_cross_realm,
|
|
|
|
get_user_including_cross_realm,
|
|
|
|
)
|
2016-06-24 02:26:09 +02:00
|
|
|
|
2017-02-23 05:50:15 +01:00
|
|
|
LARGER_THAN_MAX_MESSAGE_ID = 10000000000000000
|
2018-09-09 14:54:52 +02:00
|
|
|
MAX_MESSAGES_PER_FETCH = 5000
|
2017-02-23 05:50:15 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2016-04-21 21:47:01 +02:00
|
|
|
class BadNarrowOperator(JsonableError):
|
2017-07-21 02:17:28 +02:00
|
|
|
code = ErrorCode.BAD_NARROW
|
2021-02-12 08:20:45 +01:00
|
|
|
data_fields = ["desc"]
|
2017-07-21 02:17:28 +02:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def __init__(self, desc: str) -> None:
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
self.desc: str = desc
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2017-07-21 02:17:28 +02:00
|
|
|
@staticmethod
|
2017-11-27 09:28:57 +01:00
|
|
|
def msg_format() -> str:
|
2021-02-12 08:20:45 +01:00
|
|
|
return _("Invalid narrow operator: {desc}")
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
ConditionTransform = Callable[[ClauseElement], ClauseElement]
|
2016-09-12 02:09:24 +02:00
|
|
|
|
2019-08-11 19:07:34 +02:00
|
|
|
OptionalNarrowListT = Optional[List[Dict[str, Any]]]
|
|
|
|
|
2019-08-28 11:06:38 +02:00
|
|
|
# These delimiters will not appear in rendered messages or HTML-escaped topics.
|
|
|
|
TS_START = "<ts-match>"
|
|
|
|
TS_STOP = "</ts-match>"
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-08-28 11:06:38 +02:00
|
|
|
def ts_locs_array(
|
2021-08-21 01:07:28 +02:00
|
|
|
config: "ColumnElement[Text]",
|
|
|
|
text: "ColumnElement[Text]",
|
|
|
|
tsquery: "ColumnElement[Any]",
|
|
|
|
) -> "ColumnElement[ARRAY[Integer]]":
|
2020-06-10 06:41:04 +02:00
|
|
|
options = f"HighlightAll = TRUE, StartSel = {TS_START}, StopSel = {TS_STOP}"
|
2021-08-21 01:07:28 +02:00
|
|
|
delimited = func.ts_headline(config, text, tsquery, options, type_=Text)
|
|
|
|
part = func.unnest(
|
|
|
|
func.string_to_array(delimited, TS_START, type_=ARRAY(Text)), type_=Text
|
|
|
|
).column_valued()
|
|
|
|
part_len = func.length(part, type_=Integer) - len(TS_STOP)
|
|
|
|
match_pos = func.sum(part_len, type_=Integer).over(rows=(None, -1)) + len(TS_STOP)
|
|
|
|
match_len = func.strpos(part, TS_STOP, type_=Integer) - 1
|
|
|
|
return func.array(
|
2022-02-10 04:13:15 +01:00
|
|
|
select(postgresql.array([match_pos, match_len])).offset(1).scalar_subquery(),
|
2021-08-21 01:07:28 +02:00
|
|
|
type_=ARRAY(Integer),
|
2019-08-28 11:06:38 +02:00
|
|
|
)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
# When you add a new operator to this, also update zerver/lib/narrow.py
|
2017-11-05 11:53:59 +01:00
|
|
|
class NarrowBuilder:
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2017-06-30 01:46:57 +02:00
|
|
|
Build up a SQLAlchemy query to find messages matching a narrow.
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2017-06-30 01:46:57 +02:00
|
|
|
|
|
|
|
# This class has an important security invariant:
|
|
|
|
#
|
|
|
|
# None of these methods ever *add* messages to a query's result.
|
|
|
|
#
|
|
|
|
# That is, the `add_term` method, and its helpers the `by_*` methods,
|
2020-11-16 22:52:27 +01:00
|
|
|
# are passed a Select object representing a query for messages; they may
|
|
|
|
# call some methods on it, and then they return a resulting Select
|
2017-06-30 01:46:57 +02:00
|
|
|
# object. Things these methods may do to the queries they handle
|
|
|
|
# include
|
|
|
|
# * add conditions to filter out rows (i.e., messages), with `query.where`
|
|
|
|
# * add columns for more information on the same message, with `query.column`
|
|
|
|
# * add a join for more information on the same message
|
|
|
|
#
|
|
|
|
# Things they may not do include
|
|
|
|
# * anything that would pull in additional rows, or information on
|
|
|
|
# other messages.
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
user_profile: Optional[UserProfile],
|
2021-08-21 01:07:28 +02:00
|
|
|
msg_id_column: "ColumnElement[Integer]",
|
2021-02-12 08:19:30 +01:00
|
|
|
realm: Realm,
|
|
|
|
is_web_public_query: bool = False,
|
|
|
|
) -> None:
|
2013-12-12 18:36:32 +01:00
|
|
|
self.user_profile = user_profile
|
2013-12-10 23:32:29 +01:00
|
|
|
self.msg_id_column = msg_id_column
|
2020-08-04 19:33:43 +02:00
|
|
|
self.realm = realm
|
|
|
|
self.is_web_public_query = is_web_public_query
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def add_term(self, query: Select, term: Dict[str, Any]) -> Select:
|
2017-06-30 01:46:57 +02:00
|
|
|
"""
|
|
|
|
Extend the given query to one narrowed by the given term, and return the result.
|
|
|
|
|
|
|
|
This method satisfies an important security property: the returned
|
|
|
|
query never includes a message that the given query didn't. In
|
|
|
|
particular, if the given query will only find messages that a given
|
|
|
|
user can legitimately see, then so will the returned query.
|
|
|
|
"""
|
|
|
|
# To maintain the security property, we hold all the `by_*`
|
|
|
|
# methods to the same criterion. See the class's block comment
|
|
|
|
# for details.
|
2016-09-12 02:09:24 +02:00
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
# We have to be careful here because we're letting users call a method
|
|
|
|
# by name! The prefix 'by_' prevents it from colliding with builtin
|
|
|
|
# Python __magic__ stuff.
|
2021-02-12 08:20:45 +01:00
|
|
|
operator = term["operator"]
|
|
|
|
operand = term["operand"]
|
2014-02-11 21:36:59 +01:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
negated = term.get("negated", False)
|
2014-02-11 21:36:59 +01:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
method_name = "by_" + operator.replace("-", "_")
|
2013-12-12 18:36:32 +01:00
|
|
|
method = getattr(self, method_name, None)
|
|
|
|
if method is None:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown operator " + operator)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2014-02-12 19:09:11 +01:00
|
|
|
if negated:
|
|
|
|
maybe_negate = not_
|
|
|
|
else:
|
|
|
|
maybe_negate = lambda cond: cond
|
|
|
|
|
|
|
|
return method(query, operand, maybe_negate)
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_has(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2021-02-12 08:20:45 +01:00
|
|
|
if operand not in ["attachment", "image", "link"]:
|
2014-03-05 18:41:01 +01:00
|
|
|
raise BadNarrowOperator("unknown 'has' operand " + operand)
|
2021-02-12 08:20:45 +01:00
|
|
|
col_name = "has_" + operand
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column(col_name, Boolean)
|
2014-03-05 18:41:01 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_in(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2020-08-04 19:33:43 +02:00
|
|
|
# This operator does not support is_web_public_query.
|
|
|
|
assert not self.is_web_public_query
|
|
|
|
assert self.user_profile is not None
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
if operand == "home":
|
2014-02-27 23:57:16 +01:00
|
|
|
conditions = exclude_muting_conditions(self.user_profile, [])
|
|
|
|
return query.where(and_(*conditions))
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "all":
|
2014-02-27 23:57:16 +01:00
|
|
|
return query
|
|
|
|
|
|
|
|
raise BadNarrowOperator("unknown 'in' operand " + operand)
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_is(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2020-08-04 19:33:43 +02:00
|
|
|
# This operator class does not support is_web_public_query.
|
|
|
|
assert not self.is_web_public_query
|
|
|
|
assert self.user_profile is not None
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
if operand == "private":
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "starred":
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("flags", Integer).op("&")(UserMessage.flags.starred.mask) != 0
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "unread":
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("flags", Integer).op("&")(UserMessage.flags.read.mask) == 0
|
2017-06-19 03:21:48 +02:00
|
|
|
return query.where(maybe_negate(cond))
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "mentioned":
|
2020-11-16 22:52:27 +01:00
|
|
|
cond1 = column("flags", Integer).op("&")(UserMessage.flags.mentioned.mask) != 0
|
|
|
|
cond2 = column("flags", Integer).op("&")(UserMessage.flags.wildcard_mentioned.mask) != 0
|
2017-08-16 15:20:11 +02:00
|
|
|
cond = or_(cond1, cond2)
|
|
|
|
return query.where(maybe_negate(cond))
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "alerted":
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("flags", Integer).op("&")(UserMessage.flags.has_alert_word.mask) != 0
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2021-07-13 20:23:36 +02:00
|
|
|
elif operand == "resolved":
|
|
|
|
cond = get_resolved_topic_condition_sa()
|
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
raise BadNarrowOperator("unknown 'is' operand " + operand)
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
2014-01-07 22:15:22 +01:00
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def _pg_re_escape(self, pattern: str) -> str:
|
2014-01-07 22:15:22 +01:00
|
|
|
"""
|
|
|
|
Escape user input to place in a regex
|
|
|
|
|
2020-10-26 22:27:53 +01:00
|
|
|
Python's re.escape escapes Unicode characters in a way which PostgreSQL
|
2017-11-04 05:23:22 +01:00
|
|
|
fails on, '\u03bb' to '\\\u03bb'. This function will correctly escape
|
2020-10-26 22:27:53 +01:00
|
|
|
them for PostgreSQL, '\u03bb' to '\\u03bb'.
|
2014-01-07 22:15:22 +01:00
|
|
|
"""
|
|
|
|
s = list(pattern)
|
|
|
|
for i, c in enumerate(s):
|
|
|
|
if c not in self._alphanum:
|
2017-04-26 01:28:22 +02:00
|
|
|
if ord(c) >= 128:
|
2020-10-26 22:27:53 +01:00
|
|
|
# convert the character to hex PostgreSQL regex will take
|
2014-01-07 22:15:22 +01:00
|
|
|
# \uXXXX
|
2021-02-12 08:20:45 +01:00
|
|
|
s[i] = f"\\u{ord(c):0>4x}"
|
2014-01-07 22:15:22 +01:00
|
|
|
else:
|
2021-02-12 08:20:45 +01:00
|
|
|
s[i] = "\\" + c
|
|
|
|
return "".join(s)
|
2014-01-07 22:15:22 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def by_stream(
|
|
|
|
self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2017-03-23 07:22:28 +01:00
|
|
|
try:
|
2017-08-15 18:58:29 +02:00
|
|
|
# Because you can see your own message history for
|
|
|
|
# private streams you are no longer subscribed to, we
|
2019-08-11 18:57:54 +02:00
|
|
|
# need get_stream_by_narrow_operand_access_unchecked here.
|
2020-08-11 20:31:25 +02:00
|
|
|
stream = get_stream_by_narrow_operand_access_unchecked(operand, self.realm)
|
2020-08-04 19:33:43 +02:00
|
|
|
|
|
|
|
if self.is_web_public_query and not stream.is_web_public:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown web-public stream " + str(operand))
|
2017-03-23 07:22:28 +01:00
|
|
|
except Stream.DoesNotExist:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown stream " + str(operand))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-08-11 20:31:25 +02:00
|
|
|
if self.realm.is_zephyr_mirror_realm:
|
2017-06-30 02:24:05 +02:00
|
|
|
# MIT users expect narrowing to "social" to also show messages to
|
|
|
|
# /^(un)*social(.d)*$/ (unsocial, ununsocial, social.d, ...).
|
|
|
|
|
|
|
|
# In `ok_to_include_history`, we assume that a non-negated
|
|
|
|
# `stream` term for a public stream will limit the query to
|
|
|
|
# that specific stream. So it would be a bug to hit this
|
|
|
|
# codepath after relying on this term there. But all streams in
|
|
|
|
# a Zephyr realm are private, so that doesn't happen.
|
2021-02-12 08:19:30 +01:00
|
|
|
assert not stream.is_public()
|
2017-06-30 02:24:05 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
m = re.search(r"^(?:un)*(.+?)(?:\.d)*$", stream.name, re.IGNORECASE)
|
2017-02-23 01:06:04 +01:00
|
|
|
# Since the regex has a `.+` in it and "" is invalid as a
|
|
|
|
# stream name, this will always match
|
2021-02-12 08:19:30 +01:00
|
|
|
assert m is not None
|
2017-02-23 01:06:04 +01:00
|
|
|
base_stream_name = m.group(1)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-08-11 20:31:25 +02:00
|
|
|
matching_streams = get_active_streams(self.realm).filter(
|
2022-02-15 23:45:41 +01:00
|
|
|
name__iregex=rf"^(un)*{self._pg_re_escape(base_stream_name)}(\.d)*$"
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2019-12-06 00:15:59 +01:00
|
|
|
recipient_ids = [matching_stream.recipient_id for matching_stream in matching_streams]
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("recipient_id", Integer).in_(recipient_ids)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2019-12-05 23:26:24 +01:00
|
|
|
recipient = stream.recipient
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("recipient_id", Integer) == recipient.id
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_streams(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2021-02-12 08:20:45 +01:00
|
|
|
if operand == "public":
|
2019-08-13 20:20:36 +02:00
|
|
|
# Get all both subscribed and non subscribed public streams
|
|
|
|
# but exclude any private subscribed streams.
|
2020-08-11 20:28:57 +02:00
|
|
|
recipient_queryset = get_public_streams_queryset(self.realm)
|
2021-02-12 08:20:45 +01:00
|
|
|
elif operand == "web-public":
|
2020-08-04 19:33:43 +02:00
|
|
|
recipient_queryset = get_web_public_streams_queryset(self.realm)
|
2020-08-11 20:28:57 +02:00
|
|
|
else:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown streams operand " + operand)
|
2020-08-11 20:28:57 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
recipient_ids = recipient_queryset.values_list("recipient_id", flat=True).order_by("id")
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("recipient_id", Integer).in_(recipient_ids)
|
2020-08-11 20:28:57 +02:00
|
|
|
return query.where(maybe_negate(cond))
|
2019-08-13 20:20:36 +02:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_topic(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2020-08-11 20:31:25 +02:00
|
|
|
if self.realm.is_zephyr_mirror_realm:
|
2013-12-12 18:36:32 +01:00
|
|
|
# MIT users expect narrowing to topic "foo" to also show messages to /^foo(.d)*$/
|
|
|
|
# (foo, foo.d, foo.d.d, etc)
|
2021-02-12 08:20:45 +01:00
|
|
|
m = re.search(r"^(.*?)(?:\.d)*$", operand, re.IGNORECASE)
|
2017-02-23 01:06:04 +01:00
|
|
|
# Since the regex has a `.*` in it, this will always match
|
2021-02-12 08:19:30 +01:00
|
|
|
assert m is not None
|
2017-02-23 01:06:04 +01:00
|
|
|
base_topic = m.group(1)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
|
|
|
# Additionally, MIT users expect the empty instance and
|
|
|
|
# instance "personal" to be the same.
|
2021-02-12 08:20:45 +01:00
|
|
|
if base_topic in ("", "personal", '(instance "")'):
|
2020-11-16 22:52:27 +01:00
|
|
|
cond: ClauseElement = or_(
|
2018-11-01 22:15:43 +01:00
|
|
|
topic_match_sa(""),
|
|
|
|
topic_match_sa(".d"),
|
|
|
|
topic_match_sa(".d.d"),
|
|
|
|
topic_match_sa(".d.d.d"),
|
|
|
|
topic_match_sa(".d.d.d.d"),
|
|
|
|
topic_match_sa("personal"),
|
|
|
|
topic_match_sa("personal.d"),
|
|
|
|
topic_match_sa("personal.d.d"),
|
|
|
|
topic_match_sa("personal.d.d.d"),
|
|
|
|
topic_match_sa("personal.d.d.d.d"),
|
|
|
|
topic_match_sa('(instance "")'),
|
|
|
|
topic_match_sa('(instance "").d'),
|
|
|
|
topic_match_sa('(instance "").d.d'),
|
|
|
|
topic_match_sa('(instance "").d.d.d'),
|
|
|
|
topic_match_sa('(instance "").d.d.d.d'),
|
2017-02-22 21:23:22 +01:00
|
|
|
)
|
2013-12-12 18:36:32 +01:00
|
|
|
else:
|
2020-10-26 22:27:53 +01:00
|
|
|
# We limit `.d` counts, since PostgreSQL has much better
|
2017-02-22 21:23:22 +01:00
|
|
|
# query planning for this than they do for a regular
|
|
|
|
# expression (which would sometimes table scan).
|
|
|
|
cond = or_(
|
2018-11-01 22:15:43 +01:00
|
|
|
topic_match_sa(base_topic),
|
|
|
|
topic_match_sa(base_topic + ".d"),
|
|
|
|
topic_match_sa(base_topic + ".d.d"),
|
|
|
|
topic_match_sa(base_topic + ".d.d.d"),
|
|
|
|
topic_match_sa(base_topic + ".d.d.d.d"),
|
2017-02-22 21:23:22 +01:00
|
|
|
)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2018-11-01 22:15:43 +01:00
|
|
|
cond = topic_match_sa(operand)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def by_sender(
|
|
|
|
self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2013-12-12 18:36:32 +01:00
|
|
|
try:
|
2019-07-13 01:48:04 +02:00
|
|
|
if isinstance(operand, str):
|
2020-08-11 20:25:11 +02:00
|
|
|
sender = get_user_including_cross_realm(operand, self.realm)
|
2019-07-13 01:48:04 +02:00
|
|
|
else:
|
2020-08-11 20:25:11 +02:00
|
|
|
sender = get_user_by_id_in_realm_including_cross_realm(operand, self.realm)
|
2013-12-12 18:36:32 +01:00
|
|
|
except UserProfile.DoesNotExist:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown user " + str(operand))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("sender_id", Integer) == literal(sender.id)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_near(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2013-12-10 23:32:29 +01:00
|
|
|
return query
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def by_id(
|
|
|
|
self, query: Select, operand: Union[int, str], maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2018-11-07 00:53:02 +01:00
|
|
|
if not str(operand).isdigit():
|
|
|
|
raise BadNarrowOperator("Invalid message ID")
|
2014-02-11 23:33:24 +01:00
|
|
|
cond = self.msg_id_column == literal(operand)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def by_pm_with(
|
|
|
|
self, query: Select, operand: Union[str, Iterable[int]], maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2020-08-04 19:33:43 +02:00
|
|
|
# This operator does not support is_web_public_query.
|
|
|
|
assert not self.is_web_public_query
|
|
|
|
assert self.user_profile is not None
|
2019-06-28 21:05:58 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
if isinstance(operand, str):
|
|
|
|
email_list = operand.split(",")
|
|
|
|
user_profiles = get_user_profiles(
|
|
|
|
emails=email_list,
|
2020-08-11 20:25:11 +02:00
|
|
|
realm=self.realm,
|
2019-06-28 21:05:58 +02:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
"""
|
|
|
|
This is where we handle passing a list of user IDs for the narrow, which is the
|
|
|
|
preferred/cleaner API.
|
|
|
|
"""
|
|
|
|
user_profiles = get_user_profiles_by_ids(
|
|
|
|
user_ids=operand,
|
2020-08-11 20:25:11 +02:00
|
|
|
realm=self.realm,
|
2019-06-28 21:05:58 +02:00
|
|
|
)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
recipient = recipient_for_user_profiles(
|
|
|
|
user_profiles=user_profiles,
|
|
|
|
forwarded_mirror_message=False,
|
|
|
|
forwarder_user_profile=None,
|
|
|
|
sender=self.user_profile,
|
|
|
|
allow_deactivated=True,
|
|
|
|
)
|
2019-06-28 21:05:58 +02:00
|
|
|
except (JsonableError, ValidationError):
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown user in " + str(operand))
|
2019-06-28 21:05:58 +02:00
|
|
|
|
|
|
|
# Group DM
|
|
|
|
if recipient.type == Recipient.HUDDLE:
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("recipient_id", Integer) == recipient.id
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
narrow: Handle spurious emails in pm-with searches.
If cordelia searches on pm-with:iago@zulip.com,cordelia@zulip.com,
we now properly treat that the same way as pm-with:iago@zulip.com.
Before this fix, the query would initially go through the
huddle code path. The symptom wasn't completely obvious, as
eventually a deeper function would return a recipient id
corresponding to a single PM with @iago@zulip.com, but we would
only get messages where iago was the recipient, and not any
messages where he was the sender to cordelia.
I put the helper function for this in zerver/lib/addressee, which
is somewhat speculative. Eventually, we'll want pm-with queries
to allow for user ids, and I imagine there will be some shared
logic with other Addressee code in terms of how we handle these
strings. The way we deal with lists of emails/users for various
endpoints is kind of haphazard in the current code, although
granted it's mostly just repeating the same simple patterns. It
would be nice for some of this code to converge a bit. This
affects new messages, typing indicators, search filters, etc.,
and some endpoints have strange legacy stuff like supporting
JSON-encoded lists, so it's not trivial to clean this up.
Tweaked by tabbott to add some additional tests.
2018-10-12 17:56:46 +02:00
|
|
|
|
2019-06-28 21:05:58 +02:00
|
|
|
# 1:1 PM
|
|
|
|
other_participant = None
|
|
|
|
|
|
|
|
# Find if another person is in PM
|
|
|
|
for user in user_profiles:
|
|
|
|
if user.id != self.user_profile.id:
|
|
|
|
other_participant = user
|
|
|
|
|
|
|
|
# PM with another person
|
|
|
|
if other_participant:
|
|
|
|
# We need bidirectional messages PM with another person.
|
|
|
|
# But Recipient.PERSONAL objects only encode the person who
|
|
|
|
# received the message, and not the other participant in
|
|
|
|
# the thread (the sender), we need to do a somewhat
|
|
|
|
# complex query to get messages between these two users
|
|
|
|
# with either of them as the sender.
|
2019-12-05 23:35:33 +01:00
|
|
|
self_recipient_id = self.user_profile.recipient_id
|
2021-02-12 08:19:30 +01:00
|
|
|
cond = or_(
|
|
|
|
and_(
|
|
|
|
column("sender_id", Integer) == other_participant.id,
|
|
|
|
column("recipient_id", Integer) == self_recipient_id,
|
|
|
|
),
|
|
|
|
and_(
|
|
|
|
column("sender_id", Integer) == self.user_profile.id,
|
|
|
|
column("recipient_id", Integer) == recipient.id,
|
|
|
|
),
|
|
|
|
)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-10 23:32:29 +01:00
|
|
|
|
2019-06-28 21:05:58 +02:00
|
|
|
# PM with self
|
2021-02-12 08:19:30 +01:00
|
|
|
cond = and_(
|
|
|
|
column("sender_id", Integer) == self.user_profile.id,
|
|
|
|
column("recipient_id", Integer) == recipient.id,
|
|
|
|
)
|
2019-06-28 21:05:58 +02:00
|
|
|
return query.where(maybe_negate(cond))
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def by_group_pm_with(
|
|
|
|
self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2020-08-04 19:33:43 +02:00
|
|
|
# This operator does not support is_web_public_query.
|
|
|
|
assert not self.is_web_public_query
|
|
|
|
assert self.user_profile is not None
|
|
|
|
|
2017-03-23 23:35:37 +01:00
|
|
|
try:
|
2019-07-14 19:31:28 +02:00
|
|
|
if isinstance(operand, str):
|
2020-08-11 20:25:11 +02:00
|
|
|
narrow_profile = get_user_including_cross_realm(operand, self.realm)
|
2019-07-14 19:31:28 +02:00
|
|
|
else:
|
2020-08-11 20:25:11 +02:00
|
|
|
narrow_profile = get_user_by_id_in_realm_including_cross_realm(operand, self.realm)
|
2017-03-23 23:35:37 +01:00
|
|
|
except UserProfile.DoesNotExist:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise BadNarrowOperator("unknown user " + str(operand))
|
2017-03-23 23:35:37 +01:00
|
|
|
|
|
|
|
self_recipient_ids = [
|
2021-02-12 08:20:45 +01:00
|
|
|
recipient_tuple["recipient_id"]
|
2021-02-12 08:19:30 +01:00
|
|
|
for recipient_tuple in Subscription.objects.filter(
|
2017-03-23 23:35:37 +01:00
|
|
|
user_profile=self.user_profile,
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
recipient__type=Recipient.HUDDLE,
|
2021-02-12 08:19:30 +01:00
|
|
|
).values("recipient_id")
|
|
|
|
]
|
2017-03-23 23:35:37 +01:00
|
|
|
narrow_recipient_ids = [
|
2021-02-12 08:20:45 +01:00
|
|
|
recipient_tuple["recipient_id"]
|
2021-02-12 08:19:30 +01:00
|
|
|
for recipient_tuple in Subscription.objects.filter(
|
2017-03-23 23:35:37 +01:00
|
|
|
user_profile=narrow_profile,
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
recipient__type=Recipient.HUDDLE,
|
2021-02-12 08:19:30 +01:00
|
|
|
).values("recipient_id")
|
|
|
|
]
|
2017-03-23 23:35:37 +01:00
|
|
|
|
|
|
|
recipient_ids = set(self_recipient_ids) & set(narrow_recipient_ids)
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("recipient_id", Integer).in_(recipient_ids)
|
2017-03-23 23:35:37 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
def by_search(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
|
2022-02-12 03:39:06 +01:00
|
|
|
if settings.USING_PGROONGA:
|
2016-04-24 17:08:51 +02:00
|
|
|
return self._by_search_pgroonga(query, operand, maybe_negate)
|
|
|
|
else:
|
|
|
|
return self._by_search_tsearch(query, operand, maybe_negate)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def _by_search_pgroonga(
|
|
|
|
self, query: Select, operand: str, maybe_negate: ConditionTransform
|
2022-02-12 03:39:06 +01:00
|
|
|
) -> Select:
|
2018-05-31 04:53:47 +02:00
|
|
|
match_positions_character = func.pgroonga_match_positions_character
|
|
|
|
query_extract_keywords = func.pgroonga_query_extract_keywords
|
2021-08-21 01:07:28 +02:00
|
|
|
operand_escaped = func.escape_html(operand, type_=Text)
|
2018-05-19 05:39:13 +02:00
|
|
|
keywords = query_extract_keywords(operand_escaped)
|
2022-02-10 03:16:39 +01:00
|
|
|
query = query.add_columns(
|
2021-02-12 08:19:30 +01:00
|
|
|
match_positions_character(column("rendered_content", Text), keywords).label(
|
|
|
|
"content_matches"
|
2022-02-10 03:16:39 +01:00
|
|
|
),
|
2021-08-21 01:07:28 +02:00
|
|
|
match_positions_character(
|
|
|
|
func.escape_html(topic_column_sa(), type_=Text), keywords
|
2022-02-10 03:16:39 +01:00
|
|
|
).label("topic_matches"),
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2021-08-21 01:07:28 +02:00
|
|
|
condition = column("search_pgroonga", Text).op("&@~")(operand_escaped)
|
2016-04-24 17:08:51 +02:00
|
|
|
return query.where(maybe_negate(condition))
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def _by_search_tsearch(
|
|
|
|
self, query: Select, operand: str, maybe_negate: ConditionTransform
|
|
|
|
) -> Select:
|
2013-12-10 23:32:29 +01:00
|
|
|
tsquery = func.plainto_tsquery(literal("zulip.english_us_search"), literal(operand))
|
2022-02-10 03:16:39 +01:00
|
|
|
query = query.add_columns(
|
2021-02-12 08:19:30 +01:00
|
|
|
ts_locs_array(
|
2021-08-21 01:07:28 +02:00
|
|
|
literal("zulip.english_us_search", Text), column("rendered_content", Text), tsquery
|
2022-02-10 03:16:39 +01:00
|
|
|
).label("content_matches"),
|
|
|
|
# We HTML-escape the topic in PostgreSQL to avoid doing a server round-trip
|
2021-02-12 08:19:30 +01:00
|
|
|
ts_locs_array(
|
2021-08-21 01:07:28 +02:00
|
|
|
literal("zulip.english_us_search", Text),
|
|
|
|
func.escape_html(topic_column_sa(), type_=Text),
|
|
|
|
tsquery,
|
2022-02-10 03:16:39 +01:00
|
|
|
).label("topic_matches"),
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2013-12-02 20:29:57 +01:00
|
|
|
|
|
|
|
# Do quoted string matching. We really want phrase
|
|
|
|
# search here so we can ignore punctuation and do
|
|
|
|
# stemming, but there isn't a standard phrase search
|
2020-10-26 22:27:53 +01:00
|
|
|
# mechanism in PostgreSQL
|
2018-07-02 00:05:24 +02:00
|
|
|
for term in re.findall(r'"[^"]+"|\S+', operand):
|
2013-12-02 20:29:57 +01:00
|
|
|
if term[0] == '"' and term[-1] == '"':
|
|
|
|
term = term[1:-1]
|
2021-02-12 08:20:45 +01:00
|
|
|
term = "%" + connection.ops.prep_for_like_query(term) + "%"
|
2021-08-21 01:07:28 +02:00
|
|
|
cond: ClauseElement = or_(
|
|
|
|
column("content", Text).ilike(term), topic_column_sa().ilike(term)
|
|
|
|
)
|
2014-02-12 19:09:11 +01:00
|
|
|
query = query.where(maybe_negate(cond))
|
2013-12-02 20:29:57 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
cond = column("search_tsvector", postgresql.TSVECTOR).op("@@")(tsquery)
|
2014-02-12 19:09:11 +01:00
|
|
|
return query.where(maybe_negate(cond))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def highlight_string(text: str, locs: Iterable[Tuple[int, int]]) -> str:
|
2017-11-04 05:23:22 +01:00
|
|
|
highlight_start = '<span class="highlight">'
|
2021-02-12 08:20:45 +01:00
|
|
|
highlight_stop = "</span>"
|
2013-11-26 00:41:24 +01:00
|
|
|
pos = 0
|
2021-02-12 08:20:45 +01:00
|
|
|
result = ""
|
2017-04-06 15:59:56 +02:00
|
|
|
in_tag = False
|
2017-10-31 19:03:12 +01:00
|
|
|
|
2013-11-26 00:41:24 +01:00
|
|
|
for loc in locs:
|
|
|
|
(offset, length) = loc
|
2017-10-31 19:03:12 +01:00
|
|
|
|
|
|
|
prefix_start = pos
|
|
|
|
prefix_end = offset
|
|
|
|
match_start = offset
|
|
|
|
match_end = offset + length
|
|
|
|
|
2019-08-28 11:06:38 +02:00
|
|
|
prefix = text[prefix_start:prefix_end]
|
|
|
|
match = text[match_start:match_end]
|
2017-10-31 19:03:12 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
for character in prefix + match:
|
2021-02-12 08:20:45 +01:00
|
|
|
if character == "<":
|
2017-04-06 15:59:56 +02:00
|
|
|
in_tag = True
|
2021-02-12 08:20:45 +01:00
|
|
|
elif character == ">":
|
2017-04-06 15:59:56 +02:00
|
|
|
in_tag = False
|
2022-02-12 03:39:06 +01:00
|
|
|
if in_tag:
|
2017-10-31 19:03:12 +01:00
|
|
|
result += prefix
|
|
|
|
result += match
|
2017-04-06 15:59:56 +02:00
|
|
|
else:
|
2017-10-31 19:03:12 +01:00
|
|
|
result += prefix
|
2017-04-06 15:59:56 +02:00
|
|
|
result += highlight_start
|
2017-10-31 19:03:12 +01:00
|
|
|
result += match
|
2017-04-06 15:59:56 +02:00
|
|
|
result += highlight_stop
|
2017-10-31 19:03:12 +01:00
|
|
|
pos = match_end
|
|
|
|
|
2019-08-28 11:06:38 +02:00
|
|
|
result += text[pos:]
|
2016-08-25 08:00:52 +02:00
|
|
|
return result
|
2013-11-26 00:41:24 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def get_search_fields(
|
|
|
|
rendered_content: str,
|
|
|
|
topic_name: str,
|
|
|
|
content_matches: Iterable[Tuple[int, int]],
|
|
|
|
topic_matches: Iterable[Tuple[int, int]],
|
|
|
|
) -> Dict[str, str]:
|
2018-11-09 17:25:57 +01:00
|
|
|
return {
|
2021-02-12 08:20:45 +01:00
|
|
|
"match_content": highlight_string(rendered_content, content_matches),
|
2018-11-09 17:25:57 +01:00
|
|
|
MATCH_TOPIC: highlight_string(escape_html(topic_name), topic_matches),
|
|
|
|
}
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-08-11 19:07:34 +02:00
|
|
|
def narrow_parameter(json: str) -> OptionalNarrowListT:
|
2016-07-30 01:27:56 +02:00
|
|
|
|
2020-08-07 01:09:47 +02:00
|
|
|
data = orjson.loads(json)
|
2014-02-10 21:45:53 +01:00
|
|
|
if not isinstance(data, list):
|
|
|
|
raise ValueError("argument is not a list")
|
2017-03-19 01:46:35 +01:00
|
|
|
if len(data) == 0:
|
|
|
|
# The "empty narrow" should be None, and not []
|
|
|
|
return None
|
2014-02-10 21:45:53 +01:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def convert_term(elem: Union[Dict[str, Any], List[str]]) -> Dict[str, Any]:
|
2016-09-12 02:09:24 +02:00
|
|
|
|
2014-02-11 00:31:26 +01:00
|
|
|
# We have to support a legacy tuple format.
|
|
|
|
if isinstance(elem, list):
|
2021-02-12 08:19:30 +01:00
|
|
|
if len(elem) != 2 or any(not isinstance(x, str) for x in elem):
|
2014-02-11 00:31:26 +01:00
|
|
|
raise ValueError("element is not a string pair")
|
|
|
|
return dict(operator=elem[0], operand=elem[1])
|
|
|
|
|
|
|
|
if isinstance(elem, dict):
|
2019-07-11 18:54:28 +02:00
|
|
|
# Make sure to sync this list to frontend also when adding a new operator.
|
|
|
|
# that supports user IDs. Relevant code is located in static/js/message_fetch.js
|
2019-08-10 18:14:22 +02:00
|
|
|
# in handle_operators_supporting_id_based_api function where you will need to update
|
2019-08-10 18:10:29 +02:00
|
|
|
# operators_supporting_id, or operators_supporting_ids array.
|
2021-02-12 08:20:45 +01:00
|
|
|
operators_supporting_id = ["sender", "group-pm-with", "stream"]
|
|
|
|
operators_supporting_ids = ["pm-with"]
|
|
|
|
operators_non_empty_operand = {"search"}
|
2019-07-13 01:48:04 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
operator = elem.get("operator", "")
|
2019-08-10 18:10:29 +02:00
|
|
|
if operator in operators_supporting_id:
|
2020-06-22 22:37:00 +02:00
|
|
|
operand_validator: Validator[object] = check_string_or_int
|
2019-08-10 18:10:29 +02:00
|
|
|
elif operator in operators_supporting_ids:
|
2019-06-08 23:21:01 +02:00
|
|
|
operand_validator = check_string_or_int_list
|
2020-04-11 17:32:32 +02:00
|
|
|
elif operator in operators_non_empty_operand:
|
|
|
|
operand_validator = check_required_string
|
2019-06-08 23:21:01 +02:00
|
|
|
else:
|
|
|
|
operand_validator = check_string
|
|
|
|
|
2020-06-25 00:47:43 +02:00
|
|
|
validator = check_dict(
|
|
|
|
required_keys=[
|
2021-02-12 08:20:45 +01:00
|
|
|
("operator", check_string),
|
|
|
|
("operand", operand_validator),
|
2020-06-25 00:47:43 +02:00
|
|
|
],
|
|
|
|
optional_keys=[
|
2021-02-12 08:20:45 +01:00
|
|
|
("negated", check_bool),
|
2020-06-25 00:47:43 +02:00
|
|
|
],
|
|
|
|
)
|
2014-02-11 00:31:26 +01:00
|
|
|
|
2020-06-21 02:36:20 +02:00
|
|
|
try:
|
2021-02-12 08:20:45 +01:00
|
|
|
validator("elem", elem)
|
2020-06-21 02:36:20 +02:00
|
|
|
except ValidationError as error:
|
|
|
|
raise JsonableError(error.message)
|
2014-02-11 00:31:26 +01:00
|
|
|
|
|
|
|
# whitelist the fields we care about for now
|
2014-02-11 21:36:59 +01:00
|
|
|
return dict(
|
2021-02-12 08:20:45 +01:00
|
|
|
operator=elem["operator"],
|
|
|
|
operand=elem["operand"],
|
|
|
|
negated=elem.get("negated", False),
|
2014-02-11 21:36:59 +01:00
|
|
|
)
|
2014-02-11 00:31:26 +01:00
|
|
|
|
|
|
|
raise ValueError("element is not a dictionary")
|
2014-02-10 21:45:53 +01:00
|
|
|
|
2015-11-01 17:14:53 +01:00
|
|
|
return list(map(convert_term, data))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def ok_to_include_history(
|
|
|
|
narrow: OptionalNarrowListT, user_profile: Optional[UserProfile], is_web_public_query: bool
|
|
|
|
) -> bool:
|
2014-02-13 16:24:06 +01:00
|
|
|
# There are occasions where we need to find Message rows that
|
|
|
|
# have no corresponding UserMessage row, because the user is
|
|
|
|
# reading a public stream that might include messages that
|
|
|
|
# were sent while the user was not subscribed, but which they are
|
|
|
|
# allowed to see. We have to be very careful about constructing
|
|
|
|
# queries in those situations, so this function should return True
|
|
|
|
# only if we are 100% sure that we're gonna add a clause to the
|
|
|
|
# query that narrows to a particular public stream on the user's realm.
|
|
|
|
# If we screw this up, then we can get into a nasty situation of
|
|
|
|
# polluting our narrow results with messages from other realms.
|
2020-08-04 19:33:43 +02:00
|
|
|
|
|
|
|
# For web-public queries, we are always returning history. The
|
|
|
|
# analogues of the below stream access checks for whether streams
|
|
|
|
# have is_web_public set and banning is operators in this code
|
|
|
|
# path are done directly in NarrowBuilder.
|
|
|
|
if is_web_public_query:
|
|
|
|
assert user_profile is None
|
|
|
|
return True
|
|
|
|
|
|
|
|
assert user_profile is not None
|
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
include_history = False
|
|
|
|
if narrow is not None:
|
2014-02-10 21:45:53 +01:00
|
|
|
for term in narrow:
|
2021-02-12 08:20:45 +01:00
|
|
|
if term["operator"] == "stream" and not term.get("negated", False):
|
|
|
|
operand: Union[str, int] = term["operand"]
|
2019-08-07 17:32:19 +02:00
|
|
|
if isinstance(operand, str):
|
|
|
|
include_history = can_access_stream_history_by_name(user_profile, operand)
|
|
|
|
else:
|
|
|
|
include_history = can_access_stream_history_by_id(user_profile, operand)
|
2021-02-12 08:19:30 +01:00
|
|
|
elif (
|
2021-02-12 08:20:45 +01:00
|
|
|
term["operator"] == "streams"
|
|
|
|
and term["operand"] == "public"
|
|
|
|
and not term.get("negated", False)
|
2021-02-12 08:19:30 +01:00
|
|
|
and user_profile.can_access_public_streams()
|
|
|
|
):
|
2019-08-13 20:20:36 +02:00
|
|
|
include_history = True
|
2014-01-14 22:53:28 +01:00
|
|
|
# Disable historical messages if the user is narrowing on anything
|
|
|
|
# that's a property on the UserMessage table. There cannot be
|
|
|
|
# historical messages in these cases anyway.
|
2014-02-10 21:45:53 +01:00
|
|
|
for term in narrow:
|
2021-02-12 08:20:45 +01:00
|
|
|
if term["operator"] == "is":
|
2013-12-12 18:36:32 +01:00
|
|
|
include_history = False
|
|
|
|
|
2014-02-13 16:24:06 +01:00
|
|
|
return include_history
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def get_stream_from_narrow_access_unchecked(
|
|
|
|
narrow: OptionalNarrowListT, realm: Realm
|
|
|
|
) -> Optional[Stream]:
|
2017-03-19 01:46:35 +01:00
|
|
|
if narrow is not None:
|
|
|
|
for term in narrow:
|
2021-02-12 08:20:45 +01:00
|
|
|
if term["operator"] == "stream":
|
|
|
|
return get_stream_by_narrow_operand_access_unchecked(term["operand"], realm)
|
2014-02-25 15:41:32 +01:00
|
|
|
return None
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def exclude_muting_conditions(
|
|
|
|
user_profile: UserProfile, narrow: OptionalNarrowListT
|
|
|
|
) -> List[ClauseElement]:
|
2021-08-21 01:07:28 +02:00
|
|
|
conditions: List[ClauseElement] = []
|
2017-09-17 20:19:12 +02:00
|
|
|
stream_id = None
|
2019-08-12 18:49:06 +02:00
|
|
|
try:
|
|
|
|
# Note: It is okay here to not check access to stream
|
|
|
|
# because we are only using the stream id to exclude data,
|
|
|
|
# not to include results.
|
|
|
|
stream = get_stream_from_narrow_access_unchecked(narrow, user_profile.realm)
|
|
|
|
if stream is not None:
|
2019-08-11 18:57:54 +02:00
|
|
|
stream_id = stream.id
|
2019-08-12 18:49:06 +02:00
|
|
|
except Stream.DoesNotExist:
|
|
|
|
pass
|
2017-09-17 20:19:12 +02:00
|
|
|
|
2021-02-05 05:58:44 +01:00
|
|
|
# Stream-level muting only applies when looking at views that
|
|
|
|
# include multiple streams, since we do want users to be able to
|
|
|
|
# browser messages within a muted stream.
|
2017-09-17 20:19:12 +02:00
|
|
|
if stream_id is None:
|
2014-02-25 22:22:35 +01:00
|
|
|
rows = Subscription.objects.filter(
|
|
|
|
user_profile=user_profile,
|
|
|
|
active=True,
|
2018-08-02 23:46:05 +02:00
|
|
|
is_muted=True,
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
recipient__type=Recipient.STREAM,
|
2021-02-12 08:20:45 +01:00
|
|
|
).values("recipient_id")
|
|
|
|
muted_recipient_ids = [row["recipient_id"] for row in rows]
|
2017-02-22 23:43:22 +01:00
|
|
|
if len(muted_recipient_ids) > 0:
|
|
|
|
# Only add the condition if we have muted streams to simplify/avoid warnings.
|
2020-11-16 22:52:27 +01:00
|
|
|
condition = not_(column("recipient_id", Integer).in_(muted_recipient_ids))
|
2017-02-22 23:43:22 +01:00
|
|
|
conditions.append(condition)
|
2014-02-25 22:22:35 +01:00
|
|
|
|
2017-09-17 20:19:12 +02:00
|
|
|
conditions = exclude_topic_mutes(conditions, user_profile, stream_id)
|
2014-02-24 23:00:58 +01:00
|
|
|
|
2021-02-05 05:58:44 +01:00
|
|
|
# Muted user logic for hiding messages is implemented entirely
|
|
|
|
# client-side. This is by design, as it allows UI to hint that
|
|
|
|
# muted messages exist where their absence might make conversation
|
|
|
|
# difficult to understand. As a result, we do not need to consider
|
|
|
|
# muted users in this server-side logic for returning messages to
|
|
|
|
# clients. (We could in theory exclude PMs from muted users, but
|
|
|
|
# they're likely to be sufficiently rare to not be worth extra
|
|
|
|
# logic/testing here).
|
|
|
|
|
2014-02-25 22:22:35 +01:00
|
|
|
return conditions
|
2014-02-24 23:00:58 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def get_base_query_for_search(
|
|
|
|
user_profile: Optional[UserProfile], need_message: bool, need_user_message: bool
|
2021-08-21 01:07:28 +02:00
|
|
|
) -> Tuple[Select, "ColumnElement[Integer]"]:
|
2020-08-11 21:05:29 +02:00
|
|
|
# Handle the simple case where user_message isn't involved first.
|
|
|
|
if not need_user_message:
|
2021-02-12 08:19:30 +01:00
|
|
|
assert need_message
|
2022-02-10 04:13:15 +01:00
|
|
|
query = select(column("id", Integer).label("message_id")).select_from(
|
|
|
|
table("zerver_message")
|
|
|
|
)
|
2021-08-21 01:07:28 +02:00
|
|
|
inner_msg_id_col = literal_column("zerver_message.id", Integer)
|
2020-08-11 21:05:29 +02:00
|
|
|
return (query, inner_msg_id_col)
|
|
|
|
|
2020-08-04 19:33:43 +02:00
|
|
|
assert user_profile is not None
|
2020-08-11 21:05:29 +02:00
|
|
|
if need_message:
|
2022-02-10 04:13:15 +01:00
|
|
|
query = (
|
|
|
|
select(column("message_id", Integer), column("flags", Integer))
|
|
|
|
.where(column("user_profile_id", Integer) == literal(user_profile.id))
|
|
|
|
.select_from(
|
|
|
|
join(
|
|
|
|
table("zerver_usermessage"),
|
|
|
|
table("zerver_message"),
|
|
|
|
literal_column("zerver_usermessage.message_id", Integer)
|
|
|
|
== literal_column("zerver_message.id", Integer),
|
|
|
|
)
|
|
|
|
)
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2020-11-16 22:52:27 +01:00
|
|
|
inner_msg_id_col = column("message_id", Integer)
|
2018-04-05 21:56:27 +02:00
|
|
|
return (query, inner_msg_id_col)
|
|
|
|
|
2022-02-10 04:13:15 +01:00
|
|
|
query = (
|
|
|
|
select(column("message_id", Integer), column("flags", Integer))
|
|
|
|
.where(column("user_profile_id", Integer) == literal(user_profile.id))
|
|
|
|
.select_from(table("zerver_usermessage"))
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2020-11-16 22:52:27 +01:00
|
|
|
inner_msg_id_col = column("message_id", Integer)
|
2020-08-11 21:05:29 +02:00
|
|
|
return (query, inner_msg_id_col)
|
2018-04-05 21:56:27 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def add_narrow_conditions(
|
|
|
|
user_profile: Optional[UserProfile],
|
2021-08-21 01:07:28 +02:00
|
|
|
inner_msg_id_col: "ColumnElement[Integer]",
|
2021-02-12 08:19:30 +01:00
|
|
|
query: Select,
|
|
|
|
narrow: OptionalNarrowListT,
|
|
|
|
is_web_public_query: bool,
|
|
|
|
realm: Realm,
|
|
|
|
) -> Tuple[Select, bool]:
|
2018-04-05 21:17:21 +02:00
|
|
|
is_search = False # for now
|
2018-04-05 20:42:37 +02:00
|
|
|
|
|
|
|
if narrow is None:
|
|
|
|
return (query, is_search)
|
|
|
|
|
|
|
|
# Build the query for the narrow
|
2020-08-04 19:33:43 +02:00
|
|
|
builder = NarrowBuilder(user_profile, inner_msg_id_col, realm, is_web_public_query)
|
2018-04-05 21:17:21 +02:00
|
|
|
search_operands = []
|
2018-04-05 20:42:37 +02:00
|
|
|
|
2018-04-05 21:17:21 +02:00
|
|
|
# As we loop through terms, builder does most of the work to extend
|
|
|
|
# our query, but we need to collect the search operands and handle
|
|
|
|
# them after the loop.
|
2018-04-05 20:42:37 +02:00
|
|
|
for term in narrow:
|
2021-02-12 08:20:45 +01:00
|
|
|
if term["operator"] == "search":
|
|
|
|
search_operands.append(term["operand"])
|
2018-04-05 20:42:37 +02:00
|
|
|
else:
|
|
|
|
query = builder.add_term(query, term)
|
|
|
|
|
2018-04-05 21:17:21 +02:00
|
|
|
if search_operands:
|
|
|
|
is_search = True
|
2022-02-10 03:16:39 +01:00
|
|
|
query = query.add_columns(topic_column_sa(), column("rendered_content", Text))
|
2018-04-05 21:17:21 +02:00
|
|
|
search_term = dict(
|
2021-02-12 08:20:45 +01:00
|
|
|
operator="search",
|
|
|
|
operand=" ".join(search_operands),
|
2018-04-05 21:17:21 +02:00
|
|
|
)
|
2018-04-05 20:42:37 +02:00
|
|
|
query = builder.add_term(query, search_term)
|
|
|
|
|
|
|
|
return (query, is_search)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def find_first_unread_anchor(
|
|
|
|
sa_conn: Connection, user_profile: Optional[UserProfile], narrow: OptionalNarrowListT
|
|
|
|
) -> int:
|
2020-08-04 19:33:43 +02:00
|
|
|
# For anonymous web users, all messages are treated as read, and so
|
|
|
|
# always return LARGER_THAN_MAX_MESSAGE_ID.
|
|
|
|
if user_profile is None:
|
|
|
|
return LARGER_THAN_MAX_MESSAGE_ID
|
|
|
|
|
2018-04-05 22:17:50 +02:00
|
|
|
# We always need UserMessage in our query, because it has the unread
|
|
|
|
# flag for the user.
|
|
|
|
need_user_message = True
|
|
|
|
|
2018-04-06 17:57:20 +02:00
|
|
|
# Because we will need to call exclude_muting_conditions, unless
|
|
|
|
# the user hasn't muted anything, we will need to include Message
|
|
|
|
# in our query. It may be worth eventually adding an optimization
|
|
|
|
# for the case of a user who hasn't muted anything to avoid the
|
|
|
|
# join in that case, but it's low priority.
|
2018-04-05 22:17:50 +02:00
|
|
|
need_message = True
|
|
|
|
|
|
|
|
query, inner_msg_id_col = get_base_query_for_search(
|
|
|
|
user_profile=user_profile,
|
|
|
|
need_message=need_message,
|
|
|
|
need_user_message=need_user_message,
|
|
|
|
)
|
|
|
|
|
|
|
|
query, is_search = add_narrow_conditions(
|
|
|
|
user_profile=user_profile,
|
|
|
|
inner_msg_id_col=inner_msg_id_col,
|
|
|
|
query=query,
|
|
|
|
narrow=narrow,
|
2020-08-04 19:33:43 +02:00
|
|
|
is_web_public_query=False,
|
|
|
|
realm=user_profile.realm,
|
2018-04-05 22:17:50 +02:00
|
|
|
)
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
condition = column("flags", Integer).op("&")(UserMessage.flags.read.mask) == 0
|
2018-04-05 14:52:02 +02:00
|
|
|
|
|
|
|
# We exclude messages on muted topics when finding the first unread
|
|
|
|
# message in this narrow
|
|
|
|
muting_conditions = exclude_muting_conditions(user_profile, narrow)
|
|
|
|
if muting_conditions:
|
|
|
|
condition = and_(condition, *muting_conditions)
|
|
|
|
|
|
|
|
first_unread_query = query.where(condition)
|
|
|
|
first_unread_query = first_unread_query.order_by(inner_msg_id_col.asc()).limit(1)
|
|
|
|
first_unread_result = list(sa_conn.execute(first_unread_query).fetchall())
|
|
|
|
if len(first_unread_result) > 0:
|
|
|
|
anchor = first_unread_result[0][0]
|
|
|
|
else:
|
|
|
|
anchor = LARGER_THAN_MAX_MESSAGE_ID
|
|
|
|
|
|
|
|
return anchor
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def parse_anchor_value(anchor_val: Optional[str], use_first_unread_anchor: bool) -> Optional[int]:
|
2020-01-29 03:29:15 +01:00
|
|
|
"""Given the anchor and use_first_unread_anchor parameters passed by
|
|
|
|
the client, computes what anchor value the client requested,
|
|
|
|
handling backwards-compatibility and the various string-valued
|
|
|
|
fields. We encode use_first_unread_anchor as anchor=None.
|
|
|
|
"""
|
|
|
|
if use_first_unread_anchor:
|
|
|
|
# Backwards-compatibility: Before we added support for the
|
|
|
|
# special string-typed anchor values, clients would pass
|
|
|
|
# anchor=None and use_first_unread_anchor=True to indicate
|
|
|
|
# what is now expressed as anchor="first_unread".
|
2020-01-28 06:37:25 +01:00
|
|
|
return None
|
2020-01-29 03:29:15 +01:00
|
|
|
if anchor_val is None:
|
|
|
|
# Throw an exception if neither an anchor argument not
|
|
|
|
# use_first_unread_anchor was specified.
|
|
|
|
raise JsonableError(_("Missing 'anchor' argument."))
|
2020-01-28 06:37:25 +01:00
|
|
|
if anchor_val == "oldest":
|
|
|
|
return 0
|
|
|
|
if anchor_val == "newest":
|
|
|
|
return LARGER_THAN_MAX_MESSAGE_ID
|
2020-01-29 03:29:15 +01:00
|
|
|
if anchor_val == "first_unread":
|
|
|
|
return None
|
2020-01-28 06:37:25 +01:00
|
|
|
try:
|
|
|
|
# We don't use `.isnumeric()` to support negative numbers for
|
|
|
|
# anchor. We don't recommend it in the API (if you want the
|
|
|
|
# very first message, use 0 or 1), but it used to be supported
|
2021-05-14 00:16:30 +02:00
|
|
|
# and was used by the web app, so we need to continue
|
2020-01-28 06:37:25 +01:00
|
|
|
# supporting it for backwards-compatibility
|
|
|
|
anchor = int(anchor_val)
|
|
|
|
if anchor < 0:
|
|
|
|
return 0
|
2020-11-28 20:30:02 +01:00
|
|
|
elif anchor > LARGER_THAN_MAX_MESSAGE_ID:
|
|
|
|
return LARGER_THAN_MAX_MESSAGE_ID
|
2020-01-28 06:37:25 +01:00
|
|
|
return anchor
|
|
|
|
except ValueError:
|
|
|
|
raise JsonableError(_("Invalid anchor"))
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2014-02-13 16:24:06 +01:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def get_messages_backend(
|
|
|
|
request: HttpRequest,
|
|
|
|
maybe_user_profile: Union[UserProfile, AnonymousUser],
|
2021-04-07 21:53:14 +02:00
|
|
|
anchor_val: Optional[str] = REQ("anchor", default=None),
|
2021-02-12 08:19:30 +01:00
|
|
|
num_before: int = REQ(converter=to_non_negative_int),
|
|
|
|
num_after: int = REQ(converter=to_non_negative_int),
|
2021-02-12 08:20:45 +01:00
|
|
|
narrow: OptionalNarrowListT = REQ("narrow", converter=narrow_parameter, default=None),
|
2021-02-12 08:19:30 +01:00
|
|
|
use_first_unread_anchor_val: bool = REQ(
|
2021-04-07 22:00:44 +02:00
|
|
|
"use_first_unread_anchor", json_validator=check_bool, default=False
|
2021-02-12 08:19:30 +01:00
|
|
|
),
|
2021-08-05 19:48:43 +02:00
|
|
|
client_gravatar: bool = REQ(json_validator=check_bool, default=True),
|
2021-04-07 22:00:44 +02:00
|
|
|
apply_markdown: bool = REQ(json_validator=check_bool, default=True),
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2020-01-29 03:29:15 +01:00
|
|
|
anchor = parse_anchor_value(anchor_val, use_first_unread_anchor_val)
|
2018-09-09 14:54:52 +02:00
|
|
|
if num_before + num_after > MAX_MESSAGES_PER_FETCH:
|
2021-06-30 18:35:50 +02:00
|
|
|
raise JsonableError(
|
2021-02-12 08:19:30 +01:00
|
|
|
_("Too many messages requested (maximum {}).").format(
|
|
|
|
MAX_MESSAGES_PER_FETCH,
|
|
|
|
)
|
|
|
|
)
|
2014-02-13 16:24:06 +01:00
|
|
|
|
2021-10-03 14:16:07 +02:00
|
|
|
realm = get_valid_realm_from_request(request)
|
2020-08-04 19:33:43 +02:00
|
|
|
if not maybe_user_profile.is_authenticated:
|
|
|
|
# If user is not authenticated, clients must include
|
|
|
|
# `streams:web-public` in their narrow query to indicate this
|
|
|
|
# is a web-public query. This helps differentiate between
|
|
|
|
# cases of web-public queries (where we should return the
|
|
|
|
# web-public results only) and clients with buggy
|
|
|
|
# authentication code (where we should return an auth error).
|
2020-10-07 13:56:30 +02:00
|
|
|
#
|
|
|
|
# GetOldMessagesTest.test_unauthenticated_* tests ensure
|
|
|
|
# that we are not leaking any secure data (private messages and
|
|
|
|
# non web-public-stream messages) via this path.
|
2021-10-03 14:16:07 +02:00
|
|
|
if not realm.allow_web_public_streams_access():
|
|
|
|
raise MissingAuthenticationError()
|
2020-08-04 19:33:43 +02:00
|
|
|
if not is_web_public_narrow(narrow):
|
2020-08-31 09:31:50 +02:00
|
|
|
raise MissingAuthenticationError()
|
2020-08-04 19:33:43 +02:00
|
|
|
assert narrow is not None
|
2021-09-04 04:03:07 +02:00
|
|
|
if not is_spectator_compatible(narrow):
|
2020-08-31 09:31:50 +02:00
|
|
|
raise MissingAuthenticationError()
|
2020-08-04 19:33:43 +02:00
|
|
|
|
|
|
|
# We use None to indicate unauthenticated requests as it's more
|
|
|
|
# readable than using AnonymousUser, and the lack of Django
|
|
|
|
# stubs means that mypy can't check AnonymousUser well.
|
|
|
|
user_profile: Optional[UserProfile] = None
|
|
|
|
is_web_public_query = True
|
|
|
|
else:
|
|
|
|
assert isinstance(maybe_user_profile, UserProfile)
|
|
|
|
user_profile = maybe_user_profile
|
|
|
|
assert user_profile is not None
|
|
|
|
is_web_public_query = False
|
|
|
|
|
|
|
|
assert realm is not None
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
if (
|
|
|
|
is_web_public_query
|
|
|
|
or realm.email_address_visibility != Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE
|
|
|
|
):
|
2019-02-05 07:12:37 +01:00
|
|
|
# If email addresses are only available to administrators,
|
|
|
|
# clients cannot compute gravatars, so we force-set it to false.
|
|
|
|
client_gravatar = False
|
|
|
|
|
2020-08-04 19:33:43 +02:00
|
|
|
include_history = ok_to_include_history(narrow, user_profile, is_web_public_query)
|
2018-04-05 22:32:30 +02:00
|
|
|
if include_history:
|
2017-06-30 02:24:05 +02:00
|
|
|
# The initial query in this case doesn't use `zerver_usermessage`,
|
|
|
|
# and isn't yet limited to messages the user is entitled to see!
|
|
|
|
#
|
|
|
|
# This is OK only because we've made sure this is a narrow that
|
2020-08-04 19:33:43 +02:00
|
|
|
# will cause us to limit the query appropriately elsewhere.
|
2017-06-30 02:24:05 +02:00
|
|
|
# See `ok_to_include_history` for details.
|
2020-08-04 19:33:43 +02:00
|
|
|
#
|
|
|
|
# Note that is_web_public_query=True goes here, since
|
|
|
|
# include_history is semantically correct for is_web_public_query.
|
2018-04-05 21:56:27 +02:00
|
|
|
need_message = True
|
|
|
|
need_user_message = False
|
2018-04-05 22:32:30 +02:00
|
|
|
elif narrow is None:
|
2018-04-05 21:56:27 +02:00
|
|
|
# We need to limit to messages the user has received, but we don't actually
|
|
|
|
# need any fields from Message
|
|
|
|
need_message = False
|
|
|
|
need_user_message = True
|
2013-12-12 18:36:32 +01:00
|
|
|
else:
|
2018-04-05 21:56:27 +02:00
|
|
|
need_message = True
|
|
|
|
need_user_message = True
|
|
|
|
|
2022-02-10 03:15:46 +01:00
|
|
|
query: SelectBase
|
2018-04-05 21:56:27 +02:00
|
|
|
query, inner_msg_id_col = get_base_query_for_search(
|
|
|
|
user_profile=user_profile,
|
|
|
|
need_message=need_message,
|
|
|
|
need_user_message=need_user_message,
|
|
|
|
)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2018-04-05 20:42:37 +02:00
|
|
|
query, is_search = add_narrow_conditions(
|
|
|
|
user_profile=user_profile,
|
|
|
|
inner_msg_id_col=inner_msg_id_col,
|
|
|
|
query=query,
|
|
|
|
narrow=narrow,
|
2020-08-04 19:33:43 +02:00
|
|
|
realm=realm,
|
|
|
|
is_web_public_query=is_web_public_query,
|
2018-04-05 20:42:37 +02:00
|
|
|
)
|
2013-12-12 22:50:49 +01:00
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
if narrow is not None:
|
2013-12-12 22:50:49 +01:00
|
|
|
# Add some metadata to our logging data for narrows
|
2013-12-12 18:36:32 +01:00
|
|
|
verbose_operators = []
|
2014-02-10 21:45:53 +01:00
|
|
|
for term in narrow:
|
2021-02-12 08:20:45 +01:00
|
|
|
if term["operator"] == "is":
|
|
|
|
verbose_operators.append("is:" + term["operand"])
|
2013-12-12 18:36:32 +01:00
|
|
|
else:
|
2021-02-12 08:20:45 +01:00
|
|
|
verbose_operators.append(term["operator"])
|
2021-08-21 19:24:20 +02:00
|
|
|
log_data = RequestNotes.get_notes(request).log_data
|
2021-07-09 10:06:04 +02:00
|
|
|
assert log_data is not None
|
|
|
|
log_data["extra"] = "[{}]".format(",".join(verbose_operators))
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2022-02-10 04:59:48 +01:00
|
|
|
with get_sqlalchemy_connection() as sa_conn:
|
|
|
|
if anchor is None:
|
|
|
|
# `anchor=None` corresponds to the anchor="first_unread" parameter.
|
|
|
|
anchor = find_first_unread_anchor(
|
|
|
|
sa_conn,
|
|
|
|
user_profile,
|
|
|
|
narrow,
|
|
|
|
)
|
2020-08-04 19:33:43 +02:00
|
|
|
|
2022-02-10 04:59:48 +01:00
|
|
|
anchored_to_left = anchor == 0
|
|
|
|
|
|
|
|
# Set value that will be used to short circuit the after_query
|
|
|
|
# altogether and avoid needless conditions in the before_query.
|
|
|
|
anchored_to_right = anchor >= LARGER_THAN_MAX_MESSAGE_ID
|
|
|
|
if anchored_to_right:
|
|
|
|
num_after = 0
|
|
|
|
|
|
|
|
first_visible_message_id = get_first_visible_message_id(realm)
|
|
|
|
|
|
|
|
query = limit_query_to_range(
|
|
|
|
query=query,
|
|
|
|
num_before=num_before,
|
|
|
|
num_after=num_after,
|
|
|
|
anchor=anchor,
|
|
|
|
anchored_to_left=anchored_to_left,
|
|
|
|
anchored_to_right=anchored_to_right,
|
|
|
|
id_col=inner_msg_id_col,
|
|
|
|
first_visible_message_id=first_visible_message_id,
|
|
|
|
)
|
2017-02-22 23:39:40 +01:00
|
|
|
|
2022-02-10 04:59:48 +01:00
|
|
|
main_query = query.subquery()
|
|
|
|
query = (
|
|
|
|
select(*main_query.c)
|
|
|
|
.select_from(main_query)
|
|
|
|
.order_by(column("message_id", Integer).asc())
|
|
|
|
)
|
|
|
|
# This is a hack to tag the query we use for testing
|
|
|
|
query = query.prefix_with("/* get_messages */")
|
|
|
|
rows = list(sa_conn.execute(query).fetchall())
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2018-03-15 11:21:36 +01:00
|
|
|
query_info = post_process_limited_query(
|
|
|
|
rows=rows,
|
|
|
|
num_before=num_before,
|
|
|
|
num_after=num_after,
|
|
|
|
anchor=anchor,
|
|
|
|
anchored_to_left=anchored_to_left,
|
|
|
|
anchored_to_right=anchored_to_right,
|
2018-09-19 14:23:02 +02:00
|
|
|
first_visible_message_id=first_visible_message_id,
|
2018-03-15 11:21:36 +01:00
|
|
|
)
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
rows = query_info["rows"]
|
2018-03-15 11:21:36 +01:00
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
# The following is a little messy, but ensures that the code paths
|
|
|
|
# are similar regardless of the value of include_history. The
|
|
|
|
# 'user_messages' dictionary maps each message to the user's
|
|
|
|
# UserMessage object for that message, which we will attach to the
|
|
|
|
# rendered message dict before returning it. We attempt to
|
2016-03-31 03:39:51 +02:00
|
|
|
# bulk-fetch rendered message dicts from remote cache using the
|
2013-12-12 18:36:32 +01:00
|
|
|
# 'messages' list.
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
message_ids: List[int] = []
|
|
|
|
user_message_flags: Dict[int, List[str]] = {}
|
2020-08-04 19:33:43 +02:00
|
|
|
if is_web_public_query:
|
2021-06-15 18:03:32 +02:00
|
|
|
# For spectators, we treat all historical messages as read.
|
2020-08-04 19:33:43 +02:00
|
|
|
for row in rows:
|
|
|
|
message_id = row[0]
|
|
|
|
message_ids.append(message_id)
|
|
|
|
user_message_flags[message_id] = ["read"]
|
|
|
|
elif include_history:
|
|
|
|
assert user_profile is not None
|
2018-03-14 12:38:04 +01:00
|
|
|
message_ids = [row[0] for row in rows]
|
2013-12-10 23:32:29 +01:00
|
|
|
|
|
|
|
# TODO: This could be done with an outer join instead of two queries
|
2021-04-22 16:23:09 +02:00
|
|
|
um_rows = UserMessage.objects.filter(user_profile=user_profile, message_id__in=message_ids)
|
2017-11-07 16:18:42 +01:00
|
|
|
user_message_flags = {um.message_id: um.flags_list() for um in um_rows}
|
|
|
|
|
2017-11-07 17:12:27 +01:00
|
|
|
for message_id in message_ids:
|
|
|
|
if message_id not in user_message_flags:
|
2013-12-10 23:32:29 +01:00
|
|
|
user_message_flags[message_id] = ["read", "historical"]
|
2013-12-12 18:36:32 +01:00
|
|
|
else:
|
2018-03-14 12:38:04 +01:00
|
|
|
for row in rows:
|
2013-12-10 23:32:29 +01:00
|
|
|
message_id = row[0]
|
|
|
|
flags = row[1]
|
2017-11-07 18:40:39 +01:00
|
|
|
user_message_flags[message_id] = UserMessage.flags_list_for_flags(flags)
|
2013-12-10 23:32:29 +01:00
|
|
|
message_ids.append(message_id)
|
|
|
|
|
2020-09-02 08:14:51 +02:00
|
|
|
search_fields: Dict[int, Dict[str, str]] = {}
|
2017-11-07 17:12:27 +01:00
|
|
|
if is_search:
|
2018-03-14 12:38:04 +01:00
|
|
|
for row in rows:
|
2017-11-07 17:12:27 +01:00
|
|
|
message_id = row[0]
|
2018-11-09 17:19:17 +01:00
|
|
|
(topic_name, rendered_content, content_matches, topic_matches) = row[-4:]
|
2017-11-16 22:38:04 +01:00
|
|
|
|
|
|
|
try:
|
2021-02-12 08:19:30 +01:00
|
|
|
search_fields[message_id] = get_search_fields(
|
|
|
|
rendered_content, topic_name, content_matches, topic_matches
|
|
|
|
)
|
2017-11-16 22:38:04 +01:00
|
|
|
except UnicodeDecodeError as err: # nocoverage
|
|
|
|
# No coverage for this block since it should be
|
|
|
|
# impossible, and we plan to remove it once we've
|
|
|
|
# debugged the case that makes it happen.
|
2018-04-05 21:00:07 +02:00
|
|
|
raise Exception(str(err), message_id, narrow)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2017-11-07 17:36:29 +01:00
|
|
|
message_list = messages_for_ids(
|
|
|
|
message_ids=message_ids,
|
|
|
|
user_message_flags=user_message_flags,
|
|
|
|
search_fields=search_fields,
|
|
|
|
apply_markdown=apply_markdown,
|
|
|
|
client_gravatar=client_gravatar,
|
2020-08-04 19:33:43 +02:00
|
|
|
allow_edit_history=realm.allow_edit_history,
|
2017-11-07 17:36:29 +01:00
|
|
|
)
|
2017-10-10 09:22:21 +02:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
statsd.incr("loaded_old_messages", len(message_list))
|
2018-03-15 11:43:51 +01:00
|
|
|
|
|
|
|
ret = dict(
|
|
|
|
messages=message_list,
|
2021-02-12 08:20:45 +01:00
|
|
|
result="success",
|
|
|
|
msg="",
|
|
|
|
found_anchor=query_info["found_anchor"],
|
|
|
|
found_oldest=query_info["found_oldest"],
|
|
|
|
found_newest=query_info["found_newest"],
|
|
|
|
history_limited=query_info["history_limited"],
|
2018-03-15 11:43:51 +01:00
|
|
|
anchor=anchor,
|
|
|
|
)
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request, data=ret)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def limit_query_to_range(
|
|
|
|
query: Select,
|
|
|
|
num_before: int,
|
|
|
|
num_after: int,
|
|
|
|
anchor: int,
|
|
|
|
anchored_to_left: bool,
|
|
|
|
anchored_to_right: bool,
|
2021-08-21 01:07:28 +02:00
|
|
|
id_col: "ColumnElement[Integer]",
|
2021-02-12 08:19:30 +01:00
|
|
|
first_visible_message_id: int,
|
2022-02-10 03:15:46 +01:00
|
|
|
) -> SelectBase:
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2018-03-13 14:29:39 +01:00
|
|
|
This code is actually generic enough that we could move it to a
|
|
|
|
library, but our only caller for now is message search.
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2018-03-13 14:29:39 +01:00
|
|
|
need_before_query = (not anchored_to_left) and (num_before > 0)
|
|
|
|
need_after_query = (not anchored_to_right) and (num_after > 0)
|
|
|
|
|
|
|
|
need_both_sides = need_before_query and need_after_query
|
|
|
|
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
# The semantics of our flags are as follows:
|
|
|
|
#
|
|
|
|
# num_after = number of rows < anchor
|
|
|
|
# num_after = number of rows > anchor
|
|
|
|
#
|
|
|
|
# But we also want the row where id == anchor (if it exists),
|
|
|
|
# and we don't want to union up to 3 queries. So in some cases
|
|
|
|
# we do things like `after_limit = num_after + 1` to grab the
|
|
|
|
# anchor row in the "after" query.
|
|
|
|
#
|
|
|
|
# Note that in some cases, if the anchor row isn't found, we
|
|
|
|
# actually may fetch an extra row at one of the extremes.
|
2018-03-13 14:29:39 +01:00
|
|
|
if need_both_sides:
|
|
|
|
before_anchor = anchor - 1
|
2018-09-19 14:23:02 +02:00
|
|
|
after_anchor = max(anchor, first_visible_message_id)
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
before_limit = num_before
|
|
|
|
after_limit = num_after + 1
|
2018-03-13 14:29:39 +01:00
|
|
|
elif need_before_query:
|
|
|
|
before_anchor = anchor
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
before_limit = num_before
|
|
|
|
if not anchored_to_right:
|
|
|
|
before_limit += 1
|
|
|
|
elif need_after_query:
|
2018-09-19 14:23:02 +02:00
|
|
|
after_anchor = max(anchor, first_visible_message_id)
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
after_limit = num_after + 1
|
2018-03-13 14:29:39 +01:00
|
|
|
|
|
|
|
if need_before_query:
|
|
|
|
before_query = query
|
|
|
|
|
|
|
|
if not anchored_to_right:
|
|
|
|
before_query = before_query.where(id_col <= before_anchor)
|
|
|
|
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
before_query = before_query.order_by(id_col.desc())
|
|
|
|
before_query = before_query.limit(before_limit)
|
2018-03-13 14:29:39 +01:00
|
|
|
|
|
|
|
if need_after_query:
|
|
|
|
after_query = query
|
|
|
|
|
|
|
|
if not anchored_to_left:
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
after_query = after_query.where(id_col >= after_anchor)
|
2018-03-13 14:29:39 +01:00
|
|
|
|
search: Make `num_after`/`num_after` more consistent.
We now consistently set our query limits so that we get at
least `num_after` rows such that id > anchor. (Obviously, the
caveat is that if there aren't enough rows that fulfill the
query, we'll return the full set of rows, but that may be less
than `num_after`.) Likewise for `num_before`.
Before this change, we would sometimes return one too few rows
for narrow queries.
Now, we're still a bit broken, but in a more consistent way. If
we have a query that does not match the anchor row (which could
be true even for a non-narrow query), but which does match lots
of rows after the anchor, we'll return `num_after + 1` rows
on the right hand side, whether or not the query has narrow
parameters.
The off-by-one semantics here have probably been moot all along,
since our windows are approximate to begin with. If we set
num_after to 100, its just a rough performance optimization to
begin with, so it doesn't matter whether we return 99 or 101 rows,
as long as we set the anchor correctly on the subsequent query.
We will make the results more rigorous in a follow up commit.
2018-03-14 13:22:16 +01:00
|
|
|
after_query = after_query.order_by(id_col.asc())
|
|
|
|
after_query = after_query.limit(after_limit)
|
2018-03-13 14:29:39 +01:00
|
|
|
|
|
|
|
if need_both_sides:
|
2020-11-17 03:14:36 +01:00
|
|
|
return union_all(before_query.self_group(), after_query.self_group())
|
2018-03-13 14:29:39 +01:00
|
|
|
elif need_before_query:
|
2020-11-17 03:14:36 +01:00
|
|
|
return before_query
|
2018-03-13 14:29:39 +01:00
|
|
|
elif need_after_query:
|
2020-11-17 03:14:36 +01:00
|
|
|
return after_query
|
2018-03-13 14:29:39 +01:00
|
|
|
else:
|
|
|
|
# If we don't have either a before_query or after_query, it's because
|
|
|
|
# some combination of num_before/num_after/anchor are zero or
|
|
|
|
# use_first_unread_anchor logic found no unread messages.
|
|
|
|
#
|
|
|
|
# The most likely reason is somebody is doing an id search, so searching
|
|
|
|
# for something like `message_id = 42` is exactly what we want. In other
|
|
|
|
# cases, which could possibly be buggy API clients, at least we will
|
|
|
|
# return at most one row here.
|
2020-11-17 03:14:36 +01:00
|
|
|
return query.where(id_col == anchor)
|
2018-03-13 14:29:39 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def post_process_limited_query(
|
2021-08-21 01:07:28 +02:00
|
|
|
rows: Sequence[Union[Row, Sequence[Any]]],
|
2021-02-12 08:19:30 +01:00
|
|
|
num_before: int,
|
|
|
|
num_after: int,
|
|
|
|
anchor: int,
|
|
|
|
anchored_to_left: bool,
|
|
|
|
anchored_to_right: bool,
|
|
|
|
first_visible_message_id: int,
|
|
|
|
) -> Dict[str, Any]:
|
2018-03-15 11:20:55 +01:00
|
|
|
# Our queries may have fetched extra rows if they added
|
|
|
|
# "headroom" to the limits, but we want to truncate those
|
|
|
|
# rows.
|
|
|
|
#
|
|
|
|
# Also, in cases where we had non-zero values of num_before or
|
|
|
|
# num_after, we want to know found_oldest and found_newest, so
|
|
|
|
# that the clients will know that they got complete results.
|
|
|
|
|
2018-09-19 14:23:02 +02:00
|
|
|
if first_visible_message_id > 0:
|
2021-08-21 01:07:28 +02:00
|
|
|
visible_rows: Sequence[Union[Row, Sequence[Any]]] = [
|
2020-11-16 22:52:27 +01:00
|
|
|
r for r in rows if r[0] >= first_visible_message_id
|
|
|
|
]
|
2018-09-19 14:23:02 +02:00
|
|
|
else:
|
|
|
|
visible_rows = rows
|
|
|
|
|
|
|
|
rows_limited = len(visible_rows) != len(rows)
|
|
|
|
|
2018-03-15 11:20:55 +01:00
|
|
|
if anchored_to_right:
|
|
|
|
num_after = 0
|
2018-09-19 14:23:02 +02:00
|
|
|
before_rows = visible_rows[:]
|
2020-11-16 22:52:27 +01:00
|
|
|
anchor_rows = []
|
|
|
|
after_rows = []
|
2018-03-15 11:20:55 +01:00
|
|
|
else:
|
2018-09-19 14:23:02 +02:00
|
|
|
before_rows = [r for r in visible_rows if r[0] < anchor]
|
|
|
|
anchor_rows = [r for r in visible_rows if r[0] == anchor]
|
|
|
|
after_rows = [r for r in visible_rows if r[0] > anchor]
|
2018-03-15 11:20:55 +01:00
|
|
|
|
|
|
|
if num_before:
|
2021-02-12 08:19:30 +01:00
|
|
|
before_rows = before_rows[-1 * num_before :]
|
2018-03-15 11:20:55 +01:00
|
|
|
|
|
|
|
if num_after:
|
|
|
|
after_rows = after_rows[:num_after]
|
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
visible_rows = [*before_rows, *anchor_rows, *after_rows]
|
2018-03-15 11:20:55 +01:00
|
|
|
|
|
|
|
found_anchor = len(anchor_rows) == 1
|
|
|
|
found_oldest = anchored_to_left or (len(before_rows) < num_before)
|
|
|
|
found_newest = anchored_to_right or (len(after_rows) < num_after)
|
2018-09-19 14:23:02 +02:00
|
|
|
# BUG: history_limited is incorrect False in the event that we had
|
|
|
|
# to bump `anchor` up due to first_visible_message_id, and there
|
|
|
|
# were actually older messages. This may be a rare event in the
|
|
|
|
# context where history_limited is relevant, because it can only
|
|
|
|
# happen in one-sided queries with no num_before (see tests tagged
|
|
|
|
# BUG in PostProcessTest for examples), and we don't generally do
|
|
|
|
# those from the UI, so this might be OK for now.
|
|
|
|
#
|
|
|
|
# The correct fix for this probably involves e.g. making a
|
|
|
|
# `before_query` when we increase `anchor` just to confirm whether
|
|
|
|
# messages were hidden.
|
|
|
|
history_limited = rows_limited and found_oldest
|
2018-03-15 11:20:55 +01:00
|
|
|
|
|
|
|
return dict(
|
2018-09-19 14:23:02 +02:00
|
|
|
rows=visible_rows,
|
2018-03-15 11:20:55 +01:00
|
|
|
found_anchor=found_anchor,
|
|
|
|
found_newest=found_newest,
|
|
|
|
found_oldest=found_oldest,
|
2018-09-19 14:23:02 +02:00
|
|
|
history_limited=history_limited,
|
2018-03-15 11:20:55 +01:00
|
|
|
)
|
2020-08-04 19:33:43 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2013-12-12 18:36:32 +01:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def messages_in_narrow_backend(
|
|
|
|
request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
2021-04-07 22:00:44 +02:00
|
|
|
msg_ids: List[int] = REQ(json_validator=check_list(check_int)),
|
2021-02-12 08:19:30 +01:00
|
|
|
narrow: OptionalNarrowListT = REQ(converter=narrow_parameter),
|
|
|
|
) -> HttpResponse:
|
2016-07-30 01:27:56 +02:00
|
|
|
|
2018-01-02 18:33:28 +01:00
|
|
|
first_visible_message_id = get_first_visible_message_id(user_profile.realm)
|
|
|
|
msg_ids = [message_id for message_id in msg_ids if message_id >= first_visible_message_id]
|
2017-06-30 02:24:05 +02:00
|
|
|
# This query is limited to messages the user has access to because they
|
|
|
|
# actually received them, as reflected in `zerver_usermessage`.
|
2022-02-10 04:13:15 +01:00
|
|
|
query = (
|
|
|
|
select(column("message_id", Integer), topic_column_sa(), column("rendered_content", Text))
|
|
|
|
.where(
|
|
|
|
and_(
|
|
|
|
column("user_profile_id", Integer) == literal(user_profile.id),
|
|
|
|
column("message_id", Integer).in_(msg_ids),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
.select_from(
|
|
|
|
join(
|
|
|
|
table("zerver_usermessage"),
|
|
|
|
table("zerver_message"),
|
|
|
|
literal_column("zerver_usermessage.message_id", Integer)
|
|
|
|
== literal_column("zerver_message.id", Integer),
|
|
|
|
)
|
|
|
|
)
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2013-12-10 23:32:29 +01:00
|
|
|
|
2020-11-16 22:52:27 +01:00
|
|
|
builder = NarrowBuilder(user_profile, column("message_id", Integer), user_profile.realm)
|
2017-03-19 01:46:35 +01:00
|
|
|
if narrow is not None:
|
|
|
|
for term in narrow:
|
|
|
|
query = builder.add_term(query, term)
|
2013-12-12 18:36:32 +01:00
|
|
|
|
2020-09-02 08:14:51 +02:00
|
|
|
search_fields = {}
|
2022-02-10 04:59:48 +01:00
|
|
|
with get_sqlalchemy_connection() as sa_conn:
|
|
|
|
for row in sa_conn.execute(query).fetchall():
|
|
|
|
message_id = row._mapping["message_id"]
|
|
|
|
topic_name = row._mapping[DB_TOPIC_NAME]
|
|
|
|
rendered_content = row._mapping["rendered_content"]
|
|
|
|
if "content_matches" in row._mapping:
|
|
|
|
content_matches = row._mapping["content_matches"]
|
|
|
|
topic_matches = row._mapping["topic_matches"]
|
|
|
|
else:
|
|
|
|
content_matches = topic_matches = []
|
|
|
|
search_fields[str(message_id)] = get_search_fields(
|
|
|
|
rendered_content,
|
|
|
|
topic_name,
|
|
|
|
content_matches,
|
|
|
|
topic_matches,
|
|
|
|
)
|
2013-12-10 23:32:29 +01:00
|
|
|
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request, data={"messages": search_fields})
|