api_statistics_sender.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "api/api_statistics_sender.h"
  8. #include "apiwrap.h"
  9. #include "data/data_peer.h"
  10. #include "data/data_session.h"
  11. #include "main/main_session.h"
  12. namespace Api {
  13. StatisticsRequestSender::StatisticsRequestSender(
  14. not_null<PeerData*> peer)
  15. : _peer(peer)
  16. , _channel(peer->asChannel())
  17. , _user(peer->asUser())
  18. , _api(&_peer->session().api().instance())
  19. , _timer([=] { checkRequests(); }) {
  20. }
  21. MTP::Sender &StatisticsRequestSender::api() {
  22. return _api;
  23. }
  24. not_null<ChannelData*> StatisticsRequestSender::channel() {
  25. Expects(_channel);
  26. return _channel;
  27. }
  28. not_null<UserData*> StatisticsRequestSender::user() {
  29. Expects(_user);
  30. return _user;
  31. }
  32. void StatisticsRequestSender::checkRequests() {
  33. for (auto i = begin(_requests); i != end(_requests);) {
  34. for (auto j = begin(i->second); j != end(i->second);) {
  35. if (_api.pending(*j)) {
  36. ++j;
  37. } else {
  38. _peer->session().api().unregisterStatsRequest(
  39. i->first,
  40. *j);
  41. j = i->second.erase(j);
  42. }
  43. }
  44. if (i->second.empty()) {
  45. i = _requests.erase(i);
  46. } else {
  47. ++i;
  48. }
  49. }
  50. if (_requests.empty()) {
  51. _timer.cancel();
  52. }
  53. }
  54. auto StatisticsRequestSender::ensureRequestIsRegistered()
  55. -> StatisticsRequestSender::Registered {
  56. const auto id = _api.allocateRequestId();
  57. const auto dcId = _peer->owner().statsDcId(_peer);
  58. if (dcId) {
  59. _peer->session().api().registerStatsRequest(dcId, id);
  60. _requests[dcId].emplace(id);
  61. if (!_timer.isActive()) {
  62. constexpr auto kCheckRequestsTimer = 10 * crl::time(1000);
  63. _timer.callEach(kCheckRequestsTimer);
  64. }
  65. }
  66. return StatisticsRequestSender::Registered{ id, dcId };
  67. }
  68. StatisticsRequestSender::~StatisticsRequestSender() {
  69. for (const auto &[dcId, ids] : _requests) {
  70. for (const auto id : ids) {
  71. _peer->session().api().unregisterStatsRequest(dcId, id);
  72. }
  73. }
  74. }
  75. } // namespace Api