aboutsummaryrefslogtreecommitdiffhomepage
path: root/td/telegram/FileReferenceManager.cpp
blob: f54166a107a4fc8b9a0b4e5ba540ef1ced4fb0dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2026
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/FileReferenceManager.h"

#include "td/telegram/AnimationsManager.h"
#include "td/telegram/AttachMenuManager.h"
#include "td/telegram/AuthManager.h"
#include "td/telegram/BackgroundManager.h"
#include "td/telegram/BotInfoManager.h"
#include "td/telegram/ChatManager.h"
#include "td/telegram/CommunityId.h"
#include "td/telegram/CommunityManager.h"
#include "td/telegram/ConfigManager.h"
#include "td/telegram/DialogManager.h"
#include "td/telegram/DraftMessageManager.h"
#include "td/telegram/files/FileManager.h"
#include "td/telegram/Global.h"
#include "td/telegram/MessageQueryManager.h"
#include "td/telegram/MessagesManager.h"
#include "td/telegram/NotificationSettingsManager.h"
#include "td/telegram/QuickReplyManager.h"
#include "td/telegram/StarManager.h"
#include "td/telegram/StickerSetId.h"
#include "td/telegram/StickersManager.h"
#include "td/telegram/StoryManager.h"
#include "td/telegram/Td.h"
#include "td/telegram/UserManager.h"
#include "td/telegram/WebAppManager.h"
#include "td/telegram/WebPageId.h"
#include "td/telegram/WebPagesManager.h"

#include "td/utils/algorithm.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/overloaded.h"
#include "td/utils/SliceBuilder.h"
#include "td/utils/Time.h"

namespace td {

int VERBOSITY_NAME(file_references) = VERBOSITY_NAME(INFO);

FileReferenceManager::FileReferenceManager(Td *td, ActorShared<> parent) : td_(td), parent_(std::move(parent)) {
}

FileReferenceManager::~FileReferenceManager() {
  Scheduler::instance()->destroy_on_scheduler(G()->get_gc_scheduler_id(), file_sources_, nodes_);
}

void FileReferenceManager::tear_down() {
  parent_.reset();
}

bool FileReferenceManager::is_file_reference_error(const Status &error) {
  return error.is_error() && error.code() == 400 && begins_with(error.message(), "FILE_REFERENCE_");
}

FileReferenceManager::FileReferenceErrorSource FileReferenceManager::get_file_reference_error_source(
    const Status &error, bool expect_index) {
  CHECK(is_file_reference_error(error));
  auto offset = Slice("FILE_REFERENCE_").size();
  Slice message = error.message();
  message = message.substr(offset);
  size_t pos = 0;
  if (begins_with(message, "ATTACH_")) {
    pos = 0;
    message = message.substr(7);
  } else if (begins_with(message, "SOLUTION_")) {
    pos = 1;
    message = message.substr(9);
  } else if (begins_with(message, "ANSWER_")) {
    message = message.substr(7);
    if (message.empty() || !is_digit(message[0])) {
      // add poll answer
      pos = 0;
    } else {
      pos = 2 + to_integer<size_t>(message);
      auto underscore_pos = message.find('_');
      if (underscore_pos == Slice::npos) {
        message = Slice();
      } else {
        message = message.substr(underscore_pos + 1);
      }
    }
  } else if (!message.empty() || is_digit(message[0])) {
    pos = to_integer<size_t>(message);
    auto underscore_pos = message.find('_');
    if (underscore_pos == Slice::npos) {
      message = Slice();
    } else {
      message = message.substr(underscore_pos + 1);
    }
  } else if (expect_index) {
    LOG(ERROR) << "Expected a file reference error with an index, but receive " << error.message();
  }
  if (!message.empty() && message[0] == '_') {
    message = message.substr(1);
  }
  return {pos, begins_with(message, "COVER_")};
}

bool FileReferenceManager::on_file_reference_error(const Status &status, size_t pos, FileId file_id,
                                                   const string &file_reference,
                                                   std::function<void(size_t pos, FileId file_id)> &&on_error) {
  if (!file_id.is_valid()) {
    LOG(ERROR) << "Receive file reference error " << status << ", but have no corresponding file";
    return false;
  }
  VLOG(file_references) << "Receive " << status << " for " << file_id;
  td_->file_manager_->delete_file_reference(file_id, file_reference);
  on_error(pos, file_id);
  return true;
}

bool FileReferenceManager::process_file_reference_error(const Status &status, bool was_uploaded,
                                                        const vector<FileUploadId> &file_upload_ids,
                                                        const vector<string> &file_references,
                                                        const vector<FileId> &cover_file_ids,
                                                        const vector<string> &cover_file_references, bool expect_index,
                                                        std::function<void(size_t pos, FileId file_id)> on_error) {
  if (td_->auth_manager_->is_bot() || !is_file_reference_error(status)) {
    return false;
  }
  auto source = get_file_reference_error_source(status, expect_index);
  auto pos = source.pos_;
  if (source.is_cover_) {
    if (pos < cover_file_ids.size() && pos < cover_file_references.size()) {
      return on_file_reference_error(status, pos, cover_file_ids[pos], cover_file_references[pos], std::move(on_error));
    } else {
      LOG(ERROR) << "Receive file reference error " << status << ", but cover_file_ids = " << cover_file_ids
                 << ", cover_file_references = " << cover_file_references;
    }
  } else {
    if (pos < file_upload_ids.size() && pos < file_references.size() && !was_uploaded) {
      return on_file_reference_error(status, pos, file_upload_ids[pos].get_file_id(), file_references[pos],
                                     std::move(on_error));
    } else {
      LOG(ERROR) << "Receive file reference error " << status << ", but file_upload_ids = " << file_upload_ids
                 << ", was_uploaded = " << was_uploaded << ", file_references = " << file_references;
    }
  }
  return false;
}

bool FileReferenceManager::process_file_reference_error(const Status &status, const vector<FileId> &file_ids,
                                                        const vector<string> &file_references,
                                                        const vector<FileId> &cover_file_ids,
                                                        const vector<string> &cover_file_references, bool expect_index,
                                                        std::function<void(size_t pos, FileId file_id)> on_error) {
  if (td_->auth_manager_->is_bot() || !is_file_reference_error(status)) {
    return false;
  }
  auto source = get_file_reference_error_source(status, expect_index);
  auto pos = source.pos_;
  if (source.is_cover_) {
    if (pos < cover_file_ids.size() && pos < cover_file_references.size()) {
      return on_file_reference_error(status, pos, cover_file_ids[pos], cover_file_references[pos], std::move(on_error));
    } else {
      LOG(ERROR) << "Receive file reference error " << status << ", but cover_file_ids = " << cover_file_ids
                 << ", cover_file_references = " << cover_file_references;
    }
  } else {
    if (pos < file_ids.size() && pos < file_references.size()) {
      return on_file_reference_error(status, pos, file_ids[pos], file_references[pos], std::move(on_error));
    } else {
      LOG(ERROR) << "Receive file reference error " << status << ", but file_ids = " << file_ids
                 << ", file_references = " << file_references;
    }
  }
  return false;
}

/*
fileSourceMessage chat_id:int53 message_id:int53 = FileSource;                             // get_message_from_server
fileSourceUserProfilePhoto user_id:int53 photo_id:int64 = FileSource;                      // photos.getUserPhotos
fileSourceBasicGroupPhoto basic_group_id:int53 = FileSource;                               // no need to repair
fileSourceSupergroupPhoto supergroup_id:int53 = FileSource;                                // no need to repair
fileSourceWebPage url:string = FileSource;                                                 // messages.getWebPage
fileSourceWallpapers = FileSource;                                                         // can't be repaired
fileSourceSavedAnimations = FileSource;                                                    // messages.getSavedGifs
fileSourceRecentStickers is_attached:Bool = FileSource;                                    // messages.getRecentStickers, not reliable
fileSourceFavoriteStickers = FileSource;                                                   // messages.getFavedStickers, not reliable
fileSourceBackground background_id:int64 access_hash:int64 = FileSource;                   // account.getWallPaper
fileSourceBasicGroupFull basic_group_id:int53 = FileSource;                                // messages.getFullChat
fileSourceSupergroupFull supergroup_id:int53 = FileSource;                                 // messages.getFullChannel
fileSourceAppConfig = FileSource;                                                          // help.getAppConfig, not reliable
fileSourceSavedRingtones = FileSource;                                                     // account.getSavedRingtones
fileSourceUserFull = FileSource;                                                           // users.getFullUser
fileSourceAttachmentMenuBot user_id:int53 = FileSource;                                    // messages.getAttachMenuBot
fileSourceWebApp user_id:int53 short_name:string = FileSource;                             // messages.getAttachMenuBot
fileSourceStory chat_id:int53 story_id:int32 = FileSource;                                 // stories.getStoriesByID
fileSourceQuickReplyMessage shortcut_id:int32 message_id:int53 = FileSource;               // messages.getQuickReplyMessages
fileSourceStarTransaction chat_id:int53 transaction_id:string is_refund:Bool = FileSource; // payments.getStarsTransactionsByID
fileSourceBotMediaPreview bot_user_id:int53 = FileSource;                                  // bots.getPreviewMedias
fileSourceBotMediaPreviewInfo bot_user_id:int53 language_code:string = FileSource;         // bots.getPreviewMediaInfo
fileSourceStoryAlbum chat_id:int53 story_album_id:int32 = FileSource;                      // stories.getAlbums, not reliable
fileSourceSavedMusic user_id:int53 file_id:int32 = FileSource;                             // users.getSavedMusicByID
fileSourceDraftMessage chat_id:int53 topic:MessageTopic = FileSource;                      // messages.getPeerDialogs/messages.getForumTopicsByID/messages.getSavedDialogsByID
fileSourceRichMessage chat_id:int53 message_id:int53 = FileSource;                         // messages.getRichMessage
*/

FileSourceId FileReferenceManager::get_current_file_source_id() const {
  return FileSourceId(narrow_cast<int32>(file_sources_.size()));
}

template <class T>
FileSourceId FileReferenceManager::add_file_source_id(T &source, Slice source_str) {
  file_sources_.emplace_back(std::move(source));
  VLOG(file_references) << "Create file source " << file_sources_.size() << " for " << source_str;
  return get_current_file_source_id();
}

FileSourceId FileReferenceManager::create_message_file_source(MessageFullId message_full_id) {
  FileSourceMessage source{message_full_id};
  return add_file_source_id(source, PSLICE() << message_full_id);
}

FileSourceId FileReferenceManager::create_user_photo_file_source(UserId user_id, int64 photo_id) {
  FileSourceUserPhoto source{photo_id, user_id};
  return add_file_source_id(source, PSLICE() << "photo " << photo_id << " of " << user_id);
}

FileSourceId FileReferenceManager::create_web_page_file_source(string url) {
  FileSourceWebPage source{std::move(url)};
  auto source_str = PSTRING() << "web page of " << source.url;
  return add_file_source_id(source, source_str);
}

FileSourceId FileReferenceManager::create_saved_animations_file_source() {
  FileSourceSavedAnimations source;
  return add_file_source_id(source, "saved animations");
}

FileSourceId FileReferenceManager::create_recent_stickers_file_source(bool is_attached) {
  FileSourceRecentStickers source{is_attached};
  return add_file_source_id(source, PSLICE() << "recent " << (is_attached ? "attached " : "") << "stickers");
}

FileSourceId FileReferenceManager::create_favorite_stickers_file_source() {
  FileSourceFavoriteStickers source;
  return add_file_source_id(source, "favorite stickers");
}

FileSourceId FileReferenceManager::create_background_file_source(BackgroundId background_id, int64 access_hash) {
  FileSourceBackground source{background_id, access_hash};
  return add_file_source_id(source, PSLICE() << background_id);
}

FileSourceId FileReferenceManager::create_chat_full_file_source(ChatId chat_id) {
  FileSourceChatFull source{chat_id};
  return add_file_source_id(source, PSLICE() << "full " << chat_id);
}

FileSourceId FileReferenceManager::create_channel_full_file_source(ChannelId channel_id) {
  FileSourceChannelFull source{channel_id};
  return add_file_source_id(source, PSLICE() << "full " << channel_id);
}

FileSourceId FileReferenceManager::create_app_config_file_source() {
  FileSourceAppConfig source;
  return add_file_source_id(source, "app config");
}

FileSourceId FileReferenceManager::create_saved_ringtones_file_source() {
  FileSourceSavedRingtones source;
  return add_file_source_id(source, "saved notification sounds");
}

FileSourceId FileReferenceManager::create_user_full_file_source(UserId user_id) {
  FileSourceUserFull source{user_id};
  return add_file_source_id(source, PSLICE() << "full " << user_id);
}

FileSourceId FileReferenceManager::create_attach_menu_bot_file_source(UserId user_id) {
  FileSourceAttachMenuBot source{user_id};
  return add_file_source_id(source, PSLICE() << "attachment menu bot " << user_id);
}

FileSourceId FileReferenceManager::create_web_app_file_source(UserId user_id, const string &short_name) {
  FileSourceWebApp source{user_id, short_name};
  return add_file_source_id(source, PSLICE() << "Web App " << user_id << '/' << short_name);
}

FileSourceId FileReferenceManager::create_story_file_source(StoryFullId story_full_id) {
  FileSourceStory source{story_full_id};
  return add_file_source_id(source, PSLICE() << story_full_id);
}

FileSourceId FileReferenceManager::create_quick_reply_message_file_source(QuickReplyMessageFullId message_full_id) {
  FileSourceQuickReplyMessage source{message_full_id};
  return add_file_source_id(source, PSLICE() << "quick reply " << message_full_id);
}

FileSourceId FileReferenceManager::create_star_transaction_file_source(DialogId dialog_id, const string &transaction_id,
                                                                       bool is_refund) {
  FileSourceStarTransaction source{dialog_id, transaction_id, is_refund};
  return add_file_source_id(source, PSLICE() << "star transaction " << transaction_id << " in " << dialog_id);
}

FileSourceId FileReferenceManager::create_bot_media_preview_file_source(UserId bot_user_id) {
  FileSourceBotMediaPreview source{bot_user_id};
  return add_file_source_id(source, PSLICE() << "bot media preview " << bot_user_id);
}

FileSourceId FileReferenceManager::create_bot_media_preview_info_file_source(UserId bot_user_id,
                                                                             const string &language_code) {
  FileSourceBotMediaPreviewInfo source{bot_user_id, language_code};
  return add_file_source_id(source, PSLICE() << "bot media preview info " << bot_user_id << " for " << language_code);
}

FileSourceId FileReferenceManager::create_story_album_file_source(StoryAlbumFullId story_album_full_id) {
  FileSourceStoryAlbum source{story_album_full_id};
  return add_file_source_id(source, PSLICE() << story_album_full_id);
}

FileSourceId FileReferenceManager::create_user_saved_music_file_source(UserId user_id, int64 document_id,
                                                                       int64 access_hash) {
  FileSourceUserSavedMusic source{document_id, access_hash, user_id};
  return add_file_source_id(source, PSLICE() << "saved music " << document_id << " of " << user_id);
}

FileSourceId FileReferenceManager::create_draft_message_file_source(DialogId dialog_id, MessageTopic topic) {
  FileSourceDraftMessage source{dialog_id, topic};
  return add_file_source_id(source, PSLICE() << "draft message in " << topic << " of " << dialog_id);
}

FileSourceId FileReferenceManager::create_rich_message_file_source(MessageFullId message_full_id) {
  FileSourceRichMessage source{message_full_id};
  return add_file_source_id(source, PSLICE() << "rich " << message_full_id);
}

FileReferenceManager::Node &FileReferenceManager::add_node(NodeId node_id) {
  CHECK(node_id.is_valid());
  auto &node = nodes_[node_id];
  if (node == nullptr) {
    node = make_unique<Node>();
  }
  return *node;
}

bool FileReferenceManager::add_file_source(NodeId node_id, FileSourceId file_source_id, const char *source) {
  auto &node = add_node(node_id);
  bool is_added = node.file_source_ids.add(file_source_id);
  VLOG(file_references) << "Add " << (is_added ? "new" : "old") << ' ' << file_source_id << " for file " << node_id
                        << " from " << source;
  return is_added;
}

bool FileReferenceManager::remove_file_source(NodeId node_id, FileSourceId file_source_id, const char *source) {
  CHECK(node_id.is_valid());
  auto *node = nodes_.get_pointer(node_id);
  bool is_removed = node != nullptr && node->file_source_ids.remove(file_source_id);
  if (is_removed) {
    VLOG(file_references) << "Remove " << file_source_id << " from file " << node_id << " from " << source;
  } else {
    VLOG(file_references) << "Can't find " << file_source_id << " from file " << node_id << " to remove it from "
                          << source;
  }
  return is_removed;
}

vector<FileSourceId> FileReferenceManager::get_some_file_sources(NodeId node_id) {
  auto *node = nodes_.get_pointer(node_id);
  if (node == nullptr) {
    return {};
  }
  return node->file_source_ids.get_some_elements();
}

vector<MessageFullId> FileReferenceManager::get_some_message_file_sources(NodeId node_id) {
  auto file_source_ids = get_some_file_sources(node_id);

  vector<MessageFullId> result;
  for (auto file_source_id : file_source_ids) {
    auto index = static_cast<size_t>(file_source_id.get()) - 1;
    CHECK(index < file_sources_.size());
    const auto &file_source = file_sources_[index];
    if (file_source.get_offset() == 0) {
      result.push_back(file_source.get<FileSourceMessage>().message_full_id);
    }
  }
  return result;
}

void FileReferenceManager::merge(NodeId to_node_id, NodeId from_node_id) {
  auto *from_node_ptr = nodes_.get_pointer(from_node_id);
  if (from_node_ptr == nullptr) {
    return;
  }
  auto &from = *from_node_ptr;

  auto &to = add_node(to_node_id);
  VLOG(file_references) << "Merge " << to.file_source_ids.size() << " and " << from.file_source_ids.size()
                        << " sources of files " << to_node_id << " and " << from_node_id;
  CHECK(!to.query || to.query->proxy.is_empty());
  CHECK(!from.query || from.query->proxy.is_empty());
  if (to.query || from.query) {
    if (!to.query) {
      to.query = make_unique<Query>();
      to.query->generation = ++query_generation_;
    }
    if (from.query) {
      combine(to.query->promises, std::move(from.query->promises));
      to.query->active_queries += from.query->active_queries;
      from.query->proxy = Destination(to_node_id, to.query->generation);
    }
  }
  to.file_source_ids.merge(std::move(from.file_source_ids));
  run_node(to_node_id);
  run_node(from_node_id);
}

void FileReferenceManager::run_node(NodeId node_id) {
  CHECK(node_id.is_valid());
  auto *node_ptr = nodes_.get_pointer(node_id);
  if (node_ptr == nullptr) {
    return;
  }
  Node &node = *node_ptr;
  if (!node.query) {
    return;
  }
  if (node.query->active_queries != 0) {
    return;
  }
  VLOG(file_references) << "Trying to repair file reference for file " << node_id;
  if (node.query->promises.empty()) {
    node.query = {};
    return;
  }
  if (!node.file_source_ids.has_next()) {
    VLOG(file_references) << "Have no more file sources to repair file reference for file " << node_id;
    for (auto &p : node.query->promises) {
      if (node.file_source_ids.empty()) {
        p.set_error(400, "File source is not found");
      } else {
        p.set_error(429, "Too Many Requests: retry after 1");
      }
    }
    node.query = {};
    return;
  }
  if (node.last_successful_repair_time >= Time::now() - 60) {
    VLOG(file_references) << "Recently repaired file reference for file " << node_id << ", do not try again";
    for (auto &p : node.query->promises) {
      p.set_error(429, "Too Many Requests: retry after 60");
    }
    node.query = {};
    return;
  }
  auto file_source_id = node.file_source_ids.next();
  send_query(Destination(node_id, node.query->generation), file_source_id);
}

void FileReferenceManager::send_query(Destination dest, FileSourceId file_source_id) {
  VLOG(file_references) << "Send file reference repair query for file " << dest.node_id << " with generation "
                        << dest.generation << " from " << file_source_id;
  auto &node = add_node(dest.node_id);
  node.query->active_queries++;

  auto promise = PromiseCreator::lambda([actor_id = actor_id(this), file_manager_actor_id = G()->file_manager(), dest,
                                         file_source_id](Result<Unit> result) {
    auto new_promise = PromiseCreator::lambda([actor_id, dest, file_source_id](Result<Unit> result) {
      Status status;
      if (result.is_error()) {
        status = result.move_as_error();
      }
      send_closure(actor_id, &FileReferenceManager::on_query_result, dest, file_source_id, std::move(status), 0);
    });

    send_closure(file_manager_actor_id, &FileManager::on_file_reference_repaired, dest.node_id, file_source_id,
                 std::move(result), std::move(new_promise));
  });
  auto index = static_cast<size_t>(file_source_id.get()) - 1;
  CHECK(index < file_sources_.size());
  file_sources_[index].visit(overloaded(
      [&](const FileSourceMessage &source) {
        send_closure_later(G()->messages_manager(), &MessagesManager::get_message_from_server, source.message_full_id,
                           std::move(promise), "FileSourceMessage", nullptr);
      },
      [&](const FileSourceUserPhoto &source) {
        send_closure_later(G()->user_manager(), &UserManager::reload_user_profile_photo, source.user_id,
                           source.photo_id, std::move(promise));
      },
      [&](const FileSourceChatPhoto &source) {
        send_closure_later(G()->chat_manager(), &ChatManager::reload_chat, source.chat_id, std::move(promise),
                           "FileSourceChatPhoto");
      },
      [&](const FileSourceChannelPhoto &source) {
        send_closure_later(G()->chat_manager(), &ChatManager::reload_channel, source.channel_id, std::move(promise),
                           "FileSourceChannelPhoto");
      },
      [&](const FileSourceWallpapers &source) { promise.set_error("Can't repair old wallpapers"); },
      [&](const FileSourceWebPage &source) {
        send_closure_later(G()->web_pages_manager(), &WebPagesManager::reload_web_page_by_url, source.url, false,
                           PromiseCreator::lambda([promise = std::move(promise)](Result<WebPageId> &&result) mutable {
                             if (result.is_error()) {
                               promise.set_error(result.move_as_error());
                             } else {
                               promise.set_value(Unit());
                             }
                           }));
      },
      [&](const FileSourceSavedAnimations &source) {
        send_closure_later(G()->animations_manager(), &AnimationsManager::repair_saved_animations, std::move(promise));
      },
      [&](const FileSourceRecentStickers &source) {
        send_closure_later(G()->stickers_manager(), &StickersManager::repair_recent_stickers, source.is_attached,
                           std::move(promise));
      },
      [&](const FileSourceFavoriteStickers &source) {
        send_closure_later(G()->stickers_manager(), &StickersManager::repair_favorite_stickers, std::move(promise));
      },
      [&](const FileSourceBackground &source) {
        send_closure_later(G()->background_manager(), &BackgroundManager::reload_background, source.background_id,
                           source.access_hash, std::move(promise));
      },
      [&](const FileSourceChatFull &source) {
        send_closure_later(G()->chat_manager(), &ChatManager::reload_chat_full, source.chat_id, std::move(promise),
                           "FileSourceChatFull");
      },
      [&](const FileSourceChannelFull &source) {
        send_closure_later(G()->chat_manager(), &ChatManager::reload_channel_full, source.channel_id,
                           std::move(promise), "FileSourceChannelFull");
      },
      [&](const FileSourceAppConfig &source) {
        send_closure_later(G()->config_manager(), &ConfigManager::reload_app_config, std::move(promise));
      },
      [&](const FileSourceSavedRingtones &source) {
        send_closure_later(G()->notification_settings_manager(), &NotificationSettingsManager::repair_saved_ringtones,
                           std::move(promise));
      },
      [&](const FileSourceUserFull &source) {
        send_closure_later(G()->user_manager(), &UserManager::reload_user_full, source.user_id, std::move(promise),
                           "FileSourceUserFull");
      },
      [&](const FileSourceAttachMenuBot &source) {
        send_closure_later(G()->attach_menu_manager(), &AttachMenuManager::reload_attach_menu_bot, source.user_id,
                           std::move(promise));
      },
      [&](const FileSourceWebApp &source) {
        send_closure_later(G()->web_app_manager(), &WebAppManager::reload_web_app, source.user_id, source.short_name,
                           std::move(promise));
      },
      [&](const FileSourceStory &source) {
        send_closure_later(G()->story_manager(), &StoryManager::reload_story, source.story_full_id, std::move(promise),
                           "FileSourceStory");
      },
      [&](const FileSourceQuickReplyMessage &source) {
        send_closure_later(G()->quick_reply_manager(), &QuickReplyManager::reload_quick_reply_message,
                           source.message_full_id.get_quick_reply_shortcut_id(),
                           source.message_full_id.get_message_id(), std::move(promise));
      },
      [&](const FileSourceStarTransaction &source) {
        send_closure_later(G()->star_manager(), &StarManager::reload_star_transaction, source.dialog_id,
                           source.transaction_id, source.is_refund, std::move(promise));
      },
      [&](const FileSourceBotMediaPreview &source) {
        send_closure_later(G()->bot_info_manager(), &BotInfoManager::reload_bot_media_previews, source.bot_user_id,
                           std::move(promise));
      },
      [&](const FileSourceBotMediaPreviewInfo &source) {
        send_closure_later(G()->bot_info_manager(), &BotInfoManager::reload_bot_media_preview_info, source.bot_user_id,
                           source.language_code, std::move(promise));
      },
      [&](const FileSourceStoryAlbum &source) {
        send_closure_later(G()->story_manager(), &StoryManager::reload_story_album, source.story_album_full_id,
                           std::move(promise), "FileSourceStoryAlbum");
      },
      [&](const FileSourceUserSavedMusic &source) {
        send_closure_later(G()->user_manager(), &UserManager::reload_user_saved_music, source.user_id,
                           source.document_id, source.access_hash, std::move(promise));
      },
      [&](const FileSourceDraftMessage &source) {
        send_closure_later(G()->draft_message_manager(), &DraftMessageManager::reload_draft_message, source.dialog_id,
                           source.topic, std::move(promise));
      },
      [&](const FileSourceRichMessage &source) {
        send_closure_later(G()->message_query_manager(), &MessageQueryManager::reload_full_rich_message,
                           source.message_full_id, std::move(promise));
      }));
}

FileReferenceManager::Destination FileReferenceManager::on_query_result(Destination dest, FileSourceId file_source_id,
                                                                        Status status, int32 sub) {
  if (G()->close_flag()) {
    VLOG(file_references) << "Ignore file reference repair from " << file_source_id << " during closing";
    return dest;
  }

  VLOG(file_references) << "Receive result of file reference repair query for file " << dest.node_id
                        << " with generation " << dest.generation << " from " << file_source_id << ": " << status << " "
                        << sub;
  auto &node = add_node(dest.node_id);

  auto query = node.query.get();
  if (!query) {
    return dest;
  }
  if (query->generation != dest.generation) {
    return dest;
  }
  query->active_queries--;
  CHECK(query->active_queries >= 0);

  if (!query->proxy.is_empty()) {
    query->active_queries -= sub;
    CHECK(query->active_queries >= 0);
    auto new_proxy = on_query_result(query->proxy, file_source_id, std::move(status), query->active_queries);
    query->proxy = new_proxy;
    run_node(dest.node_id);
    return new_proxy;
  }

  if (status.is_ok()) {
    node.last_successful_repair_time = Time::now();
    for (auto &p : query->promises) {
      p.set_value(Unit());
    }
    node.query = {};
  }

  run_node(dest.node_id);
  return dest;
}

void FileReferenceManager::repair_file_reference(NodeId node_id, Promise<> promise) {
  auto main_file_id = td_->file_manager_->get_file_view(node_id).get_main_file_id();
  VLOG(file_references) << "Repair file reference for file " << node_id << "/" << main_file_id;
  node_id = main_file_id;
  auto &node = add_node(node_id);
  if (!node.query) {
    node.query = make_unique<Query>();
    node.query->generation = ++query_generation_;
    node.file_source_ids.reset_position();
    VLOG(file_references) << "Create new file reference repair query with generation " << query_generation_;
  }
  node.query->promises.push_back(std::move(promise));
  run_node(node_id);
}

void FileReferenceManager::reload_photo(PhotoSizeSource source, Promise<Unit> promise) {
  TRY_STATUS_PROMISE(promise, G()->close_status());
  switch (source.get_type("reload_photo")) {
    case PhotoSizeSource::Type::DialogPhotoBig:
    case PhotoSizeSource::Type::DialogPhotoSmall:
    case PhotoSizeSource::Type::DialogPhotoBigLegacy:
    case PhotoSizeSource::Type::DialogPhotoSmallLegacy: {
      auto dialog_id = source.dialog_photo().dialog_id;
      if (dialog_id.get_type() == DialogType::Channel) {
        auto channel_id = dialog_id.get_channel_id();
        if (!channel_id.is_regular_channel()) {
          td_->community_manager_->reload_community(CommunityId(channel_id.get()), std::move(promise), "reload_photo");
          break;
        }
      }
      td_->dialog_manager_->reload_dialog_info(dialog_id, std::move(promise));
      break;
    }
    case PhotoSizeSource::Type::StickerSetThumbnail:
    case PhotoSizeSource::Type::StickerSetThumbnailLegacy:
    case PhotoSizeSource::Type::StickerSetThumbnailVersion:
      td_->stickers_manager_->reload_sticker_set(StickerSetId(source.sticker_set_thumbnail().sticker_set_id),
                                                 source.sticker_set_thumbnail().sticker_set_access_hash,
                                                 std::move(promise));
      break;
    case PhotoSizeSource::Type::Legacy:
    case PhotoSizeSource::Type::FullLegacy:
    case PhotoSizeSource::Type::Thumbnail:
      promise.set_error("Unexpected PhotoSizeSource type");
      break;
    default:
      UNREACHABLE();
  }
}

void FileReferenceManager::get_file_search_text(FileSourceId file_source_id, string unique_file_id,
                                                Promise<string> promise) {
  auto index = static_cast<size_t>(file_source_id.get()) - 1;
  CHECK(index < file_sources_.size());
  file_sources_[index].visit(overloaded(
      [&](const FileSourceMessage &source) {
        send_closure_later(G()->messages_manager(), &MessagesManager::get_message_file_search_text,
                           source.message_full_id, std::move(unique_file_id), std::move(promise));
      },
      [&](const auto &source) { promise.set_error(500, "Unsupported file source"); }));
}

td_api::object_ptr<td_api::message> FileReferenceManager::get_message_object(FileSourceId file_source_id) const {
  auto index = static_cast<size_t>(file_source_id.get()) - 1;
  CHECK(index < file_sources_.size());
  td_api::object_ptr<td_api::message> result;
  file_sources_[index].visit(overloaded(
      [&](const FileSourceMessage &source) {
        result = td_->messages_manager_->get_message_object(source.message_full_id, "FileReferenceManager");
      },
      [&](const auto &source) { LOG(ERROR) << "Unsupported file source"; }));
  return result;
}

}  // namespace td