def update_edit_history(message: Message, last_edit_time: datetime, edit_history_event: Dict[str, Any]) -> None: message.last_edit_time = last_edit_time if message.edit_history is not None: edit_history = orjson.loads(message.edit_history) edit_history.insert(0, edit_history_event) else: edit_history = [edit_history_event] message.edit_history = orjson.dumps(edit_history).decode()
def update_messages_for_topic_edit( message: Message, propagate_mode: str, orig_topic_name: str, topic_name: Optional[str], new_stream: Optional[Stream], old_recipient_id: Optional[int], edit_history_event: Dict[str, Any], last_edit_time: datetime, ) -> List[Message]: assert (new_stream and old_recipient_id) or (not new_stream and not old_recipient_id) if old_recipient_id is not None: recipient_id = old_recipient_id else: recipient_id = message.recipient_id propagate_query = Q(recipient_id=recipient_id, subject__iexact=orig_topic_name) if propagate_mode == "change_all": propagate_query = propagate_query & ~Q(id=message.id) if propagate_mode == "change_later": propagate_query = propagate_query & Q(id__gt=message.id) messages = Message.objects.filter(propagate_query).select_related() update_fields = ["edit_history", "last_edit_time"] # Evaluate the query before running the update messages_list = list(messages) # The cached ORM objects are not changed by the upcoming # messages.update(), and the remote cache update (done by the # caller) requires the new value, so we manually update the # objects in addition to sending a bulk query to the database. if new_stream is not None: update_fields.append("recipient") for m in messages_list: m.recipient = new_stream.recipient if topic_name is not None: update_fields.append("subject") for m in messages_list: m.set_topic_name(topic_name) for message in messages_list: message.last_edit_time = last_edit_time if message.edit_history is not None: edit_history = orjson.loads(message.edit_history) edit_history.insert(0, edit_history_event) else: edit_history = [edit_history_event] message.edit_history = orjson.dumps(edit_history).decode() Message.objects.bulk_update(messages_list, update_fields) return messages_list