Skip to content

Added Recent Conversations view #1567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11.9
3 changes: 2 additions & 1 deletion docs/hotkeys.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
|Scroll down|<kbd>PgDn</kbd> / <kbd>J</kbd>|
|Go to bottom / Last message|<kbd>End</kbd> / <kbd>G</kbd>|
|Trigger the selected entry|<kbd>Enter</kbd> / <kbd>Space</kbd>|
|Open recent conversations|<kbd>^</kbd>|
|Search recent conversations|<kbd>Ctrl+f</kbd>|

## Switching Messages View
|Command|Key Combination|
Expand Down Expand Up @@ -136,4 +138,3 @@
|View current message in browser|<kbd>v</kbd>|
|Show/hide full rendered message|<kbd>f</kbd>|
|Show/hide full raw message|<kbd>r</kbd>|

10 changes: 10 additions & 0 deletions zulipterminal/config/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ class KeyBinding(TypedDict):
'help_text': 'Send a message',
'key_category': 'compose_box',
},
'OPEN_RECENT_CONVERSATIONS': {
'keys': ['^'],
'help_text': 'Open recent conversations',
'key_category': 'navigation',
},
'SAVE_AS_DRAFT': {
'keys': ['meta s'],
'help_text': 'Save current message as a draft',
Expand Down Expand Up @@ -209,6 +214,11 @@ class KeyBinding(TypedDict):
'help_text': 'Toggle topics in a stream',
'key_category': 'stream_list',
},
"SEARCH_RECENT_CONVERSATIONS": {
"keys": ["ctrl+f"],
"help_text": "Search recent conversations",
"key_category": "navigation"
},
'ALL_MESSAGES': {
'keys': ['a', 'esc'],
'help_text': 'View all messages',
Expand Down
2 changes: 1 addition & 1 deletion zulipterminal/config/ui_sizes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

TAB_WIDTH = 3
LEFT_WIDTH = 31
LEFT_WIDTH = 32
RIGHT_WIDTH = 23

# These affect popup width-scaling, dependent upon window width
Expand Down
1 change: 1 addition & 0 deletions zulipterminal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,7 @@ def copy_to_clipboard(self, text: str, text_category: str) -> None:

def _narrow_to(self, anchor: Optional[int], **narrow: Any) -> None:
already_narrowed = self.model.set_narrow(**narrow)
self.view.middle_column.set_view("messages")

if already_narrowed and anchor is None:
return
Expand Down
94 changes: 92 additions & 2 deletions zulipterminal/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections import defaultdict
from concurrent.futures import Future, ThreadPoolExecutor, wait
from copy import deepcopy
from datetime import datetime
from datetime import datetime, timedelta, timezone
from typing import (
Any,
Callable,
Expand Down Expand Up @@ -116,7 +116,6 @@ def __init__(self, controller: Any) -> None:
self.recipients: FrozenSet[Any] = frozenset()
self.index = initial_index
self.last_unread_pm = None

self.user_id = -1
self.user_email = ""
self.user_full_name = ""
Expand Down Expand Up @@ -1095,6 +1094,94 @@ def get_other_subscribers_in_stream(
if sub != self.user_id
]

def group_recent_conversations(self) -> List[Dict[str, Any]]:
"""Return the 10 most recent stream conversations within the last 30 days."""

recency_threshold = datetime.now(timezone.utc) - timedelta(days=30)
recency_timestamp = int(recency_threshold.timestamp())

# Fetch the most recent messages without a narrow
request = {
"anchor": "newest",
"num_before": 100,
"num_after": 0,
"apply_markdown": True,
"narrow": json.dumps([]), # No narrow, fetch all messages
}
response = self.client.get_messages(message_filters=request)
if response["result"] != "success":
return []

# Debug: Inspect the fetched messages
messages = [
self.modernize_message_response(msg) for msg in response["messages"]
] # noqa: E501
if messages:
most_recent_msg = max(messages, key=lambda x: x["timestamp"])
datetime.fromtimestamp(most_recent_msg["timestamp"], tz=timezone.utc)
else:
return []

# Filter for stream messages within the last 30 days
stream_msgs = [
m
for m in messages
if m["type"] == "stream" and m["timestamp"] >= recency_timestamp
]
if not stream_msgs:
return []

# Sort messages by timestamp (most recent first)
stream_msgs.sort(key=lambda x: x["timestamp"], reverse=True)

# Group messages by stream and topic
convos = defaultdict(list)
for msg in stream_msgs[:100]:
convos[(msg["stream_id"], msg["subject"])].append(msg)

# Process conversations into the desired format
processed_conversations = []
now = datetime.now(timezone.utc)
for (stream_id, topic), msg_list in sorted(
convos.items(),
key=lambda x: max(m["timestamp"] for m in x[1]),
reverse=True,
)[:30]:
stream_name = self.stream_name_from_id(stream_id)
topic_name = topic if topic else "(no topic)"
participants = set()
for msg in msg_list:
participants.add(msg["sender_full_name"])
most_recent_msg = max(msg_list, key=lambda x: x["timestamp"])
timestamp = most_recent_msg["timestamp"]
conv_time = datetime.fromtimestamp(timestamp, tz=timezone.utc)
delta = now - conv_time

# Format the time difference with the specified precision
total_seconds = int(delta.total_seconds())
if total_seconds < 60: # Less than 1 minute
time_str = "just now"
elif total_seconds < 3600: # Less than 1 hour
minutes = total_seconds // 60
time_str = f"{minutes} min{'s' if minutes != 1 else ''} ago"
elif total_seconds < 86400: # Less than 24 hours
hours = total_seconds // 3600
time_str = f"{hours} hour{'s' if hours != 1 else ''} ago"
else: # More than 24 hours
days = delta.days
time_str = f"{days} day{'s' if days != 1 else ''} ago"

processed_conversations.append(
{
"stream": stream_name,
"topic": topic_name,
"participants": list(participants),
"time": time_str,
}
)

return processed_conversations

def _clean_and_order_custom_profile_data(
self, custom_profile_data: Dict[str, CustomFieldValue]
) -> List[CustomProfileData]:
Expand Down Expand Up @@ -1418,6 +1505,9 @@ def stream_id_from_name(self, stream_name: str) -> int:
return stream_id
raise RuntimeError("Invalid stream name.")

def stream_name_from_id(self, stream_id: int) -> str:
return self.stream_dict[stream_id]["name"]

def stream_access_type(self, stream_id: int) -> StreamAccessType:
if stream_id not in self.stream_dict:
raise RuntimeError("Invalid stream id.")
Expand Down
16 changes: 13 additions & 3 deletions zulipterminal/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def middle_column_view(self) -> Any:
self.middle_column = MiddleColumnView(
self, self.model, self.write_box, self.search_box
)

return urwid.LineBox(
self.middle_column,
title="Messages",
Expand Down Expand Up @@ -160,6 +161,14 @@ def footer_view(self) -> Any:
text_header = self.get_random_help()
return urwid.AttrWrap(urwid.Text(text_header), "footer")

def on_column_focus_changed(self, index: int) -> None:
if self.middle_column.current_view == self.message_view:
self.message_view.read_message()
elif (
self.middle_column.current_view == self.middle_column.recent_convo_view
): # noqa: E501
self.middle_column.recent_convo_view.focus_restored()

def main_window(self) -> Any:
self.left_panel, self.left_tab = self.left_column_view()
self.center_panel = self.middle_column_view()
Expand All @@ -184,7 +193,8 @@ def main_window(self) -> Any:
# NOTE: set_focus_changed_callback is actually called before the
# focus is set, so the message is not read yet, it will be read when
# the focus is changed again either vertically or horizontally.
self.body._contents.set_focus_changed_callback(self.message_view.read_message)

self.body._contents.set_focus_changed_callback(self.on_column_focus_changed)

title_text = " {full_name} ({email}) - {server_name} ({url}) ".format(
full_name=self.model.user_full_name,
Expand Down Expand Up @@ -213,7 +223,6 @@ def main_window(self) -> Any:
def show_left_panel(self, *, visible: bool) -> None:
if not self.controller.autohide:
return

if visible:
self.frame.body = urwid.Overlay(
urwid.Columns(
Expand All @@ -234,7 +243,6 @@ def show_left_panel(self, *, visible: bool) -> None:
def show_right_panel(self, *, visible: bool) -> None:
if not self.controller.autohide:
return

if visible:
self.frame.body = urwid.Overlay(
urwid.Columns(
Expand Down Expand Up @@ -273,6 +281,8 @@ def keypress(self, size: urwid_Box, key: str) -> Optional[str]:
self.pm_button.activate(key)
elif is_command_key("ALL_STARRED", key):
self.starred_button.activate(key)
elif is_command_key("OPEN_RECENT_CONVERSATIONS", key):
self.time_button.activate(key)
elif is_command_key("ALL_MENTIONS", key):
self.mentioned_button.activate(key)
elif is_command_key("SEARCH_PEOPLE", key):
Expand Down
31 changes: 23 additions & 8 deletions zulipterminal/ui_tools/buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
MENTIONED_MESSAGES_MARKER,
MUTE_MARKER,
STARRED_MESSAGES_MARKER,
TIME_MENTION_MARKER,
)
from zulipterminal.config.ui_mappings import EDIT_MODE_CAPTIONS, STREAM_ACCESS_TYPE
from zulipterminal.helper import StreamData, hash_util_decode, process_media
Expand Down Expand Up @@ -129,9 +130,7 @@ def keypress(self, size: urwid_Size, key: str) -> Optional[str]:

class HomeButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = (
f"All messages [{primary_display_key_for_command('ALL_MESSAGES')}]"
)
button_text = f"All messages [{primary_display_key_for_command('ALL_MESSAGES')}]" # noqa: E501

super().__init__(
controller=controller,
Expand All @@ -145,7 +144,9 @@ def __init__(self, *, controller: Any, count: int) -> None:

class PMButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"Direct messages [{primary_display_key_for_command('ALL_PM')}]"
button_text = (
f"Direct messages [{primary_display_key_for_command('ALL_PM')}]"
)

super().__init__(
controller=controller,
Expand All @@ -159,9 +160,7 @@ def __init__(self, *, controller: Any, count: int) -> None:

class MentionedButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = (
f"Mentions [{primary_display_key_for_command('ALL_MENTIONS')}]"
)
button_text = f"Mentions [{primary_display_key_for_command('ALL_MENTIONS')}]" # noqa: E501

super().__init__(
controller=controller,
Expand All @@ -173,10 +172,26 @@ def __init__(self, *, controller: Any, count: int) -> None:
)


class TimeMentionedButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"Recent Conversations [{primary_display_key_for_command('OPEN_RECENT_CONVERSATIONS')}]" # noqa: E501
super().__init__(
controller=controller,
prefix_markup=("title", TIME_MENTION_MARKER),
label_markup=(None, button_text),
suffix_markup=("unread_count", f" ({count})" if count > 0 else ""),
show_function=self.show_recent_conversations,
count=count,
)

def show_recent_conversations(self) -> None:
self.controller.view.middle_column.set_view("recent")


class StarredButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = (
f"Starred messages [{primary_display_key_for_command('ALL_STARRED')}]"
f"Starred messages [{primary_display_key_for_command('ALL_STARRED')}]"
)

super().__init__(
Expand Down
Loading
Loading