1 //
2 // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 #pragma once
8 
9 #include "td/telegram/AccessRights.h"
10 #include "td/telegram/AffectedHistory.h"
11 #include "td/telegram/ChannelId.h"
12 #include "td/telegram/DialogAction.h"
13 #include "td/telegram/DialogDate.h"
14 #include "td/telegram/DialogDb.h"
15 #include "td/telegram/DialogFilterId.h"
16 #include "td/telegram/DialogId.h"
17 #include "td/telegram/DialogListId.h"
18 #include "td/telegram/DialogLocation.h"
19 #include "td/telegram/DialogParticipant.h"
20 #include "td/telegram/DialogSource.h"
21 #include "td/telegram/EncryptedFile.h"
22 #include "td/telegram/files/FileId.h"
23 #include "td/telegram/files/FileSourceId.h"
24 #include "td/telegram/FolderId.h"
25 #include "td/telegram/FullMessageId.h"
26 #include "td/telegram/Global.h"
27 #include "td/telegram/InputDialogId.h"
28 #include "td/telegram/InputGroupCallId.h"
29 #include "td/telegram/logevent/LogEventHelper.h"
30 #include "td/telegram/MessageContentType.h"
31 #include "td/telegram/MessageCopyOptions.h"
32 #include "td/telegram/MessageId.h"
33 #include "td/telegram/MessageLinkInfo.h"
34 #include "td/telegram/MessageReplyInfo.h"
35 #include "td/telegram/MessagesDb.h"
36 #include "td/telegram/MessageSearchFilter.h"
37 #include "td/telegram/MessageThreadInfo.h"
38 #include "td/telegram/MessageTtlSetting.h"
39 #include "td/telegram/net/DcId.h"
40 #include "td/telegram/net/NetQuery.h"
41 #include "td/telegram/Notification.h"
42 #include "td/telegram/NotificationGroupId.h"
43 #include "td/telegram/NotificationGroupKey.h"
44 #include "td/telegram/NotificationGroupType.h"
45 #include "td/telegram/NotificationId.h"
46 #include "td/telegram/NotificationSettings.h"
47 #include "td/telegram/RecentDialogList.h"
48 #include "td/telegram/ReplyMarkup.h"
49 #include "td/telegram/ReportReason.h"
50 #include "td/telegram/RestrictionReason.h"
51 #include "td/telegram/ScheduledServerMessageId.h"
52 #include "td/telegram/secret_api.h"
53 #include "td/telegram/SecretChatId.h"
54 #include "td/telegram/SecretInputMedia.h"
55 #include "td/telegram/ServerMessageId.h"
56 #include "td/telegram/td_api.h"
57 #include "td/telegram/telegram_api.h"
58 #include "td/telegram/UserId.h"
59 
60 #include "td/actor/actor.h"
61 #include "td/actor/MultiPromise.h"
62 #include "td/actor/PromiseFuture.h"
63 #include "td/actor/SignalSlot.h"
64 #include "td/actor/Timeout.h"
65 
66 #include "td/utils/buffer.h"
67 #include "td/utils/ChangesProcessor.h"
68 #include "td/utils/common.h"
69 #include "td/utils/Heap.h"
70 #include "td/utils/Hints.h"
71 #include "td/utils/logging.h"
72 #include "td/utils/Slice.h"
73 #include "td/utils/Status.h"
74 #include "td/utils/StringBuilder.h"
75 
76 #include <array>
77 #include <functional>
78 #include <map>
79 #include <memory>
80 #include <set>
81 #include <unordered_map>
82 #include <unordered_set>
83 #include <utility>
84 
85 namespace td {
86 
87 struct BinlogEvent;
88 struct Dependencies;
89 class DialogActionBar;
90 class DialogFilter;
91 class DraftMessage;
92 struct InputMessageContent;
93 class MessageContent;
94 class MultiSequenceDispatcher;
95 class Td;
96 
97 class MessagesManager final : public Actor {
98  public:
99   //  static constexpr int32 MESSAGE_FLAG_IS_UNREAD = 1 << 0;
100   static constexpr int32 MESSAGE_FLAG_IS_OUT = 1 << 1;
101   static constexpr int32 MESSAGE_FLAG_IS_FORWARDED = 1 << 2;
102   static constexpr int32 MESSAGE_FLAG_IS_REPLY = 1 << 3;
103   static constexpr int32 MESSAGE_FLAG_HAS_MENTION = 1 << 4;
104   static constexpr int32 MESSAGE_FLAG_HAS_UNREAD_CONTENT = 1 << 5;
105   static constexpr int32 MESSAGE_FLAG_HAS_REPLY_MARKUP = 1 << 6;
106   static constexpr int32 MESSAGE_FLAG_HAS_ENTITIES = 1 << 7;
107   static constexpr int32 MESSAGE_FLAG_HAS_FROM_ID = 1 << 8;
108   static constexpr int32 MESSAGE_FLAG_HAS_MEDIA = 1 << 9;
109   static constexpr int32 MESSAGE_FLAG_HAS_INTERACTION_INFO = 1 << 10;
110   static constexpr int32 MESSAGE_FLAG_IS_SENT_VIA_BOT = 1 << 11;
111   static constexpr int32 MESSAGE_FLAG_IS_SILENT = 1 << 13;
112   static constexpr int32 MESSAGE_FLAG_IS_POST = 1 << 14;
113   static constexpr int32 MESSAGE_FLAG_HAS_EDIT_DATE = 1 << 15;
114   static constexpr int32 MESSAGE_FLAG_HAS_AUTHOR_SIGNATURE = 1 << 16;
115   static constexpr int32 MESSAGE_FLAG_HAS_MEDIA_ALBUM_ID = 1 << 17;
116   static constexpr int32 MESSAGE_FLAG_IS_FROM_SCHEDULED = 1 << 18;
117   static constexpr int32 MESSAGE_FLAG_IS_LEGACY = 1 << 19;
118   static constexpr int32 MESSAGE_FLAG_HIDE_EDIT_DATE = 1 << 21;
119   static constexpr int32 MESSAGE_FLAG_IS_RESTRICTED = 1 << 22;
120   static constexpr int32 MESSAGE_FLAG_HAS_REPLY_INFO = 1 << 23;
121   static constexpr int32 MESSAGE_FLAG_IS_PINNED = 1 << 24;
122   static constexpr int32 MESSAGE_FLAG_HAS_TTL_PERIOD = 1 << 25;
123   static constexpr int32 MESSAGE_FLAG_NOFORWARDS = 1 << 26;
124 
125   static constexpr int32 SEND_MESSAGE_FLAG_IS_REPLY = 1 << 0;
126   static constexpr int32 SEND_MESSAGE_FLAG_DISABLE_WEB_PAGE_PREVIEW = 1 << 1;
127   static constexpr int32 SEND_MESSAGE_FLAG_HAS_REPLY_MARKUP = 1 << 2;
128   static constexpr int32 SEND_MESSAGE_FLAG_HAS_ENTITIES = 1 << 3;
129   //  static constexpr int32 SEND_MESSAGE_FLAG_IS_POST = 1 << 4;
130   static constexpr int32 SEND_MESSAGE_FLAG_DISABLE_NOTIFICATION = 1 << 5;
131   static constexpr int32 SEND_MESSAGE_FLAG_FROM_BACKGROUND = 1 << 6;
132   static constexpr int32 SEND_MESSAGE_FLAG_CLEAR_DRAFT = 1 << 7;
133   static constexpr int32 SEND_MESSAGE_FLAG_WITH_MY_SCORE = 1 << 8;
134   static constexpr int32 SEND_MESSAGE_FLAG_GROUP_MEDIA = 1 << 9;
135   static constexpr int32 SEND_MESSAGE_FLAG_HAS_SCHEDULE_DATE = 1 << 10;
136   static constexpr int32 SEND_MESSAGE_FLAG_HAS_MESSAGE = 1 << 11;
137   static constexpr int32 SEND_MESSAGE_FLAG_HAS_SEND_AS = 1 << 13;
138 
139   static constexpr int32 ONLINE_MEMBER_COUNT_CACHE_EXPIRE_TIME = 30 * 60;
140 
141   MessagesManager(Td *td, ActorShared<> parent);
142   MessagesManager(const MessagesManager &) = delete;
143   MessagesManager &operator=(const MessagesManager &) = delete;
144   MessagesManager(MessagesManager &&) = delete;
145   MessagesManager &operator=(MessagesManager &&) = delete;
146   ~MessagesManager() final;
147 
148   static vector<MessageId> get_message_ids(const vector<int64> &input_message_ids);
149 
150   static vector<int32> get_server_message_ids(const vector<MessageId> &message_ids);
151 
152   static vector<int32> get_scheduled_server_message_ids(const vector<MessageId> &message_ids);
153 
154   static MessageId get_message_id(const tl_object_ptr<telegram_api::Message> &message_ptr, bool is_scheduled);
155 
156   static DialogId get_message_dialog_id(const tl_object_ptr<telegram_api::Message> &message_ptr);
157 
158   tl_object_ptr<telegram_api::InputPeer> get_input_peer(DialogId dialog_id, AccessRights access_rights) const;
159 
160   static tl_object_ptr<telegram_api::InputPeer> get_input_peer_force(DialogId dialog_id);
161 
162   vector<tl_object_ptr<telegram_api::InputPeer>> get_input_peers(const vector<DialogId> &dialog_ids,
163                                                                  AccessRights access_rights) const;
164 
165   tl_object_ptr<telegram_api::InputDialogPeer> get_input_dialog_peer(DialogId dialog_id,
166                                                                      AccessRights access_rights) const;
167 
168   vector<tl_object_ptr<telegram_api::InputDialogPeer>> get_input_dialog_peers(const vector<DialogId> &dialog_ids,
169                                                                               AccessRights access_rights) const;
170 
171   tl_object_ptr<telegram_api::inputEncryptedChat> get_input_encrypted_chat(DialogId dialog_id,
172                                                                            AccessRights access_rights) const;
173 
174   bool have_input_peer(DialogId dialog_id, AccessRights access_rights) const;
175 
176   void on_get_empty_messages(DialogId dialog_id, const vector<MessageId> &empty_message_ids);
177 
178   struct MessagesInfo {
179     vector<tl_object_ptr<telegram_api::Message>> messages;
180     int32 total_count = 0;
181     bool is_channel_messages = false;
182   };
183   MessagesInfo get_messages_info(tl_object_ptr<telegram_api::messages_Messages> &&messages_ptr, const char *source);
184 
185   void get_channel_difference_if_needed(DialogId dialog_id, MessagesInfo &&messages_info,
186                                         Promise<MessagesInfo> &&promise);
187 
188   void get_channel_differences_if_needed(MessagesInfo &&messages_info, Promise<MessagesInfo> &&promise);
189 
190   void on_get_messages(vector<tl_object_ptr<telegram_api::Message>> &&messages, bool is_channel_message,
191                        bool is_scheduled, Promise<Unit> &&promise, const char *source);
192 
193   void on_get_history(DialogId dialog_id, MessageId from_message_id, MessageId old_last_new_message_id, int32 offset,
194                       int32 limit, bool from_the_end, vector<tl_object_ptr<telegram_api::Message>> &&messages,
195                       Promise<Unit> &&promise);
196 
197   void on_get_public_dialogs_search_result(const string &query, vector<tl_object_ptr<telegram_api::Peer>> &&my_peers,
198                                            vector<tl_object_ptr<telegram_api::Peer>> &&peers);
199   void on_failed_public_dialogs_search(const string &query, Status &&error);
200 
201   void on_get_message_search_result_calendar(DialogId dialog_id, MessageId from_message_id, MessageSearchFilter filter,
202                                              int64 random_id, int32 total_count,
203                                              vector<tl_object_ptr<telegram_api::Message>> &&messages,
204                                              vector<tl_object_ptr<telegram_api::searchResultsCalendarPeriod>> &&periods,
205                                              Promise<Unit> &&promise);
206   void on_failed_get_message_search_result_calendar(DialogId dialog_id, int64 random_id);
207 
208   void on_get_dialog_messages_search_result(DialogId dialog_id, const string &query, DialogId sender_dialog_id,
209                                             MessageId from_message_id, int32 offset, int32 limit,
210                                             MessageSearchFilter filter, MessageId top_thread_message_id,
211                                             int64 random_id, int32 total_count,
212                                             vector<tl_object_ptr<telegram_api::Message>> &&messages,
213                                             Promise<Unit> &&promise);
214   void on_failed_dialog_messages_search(DialogId dialog_id, int64 random_id);
215 
216   void on_get_dialog_message_count(DialogId dialog_id, MessageSearchFilter filter, int32 total_count,
217                                    Promise<int32> &&promise);
218 
219   void on_get_messages_search_result(const string &query, int32 offset_date, DialogId offset_dialog_id,
220                                      MessageId offset_message_id, int32 limit, MessageSearchFilter filter,
221                                      int32 min_date, int32 max_date, int64 random_id, int32 total_count,
222                                      vector<tl_object_ptr<telegram_api::Message>> &&messages, Promise<Unit> &&promise);
223   void on_failed_messages_search(int64 random_id);
224 
225   void on_get_scheduled_server_messages(DialogId dialog_id, uint32 generation,
226                                         vector<tl_object_ptr<telegram_api::Message>> &&messages, bool is_not_modified);
227 
228   void on_get_recent_locations(DialogId dialog_id, int32 limit, int32 total_count,
229                                vector<tl_object_ptr<telegram_api::Message>> &&messages,
230                                Promise<td_api::object_ptr<td_api::messages>> &&promise);
231 
232   void on_get_message_public_forwards(int32 total_count, vector<tl_object_ptr<telegram_api::Message>> &&messages,
233                                       Promise<td_api::object_ptr<td_api::foundMessages>> &&promise);
234 
235   // if message is from_update, flags have_previous and have_next are ignored and must be both true
236   FullMessageId on_get_message(tl_object_ptr<telegram_api::Message> message_ptr, bool from_update,
237                                bool is_channel_message, bool is_scheduled, bool have_previous, bool have_next,
238                                const char *source);
239 
240   void open_secret_message(SecretChatId secret_chat_id, int64 random_id, Promise<>);
241 
242   void on_send_secret_message_success(int64 random_id, MessageId message_id, int32 date, unique_ptr<EncryptedFile> file,
243                                       Promise<> promise);
244   void on_send_secret_message_error(int64 random_id, Status error, Promise<> promise);
245 
246   void delete_secret_messages(SecretChatId secret_chat_id, std::vector<int64> random_ids, Promise<> promise);
247 
248   void delete_secret_chat_history(SecretChatId secret_chat_id, bool remove_from_dialog_list, MessageId last_message_id,
249                                   Promise<> promise);
250 
251   void read_secret_chat_outbox(SecretChatId secret_chat_id, int32 up_to_date, int32 read_date);
252 
253   void on_update_secret_chat_state(SecretChatId secret_chat_id, SecretChatState state);
254 
255   void on_get_secret_message(SecretChatId secret_chat_id, UserId user_id, MessageId message_id, int32 date,
256                              unique_ptr<EncryptedFile> file, tl_object_ptr<secret_api::decryptedMessage> message,
257                              Promise<> promise);
258 
259   void on_secret_chat_screenshot_taken(SecretChatId secret_chat_id, UserId user_id, MessageId message_id, int32 date,
260                                        int64 random_id, Promise<> promise);
261 
262   void on_secret_chat_ttl_changed(SecretChatId secret_chat_id, UserId user_id, MessageId message_id, int32 date,
263                                   int32 ttl, int64 random_id, Promise<> promise);
264 
265   void on_update_sent_text_message(int64 random_id, tl_object_ptr<telegram_api::MessageMedia> message_media,
266                                    vector<tl_object_ptr<telegram_api::MessageEntity>> &&entities);
267 
268   void delete_pending_message_web_page(FullMessageId full_message_id);
269 
270   void on_get_dialogs(FolderId folder_id, vector<tl_object_ptr<telegram_api::Dialog>> &&dialog_folders,
271                       int32 total_count, vector<tl_object_ptr<telegram_api::Message>> &&messages,
272                       Promise<Unit> &&promise);
273 
274   void on_get_common_dialogs(UserId user_id, int64 offset_chat_id, vector<tl_object_ptr<telegram_api::Chat>> &&chats,
275                              int32 total_count);
276 
277   bool on_update_message_id(int64 random_id, MessageId new_message_id, const string &source);
278 
279   bool on_update_scheduled_message_id(int64 random_id, ScheduledServerMessageId new_message_id, const string &source);
280 
281   void on_update_dialog_draft_message(DialogId dialog_id, tl_object_ptr<telegram_api::DraftMessage> &&draft_message);
282 
283   void on_update_dialog_is_pinned(FolderId folder_id, DialogId dialog_id, bool is_pinned);
284 
285   void on_update_pinned_dialogs(FolderId folder_id);
286 
287   void on_update_dialog_is_marked_as_unread(DialogId dialog_id, bool is_marked_as_unread);
288 
289   void on_update_dialog_is_blocked(DialogId dialog_id, bool is_blocked);
290 
291   void on_update_dialog_last_pinned_message_id(DialogId dialog_id, MessageId last_pinned_message_id);
292 
293   void on_update_dialog_theme_name(DialogId dialog_id, string theme_name);
294 
295   void on_update_dialog_pending_join_requests(DialogId dialog_id, int32 pending_join_request_count,
296                                               vector<int64> pending_requesters);
297 
298   void on_update_dialog_has_scheduled_server_messages(DialogId dialog_id, bool has_scheduled_server_messages);
299 
300   void on_update_dialog_folder_id(DialogId dialog_id, FolderId folder_id);
301 
302   void on_update_dialog_group_call(DialogId dialog_id, bool has_active_group_call, bool is_group_call_empty,
303                                    const char *source, bool force = false);
304 
305   void on_update_dialog_group_call_id(DialogId dialog_id, InputGroupCallId input_group_call_id);
306 
307   void on_update_dialog_default_join_group_call_as_dialog_id(DialogId dialog_id, DialogId default_join_as_dialog_id,
308                                                              bool force);
309 
310   void on_update_dialog_default_send_message_as_dialog_id(DialogId dialog_id, DialogId default_send_as_dialog_id,
311                                                           bool force);
312 
313   void on_update_dialog_message_ttl_setting(DialogId dialog_id, MessageTtlSetting message_ttl_setting);
314 
315   void on_update_dialog_filters();
316 
317   void on_update_service_notification(tl_object_ptr<telegram_api::updateServiceNotification> &&update,
318                                       bool skip_new_entities, Promise<Unit> &&promise);
319 
320   void on_update_read_channel_inbox(tl_object_ptr<telegram_api::updateReadChannelInbox> &&update);
321 
322   void on_update_read_channel_outbox(tl_object_ptr<telegram_api::updateReadChannelOutbox> &&update);
323 
324   void on_update_read_channel_messages_contents(
325       tl_object_ptr<telegram_api::updateChannelReadMessagesContents> &&update);
326 
327   void on_update_read_message_comments(DialogId dialog_id, MessageId message_id, MessageId max_message_id,
328                                        MessageId last_read_inbox_message_id, MessageId last_read_outbox_message_id);
329 
330   void on_update_channel_too_long(tl_object_ptr<telegram_api::updateChannelTooLong> &&update, bool force_apply);
331 
332   void on_update_message_view_count(FullMessageId full_message_id, int32 view_count);
333 
334   void on_update_message_forward_count(FullMessageId full_message_id, int32 forward_count);
335 
336   void on_update_message_interaction_info(FullMessageId full_message_id, int32 view_count, int32 forward_count,
337                                           bool has_reply_info,
338                                           tl_object_ptr<telegram_api::messageReplies> &&reply_info);
339 
340   void on_update_live_location_viewed(FullMessageId full_message_id);
341 
342   void on_update_some_live_location_viewed(Promise<Unit> &&promise);
343 
344   void on_external_update_message_content(FullMessageId full_message_id);
345 
346   void on_read_channel_inbox(ChannelId channel_id, MessageId max_message_id, int32 server_unread_count, int32 pts,
347                              const char *source);
348 
349   void on_read_channel_outbox(ChannelId channel_id, MessageId max_message_id);
350 
351   void on_update_channel_max_unavailable_message_id(ChannelId channel_id, MessageId max_unavailable_message_id);
352 
353   void on_update_dialog_online_member_count(DialogId dialog_id, int32 online_member_count, bool is_from_server);
354 
355   void on_update_delete_scheduled_messages(DialogId dialog_id, vector<ScheduledServerMessageId> &&server_message_ids);
356 
357   void on_update_created_public_broadcasts(vector<ChannelId> channel_ids);
358 
359   void on_dialog_action(DialogId dialog_id, MessageId top_thread_message_id, DialogId typing_dialog_id,
360                         DialogAction action, int32 date,
361                         MessageContentType message_content_type = MessageContentType::None);
362 
363   void read_history_inbox(DialogId dialog_id, MessageId max_message_id, int32 unread_count, const char *source);
364 
365   void delete_messages(DialogId dialog_id, const vector<MessageId> &message_ids, bool revoke, Promise<Unit> &&promise);
366 
367   void delete_dialog_history(DialogId dialog_id, bool remove_from_dialog_list, bool revoke, Promise<Unit> &&promise);
368 
369   void delete_all_call_messages(bool revoke, Promise<Unit> &&promise);
370 
371   void delete_dialog_messages_by_sender(DialogId dialog_id, DialogId sender_dialog_id, Promise<Unit> &&promise);
372 
373   void delete_dialog_messages_by_date(DialogId dialog_id, int32 min_date, int32 max_date, bool revoke,
374                                       Promise<Unit> &&promise);
375 
376   void on_dialog_deleted(DialogId dialog_id, Promise<Unit> &&promise);
377 
378   void on_update_dialog_group_call_rights(DialogId dialog_id);
379 
380   void read_all_dialog_mentions(DialogId dialog_id, Promise<Unit> &&promise);
381 
382   Status add_recently_found_dialog(DialogId dialog_id) TD_WARN_UNUSED_RESULT;
383 
384   Status remove_recently_found_dialog(DialogId dialog_id) TD_WARN_UNUSED_RESULT;
385 
386   void clear_recently_found_dialogs();
387 
388   std::pair<int32, vector<DialogId>> get_recently_opened_dialogs(int32 limit, Promise<Unit> &&promise);
389 
390   DialogId resolve_dialog_username(const string &username) const;
391 
392   DialogId search_public_dialog(const string &username_to_search, bool force, Promise<Unit> &&promise);
393 
394   void reload_voice_chat_on_search(const string &username);
395 
396   void get_dialog_send_message_as_dialog_ids(DialogId dialog_id,
397                                              Promise<td_api::object_ptr<td_api::messageSenders>> &&promise,
398                                              bool is_recursive = false);
399 
400   void set_dialog_default_send_message_as_dialog_id(DialogId dialog_id, DialogId message_sender_dialog_id,
401                                                     Promise<Unit> &&promise);
402 
403   Result<td_api::object_ptr<td_api::message>> send_message(
404       DialogId dialog_id, MessageId top_thread_message_id, MessageId reply_to_message_id,
405       tl_object_ptr<td_api::messageSendOptions> &&options, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
406       tl_object_ptr<td_api::InputMessageContent> &&input_message_content) TD_WARN_UNUSED_RESULT;
407 
408   Result<vector<MessageId>> send_message_group(
409       DialogId dialog_id, MessageId top_thread_message_id, MessageId reply_to_message_id,
410       tl_object_ptr<td_api::messageSendOptions> &&options,
411       vector<tl_object_ptr<td_api::InputMessageContent>> &&input_message_contents) TD_WARN_UNUSED_RESULT;
412 
413   Result<MessageId> send_bot_start_message(UserId bot_user_id, DialogId dialog_id,
414                                            const string &parameter) TD_WARN_UNUSED_RESULT;
415 
416   Result<MessageId> send_inline_query_result_message(DialogId dialog_id, MessageId top_thread_message_id,
417                                                      MessageId reply_to_message_id,
418                                                      tl_object_ptr<td_api::messageSendOptions> &&options,
419                                                      int64 query_id, const string &result_id,
420                                                      bool hide_via_bot) TD_WARN_UNUSED_RESULT;
421 
422   Result<td_api::object_ptr<td_api::messages>> forward_messages(DialogId to_dialog_id, DialogId from_dialog_id,
423                                                                 vector<MessageId> message_ids,
424                                                                 tl_object_ptr<td_api::messageSendOptions> &&options,
425                                                                 bool in_game_share,
426                                                                 vector<MessageCopyOptions> &&copy_options,
427                                                                 bool only_preview) TD_WARN_UNUSED_RESULT;
428 
429   Result<vector<MessageId>> resend_messages(DialogId dialog_id, vector<MessageId> message_ids) TD_WARN_UNUSED_RESULT;
430 
431   void set_dialog_message_ttl_setting(DialogId dialog_id, int32 ttl, Promise<Unit> &&promise);
432 
433   Status send_screenshot_taken_notification_message(DialogId dialog_id);
434 
435   Result<MessageId> add_local_message(DialogId dialog_id, td_api::object_ptr<td_api::MessageSender> &&sender,
436                                       MessageId reply_to_message_id, bool disable_notification,
437                                       tl_object_ptr<td_api::InputMessageContent> &&input_message_content)
438       TD_WARN_UNUSED_RESULT;
439 
440   void get_message_file_type(const string &message_file_head,
441                              Promise<td_api::object_ptr<td_api::MessageFileType>> &&promise);
442 
443   void get_message_import_confirmation_text(DialogId dialog_id, Promise<string> &&promise);
444 
445   void import_messages(DialogId dialog_id, const td_api::object_ptr<td_api::InputFile> &message_file,
446                        const vector<td_api::object_ptr<td_api::InputFile>> &attached_files, Promise<Unit> &&promise);
447 
448   void start_import_messages(DialogId dialog_id, int64 import_id, vector<FileId> &&attached_file_ids,
449                              Promise<Unit> &&promise);
450 
451   void edit_message_text(FullMessageId full_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
452                          tl_object_ptr<td_api::InputMessageContent> &&input_message_content, Promise<Unit> &&promise);
453 
454   void edit_message_live_location(FullMessageId full_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
455                                   tl_object_ptr<td_api::location> &&input_location, int32 heading,
456                                   int32 proximity_alert_radius, Promise<Unit> &&promise);
457 
458   void edit_message_media(FullMessageId full_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
459                           tl_object_ptr<td_api::InputMessageContent> &&input_message_content, Promise<Unit> &&promise);
460 
461   void edit_message_caption(FullMessageId full_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
462                             tl_object_ptr<td_api::formattedText> &&input_caption, Promise<Unit> &&promise);
463 
464   void edit_message_reply_markup(FullMessageId full_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
465                                  Promise<Unit> &&promise);
466 
467   void edit_inline_message_text(const string &inline_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
468                                 tl_object_ptr<td_api::InputMessageContent> &&input_message_content,
469                                 Promise<Unit> &&promise);
470 
471   void edit_inline_message_live_location(const string &inline_message_id,
472                                          tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
473                                          tl_object_ptr<td_api::location> &&input_location, int32 heading,
474                                          int32 proximity_alert_radius, Promise<Unit> &&promise);
475 
476   void edit_inline_message_media(const string &inline_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
477                                  tl_object_ptr<td_api::InputMessageContent> &&input_message_content,
478                                  Promise<Unit> &&promise);
479 
480   void edit_inline_message_caption(const string &inline_message_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup,
481                                    tl_object_ptr<td_api::formattedText> &&input_caption, Promise<Unit> &&promise);
482 
483   void edit_inline_message_reply_markup(const string &inline_message_id,
484                                         tl_object_ptr<td_api::ReplyMarkup> &&reply_markup, Promise<Unit> &&promise);
485 
486   void edit_message_scheduling_state(FullMessageId full_message_id,
487                                      td_api::object_ptr<td_api::MessageSchedulingState> &&scheduling_state,
488                                      Promise<Unit> &&promise);
489 
490   void send_dialog_action(DialogId dialog_id, MessageId top_thread_message_id, DialogAction action,
491                           Promise<Unit> &&promise);
492 
493   void after_set_typing_query(DialogId dialog_id, int32 generation);
494 
495   vector<DialogListId> get_dialog_lists_to_add_dialog(DialogId dialog_id);
496 
497   void add_dialog_to_list(DialogId dialog_id, DialogListId dialog_list_id, Promise<Unit> &&promise);
498 
499   void set_dialog_photo(DialogId dialog_id, const tl_object_ptr<td_api::InputChatPhoto> &input_photo,
500                         Promise<Unit> &&promise);
501 
502   void set_dialog_title(DialogId dialog_id, const string &title, Promise<Unit> &&promise);
503 
504   void set_dialog_description(DialogId dialog_id, const string &description, Promise<Unit> &&promise);
505 
506   void set_dialog_permissions(DialogId dialog_id, const td_api::object_ptr<td_api::chatPermissions> &permissions,
507                               Promise<Unit> &&promise);
508 
509   void toggle_dialog_has_protected_content(DialogId dialog_id, bool has_protected_content, Promise<Unit> &&promise);
510 
511   void set_dialog_theme(DialogId dialog_id, const string &theme_name, Promise<Unit> &&promise);
512 
513   void pin_dialog_message(DialogId dialog_id, MessageId message_id, bool disable_notification, bool only_for_self,
514                           bool is_unpin, Promise<Unit> &&promise);
515 
516   void unpin_all_dialog_messages(DialogId dialog_id, Promise<Unit> &&promise);
517 
518   void get_dialog_info_full(DialogId dialog_id, Promise<Unit> &&promise, const char *source);
519 
520   string get_dialog_title(DialogId dialog_id) const;
521 
522   bool have_dialog(DialogId dialog_id) const;
523   bool have_dialog_force(DialogId dialog_id, const char *source);
524 
525   bool have_dialog_info(DialogId dialog_id) const;
526   bool have_dialog_info_force(DialogId dialog_id) const;
527 
528   void reload_dialog_info_full(DialogId dialog_id);
529 
530   void on_dialog_info_full_invalidated(DialogId dialog_id);
531 
532   bool load_dialog(DialogId dialog_id, int left_tries, Promise<Unit> &&promise);
533 
534   void load_dialogs(vector<DialogId> dialog_ids, Promise<vector<DialogId>> &&promise);
535 
536   void load_dialog_filter(DialogFilterId dialog_filter_id, bool force, Promise<Unit> &&promise);
537 
538   void get_recommended_dialog_filters(Promise<td_api::object_ptr<td_api::recommendedChatFilters>> &&promise);
539 
540   Result<DialogDate> get_dialog_list_last_date(DialogListId dialog_list_id);
541 
542   vector<DialogId> get_dialogs(DialogListId dialog_list_id, DialogDate offset, int32 limit, bool exact_limit,
543                                bool force, Promise<Unit> &&promise);
544 
545   void get_dialogs_from_list(DialogListId dialog_list_id, int32 limit,
546                              Promise<td_api::object_ptr<td_api::chats>> &&promise);
547 
548   vector<DialogId> search_public_dialogs(const string &query, Promise<Unit> &&promise);
549 
550   std::pair<int32, vector<DialogId>> search_dialogs(const string &query, int32 limit, Promise<Unit> &&promise);
551 
552   vector<DialogId> search_dialogs_on_server(const string &query, int32 limit, Promise<Unit> &&promise);
553 
554   void drop_common_dialogs_cache(UserId user_id);
555 
556   std::pair<int32, vector<DialogId>> get_common_dialogs(UserId user_id, DialogId offset_dialog_id, int32 limit,
557                                                         bool force, Promise<Unit> &&promise);
558 
559   void block_message_sender_from_replies(MessageId message_id, bool need_delete_message, bool need_delete_all_messages,
560                                          bool report_spam, Promise<Unit> &&promise);
561 
562   void get_blocked_dialogs(int32 offset, int32 limit, Promise<td_api::object_ptr<td_api::messageSenders>> &&promise);
563 
564   void on_get_blocked_dialogs(int32 offset, int32 limit, int32 total_count,
565                               vector<tl_object_ptr<telegram_api::peerBlocked>> &&blocked_peers,
566                               Promise<td_api::object_ptr<td_api::messageSenders>> &&promise);
567 
568   bool can_get_message_statistics(FullMessageId full_message_id);
569 
570   DialogId get_message_sender(FullMessageId full_message_id);
571 
572   bool have_message_force(FullMessageId full_message_id, const char *source);
573 
574   void get_message(FullMessageId full_message_id, Promise<Unit> &&promise);
575 
576   FullMessageId get_replied_message(DialogId dialog_id, MessageId message_id, bool force, Promise<Unit> &&promise);
577 
578   MessageId get_dialog_pinned_message(DialogId dialog_id, Promise<Unit> &&promise);
579 
580   void get_callback_query_message(DialogId dialog_id, MessageId message_id, int64 callback_query_id,
581                                   Promise<Unit> &&promise);
582 
583   bool get_messages(DialogId dialog_id, const vector<MessageId> &message_ids, Promise<Unit> &&promise);
584 
585   void get_message_from_server(FullMessageId full_message_id, Promise<Unit> &&promise, const char *source,
586                                tl_object_ptr<telegram_api::InputMessage> input_message = nullptr);
587 
588   void get_messages_from_server(vector<FullMessageId> &&message_ids, Promise<Unit> &&promise, const char *source,
589                                 tl_object_ptr<telegram_api::InputMessage> input_message = nullptr);
590 
591   void get_message_thread(DialogId dialog_id, MessageId message_id, Promise<MessageThreadInfo> &&promise);
592 
593   td_api::object_ptr<td_api::messageThreadInfo> get_message_thread_info_object(const MessageThreadInfo &info);
594 
595   void process_discussion_message(telegram_api::object_ptr<telegram_api::messages_discussionMessage> &&result,
596                                   DialogId dialog_id, MessageId message_id, DialogId expected_dialog_id,
597                                   MessageId expected_message_id, Promise<MessageThreadInfo> promise);
598 
599   void get_message_viewers(FullMessageId full_message_id, Promise<td_api::object_ptr<td_api::users>> &&promise);
600 
601   bool is_message_edited_recently(FullMessageId full_message_id, int32 seconds);
602 
603   bool is_deleted_secret_chat(DialogId dialog_id) const;
604 
605   Result<std::pair<string, bool>> get_message_link(FullMessageId full_message_id, int32 media_timestamp, bool for_group,
606                                                    bool for_comment);
607 
608   string get_message_embedding_code(FullMessageId full_message_id, bool for_group, Promise<Unit> &&promise);
609 
610   void on_get_public_message_link(FullMessageId full_message_id, bool for_group, string url, string html);
611 
612   void get_message_link_info(Slice url, Promise<MessageLinkInfo> &&promise);
613 
614   td_api::object_ptr<td_api::messageLinkInfo> get_message_link_info_object(const MessageLinkInfo &info) const;
615 
616   void create_dialog_filter(td_api::object_ptr<td_api::chatFilter> filter,
617                             Promise<td_api::object_ptr<td_api::chatFilterInfo>> &&promise);
618 
619   void edit_dialog_filter(DialogFilterId dialog_filter_id, td_api::object_ptr<td_api::chatFilter> filter,
620                           Promise<td_api::object_ptr<td_api::chatFilterInfo>> &&promise);
621 
622   void delete_dialog_filter(DialogFilterId dialog_filter_id, Promise<Unit> &&promise);
623 
624   void reorder_dialog_filters(vector<DialogFilterId> dialog_filter_ids, Promise<Unit> &&promise);
625 
626   Status delete_dialog_reply_markup(DialogId dialog_id, MessageId message_id) TD_WARN_UNUSED_RESULT;
627 
628   Status set_dialog_draft_message(DialogId dialog_id, MessageId top_thread_message_id,
629                                   tl_object_ptr<td_api::draftMessage> &&draft_message) TD_WARN_UNUSED_RESULT;
630 
631   void clear_all_draft_messages(bool exclude_secret_chats, Promise<Unit> &&promise);
632 
633   Status toggle_dialog_is_pinned(DialogListId dialog_list_id, DialogId dialog_id, bool is_pinned) TD_WARN_UNUSED_RESULT;
634 
635   Status toggle_dialog_is_marked_as_unread(DialogId dialog_id, bool is_marked_as_unread) TD_WARN_UNUSED_RESULT;
636 
637   Status toggle_message_sender_is_blocked(const td_api::object_ptr<td_api::MessageSender> &sender,
638                                           bool is_blocked) TD_WARN_UNUSED_RESULT;
639 
640   Status toggle_dialog_silent_send_message(DialogId dialog_id, bool silent_send_message) TD_WARN_UNUSED_RESULT;
641 
642   Status set_pinned_dialogs(DialogListId dialog_list_id, vector<DialogId> dialog_ids) TD_WARN_UNUSED_RESULT;
643 
644   Status set_dialog_client_data(DialogId dialog_id, string &&client_data) TD_WARN_UNUSED_RESULT;
645 
646   void create_dialog(DialogId dialog_id, bool force, Promise<Unit> &&promise);
647 
648   DialogId create_new_group_chat(const vector<UserId> &user_ids, const string &title, int64 &random_id,
649                                  Promise<Unit> &&promise);
650 
651   DialogId create_new_channel_chat(const string &title, bool is_megagroup, const string &description,
652                                    const DialogLocation &location, bool for_import, int64 &random_id,
653                                    Promise<Unit> &&promise);
654 
655   void create_new_secret_chat(UserId user_id, Promise<SecretChatId> &&promise);
656 
657   DialogId migrate_dialog_to_megagroup(DialogId dialog_id, Promise<Unit> &&promise);
658 
659   bool is_dialog_opened(DialogId dialog_id) const;
660 
661   Status open_dialog(DialogId dialog_id) TD_WARN_UNUSED_RESULT;
662 
663   Status close_dialog(DialogId dialog_id) TD_WARN_UNUSED_RESULT;
664 
665   Status view_messages(DialogId dialog_id, MessageId top_thread_message_id, const vector<MessageId> &message_ids,
666                        bool force_read) TD_WARN_UNUSED_RESULT;
667 
668   Status open_message_content(FullMessageId full_message_id) TD_WARN_UNUSED_RESULT;
669 
670   void click_animated_emoji_message(FullMessageId full_message_id,
671                                     Promise<td_api::object_ptr<td_api::sticker>> &&promise);
672 
673   td_api::object_ptr<td_api::updateScopeNotificationSettings> get_update_scope_notification_settings_object(
674       NotificationSettingsScope scope) const;
675 
676   vector<DialogId> get_dialog_notification_settings_exceptions(NotificationSettingsScope scope, bool filter_scope,
677                                                                bool compare_sound, bool force, Promise<Unit> &&promise);
678 
679   const ScopeNotificationSettings *get_scope_notification_settings(NotificationSettingsScope scope,
680                                                                    Promise<Unit> &&promise);
681 
682   Status set_dialog_notification_settings(DialogId dialog_id,
683                                           tl_object_ptr<td_api::chatNotificationSettings> &&notification_settings)
684       TD_WARN_UNUSED_RESULT;
685 
686   Status set_scope_notification_settings(NotificationSettingsScope scope,
687                                          tl_object_ptr<td_api::scopeNotificationSettings> &&notification_settings)
688       TD_WARN_UNUSED_RESULT;
689 
690   void reset_all_notification_settings();
691 
692   tl_object_ptr<td_api::chat> get_chat_object(DialogId dialog_id) const;
693 
694   static tl_object_ptr<td_api::chats> get_chats_object(int32 total_count, const vector<DialogId> &dialog_ids);
695 
696   static tl_object_ptr<td_api::chats> get_chats_object(const std::pair<int32, vector<DialogId>> &dialog_ids);
697 
698   tl_object_ptr<td_api::chatFilter> get_chat_filter_object(DialogFilterId dialog_filter_id) const;
699 
700   tl_object_ptr<td_api::messages> get_dialog_history(DialogId dialog_id, MessageId from_message_id, int32 offset,
701                                                      int32 limit, int left_tries, bool only_local,
702                                                      Promise<Unit> &&promise);
703 
704   std::pair<DialogId, vector<MessageId>> get_message_thread_history(DialogId dialog_id, MessageId message_id,
705                                                                     MessageId from_message_id, int32 offset,
706                                                                     int32 limit, int64 &random_id,
707                                                                     Promise<Unit> &&promise);
708 
709   td_api::object_ptr<td_api::messageCalendar> get_dialog_message_calendar(DialogId dialog_id, MessageId from_message_id,
710                                                                           MessageSearchFilter filter, int64 &random_id,
711                                                                           bool use_db, Promise<Unit> &&promise);
712 
713   std::pair<int32, vector<MessageId>> search_dialog_messages(DialogId dialog_id, const string &query,
714                                                              const td_api::object_ptr<td_api::MessageSender> &sender,
715                                                              MessageId from_message_id, int32 offset, int32 limit,
716                                                              MessageSearchFilter filter,
717                                                              MessageId top_thread_message_id, int64 &random_id,
718                                                              bool use_db, Promise<Unit> &&promise);
719 
720   struct FoundMessages {
721     vector<FullMessageId> full_message_ids;
722     string next_offset;
723     int32 total_count = 0;
724   };
725 
726   td_api::object_ptr<td_api::foundMessages> get_found_messages_object(const FoundMessages &found_messages,
727                                                                       const char *source);
728 
729   FoundMessages offline_search_messages(DialogId dialog_id, const string &query, string offset, int32 limit,
730                                         MessageSearchFilter filter, int64 &random_id, Promise<> &&promise);
731 
732   std::pair<int32, vector<FullMessageId>> search_messages(FolderId folder_id, bool ignore_folder_id,
733                                                           const string &query, int32 offset_date,
734                                                           DialogId offset_dialog_id, MessageId offset_message_id,
735                                                           int32 limit, MessageSearchFilter filter, int32 min_date,
736                                                           int32 max_date, int64 &random_id, Promise<Unit> &&promise);
737 
738   std::pair<int32, vector<FullMessageId>> search_call_messages(MessageId from_message_id, int32 limit, bool only_missed,
739                                                                int64 &random_id, bool use_db, Promise<Unit> &&promise);
740 
741   void search_dialog_recent_location_messages(DialogId dialog_id, int32 limit,
742                                               Promise<td_api::object_ptr<td_api::messages>> &&promise);
743 
744   vector<FullMessageId> get_active_live_location_messages(Promise<Unit> &&promise);
745 
746   int64 get_dialog_message_by_date(DialogId dialog_id, int32 date, Promise<Unit> &&promise);
747 
748   void on_get_dialog_message_by_date_success(DialogId dialog_id, int32 date, int64 random_id,
749                                              vector<tl_object_ptr<telegram_api::Message>> &&messages,
750                                              Promise<Unit> &&promise);
751 
752   void on_get_dialog_message_by_date_fail(int64 random_id);
753 
754   void get_dialog_sparse_message_positions(DialogId dialog_id, MessageSearchFilter filter, MessageId from_message_id,
755                                            int32 limit,
756                                            Promise<td_api::object_ptr<td_api::messagePositions>> &&promise);
757 
758   void on_get_dialog_sparse_message_positions(
759       DialogId dialog_id, MessageSearchFilter filter,
760       telegram_api::object_ptr<telegram_api::messages_searchResultsPositions> positions,
761       Promise<td_api::object_ptr<td_api::messagePositions>> &&promise);
762 
763   void get_dialog_message_count(DialogId dialog_id, MessageSearchFilter filter, bool return_local,
764                                 Promise<int32> &&promise);
765 
766   vector<MessageId> get_dialog_scheduled_messages(DialogId dialog_id, bool force, bool ignore_result,
767                                                   Promise<Unit> &&promise);
768 
769   void get_message_public_forwards(FullMessageId full_message_id, string offset, int32 limit,
770                                    Promise<td_api::object_ptr<td_api::foundMessages>> &&promise);
771 
772   tl_object_ptr<td_api::message> get_dialog_message_by_date_object(int64 random_id);
773 
774   td_api::object_ptr<td_api::message> get_dialog_event_log_message_object(
775       DialogId dialog_id, tl_object_ptr<telegram_api::Message> &&message);
776 
777   tl_object_ptr<td_api::message> get_message_object(FullMessageId full_message_id, const char *source);
778 
779   tl_object_ptr<td_api::messages> get_messages_object(int32 total_count, DialogId dialog_id,
780                                                       const vector<MessageId> &message_ids, bool skip_not_found,
781                                                       const char *source);
782 
783   tl_object_ptr<td_api::messages> get_messages_object(int32 total_count, const vector<FullMessageId> &full_message_ids,
784                                                       bool skip_not_found, const char *source);
785 
786   void process_pts_update(tl_object_ptr<telegram_api::Update> &&update);
787 
788   void skip_old_pending_pts_update(tl_object_ptr<telegram_api::Update> &&update, int32 new_pts, int32 old_pts,
789                                    int32 pts_count, const char *source);
790 
791   void add_pending_channel_update(DialogId dialog_id, tl_object_ptr<telegram_api::Update> &&update, int32 new_pts,
792                                   int32 pts_count, Promise<Unit> &&promise, const char *source,
793                                   bool is_postponed_update = false);
794 
795   bool is_old_channel_update(DialogId dialog_id, int32 new_pts);
796 
797   bool is_update_about_username_change_received(DialogId dialog_id) const;
798 
799   void on_dialog_bots_updated(DialogId dialog_id, vector<UserId> bot_user_ids, bool from_database);
800 
801   void on_dialog_photo_updated(DialogId dialog_id);
802   void on_dialog_title_updated(DialogId dialog_id);
803   void on_dialog_username_updated(DialogId dialog_id, const string &old_username, const string &new_username);
804   void on_dialog_default_permissions_updated(DialogId dialog_id);
805   void on_dialog_has_protected_content_updated(DialogId dialog_id);
806 
807   void on_dialog_user_is_contact_updated(DialogId dialog_id, bool is_contact);
808   void on_dialog_user_is_deleted_updated(DialogId dialog_id, bool is_deleted);
809 
810   void on_dialog_linked_channel_updated(DialogId dialog_id, ChannelId old_linked_channel_id,
811                                         ChannelId new_linked_channel_id) const;
812 
813   void drop_dialog_pending_join_requests(DialogId dialog_id);
814 
815   void on_resolved_username(const string &username, DialogId dialog_id);
816   void drop_username(const string &username);
817 
818   tl_object_ptr<telegram_api::InputNotifyPeer> get_input_notify_peer(DialogId dialog_id) const;
819 
820   void on_update_dialog_notify_settings(DialogId dialog_id,
821                                         tl_object_ptr<telegram_api::peerNotifySettings> &&peer_notify_settings,
822                                         const char *source);
823 
824   void on_update_scope_notify_settings(NotificationSettingsScope scope,
825                                        tl_object_ptr<telegram_api::peerNotifySettings> &&peer_notify_settings);
826 
827   void hide_dialog_action_bar(DialogId dialog_id);
828 
829   void remove_dialog_action_bar(DialogId dialog_id, Promise<Unit> &&promise);
830 
831   void reget_dialog_action_bar(DialogId dialog_id, const char *source, bool is_repair = true);
832 
833   void report_dialog(DialogId dialog_id, const vector<MessageId> &message_ids, ReportReason &&reason,
834                      Promise<Unit> &&promise);
835 
836   void report_dialog_photo(DialogId dialog_id, FileId file_id, ReportReason &&reason, Promise<Unit> &&promise);
837 
838   void on_get_peer_settings(DialogId dialog_id, tl_object_ptr<telegram_api::peerSettings> &&peer_settings,
839                             bool ignore_privacy_exception = false);
840 
841   void on_authorization_success();
842 
843   void before_get_difference();
844 
845   void after_get_difference();
846 
847   bool on_get_dialog_error(DialogId dialog_id, const Status &status, const string &source);
848 
849   void on_send_message_get_quick_ack(int64 random_id);
850 
851   void check_send_message_result(int64 random_id, DialogId dialog_id, const telegram_api::Updates *updates_ptr,
852                                  const char *source);
853 
854   FullMessageId on_send_message_success(int64 random_id, MessageId new_message_id, int32 date, int32 ttl_period,
855                                         FileId new_file_id, const char *source);
856 
857   void on_send_message_file_part_missing(int64 random_id, int bad_part);
858 
859   void on_send_message_file_reference_error(int64 random_id);
860 
861   void on_send_media_group_file_reference_error(DialogId dialog_id, vector<int64> random_ids);
862 
863   void on_send_message_fail(int64 random_id, Status error);
864 
865   void on_upload_message_media_success(DialogId dialog_id, MessageId message_id,
866                                        tl_object_ptr<telegram_api::MessageMedia> &&media);
867 
868   void on_upload_message_media_file_part_missing(DialogId dialog_id, MessageId message_id, int bad_part);
869 
870   void on_upload_message_media_fail(DialogId dialog_id, MessageId message_id, Status error);
871 
872   void on_create_new_dialog_success(int64 random_id, tl_object_ptr<telegram_api::Updates> &&updates,
873                                     DialogType expected_type, Promise<Unit> &&promise);
874 
875   void on_create_new_dialog_fail(int64 random_id, Status error, Promise<Unit> &&promise);
876 
877   void on_get_channel_difference(DialogId dialog_id, int32 request_pts, int32 request_limit,
878                                  tl_object_ptr<telegram_api::updates_ChannelDifference> &&difference_ptr);
879 
880   void force_create_dialog(DialogId dialog_id, const char *source, bool expect_no_access = false,
881                            bool force_update_dialog_pos = false);
882 
883   void send_get_dialog_notification_settings_query(DialogId dialog_id, Promise<Unit> &&promise);
884 
885   void send_get_scope_notification_settings_query(NotificationSettingsScope scope, Promise<Unit> &&promise);
886 
887   void on_get_dialog_notification_settings_query_finished(DialogId dialog_id, Status &&status);
888 
889   void on_get_dialog_query_finished(DialogId dialog_id, Status &&status);
890 
891   void remove_sponsored_dialog();
892 
893   void on_get_sponsored_dialog(tl_object_ptr<telegram_api::Peer> peer, DialogSource source,
894                                vector<tl_object_ptr<telegram_api::User>> users,
895                                vector<tl_object_ptr<telegram_api::Chat>> chats);
896 
897   FileSourceId get_message_file_source_id(FullMessageId full_message_id);
898 
899   struct MessagePushNotificationInfo {
900     NotificationGroupId group_id;
901     NotificationGroupType group_type = NotificationGroupType::Calls;
902     DialogId settings_dialog_id;
903   };
904   Result<MessagePushNotificationInfo> get_message_push_notification_info(DialogId dialog_id, MessageId message_id,
905                                                                          int64 random_id, UserId sender_user_id,
906                                                                          DialogId sender_dialog_id, int32 date,
907                                                                          bool is_from_scheduled, bool contains_mention,
908                                                                          bool is_pinned, bool is_from_binlog);
909 
910   struct MessageNotificationGroup {
911     DialogId dialog_id;
912     NotificationGroupType type = NotificationGroupType::Calls;
913     int32 total_count = 0;
914     vector<Notification> notifications;
915   };
916   MessageNotificationGroup get_message_notification_group_force(NotificationGroupId group_id);
917 
918   vector<NotificationGroupKey> get_message_notification_group_keys_from_database(NotificationGroupKey from_group_key,
919                                                                                  int32 limit);
920 
921   void get_message_notifications_from_database(DialogId dialog_id, NotificationGroupId group_id,
922                                                NotificationId from_notification_id, MessageId from_message_id,
923                                                int32 limit, Promise<vector<Notification>> promise);
924 
925   void remove_message_notification(DialogId dialog_id, NotificationGroupId group_id, NotificationId notification_id);
926 
927   void remove_message_notifications_by_message_ids(DialogId dialog_id, const vector<MessageId> &message_ids);
928 
929   void remove_message_notifications(DialogId dialog_id, NotificationGroupId group_id,
930                                     NotificationId max_notification_id, MessageId max_message_id);
931 
932   void upload_dialog_photo(DialogId dialog_id, FileId file_id, bool is_animation, double main_frame_timestamp,
933                            bool is_reupload, Promise<Unit> &&promise, vector<int> bad_parts = {});
934 
935   void on_binlog_events(vector<BinlogEvent> &&events);
936 
937   void set_poll_answer(FullMessageId full_message_id, vector<int32> &&option_ids, Promise<Unit> &&promise);
938 
939   void get_poll_voters(FullMessageId full_message_id, int32 option_id, int32 offset, int32 limit,
940                        Promise<std::pair<int32, vector<UserId>>> &&promise);
941 
942   void stop_poll(FullMessageId full_message_id, td_api::object_ptr<td_api::ReplyMarkup> &&reply_markup,
943                  Promise<Unit> &&promise);
944 
945   Result<string> get_login_button_url(FullMessageId full_message_id, int64 button_id);
946 
947   Result<ServerMessageId> get_invoice_message_id(FullMessageId full_message_id);
948 
949   Result<ServerMessageId> get_payment_successful_message_id(FullMessageId full_message_id);
950 
951   bool can_set_game_score(FullMessageId full_message_id) const;
952 
953   void get_current_state(vector<td_api::object_ptr<td_api::Update>> &updates) const;
954 
955   ActorOwn<MultiSequenceDispatcher> sequence_dispatcher_;
956 
957   static uint64 get_sequence_dispatcher_id(DialogId dialog_id, MessageContentType message_content_type);
958 
959  private:
960   class PendingPtsUpdate {
961    public:
962     tl_object_ptr<telegram_api::Update> update;
963     int32 pts;
964     int32 pts_count;
965     Promise<Unit> promise;
966 
PendingPtsUpdate(tl_object_ptr<telegram_api::Update> && update,int32 pts,int32 pts_count,Promise<Unit> && promise)967     PendingPtsUpdate(tl_object_ptr<telegram_api::Update> &&update, int32 pts, int32 pts_count, Promise<Unit> &&promise)
968         : update(std::move(update)), pts(pts), pts_count(pts_count), promise(std::move(promise)) {
969     }
970   };
971 
972   struct MessageInfo {
973     DialogId dialog_id;
974     MessageId message_id;
975     UserId sender_user_id;
976     DialogId sender_dialog_id;
977     int32 date = 0;
978     int32 ttl_period = 0;
979     int32 ttl = 0;
980     bool disable_web_page_preview = false;
981     int64 random_id = 0;
982     tl_object_ptr<telegram_api::messageFwdHeader> forward_header;
983     MessageId reply_to_message_id;
984     tl_object_ptr<telegram_api::messageReplyHeader> reply_header;
985     UserId via_bot_user_id;
986     int32 view_count = 0;
987     int32 forward_count = 0;
988     tl_object_ptr<telegram_api::messageReplies> reply_info;
989     int32 flags = 0;
990     int32 edit_date = 0;
991     vector<RestrictionReason> restriction_reasons;
992     string author_signature;
993     int64 media_album_id = 0;
994 
995     unique_ptr<MessageContent> content;
996     tl_object_ptr<telegram_api::ReplyMarkup> reply_markup;
997   };
998 
999   struct MessageForwardInfo {
1000     UserId sender_user_id;
1001     int32 date = 0;
1002     DialogId sender_dialog_id;
1003     MessageId message_id;
1004     string author_signature;
1005     string sender_name;
1006     DialogId from_dialog_id;
1007     MessageId from_message_id;
1008     string psa_type;
1009     bool is_imported = false;
1010 
1011     MessageForwardInfo() = default;
1012 
MessageForwardInfoMessageForwardInfo1013     MessageForwardInfo(UserId sender_user_id, int32 date, DialogId sender_dialog_id, MessageId message_id,
1014                        string author_signature, string sender_name, DialogId from_dialog_id, MessageId from_message_id,
1015                        string psa_type, bool is_imported)
1016         : sender_user_id(sender_user_id)
1017         , date(date)
1018         , sender_dialog_id(sender_dialog_id)
1019         , message_id(message_id)
1020         , author_signature(std::move(author_signature))
1021         , sender_name(std::move(sender_name))
1022         , from_dialog_id(from_dialog_id)
1023         , from_message_id(from_message_id)
1024         , psa_type(std::move(psa_type))
1025         , is_imported(is_imported) {
1026     }
1027 
1028     bool operator==(const MessageForwardInfo &rhs) const {
1029       return sender_user_id == rhs.sender_user_id && date == rhs.date && sender_dialog_id == rhs.sender_dialog_id &&
1030              message_id == rhs.message_id && author_signature == rhs.author_signature &&
1031              sender_name == rhs.sender_name && from_dialog_id == rhs.from_dialog_id &&
1032              from_message_id == rhs.from_message_id && psa_type == rhs.psa_type && is_imported == rhs.is_imported;
1033     }
1034 
1035     bool operator!=(const MessageForwardInfo &rhs) const {
1036       return !(*this == rhs);
1037     }
1038 
1039     friend StringBuilder &operator<<(StringBuilder &string_builder, const MessageForwardInfo &forward_info) {
1040       return string_builder << "MessageForwardInfo[" << (forward_info.is_imported ? "imported " : "") << "sender "
1041                             << forward_info.sender_user_id << "(" << forward_info.author_signature << "/"
1042                             << forward_info.sender_name << "), psa_type " << forward_info.psa_type << ", source "
1043                             << forward_info.sender_dialog_id << ", source " << forward_info.message_id << ", from "
1044                             << forward_info.from_dialog_id << ", from " << forward_info.from_message_id << " at "
1045                             << forward_info.date << " "
1046                             << "]";
1047     }
1048   };
1049 
1050   // Do not forget to update MessagesManager::update_message and all make_unique<Message> when this class is changed
1051   struct Message {
1052     int32 random_y = 0;
1053 
1054     MessageId message_id;
1055     UserId sender_user_id;
1056     DialogId sender_dialog_id;
1057     int32 date = 0;
1058     int32 edit_date = 0;
1059     int32 send_date = 0;
1060 
1061     int64 random_id = 0;
1062 
1063     unique_ptr<MessageForwardInfo> forward_info;
1064 
1065     MessageId reply_to_message_id;
1066     int64 reply_to_random_id = 0;  // for send_message
1067     DialogId reply_in_dialog_id;
1068     MessageId top_thread_message_id;
1069     MessageId linked_top_thread_message_id;
1070     vector<MessageId> local_thread_message_ids;
1071 
1072     UserId via_bot_user_id;
1073 
1074     vector<RestrictionReason> restriction_reasons;
1075 
1076     string author_signature;
1077 
1078     bool is_channel_post = false;
1079     bool is_outgoing = false;
1080     bool is_failed_to_send = false;
1081     bool disable_notification = false;
1082     bool contains_mention = false;
1083     bool contains_unread_mention = false;
1084     bool hide_edit_date = false;
1085     bool had_reply_markup = false;  // had non-inline reply markup?
1086     bool had_forward_info = false;
1087     bool is_content_secret = false;  // must be shown only while tapped
1088     bool is_mention_notification_disabled = false;
1089     bool is_from_scheduled = false;
1090     bool is_pinned = false;
1091     bool are_media_timestamp_entities_found = false;
1092     bool noforwards = false;
1093 
1094     bool has_explicit_sender = false;       // for send_message
1095     bool is_copy = false;                   // for send_message
1096     bool from_background = false;           // for send_message
1097     bool disable_web_page_preview = false;  // for send_message
1098     bool clear_draft = false;               // for send_message
1099     bool in_game_share = false;             // for send_message
1100     bool hide_via_bot = false;              // for resend_message
1101     bool is_bot_start_message = false;      // for resend_message
1102 
1103     bool have_previous = false;
1104     bool have_next = false;
1105     bool from_database = false;
1106 
1107     DialogId real_forward_from_dialog_id;    // for resend_message
1108     MessageId real_forward_from_message_id;  // for resend_message
1109 
1110     string send_emoji;  // for send_message
1111 
1112     NotificationId notification_id;
1113     NotificationId removed_notification_id;
1114 
1115     int32 max_reply_media_timestamp = -1;
1116     int32 max_own_media_timestamp = -2;  // to update replied messages on the first load
1117 
1118     int32 view_count = 0;
1119     int32 forward_count = 0;
1120     MessageReplyInfo reply_info;
1121     unique_ptr<DraftMessage> thread_draft_message;
1122     int32 interaction_info_update_date = 0;
1123 
1124     int32 legacy_layer = 0;
1125 
1126     int32 send_error_code = 0;
1127     string send_error_message;
1128     double try_resend_at = 0;
1129 
1130     int32 ttl_period = 0;       // counted from message send date
1131     int32 ttl = 0;              // counted from message content view date
1132     double ttl_expires_at = 0;  // only for TTL
1133 
1134     int64 media_album_id = 0;
1135 
1136     unique_ptr<MessageContent> content;
1137 
1138     unique_ptr<ReplyMarkup> reply_markup;
1139 
1140     int32 edited_schedule_date = 0;
1141     unique_ptr<MessageContent> edited_content;
1142     unique_ptr<ReplyMarkup> edited_reply_markup;
1143     uint64 edit_generation = 0;
1144     Promise<Unit> edit_promise;
1145 
1146     int32 last_edit_pts = 0;
1147 
1148     const char *debug_source = "null";
1149 
1150     unique_ptr<Message> left;
1151     unique_ptr<Message> right;
1152 
1153     mutable int32 last_access_date = 0;
1154     mutable bool is_update_sent = false;  // whether the message is known to the app
1155 
1156     mutable uint64 send_message_log_event_id = 0;
1157 
1158     mutable NetQueryRef send_query_ref;
1159 
1160     template <class StorerT>
1161     void store(StorerT &storer) const;
1162 
1163     template <class ParserT>
1164     void parse(ParserT &parser);
1165   };
1166 
1167   struct NotificationGroupInfo {
1168     NotificationGroupId group_id;
1169     int32 last_notification_date = 0;            // date of last notification in the group
1170     NotificationId last_notification_id;         // identifier of last notification in the group
1171     NotificationId max_removed_notification_id;  // notification identifier, up to which all notifications are removed
1172     MessageId max_removed_message_id;            // message identifier, up to which all notifications are removed
1173     bool is_changed = false;                     // true, if the group needs to be saved to database
1174     bool try_reuse = false;  // true, if the group needs to be deleted from database and tried to be reused
1175 
1176     template <class StorerT>
1177     void store(StorerT &storer) const;
1178 
1179     template <class ParserT>
1180     void parse(ParserT &parser);
1181   };
1182 
1183   struct Dialog {
1184     DialogId dialog_id;
1185     MessageId last_new_message_id;  // identifier of the last known server message received from update, there should be
1186                                     // no server messages after it
1187     MessageId last_message_id;      // identifier of the message after which currently there are no messages, i.e. a
1188                                     // message without a gap after it, memory only
1189     MessageId first_database_message_id;  // identifier of the first message in the database, needed
1190                                           // until there are no gaps in the database
1191     MessageId last_database_message_id;   // identifier of the last local or server message, if last_database_message_id
1192                                           // is known and last_message_id is known, then last_database_message_id <=
1193                                           // last_message_id
1194 
1195     std::array<MessageId, message_search_filter_count()> first_database_message_id_by_index;
1196     // use struct Count?
1197     std::array<int32, message_search_filter_count()> message_count_by_index{{0}};
1198 
1199     int32 server_unread_count = 0;
1200     int32 local_unread_count = 0;
1201     int32 unread_mention_count = 0;
1202     int32 last_read_inbox_message_date = 0;  // secret chats only
1203     MessageId last_read_inbox_message_id;
1204     MessageId last_read_outbox_message_id;
1205     MessageId last_pinned_message_id;
1206     MessageId reply_markup_message_id;
1207     DialogNotificationSettings notification_settings;
1208     MessageTtlSetting message_ttl_setting;
1209     unique_ptr<DraftMessage> draft_message;
1210     unique_ptr<DialogActionBar> action_bar;
1211     LogEventIdWithGeneration save_draft_message_log_event_id;
1212     LogEventIdWithGeneration save_notification_settings_log_event_id;
1213     std::unordered_map<int64, LogEventIdWithGeneration> read_history_log_event_ids;
1214     std::unordered_set<MessageId, MessageIdHash> updated_read_history_message_ids;
1215     LogEventIdWithGeneration set_folder_id_log_event_id;
1216     InputGroupCallId active_group_call_id;
1217     InputGroupCallId expected_active_group_call_id;
1218     DialogId default_join_group_call_as_dialog_id;
1219     DialogId default_send_message_as_dialog_id;
1220     string theme_name;
1221     int32 pending_join_request_count = 0;
1222     vector<UserId> pending_join_request_user_ids;
1223 
1224     FolderId folder_id;
1225     vector<DialogListId> dialog_list_ids;  // TODO replace with mask
1226 
1227     MessageId
1228         last_read_all_mentions_message_id;  // all mentions with a message identifier not greater than it are implicitly read
1229     MessageId
1230         max_unavailable_message_id;  // maximum unavailable message identifier for dialogs with cleared/unavailable history
1231 
1232     int32 last_clear_history_date = 0;
1233     MessageId last_clear_history_message_id;
1234     int64 order = DEFAULT_ORDER;
1235     MessageId deleted_last_message_id;
1236     int32 delete_last_message_date = 0;
1237     int32 pending_last_message_date = 0;
1238     MessageId pending_last_message_id;
1239     MessageId max_notification_message_id;
1240     MessageId last_edited_message_id;
1241     uint32 scheduled_messages_sync_generation = 0;
1242     uint32 last_repair_scheduled_messages_generation = 0;
1243 
1244     MessageId max_added_message_id;
1245     MessageId being_added_message_id;
1246     MessageId being_updated_last_new_message_id;
1247     MessageId being_updated_last_database_message_id;
1248     MessageId being_deleted_message_id;
1249 
1250     NotificationGroupInfo message_notification_group;
1251     NotificationGroupInfo mention_notification_group;
1252     NotificationId new_secret_chat_notification_id;  // secret chats only
1253     MessageId pinned_message_notification_message_id;
1254 
1255     bool has_contact_registered_message = false;
1256 
1257     bool is_last_message_deleted_locally = false;
1258 
1259     bool need_repair_action_bar = false;
1260     bool know_action_bar = false;
1261     bool has_outgoing_messages = false;
1262 
1263     bool is_opened = false;
1264     bool was_opened = false;
1265 
1266     bool need_restore_reply_markup = true;
1267 
1268     bool have_full_history = false;
1269     bool is_empty = false;
1270 
1271     bool is_last_read_inbox_message_id_inited = false;
1272     bool is_last_read_outbox_message_id_inited = false;
1273     bool is_last_pinned_message_id_inited = false;
1274     bool is_folder_id_inited = false;
1275     bool need_repair_server_unread_count = false;
1276     bool need_repair_channel_server_unread_count = false;
1277     bool is_marked_as_unread = false;
1278     bool is_blocked = false;
1279     bool is_is_blocked_inited = false;
1280     bool last_sent_has_scheduled_messages = false;
1281     bool has_scheduled_server_messages = false;
1282     bool has_scheduled_database_messages = false;
1283     bool is_has_scheduled_database_messages_checked = false;
1284     bool has_loaded_scheduled_messages_from_database = false;
1285     bool sent_scheduled_messages = false;
1286     bool had_last_yet_unsent_message = false;  // whether the dialog was stored to database without last message
1287     bool has_active_group_call = false;
1288     bool is_group_call_empty = false;
1289     bool is_message_ttl_setting_inited = false;
1290     bool has_expected_active_group_call_id = false;
1291     bool has_bots = false;
1292     bool is_has_bots_inited = false;
1293     bool is_theme_name_inited = false;
1294 
1295     bool increment_view_counter = false;
1296 
1297     bool is_update_new_chat_sent = false;
1298     bool has_unload_timeout = false;
1299     bool is_channel_difference_finished = false;
1300 
1301     bool suffix_load_done_ = false;
1302     bool suffix_load_has_query_ = false;
1303 
1304     int32 pts = 0;                                                 // for channels only
1305     int32 pending_read_channel_inbox_pts = 0;                      // for channels only
1306     int32 pending_read_channel_inbox_server_unread_count = 0;      // for channels only
1307     MessageId pending_read_channel_inbox_max_message_id;           // for channels only
1308     std::unordered_map<int64, MessageId> random_id_to_message_id;  // for secret chats only
1309 
1310     MessageId last_assigned_message_id;  // identifier of the last local or yet unsent message, assigned after
1311                                          // application start, used to guarantee that all assigned message identifiers
1312                                          // are different
1313 
1314     std::unordered_map<MessageId, std::set<MessageId>, MessageIdHash>
1315         yet_unsent_thread_message_ids;  // top_thread_message_id -> yet unsent message IDs
1316 
1317     std::unordered_map<ScheduledServerMessageId, int32, ScheduledServerMessageIdHash> scheduled_message_date;
1318 
1319     std::unordered_map<MessageId, MessageId, MessageIdHash> yet_unsent_message_id_to_persistent_message_id;
1320 
1321     std::unordered_map<int32, MessageId> last_assigned_scheduled_message_id;  // date -> message_id
1322 
1323     std::unordered_set<MessageId, MessageIdHash> deleted_message_ids;
1324     std::unordered_set<ScheduledServerMessageId, ScheduledServerMessageIdHash> deleted_scheduled_server_message_ids;
1325 
1326     std::vector<std::pair<DialogId, MessageId>> pending_new_message_notifications;
1327     std::vector<std::pair<DialogId, MessageId>> pending_new_mention_notifications;
1328 
1329     std::unordered_map<NotificationId, MessageId, NotificationIdHash> notification_id_to_message_id;
1330 
1331     string client_data;
1332 
1333     // Load from newest to oldest message
1334     MessageId suffix_load_first_message_id_;  // identifier of some message such all suffix messages in range
1335                                               // [suffix_load_first_message_id_, last_message_id] are loaded
1336     MessageId suffix_load_query_message_id_;
1337     std::vector<std::pair<Promise<>, std::function<bool(const Message *)>>> suffix_load_queries_;
1338 
1339     std::unordered_map<MessageId, int64, MessageIdHash> pending_viewed_live_locations;  // message_id -> task_id
1340     std::unordered_set<MessageId, MessageIdHash> pending_viewed_message_ids;
1341 
1342     unique_ptr<Message> messages;
1343     unique_ptr<Message> scheduled_messages;
1344 
1345     struct MessageOp {
1346       enum : int8 { Add, SetPts, Delete, DeleteAll } type;
1347       bool from_update = false;
1348       bool have_previous = false;
1349       bool have_next = false;
1350       MessageContentType content_type = MessageContentType::None;
1351       int32 pts = 0;
1352       MessageId message_id;
1353       const char *source = nullptr;
1354       double date = 0;
1355 
MessageOpDialog::MessageOp1356       MessageOp(decltype(type) type, MessageId message_id, MessageContentType content_type, bool from_update,
1357                 bool have_previous, bool have_next, const char *source)
1358           : type(type)
1359           , from_update(from_update)
1360           , have_previous(have_previous)
1361           , have_next(have_next)
1362           , content_type(content_type)
1363           , message_id(message_id)
1364           , source(source)
1365           , date(G()->server_time()) {
1366       }
1367 
MessageOpDialog::MessageOp1368       MessageOp(decltype(type) type, int32 pts, const char *source)
1369           : type(type), pts(pts), source(source), date(G()->server_time()) {
1370       }
1371     };
1372 
1373     const char *debug_set_dialog_last_database_message_id = "Unknown";  // to be removed soon
1374     vector<MessageOp> debug_message_op;
1375 
1376     // message identifiers loaded from database
1377     MessageId debug_last_new_message_id;
1378     MessageId debug_first_database_message_id;
1379     MessageId debug_last_database_message_id;
1380 
1381     Dialog() = default;
1382     Dialog(const Dialog &) = delete;
1383     Dialog &operator=(const Dialog &) = delete;
1384     Dialog(Dialog &&other) = delete;
1385     Dialog &operator=(Dialog &&other) = delete;
1386     ~Dialog();
1387 
1388     template <class StorerT>
1389     void store(StorerT &storer) const;
1390 
1391     template <class ParserT>
1392     void parse(ParserT &parser);
1393   };
1394 
1395   struct RecommendedDialogFilter {
1396     unique_ptr<DialogFilter> dialog_filter;
1397     string description;
1398   };
1399 
1400   struct DialogList {
1401     DialogListId dialog_list_id;
1402     bool is_message_unread_count_inited_ = false;
1403     bool is_dialog_unread_count_inited_ = false;
1404     bool need_unread_count_recalc_ = true;
1405     int32 unread_message_total_count_ = 0;
1406     int32 unread_message_muted_count_ = 0;
1407     int32 unread_dialog_total_count_ = 0;
1408     int32 unread_dialog_muted_count_ = 0;
1409     int32 unread_dialog_marked_count_ = 0;
1410     int32 unread_dialog_muted_marked_count_ = 0;
1411     int32 in_memory_dialog_total_count_ = 0;
1412     int32 server_dialog_total_count_ = -1;
1413     int32 secret_chat_total_count_ = -1;
1414 
1415     vector<Promise<Unit>> load_list_queries_;
1416 
1417     std::unordered_map<DialogId, int64, DialogIdHash> pinned_dialog_id_orders_;
1418     vector<DialogDate> pinned_dialogs_;
1419     bool are_pinned_dialogs_inited_ = false;
1420 
1421     DialogDate last_pinned_dialog_date_ = MIN_DIALOG_DATE;  // in memory
1422 
1423     // date of the last loaded dialog
1424     // min(folder1_last_dialog_date_, folder2_last_dialog_date, last_pinned_dialog_date_)
1425     DialogDate list_last_dialog_date_ = MIN_DIALOG_DATE;  // in memory
1426   };
1427 
1428   struct DialogFolder {
1429     FolderId folder_id;
1430     // date of the last loaded dialog in the folder
1431     DialogDate folder_last_dialog_date_{MAX_ORDINARY_DIALOG_ORDER, DialogId()};  // in memory
1432 
1433     std::set<DialogDate> ordered_dialogs_;  // all known dialogs, including with default order
1434 
1435     // date of last known user/group/channel dialog in the right order
1436     DialogDate last_server_dialog_date_{MAX_ORDINARY_DIALOG_ORDER, DialogId()};
1437     DialogDate last_loaded_database_dialog_date_{MAX_ORDINARY_DIALOG_ORDER, DialogId()};
1438     DialogDate last_database_server_dialog_date_{MAX_ORDINARY_DIALOG_ORDER, DialogId()};
1439 
1440     MultiPromiseActor load_folder_dialog_list_multipromise_{
1441         "LoadDialogListMultiPromiseActor"};  // must be defined before pending_on_get_dialogs_
1442     int32 load_dialog_list_limit_max_ = 0;
1443   };
1444 
1445   class DialogListViewIterator {
1446     MessagesManager *messages_manager_;
1447     const DialogListId *dialog_list_id_;
1448 
1449    public:
DialogListViewIterator(MessagesManager * messages_manager,const DialogListId * dialog_list_id)1450     DialogListViewIterator(MessagesManager *messages_manager, const DialogListId *dialog_list_id)
1451         : messages_manager_(messages_manager), dialog_list_id_(dialog_list_id) {
1452     }
1453 
1454     DialogList &operator*() const {
1455       auto dialog_list_ptr = messages_manager_->get_dialog_list(*dialog_list_id_);
1456       CHECK(dialog_list_ptr != nullptr);
1457       return *dialog_list_ptr;
1458     }
1459 
1460     bool operator!=(const DialogListViewIterator &other) const {
1461       return dialog_list_id_ != other.dialog_list_id_;
1462     }
1463 
1464     void operator++() {
1465       dialog_list_id_++;
1466     }
1467   };
1468 
1469   class DialogListView {
1470     MessagesManager *messages_manager_;
1471     // TODO can be optimized to store only mask of dialog lists
1472     vector<DialogListId> dialog_list_ids_;
1473 
1474    public:
DialogListView(MessagesManager * messages_manager,vector<DialogListId> dialog_list_ids)1475     DialogListView(MessagesManager *messages_manager, vector<DialogListId> dialog_list_ids)
1476         : messages_manager_(messages_manager), dialog_list_ids_(std::move(dialog_list_ids)) {
1477     }
1478 
begin()1479     DialogListViewIterator begin() {
1480       return DialogListViewIterator(messages_manager_, dialog_list_ids_.empty() ? nullptr : &dialog_list_ids_[0]);
1481     }
1482 
end()1483     DialogListViewIterator end() {
1484       return DialogListViewIterator(
1485           messages_manager_, dialog_list_ids_.empty() ? nullptr : &dialog_list_ids_[0] + dialog_list_ids_.size());
1486     }
1487   };
1488 
1489   struct DialogPositionInList {
1490     int64 order = DEFAULT_ORDER;
1491     int64 private_order = 0;
1492     int64 public_order = 0;
1493     bool is_pinned = false;
1494     bool is_sponsored = false;
1495 
1496     int32 total_dialog_count = 0;
1497 
1498     friend StringBuilder &operator<<(StringBuilder &string_builder, const DialogPositionInList &order) {
1499       return string_builder << "order = " << order.order << ", private_order = " << order.private_order
1500                             << ", public_order = " << order.public_order << ", is_pinned = " << order.is_pinned
1501                             << ", is_sponsored = " << order.is_sponsored
1502                             << ", total_dialog_count = " << order.total_dialog_count;
1503     }
1504   };
1505 
1506   class MessagesIteratorBase {
1507     vector<const Message *> stack_;
1508 
1509    protected:
1510     MessagesIteratorBase() = default;
1511 
1512     // points iterator to message with greatest id which is less or equal than message_id
MessagesIteratorBase(const Message * root,MessageId message_id)1513     MessagesIteratorBase(const Message *root, MessageId message_id) {
1514       size_t last_right_pos = 0;
1515       while (root != nullptr) {
1516         //        LOG(DEBUG) << "Have root->message_id = " << root->message_id;
1517         stack_.push_back(root);
1518         if (root->message_id <= message_id) {
1519           //          LOG(DEBUG) << "Go right";
1520           last_right_pos = stack_.size();
1521           root = root->right.get();
1522         } else {
1523           //          LOG(DEBUG) << "Go left";
1524           root = root->left.get();
1525         }
1526       }
1527       stack_.resize(last_right_pos);
1528     }
1529 
1530     const Message *operator*() const {
1531       return stack_.empty() ? nullptr : stack_.back();
1532     }
1533 
1534     ~MessagesIteratorBase() = default;
1535 
1536    public:
1537     MessagesIteratorBase(const MessagesIteratorBase &) = delete;
1538     MessagesIteratorBase &operator=(const MessagesIteratorBase &) = delete;
1539     MessagesIteratorBase(MessagesIteratorBase &&other) = default;
1540     MessagesIteratorBase &operator=(MessagesIteratorBase &&other) = default;
1541 
1542     void operator++() {
1543       if (stack_.empty()) {
1544         return;
1545       }
1546 
1547       const Message *cur = stack_.back();
1548       if (!cur->have_next) {
1549         stack_.clear();
1550         return;
1551       }
1552       if (cur->right == nullptr) {
1553         while (true) {
1554           stack_.pop_back();
1555           if (stack_.empty()) {
1556             return;
1557           }
1558           const Message *new_cur = stack_.back();
1559           if (new_cur->left.get() == cur) {
1560             return;
1561           }
1562           cur = new_cur;
1563         }
1564       }
1565 
1566       cur = cur->right.get();
1567       while (cur != nullptr) {
1568         stack_.push_back(cur);
1569         cur = cur->left.get();
1570       }
1571     }
1572 
1573     void operator--() {
1574       if (stack_.empty()) {
1575         return;
1576       }
1577 
1578       const Message *cur = stack_.back();
1579       if (!cur->have_previous) {
1580         stack_.clear();
1581         return;
1582       }
1583       if (cur->left == nullptr) {
1584         while (true) {
1585           stack_.pop_back();
1586           if (stack_.empty()) {
1587             return;
1588           }
1589           const Message *new_cur = stack_.back();
1590           if (new_cur->right.get() == cur) {
1591             return;
1592           }
1593           cur = new_cur;
1594         }
1595       }
1596 
1597       cur = cur->left.get();
1598       while (cur != nullptr) {
1599         stack_.push_back(cur);
1600         cur = cur->right.get();
1601       }
1602     }
1603   };
1604 
1605   class MessagesIterator final : public MessagesIteratorBase {
1606    public:
1607     MessagesIterator() = default;
1608 
MessagesIterator(Dialog * d,MessageId message_id)1609     MessagesIterator(Dialog *d, MessageId message_id)
1610         : MessagesIteratorBase(message_id.is_scheduled() ? d->scheduled_messages.get() : d->messages.get(),
1611                                message_id) {
1612     }
1613 
1614     Message *operator*() const {
1615       return const_cast<Message *>(MessagesIteratorBase::operator*());
1616     }
1617   };
1618 
1619   class MessagesConstIterator final : public MessagesIteratorBase {
1620    public:
1621     MessagesConstIterator() = default;
1622 
MessagesConstIterator(const Dialog * d,MessageId message_id)1623     MessagesConstIterator(const Dialog *d, MessageId message_id)
1624         : MessagesIteratorBase(message_id.is_scheduled() ? d->scheduled_messages.get() : d->messages.get(),
1625                                message_id) {
1626     }
1627 
1628     const Message *operator*() const {
1629       return MessagesIteratorBase::operator*();
1630     }
1631   };
1632 
1633   struct PendingSecretMessage {
1634     enum class Type : int32 { NewMessage, DeleteMessages, DeleteHistory };
1635     Type type = Type::NewMessage;
1636 
1637     // for NewMessage
1638     MessageInfo message_info;
1639     MultiPromiseActor load_data_multipromise{"LoadPendingSecretMessageDataMultiPromiseActor"};
1640 
1641     // for DeleteMessages/DeleteHistory
1642     DialogId dialog_id;
1643     vector<int64> random_ids;
1644     MessageId last_message_id;
1645     bool remove_from_dialog_list = false;
1646 
1647     Promise<> success_promise;
1648   };
1649 
1650   struct MessageSendOptions {
1651     bool disable_notification = false;
1652     bool from_background = false;
1653     int32 schedule_date = 0;
1654 
1655     MessageSendOptions() = default;
MessageSendOptionsMessageSendOptions1656     MessageSendOptions(bool disable_notification, bool from_background, int32 schedule_date)
1657         : disable_notification(disable_notification), from_background(from_background), schedule_date(schedule_date) {
1658     }
1659   };
1660 
1661   class BlockMessageSenderFromRepliesOnServerLogEvent;
1662   class DeleteAllCallMessagesOnServerLogEvent;
1663   class DeleteAllChannelMessagesFromSenderOnServerLogEvent;
1664   class DeleteDialogHistoryOnServerLogEvent;
1665   class DeleteDialogMessagesByDateOnServerLogEvent;
1666   class DeleteMessageLogEvent;
1667   class DeleteMessagesOnServerLogEvent;
1668   class DeleteScheduledMessagesOnServerLogEvent;
1669   class ForwardMessagesLogEvent;
1670   class GetChannelDifferenceLogEvent;
1671   class ReadAllDialogMentionsOnServerLogEvent;
1672   class ReadHistoryInSecretChatLogEvent;
1673   class ReadHistoryOnServerLogEvent;
1674   class ReadMessageContentsOnServerLogEvent;
1675   class ReadMessageThreadHistoryOnServerLogEvent;
1676   class RegetDialogLogEvent;
1677   class ReorderPinnedDialogsOnServerLogEvent;
1678   class ResetAllNotificationSettingsOnServerLogEvent;
1679   class SaveDialogDraftMessageOnServerLogEvent;
1680   class SendBotStartMessageLogEvent;
1681   class SendInlineQueryResultMessageLogEvent;
1682   class SendMessageLogEvent;
1683   class SendScreenshotTakenNotificationMessageLogEvent;
1684   class SetDialogFolderIdOnServerLogEvent;
1685   class ToggleDialogIsBlockedOnServerLogEvent;
1686   class ToggleDialogIsMarkedAsUnreadOnServerLogEvent;
1687   class ToggleDialogIsPinnedOnServerLogEvent;
1688   class ToggleDialogReportSpamStateOnServerLogEvent;
1689   class UnpinAllDialogMessagesOnServerLogEvent;
1690   class UpdateDialogNotificationSettingsOnServerLogEvent;
1691   class UpdateScopeNotificationSettingsOnServerLogEvent;
1692 
1693   class DialogFiltersLogEvent;
1694 
1695   static constexpr size_t MAX_GROUPED_MESSAGES = 10;               // server side limit
1696   static constexpr int32 MAX_GET_DIALOGS = 100;                    // server side limit
1697   static constexpr int32 MAX_GET_HISTORY = 100;                    // server side limit
1698   static constexpr int32 MAX_SEARCH_MESSAGES = 100;                // server side limit
1699   static constexpr int32 MIN_SEARCH_PUBLIC_DIALOG_PREFIX_LEN = 4;  // server side limit
1700   static constexpr int32 MIN_CHANNEL_DIFFERENCE = 1;
1701   static constexpr int32 MAX_CHANNEL_DIFFERENCE = 100;
1702   static constexpr int32 MAX_BOT_CHANNEL_DIFFERENCE = 100000;   // server side limit
1703   static constexpr int32 MAX_RECENT_DIALOGS = 50;               // some reasonable value
1704   static constexpr size_t MAX_TITLE_LENGTH = 128;               // server side limit for chat title
1705   static constexpr size_t MAX_DESCRIPTION_LENGTH = 255;         // server side limit for chat description
1706   static constexpr size_t MAX_DIALOG_FILTER_TITLE_LENGTH = 12;  // server side limit for dialog filter title
1707   static constexpr int32 MAX_PRIVATE_MESSAGE_TTL = 60;          // server side limit
1708   static constexpr int32 MAX_DIALOG_FILTERS = 10;               // server side limit
1709   static constexpr int32 DIALOG_FILTERS_CACHE_TIME = 86400;
1710 
1711   static constexpr int64 SPONSORED_DIALOG_ORDER = static_cast<int64>(2147483647) << 32;
1712   static constexpr int32 MIN_PINNED_DIALOG_DATE = 2147000000;  // some big date
1713   static constexpr int64 MAX_ORDINARY_DIALOG_ORDER =
1714       9221294780217032704;  // == get_dialog_order(MessageId(), MIN_PINNED_DIALOG_DATE - 1)
1715 
1716   static constexpr int32 UPDATE_CHANNEL_TO_LONG_FLAG_HAS_PTS = 1 << 0;
1717 
1718   static constexpr int32 CHANNEL_DIFFERENCE_FLAG_IS_FINAL = 1 << 0;
1719   static constexpr int32 CHANNEL_DIFFERENCE_FLAG_HAS_TIMEOUT = 1 << 1;
1720 
1721   static constexpr int32 DIALOG_FLAG_HAS_PTS = 1 << 0;
1722   static constexpr int32 DIALOG_FLAG_HAS_DRAFT = 1 << 1;
1723   static constexpr int32 DIALOG_FLAG_IS_PINNED = 1 << 2;
1724   static constexpr int32 DIALOG_FLAG_HAS_FOLDER_ID = 1 << 4;
1725 
1726   static constexpr int32 MAX_MESSAGE_VIEW_DELAY = 1;  // seconds
1727   static constexpr int32 MIN_SAVE_DRAFT_DELAY = 1;    // seconds
1728   static constexpr int32 MIN_READ_HISTORY_DELAY = 3;  // seconds
1729   static constexpr int32 MAX_SAVE_DIALOG_DELAY = 0;   // seconds
1730 
1731   static constexpr int32 LIVE_LOCATION_VIEW_PERIOD = 60;  // seconds, server-side limit
1732 
1733   static constexpr int32 USERNAME_CACHE_EXPIRE_TIME = 3 * 86400;
1734   static constexpr int32 USERNAME_CACHE_EXPIRE_TIME_SHORT = 900;
1735   static constexpr int32 AUTH_NOTIFICATION_ID_CACHE_TIME = 7 * 86400;
1736 
1737   static constexpr int32 ONLINE_MEMBER_COUNT_UPDATE_TIME = 5 * 60;
1738 
1739   static constexpr int32 MAX_RESEND_DELAY = 86400;  // seconds, some resonable limit
1740 
1741   static constexpr int32 SCHEDULE_WHEN_ONLINE_DATE = 2147483646;
1742 
1743   static constexpr double DIALOG_ACTION_TIMEOUT = 5.5;
1744 
1745   static constexpr const char *DELETE_MESSAGE_USER_REQUEST_SOURCE = "user request";
1746 
1747   static constexpr bool DROP_SEND_MESSAGE_UPDATES = false;
1748 
1749   static FullMessageId get_full_message_id(const tl_object_ptr<telegram_api::Message> &message_ptr, bool is_scheduled);
1750 
1751   static int32 get_message_date(const tl_object_ptr<telegram_api::Message> &message_ptr);
1752 
1753   static bool is_dialog_inited(const Dialog *d);
1754 
1755   int32 get_dialog_mute_until(const Dialog *d) const;
1756 
1757   bool is_dialog_muted(const Dialog *d) const;
1758 
1759   bool is_dialog_pinned_message_notifications_disabled(const Dialog *d) const;
1760 
1761   bool is_dialog_mention_notifications_disabled(const Dialog *d) const;
1762 
1763   bool is_dialog_pinned(DialogListId dialog_list_id, DialogId dialog_id) const;
1764 
1765   int64 get_dialog_pinned_order(DialogListId dialog_list_id, DialogId dialog_id) const;
1766 
1767   static int64 get_dialog_pinned_order(const DialogList *list, DialogId dialog_id);
1768 
1769   void open_dialog(Dialog *d);
1770 
1771   void close_dialog(Dialog *d);
1772 
1773   DialogId get_my_dialog_id() const;
1774 
1775   void on_resolve_secret_chat_message_via_bot_username(const string &via_bot_username, MessageInfo *message_info_ptr,
1776                                                        Promise<Unit> &&promise);
1777 
1778   void add_secret_message(unique_ptr<PendingSecretMessage> pending_secret_message, Promise<Unit> lock_promise = Auto());
1779 
1780   void on_add_secret_message_ready(int64 token);
1781 
1782   void finish_add_secret_message(unique_ptr<PendingSecretMessage> pending_secret_message);
1783 
1784   void finish_delete_secret_messages(DialogId dialog_id, std::vector<int64> random_ids, Promise<> promise);
1785 
1786   void finish_delete_secret_chat_history(DialogId dialog_id, bool remove_from_dialog_list, MessageId last_message_id,
1787                                          Promise<> promise);
1788 
1789   MessageInfo parse_telegram_api_message(tl_object_ptr<telegram_api::Message> message_ptr, bool is_scheduled,
1790                                          const char *source) const;
1791 
1792   std::pair<DialogId, unique_ptr<Message>> create_message(MessageInfo &&message_info, bool is_channel_message);
1793 
1794   MessageId find_old_message_id(DialogId dialog_id, MessageId message_id) const;
1795 
1796   void delete_update_message_id(DialogId dialog_id, MessageId message_id);
1797 
1798   FullMessageId on_get_message(MessageInfo &&message_info, bool from_update, bool is_channel_message,
1799                                bool have_previous, bool have_next, const char *source);
1800 
1801   Result<InputMessageContent> process_input_message_content(
1802       DialogId dialog_id, tl_object_ptr<td_api::InputMessageContent> &&input_message_content);
1803 
1804   Result<MessageCopyOptions> process_message_copy_options(DialogId dialog_id,
1805                                                           tl_object_ptr<td_api::messageCopyOptions> &&options) const;
1806 
1807   Result<MessageSendOptions> process_message_send_options(DialogId dialog_id,
1808                                                           tl_object_ptr<td_api::messageSendOptions> &&options) const;
1809 
1810   static Status can_use_message_send_options(const MessageSendOptions &options,
1811                                              const unique_ptr<MessageContent> &content, int32 ttl);
1812   static Status can_use_message_send_options(const MessageSendOptions &options, const InputMessageContent &content);
1813 
1814   Status can_use_top_thread_message_id(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id);
1815 
1816   bool is_anonymous_administrator(DialogId dialog_id, string *author_signature) const;
1817 
1818   int64 generate_new_random_id();
1819 
1820   unique_ptr<Message> create_message_to_send(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id,
1821                                              const MessageSendOptions &options, unique_ptr<MessageContent> &&content,
1822                                              bool suppress_reply_info, unique_ptr<MessageForwardInfo> forward_info,
1823                                              bool is_copy, DialogId send_as_dialog_id) const;
1824 
1825   Message *get_message_to_send(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id,
1826                                const MessageSendOptions &options, unique_ptr<MessageContent> &&content,
1827                                bool *need_update_dialog_pos, bool suppress_reply_info = false,
1828                                unique_ptr<MessageForwardInfo> forward_info = nullptr, bool is_copy = false,
1829                                DialogId sender_dialog_id = DialogId());
1830 
1831   int64 begin_send_message(DialogId dialog_id, const Message *m);
1832 
1833   Status can_send_message(DialogId dialog_id) const TD_WARN_UNUSED_RESULT;
1834 
1835   bool can_resend_message(const Message *m) const;
1836 
1837   bool can_edit_message(DialogId dialog_id, const Message *m, bool is_editing, bool only_reply_markup = false) const;
1838 
1839   static bool can_overflow_message_id(DialogId dialog_id);
1840 
1841   bool can_report_dialog(DialogId dialog_id) const;
1842 
1843   Status can_pin_messages(DialogId dialog_id) const;
1844 
1845   static Status can_get_media_timestamp_link(DialogId dialog_id, const Message *m);
1846 
1847   Status can_get_message_viewers(FullMessageId full_message_id) TD_WARN_UNUSED_RESULT;
1848 
1849   Status can_get_message_viewers(DialogId dialog_id, const Message *m) const TD_WARN_UNUSED_RESULT;
1850 
1851   void cancel_edit_message_media(DialogId dialog_id, Message *m, Slice error_message);
1852 
1853   void on_message_media_edited(DialogId dialog_id, MessageId message_id, FileId file_id, FileId thumbnail_file_id,
1854                                bool was_uploaded, bool was_thumbnail_uploaded, string file_reference,
1855                                int32 schedule_date, uint64 generation, Result<int32> &&result);
1856 
1857   static MessageId get_persistent_message_id(const Dialog *d, MessageId message_id);
1858 
1859   static FullMessageId get_replied_message_id(DialogId dialog_id, const Message *m);
1860 
1861   MessageId get_reply_to_message_id(Dialog *d, MessageId top_thread_message_id, MessageId message_id, bool for_draft);
1862 
1863   static void fix_server_reply_to_message_id(DialogId dialog_id, MessageId message_id, DialogId reply_in_dialog_id,
1864                                              MessageId &reply_to_message_id);
1865 
1866   bool can_set_game_score(DialogId dialog_id, const Message *m) const;
1867 
1868   void add_postponed_channel_update(DialogId dialog_id, tl_object_ptr<telegram_api::Update> &&update, int32 new_pts,
1869                                     int32 pts_count, Promise<Unit> &&promise);
1870 
1871   void process_channel_update(tl_object_ptr<telegram_api::Update> &&update);
1872 
1873   void on_message_edited(FullMessageId full_message_id, int32 pts);
1874 
1875   void delete_messages_from_updates(const vector<MessageId> &message_ids);
1876 
1877   void delete_dialog_messages(DialogId dialog_id, const vector<MessageId> &message_ids, bool from_updates,
1878                               bool skip_update_for_not_found_messages, const char *source);
1879 
1880   void update_dialog_pinned_messages_from_updates(DialogId dialog_id, const vector<MessageId> &message_ids,
1881                                                   bool is_pin);
1882 
1883   bool update_message_is_pinned(Dialog *d, Message *m, bool is_pin, const char *source);
1884 
1885   void do_forward_messages(DialogId to_dialog_id, DialogId from_dialog_id, const vector<Message *> &messages,
1886                            const vector<MessageId> &message_ids, uint64 log_event_id);
1887 
1888   Result<td_api::object_ptr<td_api::message>> forward_message(DialogId to_dialog_id, DialogId from_dialog_id,
1889                                                               MessageId message_id,
1890                                                               tl_object_ptr<td_api::messageSendOptions> &&options,
1891                                                               bool in_game_share,
1892                                                               MessageCopyOptions &&copy_options) TD_WARN_UNUSED_RESULT;
1893 
1894   unique_ptr<MessageForwardInfo> create_message_forward_info(DialogId from_dialog_id, DialogId to_dialog_id,
1895                                                              const Message *forwarded_message) const;
1896 
1897   void fix_forwarded_message(Message *m, DialogId to_dialog_id, const Message *forwarded_message,
1898                              int64 media_album_id) const;
1899 
1900   struct ForwardedMessages {
1901     struct CopiedMessage {
1902       unique_ptr<MessageContent> content;
1903       MessageId top_thread_message_id;
1904       MessageId reply_to_message_id;
1905       unique_ptr<ReplyMarkup> reply_markup;
1906       int64 media_album_id;
1907       bool disable_web_page_preview;
1908       size_t index;
1909     };
1910     vector<CopiedMessage> copied_messages;
1911 
1912     struct ForwardedMessageContent {
1913       unique_ptr<MessageContent> content;
1914       int64 media_album_id;
1915       size_t index;
1916     };
1917     vector<ForwardedMessageContent> forwarded_message_contents;
1918 
1919     Dialog *from_dialog;
1920     Dialog *to_dialog;
1921     MessageSendOptions message_send_options;
1922   };
1923 
1924   Result<ForwardedMessages> get_forwarded_messages(DialogId to_dialog_id, DialogId from_dialog_id,
1925                                                    const vector<MessageId> &message_ids,
1926                                                    tl_object_ptr<td_api::messageSendOptions> &&options,
1927                                                    bool in_game_share, vector<MessageCopyOptions> &&copy_options);
1928 
1929   void do_send_media(DialogId dialog_id, Message *m, FileId file_id, FileId thumbnail_file_id,
1930                      tl_object_ptr<telegram_api::InputFile> input_file,
1931                      tl_object_ptr<telegram_api::InputFile> input_thumbnail);
1932 
1933   void do_send_secret_media(DialogId dialog_id, Message *m, FileId file_id, FileId thumbnail_file_id,
1934                             tl_object_ptr<telegram_api::InputEncryptedFile> input_encrypted_file,
1935                             BufferSlice thumbnail);
1936 
1937   void do_send_message(DialogId dialog_id, const Message *m, vector<int> bad_parts = {});
1938 
1939   void on_message_media_uploaded(DialogId dialog_id, const Message *m,
1940                                  tl_object_ptr<telegram_api::InputMedia> &&input_media, FileId file_id,
1941                                  FileId thumbnail_file_id);
1942 
1943   void on_secret_message_media_uploaded(DialogId dialog_id, const Message *m, SecretInputMedia &&secret_input_media,
1944                                         FileId file_id, FileId thumbnail_file_id);
1945 
1946   void on_upload_message_media_finished(int64 media_album_id, DialogId dialog_id, MessageId message_id, Status result);
1947 
1948   void do_send_message_group(int64 media_album_id);
1949 
1950   void on_text_message_ready_to_send(DialogId dialog_id, MessageId message_id);
1951 
1952   void on_media_message_ready_to_send(DialogId dialog_id, MessageId message_id, Promise<Message *> &&promise);
1953 
1954   void on_yet_unsent_media_queue_updated(DialogId dialog_id);
1955 
1956   static void save_send_bot_start_message_log_event(UserId bot_user_id, DialogId dialog_id, const string &parameter,
1957                                                     const Message *m);
1958 
1959   void do_send_bot_start_message(UserId bot_user_id, DialogId dialog_id, const string &parameter, const Message *m);
1960 
1961   static void save_send_inline_query_result_message_log_event(DialogId dialog_id, const Message *m, int64 query_id,
1962                                                               const string &result_id);
1963 
1964   void do_send_inline_query_result_message(DialogId dialog_id, const Message *m, int64 query_id,
1965                                            const string &result_id);
1966 
1967   static uint64 save_send_screenshot_taken_notification_message_log_event(DialogId dialog_id, const Message *m);
1968 
1969   void do_send_screenshot_taken_notification_message(DialogId dialog_id, const Message *m, uint64 log_event_id);
1970 
1971   Message *continue_send_message(DialogId dialog_id, unique_ptr<Message> &&m, uint64 log_event_id);
1972 
1973   bool is_message_unload_enabled() const;
1974 
1975   int64 generate_new_media_album_id();
1976 
1977   static bool can_forward_message(DialogId from_dialog_id, const Message *m);
1978 
1979   bool can_save_message(DialogId dialog_id, const Message *m) const;
1980 
1981   bool can_get_message_statistics(DialogId dialog_id, const Message *m) const;
1982 
1983   static bool can_delete_channel_message(const DialogParticipantStatus &status, const Message *m, bool is_bot);
1984 
1985   bool can_delete_message(DialogId dialog_id, const Message *m) const;
1986 
1987   bool can_revoke_message(DialogId dialog_id, const Message *m) const;
1988 
1989   bool can_unload_message(const Dialog *d, const Message *m) const;
1990 
1991   void unload_message(Dialog *d, MessageId message_id);
1992 
1993   unique_ptr<Message> delete_message(Dialog *d, MessageId message_id, bool is_permanently_deleted,
1994                                      bool *need_update_dialog_pos, const char *source);
1995 
1996   unique_ptr<Message> do_delete_message(Dialog *d, MessageId message_id, bool is_permanently_deleted,
1997                                         bool only_from_memory, bool *need_update_dialog_pos, const char *source);
1998 
1999   unique_ptr<Message> do_delete_scheduled_message(Dialog *d, MessageId message_id, bool is_permanently_deleted,
2000                                                   const char *source);
2001 
2002   void on_message_deleted(Dialog *d, Message *m, bool is_permanently_deleted, const char *source);
2003 
2004   int32 get_unload_dialog_delay() const;
2005 
2006   void unload_dialog(DialogId dialog_id);
2007 
2008   void delete_all_dialog_messages(Dialog *d, bool remove_from_dialog_list, bool is_permanently_deleted);
2009 
2010   void do_delete_all_dialog_messages(Dialog *d, unique_ptr<Message> &message, bool is_permanently_deleted,
2011                                      vector<int64> &deleted_message_ids);
2012 
2013   void erase_delete_messages_log_event(uint64 log_event_id);
2014 
2015   void delete_sent_message_on_server(DialogId dialog_id, MessageId message_id);
2016 
2017   void delete_messages_on_server(DialogId dialog_id, vector<MessageId> message_ids, bool revoke, uint64 log_event_id,
2018                                  Promise<Unit> &&promise);
2019 
2020   void delete_scheduled_messages_on_server(DialogId dialog_id, vector<MessageId> message_ids, uint64 log_event_id,
2021                                            Promise<Unit> &&promise);
2022 
2023   void delete_dialog_history_on_server(DialogId dialog_id, MessageId max_message_id, bool remove_from_dialog_list,
2024                                        bool revoke, bool allow_error, uint64 log_event_id, Promise<Unit> &&promise);
2025 
2026   void delete_all_call_messages_on_server(bool revoke, uint64 log_event_id, Promise<Unit> &&promise);
2027 
2028   void block_message_sender_from_replies_on_server(MessageId message_id, bool need_delete_message,
2029                                                    bool need_delete_all_messages, bool report_spam, uint64 log_event_id,
2030                                                    Promise<Unit> &&promise);
2031 
2032   void delete_all_channel_messages_by_sender_on_server(ChannelId channel_id, DialogId sender_dialog_id,
2033                                                        uint64 log_event_id, Promise<Unit> &&promise);
2034 
2035   void delete_dialog_messages_by_date_on_server(DialogId dialog_id, int32 min_date, int32 max_date, bool revoke,
2036                                                 uint64 log_event_id, Promise<Unit> &&promise);
2037 
2038   void read_all_dialog_mentions_on_server(DialogId dialog_id, uint64 log_event_id, Promise<Unit> &&promise);
2039 
2040   void unpin_all_dialog_messages_on_server(DialogId dialog_id, uint64 log_event_id, Promise<Unit> &&promise);
2041 
2042   using AffectedHistoryQuery = std::function<void(DialogId, Promise<AffectedHistory>)>;
2043 
2044   void run_affected_history_query_until_complete(DialogId dialog_id, AffectedHistoryQuery query,
2045                                                  bool get_affected_messages, Promise<Unit> &&promise);
2046 
2047   void on_get_affected_history(DialogId dialog_id, AffectedHistoryQuery query, bool get_affected_messages,
2048                                AffectedHistory affected_history, Promise<Unit> &&promise);
2049 
2050   static MessageId find_message_by_date(const Message *m, int32 date);
2051 
2052   static void find_messages_by_date(const Message *m, int32 min_date, int32 max_date, vector<MessageId> &message_ids);
2053 
2054   static void find_messages(const Message *m, vector<MessageId> &message_ids,
2055                             const std::function<bool(const Message *)> &condition);
2056 
2057   static void find_old_messages(const Message *m, MessageId max_message_id, vector<MessageId> &message_ids);
2058 
2059   static void find_newer_messages(const Message *m, MessageId min_message_id, vector<MessageId> &message_ids);
2060 
2061   void find_unloadable_messages(const Dialog *d, int32 unload_before_date, const Message *m,
2062                                 vector<MessageId> &message_ids, int32 &left_to_unload) const;
2063 
2064   void on_pending_message_views_timeout(DialogId dialog_id);
2065 
2066   void update_message_interaction_info(FullMessageId full_message_id, int32 view_count, int32 forward_count,
2067                                        bool has_reply_info, tl_object_ptr<telegram_api::messageReplies> &&reply_info);
2068 
2069   bool is_active_message_reply_info(DialogId dialog_id, const MessageReplyInfo &info) const;
2070 
2071   bool is_visible_message_reply_info(DialogId dialog_id, const Message *m) const;
2072 
2073   void on_message_reply_info_changed(DialogId dialog_id, const Message *m) const;
2074 
2075   Result<FullMessageId> get_top_thread_full_message_id(DialogId dialog_id, const Message *m) const;
2076 
2077   td_api::object_ptr<td_api::messageInteractionInfo> get_message_interaction_info_object(DialogId dialog_id,
2078                                                                                          const Message *m) const;
2079 
2080   bool update_message_interaction_info(DialogId dialog_id, Message *m, int32 view_count, int32 forward_count,
2081                                        bool has_reply_info, MessageReplyInfo &&reply_info, const char *source);
2082 
2083   bool update_message_contains_unread_mention(Dialog *d, Message *m, bool contains_unread_mention, const char *source);
2084 
2085   void read_message_content_from_updates(MessageId message_id);
2086 
2087   void read_channel_message_content_from_updates(Dialog *d, MessageId message_id);
2088 
2089   bool read_message_content(Dialog *d, Message *m, bool is_local_read, const char *source);
2090 
2091   void read_message_contents_on_server(DialogId dialog_id, vector<MessageId> message_ids, uint64 log_event_id,
2092                                        Promise<Unit> &&promise, bool skip_log_event = false);
2093 
2094   bool has_incoming_notification(DialogId dialog_id, const Message *m) const;
2095 
2096   int32 calc_new_unread_count_from_last_unread(Dialog *d, MessageId max_message_id, MessageType type) const;
2097 
2098   int32 calc_new_unread_count_from_the_end(Dialog *d, MessageId max_message_id, MessageType type,
2099                                            int32 hint_unread_count) const;
2100 
2101   int32 calc_new_unread_count(Dialog *d, MessageId max_message_id, MessageType type, int32 hint_unread_count) const;
2102 
2103   void repair_server_unread_count(DialogId dialog_id, int32 unread_count);
2104 
2105   void repair_channel_server_unread_count(Dialog *d);
2106 
2107   void read_history_outbox(DialogId dialog_id, MessageId max_message_id, int32 read_date = -1);
2108 
2109   void read_history_on_server(Dialog *d, MessageId max_message_id);
2110 
2111   void do_read_history_on_server(DialogId dialog_id);
2112 
2113   void read_history_on_server_impl(Dialog *d, MessageId max_message_id);
2114 
2115   void read_message_thread_history_on_server_impl(Dialog *d, MessageId top_thread_message_id, MessageId max_message_id);
2116 
2117   void on_read_history_finished(DialogId dialog_id, MessageId top_thread_message_id, uint64 generation);
2118 
2119   void read_message_thread_history_on_server(Dialog *d, MessageId top_thread_message_id, MessageId max_message_id,
2120                                              MessageId last_message_id);
2121 
2122   void read_secret_chat_outbox_inner(DialogId dialog_id, int32 up_to_date, int32 read_date);
2123 
2124   void set_dialog_max_unavailable_message_id(DialogId dialog_id, MessageId max_unavailable_message_id, bool from_update,
2125                                              const char *source);
2126 
2127   void set_dialog_online_member_count(DialogId dialog_id, int32 online_member_count, bool is_from_server,
2128                                       const char *source);
2129 
2130   void on_update_dialog_online_member_count_timeout(DialogId dialog_id);
2131 
2132   bool delete_newer_server_messages_at_the_end(Dialog *d, MessageId max_message_id);
2133 
2134   template <class T, class It>
2135   vector<MessageId> get_message_history_slice(const T &begin, It it, const T &end, MessageId from_message_id,
2136                                               int32 offset, int32 limit);
2137 
2138   void preload_newer_messages(const Dialog *d, MessageId max_message_id);
2139 
2140   void preload_older_messages(const Dialog *d, MessageId min_message_id);
2141 
2142   void on_get_history_from_database(DialogId dialog_id, MessageId from_message_id,
2143                                     MessageId old_last_database_message_id, int32 offset, int32 limit,
2144                                     bool from_the_end, bool only_local, vector<MessagesDbDialogMessage> &&messages,
2145                                     Promise<Unit> &&promise);
2146 
2147   void get_history_from_the_end(DialogId dialog_id, bool from_database, bool only_local, Promise<Unit> &&promise);
2148 
2149   void get_history_from_the_end_impl(const Dialog *d, bool from_database, bool only_local, Promise<Unit> &&promise);
2150 
2151   void get_history(DialogId dialog_id, MessageId from_message_id, int32 offset, int32 limit, bool from_database,
2152                    bool only_local, Promise<Unit> &&promise);
2153 
2154   void get_history_impl(const Dialog *d, MessageId from_message_id, int32 offset, int32 limit, bool from_database,
2155                         bool only_local, Promise<Unit> &&promise);
2156 
2157   void load_messages(DialogId dialog_id, MessageId from_message_id, int32 offset, int32 limit, int left_tries,
2158                      bool only_local, Promise<Unit> &&promise);
2159 
2160   void load_messages_impl(const Dialog *d, MessageId from_message_id, int32 offset, int32 limit, int left_tries,
2161                           bool only_local, Promise<Unit> &&promise);
2162 
2163   void load_dialog_scheduled_messages(DialogId dialog_id, bool from_database, int64 hash, Promise<Unit> &&promise);
2164 
2165   void on_get_scheduled_messages_from_database(DialogId dialog_id, vector<MessagesDbDialogMessage> &&messages);
2166 
2167   static int32 get_random_y(MessageId message_id);
2168 
2169   static void set_message_id(unique_ptr<Message> &message, MessageId message_id);
2170 
2171   static bool is_allowed_useless_update(const tl_object_ptr<telegram_api::Update> &update);
2172 
2173   bool is_message_auto_read(DialogId dialog_id, bool is_outgoing) const;
2174 
2175   void fail_send_message(FullMessageId full_message_id, int error_code, const string &error_message);
2176 
2177   void fail_send_message(FullMessageId full_message_id, Status error);
2178 
2179   void fail_edit_message_media(FullMessageId full_message_id, Status &&error);
2180 
2181   void on_dialog_updated(DialogId dialog_id, const char *source);
2182 
2183   static BufferSlice get_dialog_database_value(const Dialog *d);
2184 
2185   void save_dialog_to_database(DialogId dialog_id);
2186 
2187   void on_save_dialog_to_database(DialogId dialog_id, bool can_reuse_notification_group, bool success);
2188 
2189   void try_reuse_notification_group(NotificationGroupInfo &group_info);
2190 
2191   void load_dialog_list(DialogList &list, int32 limit, Promise<Unit> &&promise);
2192 
2193   void load_folder_dialog_list(FolderId folder_id, int32 limit, bool only_local);
2194 
2195   void on_load_folder_dialog_list(FolderId folder_id, Result<Unit> &&result);
2196 
2197   void load_folder_dialog_list_from_database(FolderId folder_id, int32 limit, Promise<Unit> &&promise);
2198 
2199   void preload_folder_dialog_list(FolderId folder_id);
2200 
2201   void get_dialogs_from_list_impl(int64 task_id);
2202 
2203   void on_get_dialogs_from_list(int64 task_id, Result<Unit> &&result);
2204 
2205   static void invalidate_message_indexes(Dialog *d);
2206 
2207   void update_message_count_by_index(Dialog *d, int diff, const Message *m);
2208 
2209   void update_message_count_by_index(Dialog *d, int diff, int32 index_mask);
2210 
2211   int32 get_message_index_mask(DialogId dialog_id, const Message *m) const;
2212 
2213   void update_reply_count_by_message(Dialog *d, int diff, const Message *m);
2214 
2215   void update_message_reply_count(Dialog *d, MessageId message_id, DialogId replier_dialog_id,
2216                                   MessageId reply_message_id, int32 update_date, int diff, bool is_recursive = false);
2217 
2218   Message *add_message_to_dialog(DialogId dialog_id, unique_ptr<Message> message, bool from_update, bool *need_update,
2219                                  bool *need_update_dialog_pos, const char *source);
2220 
2221   Message *add_message_to_dialog(Dialog *d, unique_ptr<Message> message, bool from_update, bool *need_update,
2222                                  bool *need_update_dialog_pos, const char *source);
2223 
2224   Message *add_scheduled_message_to_dialog(Dialog *d, unique_ptr<Message> message, bool from_update, bool *need_update,
2225                                            const char *source);
2226 
2227   void register_new_local_message_id(Dialog *d, const Message *m);
2228 
2229   void on_message_changed(const Dialog *d, const Message *m, bool need_send_update, const char *source);
2230 
2231   bool need_delete_file(FullMessageId full_message_id, FileId file_id) const;
2232 
2233   bool need_delete_message_files(DialogId dialog_id, const Message *m) const;
2234 
2235   void add_message_to_database(const Dialog *d, const Message *m, const char *source);
2236 
2237   void delete_all_dialog_messages_from_database(Dialog *d, MessageId max_message_id, const char *source);
2238 
2239   void delete_message_from_database(Dialog *d, MessageId message_id, const Message *m, bool is_permanently_deleted);
2240 
2241   void delete_message_files(DialogId dialog_id, const Message *m) const;
2242 
2243   static void add_random_id_to_message_id_correspondence(Dialog *d, int64 random_id, MessageId message_id);
2244 
2245   static void delete_random_id_to_message_id_correspondence(Dialog *d, int64 random_id, MessageId message_id);
2246 
2247   static void add_notification_id_to_message_id_correspondence(Dialog *d, NotificationId notification_id,
2248                                                                MessageId message_id);
2249 
2250   static void delete_notification_id_to_message_id_correspondence(Dialog *d, NotificationId notification_id,
2251                                                                   MessageId message_id);
2252 
2253   void remove_message_notification_id(Dialog *d, Message *m, bool is_permanent, bool force_update,
2254                                       bool ignore_pinned_message_notification_removal = false);
2255 
2256   void remove_new_secret_chat_notification(Dialog *d, bool is_permanent);
2257 
2258   void fix_dialog_last_notification_id(Dialog *d, bool from_mentions, MessageId message_id);
2259 
2260   void do_fix_dialog_last_notification_id(DialogId dialog_id, bool from_mentions,
2261                                           NotificationId prev_last_notification_id,
2262                                           Result<vector<Notification>> result);
2263 
2264   void do_delete_message_log_event(const DeleteMessageLogEvent &log_event) const;
2265 
2266   static void attach_message_to_previous(Dialog *d, MessageId message_id, const char *source);
2267 
2268   static void attach_message_to_next(Dialog *d, MessageId message_id, const char *source);
2269 
2270   bool update_message(Dialog *d, Message *old_message, unique_ptr<Message> new_message, bool *need_update_dialog_pos,
2271                       bool is_message_in_dialog);
2272 
2273   static bool need_message_changed_warning(const Message *old_message);
2274 
2275   bool update_message_content(DialogId dialog_id, Message *old_message, unique_ptr<MessageContent> new_content,
2276                               bool need_send_update_message_content, bool need_merge_files, bool is_message_in_dialog);
2277 
2278   void update_message_max_reply_media_timestamp(const Dialog *d, Message *m, bool need_send_update_message_content);
2279 
2280   void update_message_max_own_media_timestamp(const Dialog *d, Message *m);
2281 
2282   void update_message_max_reply_media_timestamp_in_replied_messages(DialogId dialog_id, MessageId reply_to_message_id);
2283 
2284   void register_message_reply(const Dialog *d, const Message *m);
2285 
2286   void reregister_message_reply(const Dialog *d, const Message *m);
2287 
2288   void unregister_message_reply(const Dialog *d, const Message *m);
2289 
2290   void send_update_new_message(const Dialog *d, const Message *m);
2291 
2292   static bool is_from_mention_notification_group(const Dialog *d, const Message *m);
2293 
2294   static bool is_message_notification_active(const Dialog *d, const Message *m);
2295 
2296   static NotificationGroupInfo &get_notification_group_info(Dialog *d, const Message *m);
2297 
2298   NotificationGroupId get_dialog_notification_group_id(DialogId dialog_id, NotificationGroupInfo &group_info);
2299 
2300   NotificationId get_next_notification_id(Dialog *d, NotificationGroupId notification_group_id, MessageId message_id);
2301 
2302   void try_add_pinned_message_notification(Dialog *d, vector<Notification> &res, NotificationId max_notification_id,
2303                                            int32 limit);
2304 
2305   vector<Notification> get_message_notifications_from_database_force(Dialog *d, bool from_mentions, int32 limit);
2306 
2307   static Result<vector<MessagesDbDialogMessage>> do_get_message_notifications_from_database_force(
2308       Dialog *d, bool from_mentions, NotificationId from_notification_id, MessageId from_message_id, int32 limit);
2309 
2310   void do_get_message_notifications_from_database(Dialog *d, bool from_mentions,
2311                                                   NotificationId initial_from_notification_id,
2312                                                   NotificationId from_notification_id, MessageId from_message_id,
2313                                                   int32 limit, Promise<vector<Notification>> promise);
2314 
2315   void on_get_message_notifications_from_database(DialogId dialog_id, bool from_mentions,
2316                                                   NotificationId initial_from_notification_id, int32 limit,
2317                                                   Result<vector<MessagesDbDialogMessage>> result,
2318                                                   Promise<vector<Notification>> promise);
2319 
2320   void do_remove_message_notification(DialogId dialog_id, bool from_mentions, NotificationId notification_id,
2321                                       vector<MessagesDbDialogMessage> result);
2322 
2323   int32 get_dialog_pending_notification_count(const Dialog *d, bool from_mentions) const;
2324 
2325   void update_dialog_mention_notification_count(const Dialog *d);
2326 
2327   bool is_message_notification_disabled(const Dialog *d, const Message *m) const;
2328 
2329   bool is_dialog_message_notification_disabled(DialogId dialog_id, int32 message_date) const;
2330 
2331   bool may_need_message_notification(const Dialog *d, const Message *m) const;
2332 
2333   bool add_new_message_notification(Dialog *d, Message *m, bool force);
2334 
2335   void flush_pending_new_message_notifications(DialogId dialog_id, bool from_mentions, DialogId settings_dialog_id);
2336 
2337   void remove_all_dialog_notifications(Dialog *d, bool from_mentions, const char *source);
2338 
2339   void remove_message_dialog_notifications(Dialog *d, MessageId max_message_id, bool from_mentions, const char *source);
2340 
2341   bool need_skip_bot_commands(DialogId dialog_id, const Message *m) const;
2342 
2343   void send_update_message_send_succeeded(Dialog *d, MessageId old_message_id, const Message *m) const;
2344 
2345   void send_update_message_content(DialogId dialog_id, Message *m, bool is_message_in_dialog, const char *source);
2346 
2347   void send_update_message_content(const Dialog *d, Message *m, bool is_message_in_dialog, const char *source);
2348 
2349   void send_update_message_content_impl(DialogId dialog_id, const Message *m, const char *source) const;
2350 
2351   void send_update_message_edited(DialogId dialog_id, const Message *m);
2352 
2353   void send_update_message_interaction_info(DialogId dialog_id, const Message *m) const;
2354 
2355   void send_update_message_live_location_viewed(FullMessageId full_message_id);
2356 
2357   void send_update_delete_messages(DialogId dialog_id, vector<int64> &&message_ids, bool is_permanent,
2358                                    bool from_cache) const;
2359 
2360   void send_update_new_chat(Dialog *d);
2361 
2362   void send_update_chat_draft_message(const Dialog *d);
2363 
2364   void send_update_chat_last_message(Dialog *d, const char *source);
2365 
2366   void send_update_chat_last_message_impl(const Dialog *d, const char *source) const;
2367 
2368   void send_update_chat_filters();
2369 
2370   void send_update_unread_message_count(DialogList &list, DialogId dialog_id, bool force, const char *source,
2371                                         bool from_database = false);
2372 
2373   void send_update_unread_chat_count(DialogList &list, DialogId dialog_id, bool force, const char *source,
2374                                      bool from_database = false);
2375 
2376   void send_update_chat_read_inbox(const Dialog *d, bool force, const char *source);
2377 
2378   void send_update_chat_read_outbox(const Dialog *d);
2379 
2380   void send_update_chat_unread_mention_count(const Dialog *d);
2381 
2382   void send_update_chat_position(DialogListId dialog_list_id, const Dialog *d, const char *source) const;
2383 
2384   void send_update_chat_online_member_count(DialogId dialog_id, int32 online_member_count) const;
2385 
2386   void send_update_secret_chats_with_user_action_bar(const Dialog *d) const;
2387 
2388   void send_update_chat_action_bar(Dialog *d);
2389 
2390   void send_update_secret_chats_with_user_theme(const Dialog *d) const;
2391 
2392   void send_update_chat_theme(const Dialog *d);
2393 
2394   void send_update_chat_pending_join_requests(const Dialog *d);
2395 
2396   void send_update_chat_video_chat(const Dialog *d);
2397 
2398   void send_update_chat_default_message_sender_id(const Dialog *d);
2399 
2400   void send_update_chat_message_ttl_setting(const Dialog *d);
2401 
2402   void send_update_chat_has_scheduled_messages(Dialog *d, bool from_deletion);
2403 
2404   void send_update_chat_action(DialogId dialog_id, MessageId top_thread_message_id, DialogId typing_dialog_id,
2405                                const DialogAction &action);
2406 
2407   void repair_dialog_action_bar(Dialog *d, const char *source);
2408 
2409   void hide_dialog_action_bar(Dialog *d);
2410 
2411   void repair_dialog_active_group_call_id(DialogId dialog_id);
2412 
2413   void do_repair_dialog_active_group_call_id(DialogId dialog_id);
2414 
2415   static Result<int32> get_message_schedule_date(td_api::object_ptr<td_api::MessageSchedulingState> &&scheduling_state);
2416 
2417   tl_object_ptr<td_api::MessageSendingState> get_message_sending_state_object(const Message *m) const;
2418 
2419   static tl_object_ptr<td_api::MessageSchedulingState> get_message_scheduling_state_object(int32 send_date);
2420 
2421   tl_object_ptr<td_api::message> get_message_object(DialogId dialog_id, const Message *m, const char *source,
2422                                                     bool for_event_log = false) const;
2423 
2424   static tl_object_ptr<td_api::messages> get_messages_object(int32 total_count,
2425                                                              vector<tl_object_ptr<td_api::message>> &&messages,
2426                                                              bool skip_not_found);
2427 
2428   vector<DialogId> sort_dialogs_by_order(const vector<DialogId> &dialog_ids, int32 limit) const;
2429 
2430   vector<DialogId> get_peers_dialog_ids(vector<tl_object_ptr<telegram_api::Peer>> &&peers);
2431 
2432   static bool need_unread_counter(int64 dialog_order);
2433 
2434   int32 get_dialog_total_count(const DialogList &list) const;
2435 
2436   void repair_server_dialog_total_count(DialogListId dialog_list_id);
2437 
2438   void repair_secret_chat_total_count(DialogListId dialog_list_id);
2439 
2440   void on_get_secret_chat_total_count(DialogListId dialog_list_id, int32 total_count);
2441 
2442   void recalc_unread_count(DialogListId dialog_list_id, int32 old_dialog_total_count, bool force);
2443 
2444   td_api::object_ptr<td_api::updateChatFilters> get_update_chat_filters_object() const;
2445 
2446   td_api::object_ptr<td_api::updateUnreadMessageCount> get_update_unread_message_count_object(
2447       const DialogList &list) const;
2448 
2449   td_api::object_ptr<td_api::updateUnreadChatCount> get_update_unread_chat_count_object(const DialogList &list) const;
2450 
2451   static void save_unread_chat_count(const DialogList &list);
2452 
2453   void set_dialog_last_read_inbox_message_id(Dialog *d, MessageId message_id, int32 server_unread_count,
2454                                              int32 local_unread_count, bool force_update, const char *source);
2455 
2456   void set_dialog_last_read_outbox_message_id(Dialog *d, MessageId message_id);
2457 
2458   void set_dialog_last_message_id(Dialog *d, MessageId last_message_id, const char *source);
2459 
2460   void set_dialog_first_database_message_id(Dialog *d, MessageId first_database_message_id, const char *source);
2461 
2462   void set_dialog_last_database_message_id(Dialog *d, MessageId last_database_message_id, const char *source,
2463                                            bool is_loaded_from_database = false);
2464 
2465   void set_dialog_last_new_message_id(Dialog *d, MessageId last_new_message_id, const char *source);
2466 
2467   void set_dialog_last_clear_history_date(Dialog *d, int32 date, MessageId last_clear_history_message_id,
2468                                           const char *source, bool is_loaded_from_database = false);
2469 
2470   static void set_dialog_unread_mention_count(Dialog *d, int32 unread_mention_count);
2471 
2472   void set_dialog_is_empty(Dialog *d, const char *source);
2473 
2474   void remove_dialog_newer_messages(Dialog *d, MessageId from_message_id, const char *source);
2475 
2476   static int32 get_pinned_dialogs_limit(DialogListId dialog_list_id);
2477 
2478   static vector<DialogId> remove_secret_chat_dialog_ids(vector<DialogId> dialog_ids);
2479 
2480   bool set_dialog_is_pinned(DialogId dialog_id, bool is_pinned);
2481 
2482   bool set_dialog_is_pinned(DialogListId dialog_list_id, Dialog *d, bool is_pinned,
2483                             bool need_update_dialog_lists = true);
2484 
2485   void set_dialog_is_marked_as_unread(Dialog *d, bool is_marked_as_unread);
2486 
2487   void set_dialog_is_blocked(Dialog *d, bool is_blocked);
2488 
2489   void set_dialog_has_bots(Dialog *d, bool has_bots);
2490 
2491   void set_dialog_last_pinned_message_id(Dialog *d, MessageId last_pinned_message_id);
2492 
2493   void drop_dialog_last_pinned_message_id(Dialog *d);
2494 
2495   void set_dialog_theme_name(Dialog *d, string theme_name);
2496 
2497   void fix_pending_join_requests(DialogId dialog_id, int32 &pending_join_request_count,
2498                                  vector<UserId> &pending_join_request_user_ids) const;
2499 
2500   void set_dialog_pending_join_requests(Dialog *d, int32 pending_join_request_count,
2501                                         vector<UserId> pending_join_request_user_ids);
2502 
2503   void repair_dialog_scheduled_messages(Dialog *d);
2504 
2505   void set_dialog_has_scheduled_server_messages(Dialog *d, bool has_scheduled_server_messages);
2506 
2507   void set_dialog_has_scheduled_database_messages(DialogId dialog_id, bool has_scheduled_database_messages);
2508 
2509   void set_dialog_has_scheduled_database_messages_impl(Dialog *d, bool has_scheduled_database_messages);
2510 
2511   void set_dialog_folder_id(Dialog *d, FolderId folder_id);
2512 
2513   void do_set_dialog_folder_id(Dialog *d, FolderId folder_id);
2514 
2515   void toggle_dialog_is_pinned_on_server(DialogId dialog_id, bool is_pinned, uint64 log_event_id);
2516 
2517   void toggle_dialog_is_marked_as_unread_on_server(DialogId dialog_id, bool is_marked_as_unread, uint64 log_event_id);
2518 
2519   void toggle_dialog_is_blocked_on_server(DialogId dialog_id, bool is_blocked, uint64 log_event_id);
2520 
2521   void reorder_pinned_dialogs_on_server(FolderId folder_id, const vector<DialogId> &dialog_ids, uint64 log_event_id);
2522 
2523   void set_dialog_reply_markup(Dialog *d, MessageId message_id);
2524 
2525   void try_restore_dialog_reply_markup(Dialog *d, const Message *m);
2526 
2527   void set_dialog_pinned_message_notification(Dialog *d, MessageId message_id, const char *source);
2528 
2529   void remove_dialog_pinned_message_notification(Dialog *d, const char *source);
2530 
2531   void remove_dialog_mention_notifications(Dialog *d);
2532 
2533   bool set_dialog_last_notification(DialogId dialog_id, NotificationGroupInfo &group_info, int32 last_notification_date,
2534                                     NotificationId last_notification_id, const char *source);
2535 
2536   static string get_notification_settings_scope_database_key(NotificationSettingsScope scope);
2537 
2538   static void save_scope_notification_settings(NotificationSettingsScope scope,
2539                                                const ScopeNotificationSettings &new_settings);
2540 
2541   bool update_dialog_notification_settings(DialogId dialog_id, DialogNotificationSettings *current_settings,
2542                                            const DialogNotificationSettings &new_settings);
2543 
2544   bool update_scope_notification_settings(NotificationSettingsScope scope, ScopeNotificationSettings *current_settings,
2545                                           const ScopeNotificationSettings &new_settings);
2546 
2547   void schedule_dialog_unmute(DialogId dialog_id, bool use_default, int32 mute_until);
2548 
2549   void update_dialog_unmute_timeout(Dialog *d, bool &old_use_default, int32 &old_mute_until, bool new_use_default,
2550                                     int32 new_mute_until);
2551 
2552   void schedule_scope_unmute(NotificationSettingsScope scope, int32 mute_until);
2553 
2554   void update_scope_unmute_timeout(NotificationSettingsScope scope, int32 &old_mute_until, int32 new_mute_until);
2555 
2556   void on_dialog_unmute(DialogId dialog_id);
2557 
2558   void on_scope_unmute(NotificationSettingsScope scope);
2559 
2560   bool update_dialog_silent_send_message(Dialog *d, bool silent_send_message);
2561 
2562   bool is_dialog_action_unneeded(DialogId dialog_id) const;
2563 
2564   void on_send_dialog_action_timeout(DialogId dialog_id);
2565 
2566   void on_active_dialog_action_timeout(DialogId dialog_id);
2567 
2568   void clear_active_dialog_actions(DialogId dialog_id);
2569 
2570   void cancel_dialog_action(DialogId dialog_id, const Message *m);
2571 
2572   Dialog *get_dialog_by_message_id(MessageId message_id);
2573 
2574   MessageId get_message_id_by_random_id(Dialog *d, int64 random_id, const char *source);
2575 
2576   Dialog *add_dialog(DialogId dialog_id, const char *source);
2577 
2578   Dialog *add_new_dialog(unique_ptr<Dialog> &&d, bool is_loaded_from_database, const char *source);
2579 
2580   void fix_new_dialog(Dialog *d, unique_ptr<Message> &&last_database_message, MessageId last_database_message_id,
2581                       int64 order, int32 last_clear_history_date, MessageId last_clear_history_message_id,
2582                       DialogId default_join_group_call_as_dialog_id, DialogId default_send_message_as_dialog_id,
2583                       bool is_loaded_from_database);
2584 
2585   void add_dialog_last_database_message(Dialog *d, unique_ptr<Message> &&last_database_message);
2586 
2587   void fix_dialog_action_bar(const Dialog *d, DialogActionBar *action_bar);
2588 
2589   td_api::object_ptr<td_api::ChatType> get_chat_type_object(DialogId dialog_id) const;
2590 
2591   td_api::object_ptr<td_api::ChatActionBar> get_chat_action_bar_object(const Dialog *d) const;
2592 
2593   string get_dialog_theme_name(const Dialog *d) const;
2594 
2595   td_api::object_ptr<td_api::chatJoinRequestsInfo> get_chat_join_requests_info_object(const Dialog *d) const;
2596 
2597   td_api::object_ptr<td_api::videoChat> get_video_chat_object(const Dialog *d) const;
2598 
2599   td_api::object_ptr<td_api::MessageSender> get_default_sender_id_object(const Dialog *d) const;
2600 
2601   td_api::object_ptr<td_api::chat> get_chat_object(const Dialog *d) const;
2602 
2603   Dialog *get_dialog(DialogId dialog_id);
2604   const Dialog *get_dialog(DialogId dialog_id) const;
2605 
2606   Dialog *get_dialog_force(DialogId dialog_id, const char *source = "get_dialog_force");
2607 
2608   Dialog *on_load_dialog_from_database(DialogId dialog_id, BufferSlice &&value, const char *source);
2609 
2610   void on_get_dialogs_from_database(FolderId folder_id, int32 limit, DialogDbGetDialogsResult &&dialogs,
2611                                     Promise<Unit> &&promise);
2612 
2613   void send_get_dialog_query(DialogId dialog_id, Promise<Unit> &&promise, uint64 log_event_id, const char *source);
2614 
2615   void send_search_public_dialogs_query(const string &query, Promise<Unit> &&promise);
2616 
2617   vector<DialogId> get_pinned_dialog_ids(DialogListId dialog_list_id) const;
2618 
2619   void reload_pinned_dialogs(DialogListId dialog_list_id, Promise<Unit> &&promise);
2620 
2621   static double get_dialog_filters_cache_time();
2622 
2623   void schedule_dialog_filters_reload(double timeout);
2624 
2625   static void on_reload_dialog_filters_timeout(void *messages_manager_ptr);
2626 
2627   void reload_dialog_filters();
2628 
2629   void on_get_dialog_filters(Result<vector<tl_object_ptr<telegram_api::dialogFilter>>> r_filters, bool dummy);
2630 
2631   bool need_synchronize_dialog_filters() const;
2632 
2633   void synchronize_dialog_filters();
2634 
2635   void update_dialogs_hints(const Dialog *d);
2636   void update_dialogs_hints_rating(const Dialog *d);
2637 
2638   td_api::object_ptr<td_api::chatFilter> get_chat_filter_object(const DialogFilter *filter) const;
2639 
2640   void load_dialog_filter(const DialogFilter *filter, bool force, Promise<Unit> &&promise);
2641 
2642   void on_get_recommended_dialog_filters(Result<vector<tl_object_ptr<telegram_api::dialogFilterSuggested>>> result,
2643                                          Promise<td_api::object_ptr<td_api::recommendedChatFilters>> &&promise);
2644 
2645   void on_load_recommended_dialog_filters(Result<Unit> &&result, vector<RecommendedDialogFilter> &&filters,
2646                                           Promise<td_api::object_ptr<td_api::recommendedChatFilters>> &&promise);
2647 
2648   InputDialogId get_input_dialog_id(DialogId dialog_id) const;
2649 
2650   void sort_dialog_filter_input_dialog_ids(DialogFilter *dialog_filter, const char *source) const;
2651 
2652   Result<unique_ptr<DialogFilter>> create_dialog_filter(DialogFilterId dialog_filter_id,
2653                                                         td_api::object_ptr<td_api::chatFilter> filter);
2654 
2655   void update_dialog_filter_on_server(unique_ptr<DialogFilter> &&dialog_filter);
2656 
2657   void on_update_dialog_filter(unique_ptr<DialogFilter> dialog_filter, Status result);
2658 
2659   void delete_dialog_filter_on_server(DialogFilterId dialog_filter_id);
2660 
2661   void on_delete_dialog_filter(DialogFilterId dialog_filter_id, Status result);
2662 
2663   void reorder_dialog_filters_on_server(vector<DialogFilterId> dialog_filter_ids);
2664 
2665   void on_reorder_dialog_filters(vector<DialogFilterId> dialog_filter_ids, Status result);
2666 
2667   void save_dialog_filters();
2668 
2669   void add_dialog_filter(unique_ptr<DialogFilter> dialog_filter, bool at_beginning, const char *source);
2670 
2671   void edit_dialog_filter(unique_ptr<DialogFilter> new_dialog_filter, const char *source);
2672 
2673   void delete_dialog_filter(DialogFilterId dialog_filter_id, const char *source);
2674 
2675   static bool set_dialog_filters_order(vector<unique_ptr<DialogFilter>> &dialog_filters,
2676                                        vector<DialogFilterId> dialog_filter_ids);
2677 
2678   const DialogFilter *get_server_dialog_filter(DialogFilterId dialog_filter_id) const;
2679 
2680   DialogFilter *get_dialog_filter(DialogFilterId dialog_filter_id);
2681   const DialogFilter *get_dialog_filter(DialogFilterId dialog_filter_id) const;
2682 
2683   static vector<DialogFilterId> get_dialog_filter_ids(const vector<unique_ptr<DialogFilter>> &dialog_filters);
2684 
2685   static vector<FolderId> get_dialog_filter_folder_ids(const DialogFilter *filter);
2686 
2687   vector<FolderId> get_dialog_list_folder_ids(const DialogList &list) const;
2688 
2689   bool has_dialogs_from_folder(const DialogList &list, const DialogFolder &folder) const;
2690 
2691   static bool is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id);
2692 
2693   static void add_dialog_to_list(Dialog *d, DialogListId dialog_list_id);
2694 
2695   static void remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id);
2696 
2697   bool need_dialog_in_filter(const Dialog *d, const DialogFilter *filter) const;
2698 
2699   bool need_dialog_in_list(const Dialog *d, const DialogList &list) const;
2700 
2701   static bool need_send_update_chat_position(const DialogPositionInList &old_position,
2702                                              const DialogPositionInList &new_position);
2703 
2704   DialogPositionInList get_dialog_position_in_list(const DialogList *list, const Dialog *d, bool actual = false) const;
2705 
2706   std::unordered_map<DialogListId, DialogPositionInList, DialogListIdHash> get_dialog_positions(const Dialog *d) const;
2707 
2708   static vector<DialogListId> get_dialog_list_ids(const Dialog *d);
2709 
2710   DialogListView get_dialog_lists(const Dialog *d);
2711 
2712   DialogList &add_dialog_list(DialogListId dialog_list_id);
2713 
2714   DialogList *get_dialog_list(DialogListId dialog_list_id);
2715   const DialogList *get_dialog_list(DialogListId dialog_list_id) const;
2716 
2717   DialogFolder *get_dialog_folder(FolderId folder_id);
2718   const DialogFolder *get_dialog_folder(FolderId folder_id) const;
2719 
2720   static unique_ptr<Message> *treap_find_message(unique_ptr<Message> *v, MessageId message_id);
2721   static const unique_ptr<Message> *treap_find_message(const unique_ptr<Message> *v, MessageId message_id);
2722 
2723   static Message *treap_insert_message(unique_ptr<Message> *v, unique_ptr<Message> message);
2724   static unique_ptr<Message> treap_delete_message(unique_ptr<Message> *v);
2725 
2726   static Message *get_message(Dialog *d, MessageId message_id);
2727   static const Message *get_message(const Dialog *d, MessageId message_id);
2728 
2729   Message *get_message(FullMessageId full_message_id);
2730   const Message *get_message(FullMessageId full_message_id) const;
2731 
2732   bool have_message_force(Dialog *d, MessageId message_id, const char *source);
2733 
2734   Message *get_message_force(Dialog *d, MessageId message_id, const char *source);
2735 
2736   Message *get_message_force(FullMessageId full_message_id, const char *source);
2737 
2738   void get_message_force_from_server(Dialog *d, MessageId message_id, Promise<Unit> &&promise,
2739                                      tl_object_ptr<telegram_api::InputMessage> input_message = nullptr);
2740 
2741   Message *on_get_message_from_database(const MessagesDbMessage &message, bool is_scheduled, const char *source);
2742 
2743   Message *on_get_message_from_database(Dialog *d, const MessagesDbDialogMessage &message, bool is_scheduled,
2744                                         const char *source);
2745 
2746   Message *on_get_message_from_database(Dialog *d, DialogId dialog_id, MessageId message_id, const BufferSlice &value,
2747                                         bool is_scheduled, const char *source);
2748 
2749   void get_dialog_message_by_date_from_server(const Dialog *d, int32 date, int64 random_id, bool after_database_search,
2750                                               Promise<Unit> &&promise);
2751 
2752   void on_get_dialog_message_by_date_from_database(DialogId dialog_id, int32 date, int64 random_id,
2753                                                    Result<MessagesDbDialogMessage> result, Promise<Unit> promise);
2754 
2755   std::pair<bool, int32> get_dialog_mute_until(DialogId dialog_id, const Dialog *d) const;
2756 
2757   NotificationSettingsScope get_dialog_notification_setting_scope(DialogId dialog_id) const;
2758 
2759   int32 get_scope_mute_until(DialogId dialog_id) const;
2760 
2761   DialogNotificationSettings *get_dialog_notification_settings(DialogId dialog_id, bool force);
2762 
2763   ScopeNotificationSettings *get_scope_notification_settings(NotificationSettingsScope scope);
2764 
2765   const ScopeNotificationSettings *get_scope_notification_settings(NotificationSettingsScope scope) const;
2766 
2767   vector<FileId> get_message_file_ids(const Message *m) const;
2768 
2769   void cancel_upload_message_content_files(const MessageContent *content);
2770 
2771   static void cancel_upload_file(FileId file_id);
2772 
2773   void cancel_send_message_query(DialogId dialog_id, Message *m);
2774 
2775   void cancel_send_deleted_message(DialogId dialog_id, Message *m, bool is_permanently_deleted);
2776 
2777   bool is_discussion_message(DialogId dialog_id, const Message *m) const;
2778 
2779   bool has_message_sender_user_id(DialogId dialog_id, const Message *m) const;
2780 
2781   int32 get_message_own_max_media_timestamp(const Message *m) const;
2782 
2783   static int32 get_message_max_media_timestamp(const Message *m);
2784 
2785   static bool get_message_disable_web_page_preview(const Message *m);
2786 
2787   static int32 get_message_flags(const Message *m);
2788 
2789   tl_object_ptr<telegram_api::InputPeer> get_send_message_as_input_peer(const Message *m) const;
2790 
2791   static bool is_forward_info_sender_hidden(const MessageForwardInfo *forward_info);
2792 
2793   unique_ptr<MessageForwardInfo> get_message_forward_info(
2794       tl_object_ptr<telegram_api::messageFwdHeader> &&forward_header);
2795 
2796   td_api::object_ptr<td_api::messageForwardInfo> get_message_forward_info_object(
2797       const unique_ptr<MessageForwardInfo> &forward_info) const;
2798 
2799   void ttl_read_history(Dialog *d, bool is_outgoing, MessageId from_message_id, MessageId till_message_id,
2800                         double view_date);
2801   void ttl_read_history_impl(DialogId dialog_id, bool is_outgoing, MessageId from_message_id, MessageId till_message_id,
2802                              double view_date);
2803   void ttl_on_view(const Dialog *d, Message *m, double view_date, double now);
2804   bool ttl_on_open(Dialog *d, Message *m, double now, bool is_local_read);
2805   void ttl_register_message(DialogId dialog_id, const Message *m, double now);
2806   void ttl_unregister_message(DialogId dialog_id, const Message *m, const char *source);
2807   void ttl_period_register_message(DialogId dialog_id, const Message *m, double server_time);
2808   void ttl_period_unregister_message(DialogId dialog_id, const Message *m);
2809   void ttl_loop(double now);
2810   void ttl_update_timeout(double now);
2811 
2812   void on_message_ttl_expired(Dialog *d, Message *m);
2813   void on_message_ttl_expired_impl(Dialog *d, Message *m);
2814 
2815   void start_up() final;
2816 
2817   void loop() final;
2818 
2819   void tear_down() final;
2820 
2821   void hangup() final;
2822 
2823   void create_folders();
2824   void init();
2825 
2826   void ttl_db_loop_start(double server_now);
2827   void ttl_db_loop(double server_now);
2828   void ttl_db_on_result(Result<std::pair<std::vector<MessagesDbMessage>, int32>> r_result, bool dummy);
2829 
2830   void on_get_message_link_dialog(MessageLinkInfo &&info, Promise<MessageLinkInfo> &&promise);
2831 
2832   void on_get_message_link_message(MessageLinkInfo &&info, DialogId dialog_id, Promise<MessageLinkInfo> &&promise);
2833 
2834   void on_get_message_link_discussion_message(MessageLinkInfo &&info, DialogId comment_dialog_id,
2835                                               Promise<MessageLinkInfo> &&promise);
2836 
2837   void process_discussion_message_impl(telegram_api::object_ptr<telegram_api::messages_discussionMessage> &&result,
2838                                        DialogId dialog_id, MessageId message_id, DialogId expected_dialog_id,
2839                                        MessageId expected_message_id, Promise<MessageThreadInfo> promise);
2840 
2841   void on_get_discussion_message(DialogId dialog_id, MessageId message_id, MessageThreadInfo &&message_thread_info,
2842                                  Promise<MessageThreadInfo> &&promise);
2843 
2844   void on_get_message_viewers(DialogId dialog_id, vector<UserId> user_ids, bool is_recursive,
2845                               Promise<td_api::object_ptr<td_api::users>> &&promise);
2846 
2847   static MessageId get_first_database_message_id_by_index(const Dialog *d, MessageSearchFilter filter);
2848 
2849   void on_get_message_calendar_from_database(int64 random_id, DialogId dialog_id, MessageId from_message_id,
2850                                              MessageId first_db_message_id, MessageSearchFilter filter,
2851                                              Result<MessagesDbCalendar> r_calendar, Promise<Unit> promise);
2852 
2853   void on_search_dialog_messages_db_result(int64 random_id, DialogId dialog_id, MessageId from_message_id,
2854                                            MessageId first_db_message_id, MessageSearchFilter filter, int32 offset,
2855                                            int32 limit, Result<vector<MessagesDbDialogMessage>> r_messages,
2856                                            Promise<Unit> promise);
2857 
2858   void on_messages_db_fts_result(Result<MessagesDbFtsResult> result, string offset, int32 limit, int64 random_id,
2859                                  Promise<Unit> &&promise);
2860 
2861   void on_messages_db_calls_result(Result<MessagesDbCallsResult> result, int64 random_id, MessageId first_db_message_id,
2862                                    MessageSearchFilter filter, Promise<Unit> &&promise);
2863 
2864   void on_load_active_live_location_full_message_ids_from_database(string value);
2865 
2866   void on_load_active_live_location_messages_finished();
2867 
2868   void try_add_active_live_location(DialogId dialog_id, const Message *m);
2869 
2870   void add_active_live_location(FullMessageId full_message_id);
2871 
2872   bool delete_active_live_location(DialogId dialog_id, const Message *m);
2873 
2874   void save_active_live_locations();
2875 
2876   void on_message_live_location_viewed(Dialog *d, const Message *m);
2877 
2878   void view_message_live_location_on_server(int64 task_id);
2879 
2880   void view_message_live_location_on_server_impl(int64 task_id, FullMessageId full_message_id);
2881 
2882   void on_message_live_location_viewed_on_server(int64 task_id);
2883 
2884   void try_add_bot_command_message_id(DialogId dialog_id, const Message *m);
2885 
2886   void delete_bot_command_message_id(DialogId dialog_id, MessageId message_id);
2887 
2888   void add_message_file_sources(DialogId dialog_id, const Message *m);
2889 
2890   void remove_message_file_sources(DialogId dialog_id, const Message *m);
2891 
2892   void change_message_files(DialogId dialog_id, const Message *m, const vector<FileId> &old_file_ids);
2893 
2894   Result<unique_ptr<ReplyMarkup>> get_dialog_reply_markup(
2895       DialogId dialog_id, tl_object_ptr<td_api::ReplyMarkup> &&reply_markup_ptr) const TD_WARN_UNUSED_RESULT;
2896 
2897   const DialogPhoto *get_dialog_photo(DialogId dialog_id) const;
2898 
2899   string get_dialog_username(DialogId dialog_id) const;
2900 
2901   RestrictedRights get_dialog_default_permissions(DialogId dialog_id) const;
2902 
2903   bool get_dialog_has_protected_content(DialogId dialog_id) const;
2904 
2905   bool get_dialog_has_scheduled_messages(const Dialog *d) const;
2906 
2907   static int64 get_dialog_order(MessageId message_id, int32 message_date);
2908 
2909   bool is_dialog_sponsored(const Dialog *d) const;
2910 
2911   int64 get_dialog_base_order(const Dialog *d) const;
2912 
2913   int64 get_dialog_private_order(const DialogList *list, const Dialog *d) const;
2914 
2915   td_api::object_ptr<td_api::chatPosition> get_chat_position_object(DialogListId dialog_list_id, const Dialog *d) const;
2916 
2917   vector<td_api::object_ptr<td_api::chatPosition>> get_chat_positions_object(const Dialog *d) const;
2918 
2919   bool update_dialog_draft_message(Dialog *d, unique_ptr<DraftMessage> &&draft_message, bool from_update,
2920                                    bool need_update_dialog_pos);
2921 
2922   void save_dialog_draft_message_on_server(DialogId dialog_id);
2923 
2924   void on_saved_dialog_draft_message(DialogId dialog_id, uint64 generation);
2925 
2926   void update_dialog_notification_settings_on_server(DialogId dialog_id, bool from_binlog);
2927 
2928   void send_update_dialog_notification_settings_query(const Dialog *d, Promise<Unit> &&promise);
2929 
2930   void on_updated_dialog_notification_settings(DialogId dialog_id, uint64 generation);
2931 
2932   void update_scope_notification_settings_on_server(NotificationSettingsScope scope, uint64 log_event_id);
2933 
2934   void reset_all_notification_settings_on_server(uint64 log_event_id);
2935 
2936   void toggle_dialog_report_spam_state_on_server(DialogId dialog_id, bool is_spam_dialog, uint64 log_event_id,
2937                                                  Promise<Unit> &&promise);
2938 
2939   void set_dialog_folder_id_on_server(DialogId dialog_id, bool from_binlog);
2940 
2941   void on_updated_dialog_folder_id(DialogId dialog_id, uint64 generation);
2942 
2943   int64 get_next_pinned_dialog_order();
2944 
2945   bool is_removed_from_dialog_list(const Dialog *d) const;
2946 
2947   void update_dialog_pos(Dialog *d, const char *source, bool need_send_update = true,
2948                          bool is_loaded_from_database = false);
2949 
2950   bool set_dialog_order(Dialog *d, int64 new_order, bool need_send_update, bool is_loaded_from_database,
2951                         const char *source);
2952 
2953   void update_dialog_lists(Dialog *d,
2954                            std::unordered_map<DialogListId, DialogPositionInList, DialogListIdHash> &&old_positions,
2955                            bool need_send_update, bool is_loaded_from_database, const char *source);
2956 
2957   void update_last_dialog_date(FolderId folder_id);
2958 
2959   bool do_update_list_last_pinned_dialog_date(DialogList &list) const;
2960 
2961   void update_list_last_pinned_dialog_date(DialogList &list);
2962 
2963   bool do_update_list_last_dialog_date(DialogList &list, const vector<FolderId> &folder_ids) const;
2964 
2965   void update_list_last_dialog_date(DialogList &list);
2966 
2967   void load_notification_settings();
2968 
2969   static string get_channel_pts_key(DialogId dialog_id);
2970 
2971   int32 load_channel_pts(DialogId dialog_id) const;
2972 
2973   void set_channel_pts(Dialog *d, int32 new_pts, const char *source);
2974 
2975   bool need_channel_difference_to_add_message(DialogId dialog_id,
2976                                               const tl_object_ptr<telegram_api::Message> &message_ptr);
2977 
2978   void run_after_channel_difference(DialogId dialog_id, Promise<Unit> &&promise);
2979 
2980   bool running_get_channel_difference(DialogId dialog_id) const;
2981 
2982   void on_channel_get_difference_timeout(DialogId dialog_id);
2983 
2984   void get_channel_difference(DialogId dialog_id, int32 pts, bool force, const char *source);
2985 
2986   void do_get_channel_difference(DialogId dialog_id, int32 pts, bool force,
2987                                  tl_object_ptr<telegram_api::InputChannel> &&input_channel, const char *source);
2988 
2989   void process_get_channel_difference_updates(DialogId dialog_id, int32 new_pts,
2990                                               vector<tl_object_ptr<telegram_api::Message>> &&new_messages,
2991                                               vector<tl_object_ptr<telegram_api::Update>> &&other_updates);
2992 
2993   void on_get_channel_dialog(DialogId dialog_id, MessageId last_message_id, MessageId read_inbox_max_message_id,
2994                              int32 server_unread_count, int32 unread_mention_count,
2995                              MessageId read_outbox_max_message_id,
2996                              vector<tl_object_ptr<telegram_api::Message>> &&messages);
2997 
2998   void after_get_channel_difference(DialogId dialog_id, bool success);
2999 
3000   static void on_channel_get_difference_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3001 
3002   static void on_pending_message_views_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3003 
3004   static void on_pending_message_live_location_view_timeout_callback(void *messages_manager_ptr, int64 task_id);
3005 
3006   static void on_pending_draft_message_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3007 
3008   static void on_pending_read_history_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3009 
3010   static void on_pending_updated_dialog_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3011 
3012   static void on_pending_unload_dialog_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3013 
3014   static void on_dialog_unmute_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3015 
3016   static void on_pending_send_dialog_action_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3017 
3018   static void on_active_dialog_action_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3019 
3020   static void on_update_dialog_online_member_count_timeout_callback(void *messages_manager_ptr, int64 dialog_id_int);
3021 
3022   static void on_preload_folder_dialog_list_timeout_callback(void *messages_manager_ptr, int64 folder_id_int);
3023 
3024   void load_secret_thumbnail(FileId thumbnail_file_id);
3025 
3026   void on_upload_media(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file,
3027                        tl_object_ptr<telegram_api::InputEncryptedFile> input_encrypted_file);
3028   void on_upload_media_error(FileId file_id, Status status);
3029 
3030   void on_load_secret_thumbnail(FileId thumbnail_file_id, BufferSlice thumbnail);
3031   void on_upload_thumbnail(FileId thumbnail_file_id, tl_object_ptr<telegram_api::InputFile> thumbnail_input_file);
3032 
3033   void on_upload_dialog_photo(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file);
3034   void on_upload_dialog_photo_error(FileId file_id, Status status);
3035 
3036   void send_edit_dialog_photo_query(DialogId dialog_id, FileId file_id,
3037                                     tl_object_ptr<telegram_api::InputChatPhoto> &&input_chat_photo,
3038                                     Promise<Unit> &&promise);
3039 
3040   void upload_imported_messages(DialogId dialog_id, FileId file_id, vector<FileId> attached_file_ids, bool is_reupload,
3041                                 Promise<Unit> &&promise, vector<int> bad_parts = {});
3042 
3043   void on_upload_imported_messages(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file);
3044   void on_upload_imported_messages_error(FileId file_id, Status status);
3045 
3046   void upload_imported_message_attachment(DialogId dialog_id, int64 import_id, FileId file_id, bool is_reupload,
3047                                           Promise<Unit> &&promise, vector<int> bad_parts = {});
3048 
3049   void on_upload_imported_message_attachment(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file);
3050   void on_upload_imported_message_attachment_error(FileId file_id, Status status);
3051 
3052   void on_imported_message_attachments_uploaded(int64 random_id, Result<Unit> &&result);
3053 
3054   Status can_import_messages(DialogId dialog_id);
3055 
3056   void send_get_message_public_forwards_query(DcId dc_id, FullMessageId full_message_id, string offset, int32 limit,
3057                                               Promise<td_api::object_ptr<td_api::foundMessages>> &&promise);
3058 
3059   void add_sponsored_dialog(const Dialog *d, DialogSource source);
3060 
3061   void save_sponsored_dialog();
3062 
3063   void set_sponsored_dialog(DialogId dialog_id, DialogSource source);
3064 
3065   Dialog *get_service_notifications_dialog();
3066 
3067   void save_auth_notification_ids();
3068 
3069   static MessageId get_next_message_id(Dialog *d, MessageType type);
3070 
3071   static MessageId get_next_local_message_id(Dialog *d);
3072 
3073   static MessageId get_next_yet_unsent_message_id(Dialog *d);
3074 
3075   static MessageId get_next_yet_unsent_scheduled_message_id(Dialog *d, int32 date);
3076 
3077   void reget_message_from_server_if_needed(DialogId dialog_id, const Message *m);
3078 
3079   void speculatively_update_active_group_call_id(Dialog *d, const Message *m);
3080 
3081   void speculatively_update_channel_participants(DialogId dialog_id, const Message *m);
3082 
3083   void update_sent_message_contents(DialogId dialog_id, const Message *m);
3084 
3085   void update_used_hashtags(DialogId dialog_id, const Message *m);
3086 
3087   void update_top_dialogs(DialogId dialog_id, const Message *m);
3088 
3089   void update_forward_count(DialogId dialog_id, const Message *m);
3090 
3091   void update_forward_count(DialogId dialog_id, MessageId message_id, int32 update_date);
3092 
3093   void update_has_outgoing_messages(DialogId dialog_id, const Message *m);
3094 
3095   string get_message_search_text(const Message *m) const;
3096 
3097   unique_ptr<Message> parse_message(DialogId dialog_id, MessageId expected_message_id, const BufferSlice &value,
3098                                     bool is_scheduled);
3099 
3100   unique_ptr<Dialog> parse_dialog(DialogId dialog_id, const BufferSlice &value, const char *source);
3101 
3102   void load_calls_db_state();
3103   void save_calls_db_state();
3104 
is_debug_message_op_enabled()3105   static constexpr bool is_debug_message_op_enabled() {
3106     return !LOG_IS_STRIPPED(ERROR) && false;
3107   }
3108 
3109   static void dump_debug_message_op(const Dialog *d, int priority = 0);
3110 
3111   static void add_message_dependencies(Dependencies &dependencies, const Message *m);
3112 
3113   static void save_send_message_log_event(DialogId dialog_id, const Message *m);
3114 
3115   static uint64 save_toggle_dialog_report_spam_state_on_server_log_event(DialogId dialog_id, bool is_spam_dialog);
3116 
3117   static uint64 save_delete_messages_on_server_log_event(DialogId dialog_id, const vector<MessageId> &message_ids,
3118                                                          bool revoke);
3119 
3120   static uint64 save_delete_scheduled_messages_on_server_log_event(DialogId dialog_id,
3121                                                                    const vector<MessageId> &message_ids);
3122 
3123   static uint64 save_delete_dialog_history_on_server_log_event(DialogId dialog_id, MessageId max_message_id,
3124                                                                bool remove_from_dialog_list, bool revoke);
3125 
3126   static uint64 save_delete_all_call_messages_on_server_log_event(bool revoke);
3127 
3128   static uint64 save_block_message_sender_from_replies_on_server_log_event(MessageId message_id,
3129                                                                            bool need_delete_message,
3130                                                                            bool need_delete_all_messages,
3131                                                                            bool report_spam);
3132 
3133   static uint64 save_delete_all_channel_messages_by_sender_on_server_log_event(ChannelId channel_id,
3134                                                                                DialogId sender_dialog_id);
3135 
3136   static uint64 save_delete_dialog_messages_by_date_on_server_log_event(DialogId dialog_id, int32 min_date,
3137                                                                         int32 max_date, bool revoke);
3138 
3139   static uint64 save_read_all_dialog_mentions_on_server_log_event(DialogId dialog_id);
3140 
3141   static uint64 save_toggle_dialog_is_pinned_on_server_log_event(DialogId dialog_id, bool is_pinned);
3142 
3143   static uint64 save_reorder_pinned_dialogs_on_server_log_event(FolderId folder_id, const vector<DialogId> &dialog_ids);
3144 
3145   static uint64 save_toggle_dialog_is_marked_as_unread_on_server_log_event(DialogId dialog_id,
3146                                                                            bool is_marked_as_unread);
3147 
3148   static uint64 save_toggle_dialog_is_blocked_on_server_log_event(DialogId dialog_id, bool is_blocked);
3149 
3150   static uint64 save_read_message_contents_on_server_log_event(DialogId dialog_id,
3151                                                                const vector<MessageId> &message_ids);
3152 
3153   static uint64 save_update_scope_notification_settings_on_server_log_event(NotificationSettingsScope scope);
3154 
3155   static uint64 save_reset_all_notification_settings_on_server_log_event();
3156 
3157   static uint64 save_reget_dialog_log_event(DialogId dialog_id);
3158 
3159   static uint64 save_forward_messages_log_event(DialogId to_dialog_id, DialogId from_dialog_id,
3160                                                 const vector<Message *> &messages,
3161                                                 const vector<MessageId> &message_ids);
3162 
3163   static uint64 save_unpin_all_dialog_messages_on_server_log_event(DialogId dialog_id);
3164 
3165   void suffix_load_loop(Dialog *d);
3166   static void suffix_load_update_first_message_id(Dialog *d);
3167   void suffix_load_query_ready(DialogId dialog_id);
3168   void suffix_load_add_query(Dialog *d, std::pair<Promise<>, std::function<bool(const Message *)>> query);
3169   void suffix_load_till_date(Dialog *d, int32 date, Promise<> promise);
3170   void suffix_load_till_message_id(Dialog *d, MessageId message_id, Promise<> promise);
3171 
3172   bool is_group_dialog(DialogId dialog_id) const;
3173 
3174   bool is_broadcast_channel(DialogId dialog_id) const;
3175 
3176   bool is_deleted_secret_chat(const Dialog *d) const;
3177 
3178   static int32 get_message_schedule_date(const Message *m);
3179 
3180   static DialogId get_message_original_sender(const Message *m);
3181 
3182   static DialogId get_message_sender(const Message *m);
3183 
3184   RecentDialogList recently_found_dialogs_;
3185   RecentDialogList recently_opened_dialogs_;
3186 
3187   class UploadMediaCallback;
3188   class UploadThumbnailCallback;
3189   class UploadDialogPhotoCallback;
3190   class UploadImportedMessagesCallback;
3191   class UploadImportedMessageAttachmentCallback;
3192 
3193   std::shared_ptr<UploadMediaCallback> upload_media_callback_;
3194   std::shared_ptr<UploadThumbnailCallback> upload_thumbnail_callback_;
3195   std::shared_ptr<UploadDialogPhotoCallback> upload_dialog_photo_callback_;
3196   std::shared_ptr<UploadImportedMessagesCallback> upload_imported_messages_callback_;
3197   std::shared_ptr<UploadImportedMessageAttachmentCallback> upload_imported_message_attachment_callback_;
3198 
3199   double last_channel_pts_jump_warning_time_ = 0;
3200 
3201   std::unordered_map<FileId, std::pair<FullMessageId, FileId>, FileIdHash>
3202       being_uploaded_files_;  // file_id -> message, thumbnail_file_id
3203   struct UploadedThumbnailInfo {
3204     FullMessageId full_message_id;
3205     FileId file_id;                                     // original file file_id
3206     tl_object_ptr<telegram_api::InputFile> input_file;  // original file InputFile
3207   };
3208   std::unordered_map<FileId, UploadedThumbnailInfo, FileIdHash> being_uploaded_thumbnails_;  // thumbnail_file_id -> ...
3209   struct UploadedSecretThumbnailInfo {
3210     FullMessageId full_message_id;
3211     FileId file_id;                                              // original file file_id
3212     tl_object_ptr<telegram_api::InputEncryptedFile> input_file;  // original file InputEncryptedFile
3213   };
3214   std::unordered_map<FileId, UploadedSecretThumbnailInfo, FileIdHash>
3215       being_loaded_secret_thumbnails_;  // thumbnail_file_id -> ...
3216 
3217   // TTL
3218   class TtlNode final : private HeapNode {
3219    public:
TtlNode(DialogId dialog_id,MessageId message_id,bool by_ttl_period)3220     TtlNode(DialogId dialog_id, MessageId message_id, bool by_ttl_period)
3221         : full_message_id_(dialog_id, message_id), by_ttl_period_(by_ttl_period) {
3222     }
3223 
3224     FullMessageId full_message_id_;
3225     bool by_ttl_period_;
3226 
as_heap_node()3227     HeapNode *as_heap_node() const {
3228       return const_cast<HeapNode *>(static_cast<const HeapNode *>(this));
3229     }
from_heap_node(HeapNode * node)3230     static TtlNode *from_heap_node(HeapNode *node) {
3231       return static_cast<TtlNode *>(node);
3232     }
3233 
3234     bool operator==(const TtlNode &other) const {
3235       return full_message_id_ == other.full_message_id_;
3236     }
3237   };
3238   struct TtlNodeHash {
operatorTtlNodeHash3239     std::size_t operator()(const TtlNode &ttl_node) const {
3240       return FullMessageIdHash()(ttl_node.full_message_id_) * 2 + static_cast<size_t>(ttl_node.by_ttl_period_);
3241     }
3242   };
3243   std::unordered_set<TtlNode, TtlNodeHash> ttl_nodes_;
3244   KHeap<double> ttl_heap_;
3245   Slot ttl_slot_;
3246 
3247   enum YieldType : int32 { None, TtlDb };  // None must be first
3248   int32 ttl_db_expires_from_;
3249   int32 ttl_db_expires_till_;
3250   bool ttl_db_has_query_;
3251   Slot ttl_db_slot_;
3252 
3253   std::unordered_map<int64, FullMessageId> being_sent_messages_;  // message_random_id -> message
3254 
3255   std::unordered_map<FullMessageId, MessageId, FullMessageIdHash>
3256       update_message_ids_;  // new_message_id -> temporary_id
3257   std::unordered_map<DialogId, std::unordered_map<ScheduledServerMessageId, MessageId, ScheduledServerMessageIdHash>,
3258                      DialogIdHash>
3259       update_scheduled_message_ids_;  // new_message_id -> temporary_id
3260 
3261   const char *debug_add_message_to_dialog_fail_reason_ = "";
3262 
3263   struct UploadedDialogPhotoInfo {
3264     DialogId dialog_id;
3265     double main_frame_timestamp;
3266     bool is_animation;
3267     bool is_reupload;
3268     Promise<Unit> promise;
3269 
UploadedDialogPhotoInfoUploadedDialogPhotoInfo3270     UploadedDialogPhotoInfo(DialogId dialog_id, double main_frame_timestamp, bool is_animation, bool is_reupload,
3271                             Promise<Unit> promise)
3272         : dialog_id(dialog_id)
3273         , main_frame_timestamp(main_frame_timestamp)
3274         , is_animation(is_animation)
3275         , is_reupload(is_reupload)
3276         , promise(std::move(promise)) {
3277     }
3278   };
3279   std::unordered_map<FileId, UploadedDialogPhotoInfo, FileIdHash> being_uploaded_dialog_photos_;
3280 
3281   struct UploadedImportedMessagesInfo {
3282     DialogId dialog_id;
3283     vector<FileId> attached_file_ids;
3284     bool is_reupload;
3285     Promise<Unit> promise;
3286 
UploadedImportedMessagesInfoUploadedImportedMessagesInfo3287     UploadedImportedMessagesInfo(DialogId dialog_id, vector<FileId> &&attached_file_ids, bool is_reupload,
3288                                  Promise<Unit> &&promise)
3289         : dialog_id(dialog_id)
3290         , attached_file_ids(std::move(attached_file_ids))
3291         , is_reupload(is_reupload)
3292         , promise(std::move(promise)) {
3293     }
3294   };
3295   std::unordered_map<FileId, unique_ptr<UploadedImportedMessagesInfo>, FileIdHash> being_uploaded_imported_messages_;
3296 
3297   struct UploadedImportedMessageAttachmentInfo {
3298     DialogId dialog_id;
3299     int64 import_id;
3300     bool is_reupload;
3301     Promise<Unit> promise;
3302 
UploadedImportedMessageAttachmentInfoUploadedImportedMessageAttachmentInfo3303     UploadedImportedMessageAttachmentInfo(DialogId dialog_id, int64 import_id, bool is_reupload,
3304                                           Promise<Unit> &&promise)
3305         : dialog_id(dialog_id), import_id(import_id), is_reupload(is_reupload), promise(std::move(promise)) {
3306     }
3307   };
3308   std::unordered_map<FileId, unique_ptr<UploadedImportedMessageAttachmentInfo>, FileIdHash>
3309       being_uploaded_imported_message_attachments_;
3310 
3311   struct PendingMessageImport {
3312     MultiPromiseActor upload_files_multipromise{"UploadAttachedFilesMultiPromiseActor"};
3313     DialogId dialog_id;
3314     int64 import_id = 0;
3315     Promise<Unit> promise;
3316   };
3317   std::unordered_map<int64, unique_ptr<PendingMessageImport>> pending_message_imports_;
3318 
3319   struct PendingMessageGroupSend {
3320     DialogId dialog_id;
3321     size_t finished_count = 0;
3322     vector<MessageId> message_ids;
3323     vector<bool> is_finished;
3324     vector<Status> results;
3325   };
3326   std::unordered_map<int64, PendingMessageGroupSend> pending_message_group_sends_;  // media_album_id -> ...
3327 
3328   std::unordered_map<MessageId, DialogId, MessageIdHash> message_id_to_dialog_id_;
3329   std::unordered_map<MessageId, DialogId, MessageIdHash> last_clear_history_message_id_to_dialog_id_;
3330 
3331   bool created_public_broadcasts_inited_ = false;
3332   vector<ChannelId> created_public_broadcasts_;
3333 
3334   std::unordered_map<int64, DialogId> created_dialogs_;                                // random_id -> dialog_id
3335   std::unordered_map<DialogId, Promise<Unit>, DialogIdHash> pending_created_dialogs_;  // dialog_id -> promise
3336 
3337   bool running_get_difference_ = false;  // true after before_get_difference and false after after_get_difference
3338 
3339   std::unordered_map<DialogId, unique_ptr<Dialog>, DialogIdHash> dialogs_;
3340 
3341   std::unordered_set<DialogId, DialogIdHash>
3342       loaded_dialogs_;  // dialogs loaded from database, but not added to dialogs_
3343 
3344   std::unordered_set<DialogId, DialogIdHash> postponed_chat_read_inbox_updates_;
3345 
3346   struct PendingGetMessageRequest {
3347     MessageId message_id;
3348     Promise<Unit> promise;
3349     tl_object_ptr<telegram_api::InputMessage> input_message;
3350 
PendingGetMessageRequestPendingGetMessageRequest3351     PendingGetMessageRequest(MessageId message_id, Promise<Unit> promise,
3352                              tl_object_ptr<telegram_api::InputMessage> input_message)
3353         : message_id(message_id), promise(std::move(promise)), input_message(std::move(input_message)) {
3354     }
3355   };
3356 
3357   std::unordered_map<string, vector<Promise<Unit>>> search_public_dialogs_queries_;
3358   std::unordered_map<string, vector<DialogId>> found_public_dialogs_;     // TODO time bound cache
3359   std::unordered_map<string, vector<DialogId>> found_on_server_dialogs_;  // TODO time bound cache
3360 
3361   struct CommonDialogs {
3362     vector<DialogId> dialog_ids;
3363     double received_date = 0;
3364     int32 total_count = 0;
3365     bool is_outdated = false;
3366   };
3367   std::unordered_map<UserId, CommonDialogs, UserIdHash> found_common_dialogs_;
3368 
3369   std::unordered_map<int64, FullMessageId> get_dialog_message_by_date_results_;
3370 
3371   std::unordered_map<int64, td_api::object_ptr<td_api::messageCalendar>> found_dialog_message_calendars_;
3372   std::unordered_map<int64, std::pair<int32, vector<MessageId>>>
3373       found_dialog_messages_;                                            // random_id -> [total_count, [message_id]...]
3374   std::unordered_map<int64, DialogId> found_dialog_messages_dialog_id_;  // random_id -> dialog_id
3375   std::unordered_map<int64, std::pair<int32, vector<FullMessageId>>>
3376       found_messages_;  // random_id -> [total_count, [full_message_id]...]
3377   std::unordered_map<int64, std::pair<int32, vector<FullMessageId>>>
3378       found_call_messages_;  // random_id -> [total_count, [full_message_id]...]
3379 
3380   std::unordered_map<int64, FoundMessages> found_fts_messages_;  // random_id -> FoundMessages
3381 
3382   struct MessageEmbeddingCodes {
3383     std::unordered_map<MessageId, string, MessageIdHash> embedding_codes_;
3384   };
3385   std::unordered_map<DialogId, MessageEmbeddingCodes, DialogIdHash> message_embedding_codes_[2];
3386 
3387   std::unordered_map<DialogId, vector<Promise<Unit>>, DialogIdHash> get_dialog_notification_settings_queries_;
3388 
3389   std::unordered_map<DialogId, vector<Promise<Unit>>, DialogIdHash> get_dialog_queries_;
3390   std::unordered_map<DialogId, uint64, DialogIdHash> get_dialog_query_log_event_id_;
3391 
3392   std::unordered_map<FullMessageId, int32, FullMessageIdHash> replied_by_yet_unsent_messages_;
3393 
3394   // full_message_id -> replies with media timestamps
3395   std::unordered_map<FullMessageId, std::unordered_set<MessageId, MessageIdHash>, FullMessageIdHash>
3396       replied_by_media_timestamp_messages_;
3397 
3398   struct ActiveDialogAction {
3399     MessageId top_thread_message_id;
3400     DialogId typing_dialog_id;
3401     DialogAction action;
3402     double start_time;
3403 
ActiveDialogActionActiveDialogAction3404     ActiveDialogAction(MessageId top_thread_message_id, DialogId typing_dialog_id, DialogAction action,
3405                        double start_time)
3406         : top_thread_message_id(top_thread_message_id)
3407         , typing_dialog_id(typing_dialog_id)
3408         , action(std::move(action))
3409         , start_time(start_time) {
3410     }
3411   };
3412 
3413   std::unordered_map<DialogId, std::vector<ActiveDialogAction>, DialogIdHash> active_dialog_actions_;
3414 
3415   ScopeNotificationSettings users_notification_settings_;
3416   ScopeNotificationSettings chats_notification_settings_;
3417   ScopeNotificationSettings channels_notification_settings_;
3418 
3419   std::unordered_map<NotificationGroupId, DialogId, NotificationGroupIdHash> notification_group_id_to_dialog_id_;
3420 
3421   uint64 current_message_edit_generation_ = 0;
3422 
3423   std::unordered_set<DialogListId, DialogListIdHash> postponed_unread_message_count_updates_;
3424   std::unordered_set<DialogListId, DialogListIdHash> postponed_unread_chat_count_updates_;
3425 
3426   int64 current_pinned_dialog_order_ = static_cast<int64>(MIN_PINNED_DIALOG_DATE) << 32;
3427 
3428   std::unordered_map<DialogListId, DialogList, DialogListIdHash> dialog_lists_;
3429   std::unordered_map<FolderId, DialogFolder, FolderIdHash> dialog_folders_;
3430 
3431   bool are_dialog_filters_being_synchronized_ = false;
3432   bool are_dialog_filters_being_reloaded_ = false;
3433   bool need_dialog_filters_reload_ = false;
3434   bool disable_get_dialog_filter_ = false;
3435   bool is_update_chat_filters_sent_ = false;
3436   int32 dialog_filters_updated_date_ = 0;
3437   vector<unique_ptr<DialogFilter>> server_dialog_filters_;
3438   vector<unique_ptr<DialogFilter>> dialog_filters_;
3439   vector<RecommendedDialogFilter> recommended_dialog_filters_;
3440   vector<Promise<Unit>> dialog_filter_reload_queries_;
3441 
3442   std::unordered_map<DialogId, string, DialogIdHash> active_get_channel_differencies_;
3443   std::unordered_map<DialogId, uint64, DialogIdHash> get_channel_difference_to_log_event_id_;
3444   std::unordered_map<DialogId, int32, DialogIdHash> channel_get_difference_retry_timeouts_;
3445   std::unordered_map<DialogId, std::multimap<int32, PendingPtsUpdate>, DialogIdHash> postponed_channel_updates_;
3446   std::unordered_set<DialogId, DialogIdHash> is_channel_difference_finished_;
3447 
3448   MultiTimeout channel_get_difference_timeout_{"ChannelGetDifferenceTimeout"};
3449   MultiTimeout channel_get_difference_retry_timeout_{"ChannelGetDifferenceRetryTimeout"};
3450   MultiTimeout pending_message_views_timeout_{"PendingMessageViewsTimeout"};
3451   MultiTimeout pending_message_live_location_view_timeout_{"PendingMessageLiveLocationViewTimeout"};
3452   MultiTimeout pending_draft_message_timeout_{"PendingDraftMessageTimeout"};
3453   MultiTimeout pending_read_history_timeout_{"PendingReadHistoryTimeout"};
3454   MultiTimeout pending_updated_dialog_timeout_{"PendingUpdatedDialogTimeout"};
3455   MultiTimeout pending_unload_dialog_timeout_{"PendingUnloadDialogTimeout"};
3456   MultiTimeout dialog_unmute_timeout_{"DialogUnmuteTimeout"};
3457   MultiTimeout pending_send_dialog_action_timeout_{"PendingSendDialogActionTimeout"};
3458   MultiTimeout active_dialog_action_timeout_{"ActiveDialogActionTimeout"};
3459   MultiTimeout update_dialog_online_member_count_timeout_{"UpdateDialogOnlineMemberCountTimeout"};
3460   MultiTimeout preload_folder_dialog_list_timeout_{"PreloadFolderDialogListTimeout"};
3461 
3462   Timeout reload_dialog_filters_timeout_;
3463 
3464   Hints dialogs_hints_;  // search dialogs by title and username
3465 
3466   std::unordered_set<FullMessageId, FullMessageIdHash> active_live_location_full_message_ids_;
3467   bool are_active_live_location_messages_loaded_ = false;
3468   vector<Promise<Unit>> load_active_live_location_messages_queries_;
3469 
3470   std::unordered_map<DialogId, vector<Promise<Unit>>, DialogIdHash> load_scheduled_messages_from_database_queries_;
3471 
3472   struct ResolvedUsername {
3473     DialogId dialog_id;
3474     double expires_at;
3475   };
3476 
3477   std::unordered_map<string, ResolvedUsername> resolved_usernames_;
3478   std::unordered_map<string, DialogId> inaccessible_resolved_usernames_;
3479   std::unordered_set<string> reload_voice_chat_on_search_usernames_;
3480 
3481   struct GetDialogsTask {
3482     DialogListId dialog_list_id;
3483     int32 limit;
3484     int32 retry_count;
3485     DialogDate last_dialog_date = MIN_DIALOG_DATE;
3486     Promise<td_api::object_ptr<td_api::chats>> promise;
3487   };
3488 
3489   std::unordered_map<int64, GetDialogsTask> get_dialogs_tasks_;
3490   int64 current_get_dialogs_task_id_ = 0;
3491 
3492   struct PendingOnGetDialogs {
3493     FolderId folder_id;
3494     vector<tl_object_ptr<telegram_api::Dialog>> dialogs;
3495     int32 total_count;
3496     vector<tl_object_ptr<telegram_api::Message>> messages;
3497     Promise<Unit> promise;
3498   };
3499 
3500   vector<PendingOnGetDialogs> pending_on_get_dialogs_;
3501   std::unordered_map<DialogId, PendingOnGetDialogs, DialogIdHash> pending_channel_on_get_dialogs_;
3502 
3503   std::unordered_map<DialogId, vector<Promise<Unit>>, DialogIdHash> run_after_get_channel_difference_;
3504 
3505   ChangesProcessor<unique_ptr<PendingSecretMessage>> pending_secret_messages_;
3506 
3507   std::unordered_map<DialogId, vector<DialogId>, DialogIdHash>
3508       pending_add_dialog_last_database_message_dependent_dialogs_;
3509   std::unordered_map<DialogId, std::pair<int32, unique_ptr<Message>>, DialogIdHash>
3510       pending_add_dialog_last_database_message_;  // dialog -> dependency counter + message
3511 
3512   std::unordered_map<DialogId, vector<DialogId>, DialogIdHash>
3513       pending_add_default_join_group_call_as_dialog_id_;  // dialog_id -> dependent dialogs
3514 
3515   std::unordered_map<DialogId, vector<DialogId>, DialogIdHash>
3516       pending_add_default_send_message_as_dialog_id_;  // dialog_id -> dependent dialogs
3517 
3518   struct MessageIds {
3519     std::unordered_set<MessageId, MessageIdHash> message_ids;
3520   };
3521   std::unordered_map<DialogId, MessageIds, DialogIdHash> dialog_bot_command_message_ids_;
3522 
3523   struct CallsDbState {
3524     std::array<MessageId, 2> first_calls_database_message_id_by_index;
3525     std::array<int32, 2> message_count_by_index;
3526 
3527     template <class StorerT>
3528     void store(StorerT &storer) const;
3529 
3530     template <class ParserT>
3531     void parse(ParserT &parser);
3532   };
3533 
3534   CallsDbState calls_db_state_;
3535 
3536   int64 viewed_live_location_task_id_ = 0;
3537   std::unordered_map<int64, FullMessageId> viewed_live_location_tasks_;  // task_id -> task
3538 
3539   std::unordered_map<uint64, std::map<MessageId, Promise<Message *>>> yet_unsent_media_queues_;
3540 
3541   std::unordered_map<DialogId, NetQueryRef, DialogIdHash> set_typing_query_;
3542 
3543   std::unordered_map<FullMessageId, FileSourceId, FullMessageIdHash> full_message_id_to_file_source_id_;
3544 
3545   std::unordered_map<DialogId, int32, DialogIdHash> last_outgoing_forwarded_message_date_;
3546 
3547   struct OnlineMemberCountInfo {
3548     int32 online_member_count = 0;
3549     double updated_time = 0;
3550     bool is_update_sent = false;
3551   };
3552 
3553   std::unordered_map<DialogId, OnlineMemberCountInfo, DialogIdHash> dialog_online_member_counts_;
3554 
3555   std::unordered_map<DialogId, std::pair<bool, bool>, DialogIdHash> pending_dialog_group_call_updates_;
3556 
3557   std::unordered_map<string, int32> auth_notification_id_date_;
3558 
3559   std::unordered_map<DialogId, MessageId, DialogIdHash> previous_repaired_read_inbox_max_message_id_;
3560 
3561   uint32 scheduled_messages_sync_generation_ = 1;
3562 
3563   int64 authorization_date_ = 0;
3564 
3565   DialogId removed_sponsored_dialog_id_;
3566   DialogId sponsored_dialog_id_;
3567   DialogSource sponsored_dialog_source_;
3568 
3569   FullMessageId being_readded_message_id_;
3570 
3571   DialogId being_added_dialog_id_;
3572   DialogId being_added_by_new_message_dialog_id_;
3573 
3574   DialogId debug_channel_difference_dialog_;
3575 
3576   double start_time_ = 0;
3577   bool is_inited_ = false;
3578 
3579   Td *td_;
3580   ActorShared<> parent_;
3581 };
3582 
3583 }  // namespace td
3584