Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

narrow: Add ability to anchor on a date.

Shubham Padiafec8462f7913
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index 8c1960030bd..32e130633ed 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,12 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 445**
+
+* [`GET /messages`](/api/get-messages): Added a new `date` value for
+ the `anchor` parameter, and new `anchor_date` parameter, to support
+ fetching messages around a specific date/time.
+
**Feature level 444**
* [`PATCH /settings`](/api/update-settings): Added support for bulk updating
diff --git a/version.py b/version.py
index 97229a71b0f..cd0d8f4d8cf 100644
--- a/version.py
+++ b/version.py
@@ -35,7 +35,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# new level means in api_docs/changelog.md, as well as "**Changes**"
# entries in the endpoint's documentation in `zulip.yaml`.
-API_FEATURE_LEVEL = 444
+API_FEATURE_LEVEL = 445
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py
index 01778da9fbf..ec560dd4e3b 100644
--- a/zerver/lib/narrow.py
+++ b/zerver/lib/narrow.py
@@ -1,6 +1,7 @@
import re
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
+from datetime import datetime, timezone
from typing import Any, Generic, Literal, TypeAlias, TypedDict, TypeVar
from django.conf import settings
@@ -61,6 +62,7 @@ from zerver.lib.user_groups import get_recursive_membership_groups
from zerver.lib.user_topics import exclude_stream_and_topic_mutes
from zerver.lib.validator import (
check_bool,
+ check_iso_datetime,
check_required_string,
check_string,
check_string_or_int,
@@ -189,8 +191,8 @@ LARGER_THAN_MAX_MESSAGE_ID = 10000000000000000
class AnchorInfo(TypedDict):
- type: Literal["message_id", "first_unread"]
- value: int | None
+ type: Literal["message_id", "first_unread", "date"]
+ value: int | datetime | None
DEFAULT_ANCHOR_INFO: AnchorInfo = AnchorInfo(type="first_unread", value=None)
@@ -1206,7 +1208,38 @@ def find_first_unread_anchor(
return anchor
-def parse_anchor_value(anchor_val: str | None, use_first_unread_anchor: bool) -> AnchorInfo:
+def find_date_anchor(
+ *,
+ sa_conn: Connection,
+ anchor_date: datetime,
+ query: Select,
+ inner_msg_id_col: ColumnElement[Integer],
+) -> int | None:
+ date_sent_col = literal_column("zerver_message.date_sent")
+
+ first_row_after_date_anchor = sa_conn.execute(
+ query.where(date_sent_col >= anchor_date)
+ .order_by(date_sent_col.asc(), inner_msg_id_col.asc())
+ .limit(1)
+ ).fetchone()
+ if first_row_after_date_anchor is not None:
+ return first_row_after_date_anchor[0]
+
+ # If nothing is on/after the anchor date, fall back to the newest message.
+ last_row_before_date_anchor = sa_conn.execute(
+ query.order_by(date_sent_col.desc(), inner_msg_id_col.desc()).limit(1)
+ ).fetchone()
+ if last_row_before_date_anchor is not None:
+ return last_row_before_date_anchor[0]
+
+ return None
+
+
+def parse_anchor_value(
+ anchor_val: str | None,
+ use_first_unread_anchor: bool,
+ anchor_date: str | None = None,
+) -> AnchorInfo:
"""Given the anchor and use_first_unread_anchor parameters passed by
the client, computes what anchor type and value the client requested,
handling backwards-compatibility and the various string-valued
@@ -1222,6 +1255,18 @@ def parse_anchor_value(anchor_val: str | None, use_first_unread_anchor: bool) ->
# Throw an exception if neither an anchor argument nor
# use_first_unread_anchor was specified.
raise JsonableError(_("Missing 'anchor' argument."))
+ if anchor_val == "date":
+ if anchor_date is None:
+ raise JsonableError(_("Missing 'anchor_date' argument."))
+ try:
+ # For date without time, this function will set the time to
+ # midnight.
+ anchor_datetime = check_iso_datetime("anchor_date", anchor_date)
+ except ValidationError as error:
+ raise JsonableError(error.message)
+ if anchor_datetime.tzinfo is None:
+ anchor_datetime = anchor_datetime.replace(tzinfo=timezone.utc)
+ return AnchorInfo(type="date", value=anchor_datetime)
if anchor_val == "oldest":
return AnchorInfo(type="message_id", value=0)
if anchor_val == "newest":
@@ -1485,6 +1530,31 @@ def fetch_messages(
if client_requested_message_ids is not None:
query = query.filter(inner_msg_id_col.in_(client_requested_message_ids))
else:
+ if anchor_type == "date":
+ assert isinstance(anchor_value, datetime)
+ anchor_value = find_date_anchor(
+ sa_conn=sa_conn,
+ anchor_date=anchor_value,
+ query=query,
+ inner_msg_id_col=inner_msg_id_col,
+ )
+ # We did not find any message before or after the given timestamp,
+ # which means there are no messages in this narrow.
+ if anchor_value is None:
+ return FetchedMessages(
+ rows=[],
+ found_anchor=False,
+ found_newest=False,
+ found_oldest=False,
+ history_limited=False,
+ # We first tried to find a message that was sent after our
+ # anchor_date. When we did not find that, we went and looked
+ # for the newest message i.e LARGER_THAN_MAX_MESSAGE_ID.
+ anchor=LARGER_THAN_MAX_MESSAGE_ID,
+ include_history=include_history,
+ is_search=is_search,
+ )
+
if anchor_type == "first_unread":
anchor_value = find_first_unread_anchor(
sa_conn,
@@ -1496,7 +1566,7 @@ def fetch_messages(
need_user_message,
)
- assert anchor_value is not None
+ assert isinstance(anchor_value, int)
anchored_to_left = anchor_value == 0
@@ -1546,7 +1616,7 @@ def fetch_messages(
is_search=is_search,
)
- assert anchor_value is not None
+ assert isinstance(anchor_value, int)
query_info = post_process_limited_query(
rows=rows,
num_before=num_before,
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index 4777baea87f..40764f65be1 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -7914,6 +7914,7 @@ paths:
- use_first_unread_anchor
- include_anchor
- message_ids
+ - anchor_date
parameters:
- name: anchor
in: query
@@ -7926,8 +7927,13 @@ paths:
- `oldest`: The oldest message.
- `first_unread`: The oldest unread message matching the
query, if any; otherwise, the most recent message.
+ - `date`: The first message on or after the datetime indicated by the
+ [`anchor_date`](#parameter-anchor_date), if any; otherwise, the most
+ recent message.
- **Changes**: String values are new in Zulip 3.0 (feature level 1). The
+ **Changes**: The `date` value is new in Zulip 12.0 (feature level 445).
+
+ String values are new in Zulip 3.0 (feature level 1). The
`first_unread` functionality was supported in Zulip 2.1.x
and older by not sending `anchor` and using `use_first_unread_anchor`.
@@ -7949,6 +7955,20 @@ paths:
type: boolean
default: true
example: false
+ - name: anchor_date
+ in: query
+ description: |
+ The date or datetime to use for finding the anchor message when `anchor` is
+ `date`. Accepted formats include ISO 8601 date-only strings
+ (e.g. `2005-04-18`) as well as full datetime strings
+ (e.g. `2005-04-18T12:34:56Z`). If only a date is provided, the datetime is set to
+ midnight (00:00) on that day in UTC. If no timezone is provided, UTC is
+ assumed.
+
+ **Changes**: New in Zulip 12.0 (feature level 445).
+ schema:
+ type: string
+ example: "2005-04-18T12:34:56Z"
- name: num_before
in: query
description: |
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index 78b2cca302a..701e659ef75 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -1,6 +1,6 @@
from collections.abc import Sequence
from dataclasses import dataclass
-from datetime import timedelta
+from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
from unittest import mock
@@ -4418,6 +4418,27 @@ class GetOldMessagesTest(ZulipTestCase):
result = orjson.loads(payload.content)
self.assertEqual(result["anchor"], LARGER_THAN_MAX_MESSAGE_ID)
+ # With anchor input as date, see if response anchor value matches
+ # first message on/after date
+ anchor_date = Message.objects.get(id=first_message_id).date_sent
+ query_params = dict(
+ anchor="date",
+ anchor_date=anchor_date.isoformat(),
+ num_before=10,
+ num_after=10,
+ narrow="[]",
+ )
+ request = HostRequestMock(query_params, user_profile)
+
+ payload = get_messages_backend(
+ request,
+ user_profile,
+ num_before=10,
+ num_after=10,
+ )
+ result = orjson.loads(payload.content)
+ self.assertEqual(result["anchor"], first_message_id)
+
# With anchor input negative, see if
# response anchor value is clamped to 0
query_params = dict(
@@ -4456,6 +4477,153 @@ class GetOldMessagesTest(ZulipTestCase):
result = orjson.loads(payload.content)
self.assertEqual(result["anchor"], LARGER_THAN_MAX_MESSAGE_ID)
+ def test_anchor_date_requires_value(self) -> None:
+ self.login("hamlet")
+ result = self.client_get(
+ "/json/messages",
+ dict(anchor="date"),
+ )
+ self.assert_json_error(result, "Missing 'anchor_date' argument.")
+
+ def test_anchor_date_rejects_invalid_iso_string(self) -> None:
+ self.login("hamlet")
+ result = self.client_get(
+ "/json/messages",
+ dict(
+ anchor="date",
+ anchor_date="not-a-date",
+ num_before=0,
+ num_after=1,
+ narrow="[]",
+ ),
+ )
+ self.assert_json_error(result, "anchor_date is not an ISO 8601 datetime string")
+
+ def test_anchor_date_accepts_iso8601_strings(self) -> None:
+ self.login("hamlet")
+ hamlet = self.example_user("hamlet")
+ self.subscribe(hamlet, "Denmark")
+
+ message_time = datetime(2005, 4, 18, 0, 1, 0, 123000, tzinfo=timezone.utc)
+ message_id = self.send_stream_message(hamlet, "Denmark")
+ Message.objects.filter(id=message_id).update(date_sent=message_time)
+
+ anchor_date_values = [
+ message_time.date().isoformat(), # 2005-04-18
+ message_time.isoformat(), # 2005-04-18T00:01:00.123000+00:00
+ message_time.replace(tzinfo=None).isoformat(), # 2005-04-18T00:01:00.123000
+ message_time.isoformat().replace("+00:00", "Z"), # 2005-04-18T00:01:00.123000Z
+ message_time.astimezone(
+ timezone(timedelta(hours=5, minutes=30))
+ ).isoformat(), # 2005-04-18T05:31:00.123000+05:30
+ message_time.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%MZ"), # 2005-04-18T00:01Z
+ ]
+
+ for anchor_date_value in anchor_date_values:
+ with self.subTest(anchor_date=anchor_date_value):
+ result = self.get_and_check_messages(
+ {
+ "anchor": "date",
+ "anchor_date": anchor_date_value,
+ "num_before": 0,
+ "num_after": 1,
+ "narrow": orjson.dumps(
+ [dict(operator="channel", operand="Denmark")]
+ ).decode(),
+ },
+ )
+ self.assertEqual(result["anchor"], message_id)
+ self.assert_length(result["messages"], 1)
+ self.assertEqual(result["messages"][0]["id"], message_id)
+ self.assertTrue(result["found_anchor"])
+
+ def test_anchor_date(self) -> None:
+ self.login("hamlet")
+ hamlet = self.example_user("hamlet")
+ self.subscribe(hamlet, "Denmark")
+ self.subscribe(hamlet, "Scotland")
+ sender = self.example_user("othello")
+
+ base_time = timezone_now()
+ anchor_message_id = self.send_stream_message(sender, "Denmark")
+ newer_message_id = self.send_stream_message(sender, "Denmark")
+ Message.objects.filter(id=anchor_message_id).update(date_sent=base_time)
+ Message.objects.filter(id=newer_message_id).update(
+ date_sent=base_time + timedelta(minutes=30)
+ )
+
+ get_and_check_messages_options: dict[str, str | int] = {
+ "anchor": "date",
+ "anchor_date": base_time.isoformat(),
+ "num_before": 0,
+ "num_after": 0,
+ "narrow": "[]",
+ }
+
+ with self.assert_database_query_count(12):
+ result = self.get_and_check_messages(get_and_check_messages_options)
+
+ self.assertEqual(result["anchor"], anchor_message_id)
+ self.assert_length(result["messages"], 1)
+ self.assertEqual(result["messages"][0]["id"], anchor_message_id)
+ self.assertTrue(result["found_anchor"])
+
+ # In case of multiple messages at the same timestamp,
+ # we should choose the message sent first.
+ first_message_with_same_timestamp_id = anchor_message_id
+ Message.objects.filter(id=newer_message_id).update(date_sent=base_time)
+ with self.assert_database_query_count(12):
+ result = self.get_and_check_messages(get_and_check_messages_options)
+ self.assertEqual(result["anchor"], first_message_with_same_timestamp_id)
+ self.assert_length(result["messages"], 1)
+ self.assertEqual(result["messages"][0]["id"], first_message_with_same_timestamp_id)
+ self.assertTrue(result["found_anchor"])
+
+ # In case of no message at or after the anchor date,
+ # we should fall back to the newest message.
+ with self.assert_database_query_count(13):
+ result = self.get_and_check_messages(
+ {
+ **get_and_check_messages_options,
+ "anchor_date": (base_time + timedelta(days=1)).isoformat(),
+ }
+ )
+ self.assertEqual(result["anchor"], newer_message_id)
+ self.assert_length(result["messages"], 1)
+ self.assertEqual(result["messages"][0]["id"], newer_message_id)
+ self.assertTrue(result["found_anchor"])
+
+ # Narrow conditions should be respected when passing `anchor_date`.
+ scotland_channel_message_id = self.send_stream_message(sender, "Scotland")
+ Message.objects.filter(id=scotland_channel_message_id).update(date_sent=base_time)
+ with self.assert_database_query_count(14):
+ result = self.get_and_check_messages(
+ {
+ **get_and_check_messages_options,
+ "narrow": orjson.dumps([dict(operator="channel", operand="Scotland")]).decode(),
+ }
+ )
+ self.assertEqual(result["anchor"], scotland_channel_message_id)
+ self.assert_length(result["messages"], 1)
+ self.assertEqual(result["messages"][0]["id"], scotland_channel_message_id)
+ self.assertTrue(result["found_anchor"])
+
+ # If the narrow has no matching messages, we should return an empty result.
+ empty_stream = "Empty stream"
+ self.subscribe(hamlet, empty_stream)
+ result = self.get_and_check_messages(
+ {
+ **get_and_check_messages_options,
+ "anchor_date": (base_time + timedelta(days=2)).isoformat(),
+ "narrow": orjson.dumps([dict(operator="channel", operand=empty_stream)]).decode(),
+ }
+ )
+ self.assertEqual(result["anchor"], LARGER_THAN_MAX_MESSAGE_ID)
+ self.assert_length(result["messages"], 0)
+ self.assertFalse(result["found_anchor"])
+ self.assertFalse(result["found_newest"])
+ self.assertFalse(result["found_oldest"])
+
def test_use_first_unread_anchor_with_some_unread_messages(self) -> None:
user_profile = self.example_user("hamlet")
diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py
index e4f91b7b96f..9d74e9f9481 100644
--- a/zerver/tests/test_openapi.py
+++ b/zerver/tests/test_openapi.py
@@ -808,7 +808,12 @@ class TestCurlExampleGeneration(ZulipTestCase):
generated_curl_example = self.curl_example(
"/messages",
"GET",
- exclude=["use_first_unread_anchor", "message_ids", "allow_empty_topic_name"],
+ exclude=[
+ "use_first_unread_anchor",
+ "message_ids",
+ "allow_empty_topic_name",
+ "anchor_date",
+ ],
)
expected_curl_example = [
"```curl",
@@ -890,6 +895,7 @@ class TestCurlExampleGeneration(ZulipTestCase):
"use_first_unread_anchor",
"message_ids",
"allow_empty_topic_name",
+ "anchor_date",
],
)
expected_curl_example = [
diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.py
index 9eec21d4468..e92164867f3 100644
--- a/zerver/views/message_fetch.py
+++ b/zerver/views/message_fetch.py
@@ -111,6 +111,7 @@ def get_messages_backend(
*,
allow_empty_topic_name: Json[bool] = False,
anchor_val: Annotated[str | None, ApiParamConfig("anchor")] = None,
+ anchor_date: str | None = None,
apply_markdown: Json[bool] = True,
client_gravatar: Json[bool] = True,
client_requested_message_ids: Annotated[
@@ -143,7 +144,7 @@ def get_messages_backend(
anchor_info = None
if client_requested_message_ids is None:
- anchor_info = parse_anchor_value(anchor_val, use_first_unread_anchor_val)
+ anchor_info = parse_anchor_value(anchor_val, use_first_unread_anchor_val, anchor_date)
realm = get_valid_realm_from_request(request)
narrow = clean_narrow_for_message_fetch(narrow, realm, maybe_user_profile)