2023-11-19 19:45:19 +01:00
|
|
|
from datetime import datetime
|
2022-04-14 23:41:59 +02:00
|
|
|
|
|
|
|
from zerver.lib.queue import queue_json_publish
|
|
|
|
from zerver.lib.timestamp import datetime_to_timestamp
|
2024-01-22 21:52:11 +01:00
|
|
|
from zerver.models import UserActivityInterval, UserProfile
|
2022-04-14 23:41:59 +02:00
|
|
|
|
|
|
|
|
2023-11-19 19:45:19 +01:00
|
|
|
def do_update_user_activity_interval(user_profile: UserProfile, log_time: datetime) -> None:
|
2022-04-14 23:41:59 +02:00
|
|
|
effective_end = log_time + UserActivityInterval.MIN_INTERVAL_LENGTH
|
|
|
|
# This code isn't perfect, because with various races we might end
|
|
|
|
# up creating two overlapping intervals, but that shouldn't happen
|
|
|
|
# often, and can be corrected for in post-processing
|
|
|
|
try:
|
|
|
|
last = UserActivityInterval.objects.filter(user_profile=user_profile).order_by("-end")[0]
|
|
|
|
# Two intervals overlap iff each interval ends after the other
|
|
|
|
# begins. In this case, we just extend the old interval to
|
|
|
|
# include the new interval.
|
|
|
|
if log_time <= last.end and effective_end >= last.start:
|
|
|
|
last.end = max(last.end, effective_end)
|
|
|
|
last.start = min(last.start, log_time)
|
|
|
|
last.save(update_fields=["start", "end"])
|
|
|
|
return
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Otherwise, the intervals don't overlap, so we should make a new one
|
|
|
|
UserActivityInterval.objects.create(
|
|
|
|
user_profile=user_profile, start=log_time, end=effective_end
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-11-19 19:45:19 +01:00
|
|
|
def update_user_activity_interval(user_profile: UserProfile, log_time: datetime) -> None:
|
2022-04-14 23:41:59 +02:00
|
|
|
event = {"user_profile_id": user_profile.id, "time": datetime_to_timestamp(log_time)}
|
|
|
|
queue_json_publish("user_activity_interval", event)
|