Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
presence: Fix for last active time for invisible mode.
Mateusz Mandera9649e0d7c06b
diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.pyindex 708cc419679..540cf3dcfdc 100644--- a/zerver/actions/user_settings.py+++ b/zerver/actions/user_settings.py@@ -576,25 +576,79 @@ def do_change_user_setting(status = UserPresence.LEGACY_STATUS_ACTIVE_INTpresence_time = timezone_now()else:- # HACK: Remove existing presence data for the current user- # when disabling presence. This hack will go away when we- # replace our presence data structure with a simpler model- # that doesn't separate individual clients.- UserPresence.objects.filter(user_profile_id=user_profile.id).delete()-- # We create a single presence entry for the user, old- # enough to be guaranteed to be treated as offline by- # correct clients, such that the user will, for as long as- # presence remains disabled, appear to have been last- # online a few minutes before they disabled presence.+ # We want to ensure the user's presence data is such that+ # they will be treated as offline by correct clients,+ # There are two cases:#- # We add a small additional offset as a fudge factor in- # case of clock skew.- status = UserPresence.LEGACY_STATUS_IDLE_INT- presence_time = timezone_now() - timedelta(- seconds=settings.OFFLINE_THRESHOLD_SECS + 120+ # (1) If the user's presence was current, we backdate it+ # so that the user will, for as long as presence+ # remains disabled, appear to have been last online a+ # few minutes before they disabled presence.+ #+ # (2) If the user only has a presence older than what our+ # backdate would be, we keep the original value - it+ # already guarantees that the user will appear to be+ # offline.+ backdated_presence_time = timezone_now() - timedelta(+ # We add a small additional offset as a fudge factor in+ # case of clock skew.+ seconds=settings.OFFLINE_THRESHOLD_SECS+ + settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS+ + 10+ )+ minimum_previous_presence_time = backdated_presence_time - timedelta(+ seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS + 10)+ try:+ presence: UserPresence | None = UserPresence.objects.get(user_profile=user_profile)+ assert presence is not None+ assert presence.last_connected_time is not None++ original_last_active_time = presence.last_active_time+ if presence.last_connected_time <= backdated_presence_time:+ # This is case (2), so we don't need to do+ # anything. presence is already as intended.+ # last_active_time <= last_connected_time always holds, so+ # last_active_time <= backdated_presence_time is also ensured here.+ return++ # do_update_user_presence will only send an event if+ # the presence event it receives is sufficiently newer+ # than whatever it had before, so we backdate the+ # existing presence data if necessary to ensure that+ # our new update event will be seen as new by clients.+ presence_time = backdated_presence_time+ presence.last_connected_time = min(+ minimum_previous_presence_time, presence.last_connected_time+ )+ update_fields = ["last_connected_time"]++ if (+ original_last_active_time is None+ or original_last_active_time < backdated_presence_time+ ):+ # If the user's last_active_time was old enough (or nonexistent), we don't want to perturb+ # it, as it's already in a correct state. Thus we only do_update_user_presence with an+ # IDLE status - which will only update the last_connected_time.+ status = UserPresence.LEGACY_STATUS_IDLE_INT+ else:+ assert presence.last_active_time is not None+ presence.last_active_time = min(+ minimum_previous_presence_time, presence.last_active_time+ )+ update_fields.append("last_active_time")+ status = UserPresence.LEGACY_STATUS_ACTIVE_INT+ presence.save(update_fields=update_fields)++ except UserPresence.DoesNotExist:+ # If the user has no presence data at all, that should+ # logically get consistent treatment with having very+ # old presence data (case (2) above). We want to leave+ # their presence state intact - so just return without+ # doing anything.+ return+# do_update_user_presence doesn't allow being run inside another# transaction.atomic block, so we need to use on_commit here to ensure# it gets executed outside of our current transaction.diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 0342c7bc45e..084cab9f5be 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -15,6 +15,7 @@ from typing import Anyfrom unittest import mockimport orjson+import time_machinefrom dateutil.parser import parse as dateparserfrom django.utils.timezone import now as timezone_nowfrom typing_extensions import override@@ -1773,14 +1774,22 @@ class NormalActionsTest(BaseAction):def test_away_events(self) -> None:client = get_client("website")+ now = timezone_now()# Updating user status to away activates the codepath of disabling- # the presence_enabled user setting. Correctly simulating the presence- # event status for a typical user requires settings the user's date_joined- # further into the past. See test_change_presence_enabled for more details,- # since it tests that codepath directly.- self.user_profile.date_joined = timezone_now() - timedelta(days=15)- self.user_profile.save()+ # the presence_enabled user setting.+ # See test_change_presence_enabled for more details, since it tests that codepath directly.+ #+ # Set up an initial presence state for the user:+ UserPresence.objects.filter(user_profile=self.user_profile).delete()+ with time_machine.travel(now, tick=False):+ result = self.api_post(+ self.user_profile,+ "/api/v1/users/me/presence",+ dict(status="active"),+ HTTP_USER_AGENT="ZulipAndroid/1.0",+ )+ self.assert_json_success(result)# Set allaway_val = True@@ -1807,7 +1816,7 @@ class NormalActionsTest(BaseAction):events[3],has_email=True,presence_key="website",- status="active" if not away_val else "idle",+ status="active",)# Remove all@@ -1835,7 +1844,7 @@ class NormalActionsTest(BaseAction):events[3],has_email=True,presence_key="website",- status="active" if not away_val else "idle",+ status="active",)# Only set away@@ -1859,7 +1868,7 @@ class NormalActionsTest(BaseAction):events[3],has_email=True,presence_key="website",- status="active" if not away_val else "idle",+ status="active",)# Only set status_text@@ -1918,7 +1927,7 @@ class NormalActionsTest(BaseAction):# We no longer store information about the client and we simply# set the field to 'website' for backwards compatibility.presence_key="website",- status="idle",+ status="active",)def test_user_group_events(self) -> None:@@ -2756,16 +2765,11 @@ class NormalActionsTest(BaseAction):def test_change_presence_enabled(self) -> None:presence_enabled_setting = "presence_enabled"+ UserPresence.objects.filter(user_profile=self.user_profile).delete()# Disabling presence will lead to the creation of a UserPresence object for the user- # with a last_connected_time slightly preceding the moment of flipping the setting- # and last_active_time set to None. The presence API defaults to user_profile.date_joined- # for backwards compatibility when dealing with a None value. Thus for this test to properly- # check that the presence event emitted will have "idle" status, we need to simulate- # the (more realistic) scenario where date_joined is further in the past and not super recent.- self.user_profile.date_joined = timezone_now() - timedelta(days=15)- self.user_profile.save()-+ # with a last_connected_time and last_active_time slightly preceding the moment of flipping the+ # setting.for val in [True, False]:with self.verify_action(num_events=3) as events:do_change_user_setting(@@ -2777,11 +2781,7 @@ class NormalActionsTest(BaseAction):check_user_settings_update("events[0]", events[0])check_update_global_notifications("events[1]", events[1], val)check_presence(- "events[2]",- events[2],- has_email=True,- presence_key="website",- status="active" if val else "idle",+ "events[2]", events[2], has_email=True, presence_key="website", status="active")def test_change_notification_sound(self) -> None:diff --git a/zerver/tests/test_presence.py b/zerver/tests/test_presence.pyindex a12d3a35660..446dfa1bd98 100644--- a/zerver/tests/test_presence.py+++ b/zerver/tests/test_presence.py@@ -8,6 +8,7 @@ from django.db import connectionfrom django.utils.timezone import now as timezone_nowfrom typing_extensions import override+from zerver.actions.user_settings import do_change_user_settingfrom zerver.actions.users import do_deactivate_userfrom zerver.lib.presence import format_legacy_presence_dict, get_presence_dict_by_realmfrom zerver.lib.test_classes import ZulipTestCase@@ -1011,6 +1012,88 @@ class GetRealmStatusesTest(ZulipTestCase):set(json["presences"].keys()), {hamlet.email, polonius.email, othello.email})+ def test_do_change_user_setting_presence_enabled(self) -> None:+ """+ Tests the logic for backdating user's presence+ """+ hamlet = self.example_user("hamlet")+ UserPresence.objects.filter(user_profile=hamlet).delete()+ now = timezone_now()++ # If the user has no presence at all, disabling presence_enabled should not change that state.+ with time_machine.travel(now, tick=False), self.captureOnCommitCallbacks(execute=True):+ do_change_user_setting(hamlet, "presence_enabled", False, acting_user=hamlet)+ self.assertFalse(UserPresence.objects.filter(user_profile=hamlet).exists())++ # Enabling presence_enabled creates a new, current presence record.+ with time_machine.travel(now, tick=False), self.captureOnCommitCallbacks(execute=True):+ do_change_user_setting(hamlet, "presence_enabled", True, acting_user=hamlet)++ presence = UserPresence.objects.get(user_profile=hamlet)+ self.assertEqual(presence.last_connected_time, now)+ self.assertEqual(presence.last_active_time, now)++ # Disabling presence_enabled with a very recent presence record will cause it to get backdated+ # by some minutes to make the user immediately appear offline.+ with time_machine.travel(now, tick=False), self.captureOnCommitCallbacks(execute=True):+ do_change_user_setting(hamlet, "presence_enabled", False, acting_user=hamlet)+ presence = UserPresence.objects.get(user_profile=hamlet)+ self.assertEqual(+ presence.last_connected_time,+ now+ - timedelta(+ seconds=settings.OFFLINE_THRESHOLD_SECS+ + settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS+ + 10+ ),+ )+ self.assertEqual(+ presence.last_active_time,+ now+ - timedelta(+ seconds=settings.OFFLINE_THRESHOLD_SECS+ + settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS+ + 10+ ),+ )++ # Now we set up a very old presence record.+ hamlet.presence_enabled = True+ hamlet.save()+ presence.last_connected_time = now - timedelta(days=100)+ presence.last_active_time = now - timedelta(days=100)+ presence.save()++ # With a very old presence record, disabling presence_enabled should not change that.+ with time_machine.travel(now, tick=False), self.captureOnCommitCallbacks(execute=True):+ do_change_user_setting(hamlet, "presence_enabled", False, acting_user=hamlet)+ presence = UserPresence.objects.get(user_profile=hamlet)+ self.assertEqual(presence.last_connected_time, now - timedelta(days=100))+ self.assertEqual(presence.last_active_time, now - timedelta(days=100))++ hamlet.presence_enabled = True+ hamlet.save()+ # Now set up the final edge case - a very old last_active_time and a recent last_connected_time.+ # In this case, last_connected_time should get backdated (to ensure the user appears offline),+ # without pushing last_active_time forward.+ presence.last_active_time = now - timedelta(days=100)+ presence.last_connected_time = now - timedelta(seconds=1)+ presence.save()++ with time_machine.travel(now, tick=False), self.captureOnCommitCallbacks(execute=True):+ do_change_user_setting(hamlet, "presence_enabled", False, acting_user=hamlet)+ presence = UserPresence.objects.get(user_profile=hamlet)+ self.assertEqual(+ presence.last_connected_time,+ now+ - timedelta(+ seconds=settings.OFFLINE_THRESHOLD_SECS+ + settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS+ + 10+ ),+ )+ self.assertEqual(presence.last_active_time, now - timedelta(days=100))+def test_presence_disabled(self) -> None:# Disable presence status and test whether the presence# is reported or not.diff --git a/zerver/tests/test_user_status.py b/zerver/tests/test_user_status.pyindex 55939ef25ee..768e73eaa42 100644--- a/zerver/tests/test_user_status.py+++ b/zerver/tests/test_user_status.py@@ -1,6 +1,8 @@from typing import Anyimport orjson+import time_machine+from django.utils.timezone import now as timezone_nowfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.user_status import (@@ -11,6 +13,7 @@ from zerver.lib.user_status import ()from zerver.models import UserProfile, UserStatusfrom zerver.models.clients import get_client+from zerver.models.presence import UserPresencedef user_status_info(user: UserProfile, acting_user: UserProfile | None = None) -> UserInfoDict:@@ -191,9 +194,21 @@ class UserStatusTest(ZulipTestCase):def test_endpoints(self) -> None:hamlet = self.example_user("hamlet")realm = hamlet.realm+ now = timezone_now()self.login_user(hamlet)+ # Set up an initial presence state for the user.+ UserPresence.objects.filter(user_profile=hamlet).delete()+ with time_machine.travel(now, tick=False):+ result = self.api_post(+ hamlet,+ "/api/v1/users/me/presence",+ dict(status="active"),+ HTTP_USER_AGENT="ZulipAndroid/1.0",+ )+ self.assert_json_success(result)+# Try to omit parameter--this should be an error.payload: dict[str, Any] = {}result = self.client_post("/json/users/me/status", payload)