-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Expand file tree
/
Copy pathgift_auctions.cpp
More file actions
559 lines (506 loc) · 15.3 KB
/
Copy pathgift_auctions.cpp
File metadata and controls
559 lines (506 loc) · 15.3 KB
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
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "data/components/gift_auctions.h"
#include "api/api_hash.h"
#include "api/api_premium.h"
#include "api/api_text_entities.h"
#include "apiwrap.h"
#include "data/data_session.h"
#include "main/main_session.h"
namespace Data {
GiftAuctions::GiftAuctions(not_null<Main::Session*> session)
: _session(session)
, _timer([=] { checkSubscriptions(); }) {
crl::on_main(_session, [=] {
rpl::merge(
_session->data().chatsListChanges(),
_session->data().chatsListLoadedEvents()
) | rpl::filter(
!rpl::mappers::_1
) | rpl::take(1) | rpl::on_next([=] {
requestActive();
}, _lifetime);
});
}
GiftAuctions::~GiftAuctions() = default;
void GiftAuctions::resolveSlug(const QString &slug, Fn<void(uint64)> done) {
const auto it = _slugToGiftId.find(slug);
if (it != _slugToGiftId.end()) {
done(it->second);
return;
}
auto &request = _slugRequests[slug];
request.callbacks.push_back(std::move(done));
if (request.callbacks.size() > 1) {
return;
}
_session->api().request(MTPpayments_GetStarGiftAuctionState(
MTP_inputStarGiftAuctionSlug(MTP_string(slug)),
MTP_int(0)
)).done([=](const MTPpayments_StarGiftAuctionState &result) {
const auto &data = result.data();
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
auto gift = Api::FromTL(_session, data.vgift());
if (!gift || !gift->id) {
_slugRequests.erase(slug);
return;
}
const auto giftId = gift->id;
_slugToGiftId.emplace(slug, giftId);
auto &entry = _map[giftId];
if (!entry) {
entry = std::make_unique<Entry>();
}
const auto raw = entry.get();
raw->state.gift = std::move(gift);
applyStateResponse(raw, result);
auto callbacks = std::move(_slugRequests[slug].callbacks);
_slugRequests.erase(slug);
for (const auto &callback : callbacks) {
callback(giftId);
}
}).fail([=] {
_slugRequests.erase(slug);
}).send();
}
void GiftAuctions::applyStateResponse(
not_null<Entry*> entry,
const MTPpayments_StarGiftAuctionState &result) {
const auto &data = result.data();
const auto timeout = data.vtimeout().v;
const auto ms = timeout * crl::time(1000);
entry->state.subscribedTill = ms ? (crl::now() + ms) : -1;
const auto was = myStateKey(entry->state);
apply(entry, data.vstate());
apply(entry, data.vuser_state());
if (entry->changes.has_consumers()) {
entry->changes.fire({});
if (ms && (!_timer.isActive() || _timer.remainingTime() > ms)) {
_timer.callOnce(ms);
}
}
if (was != myStateKey(entry->state)) {
_activeChanged.fire({});
}
}
rpl::producer<GiftAuctionState> GiftAuctions::state(uint64 giftId) {
return [=](auto consumer) {
auto lifetime = rpl::lifetime();
auto &entry = _map[giftId];
if (!entry) {
entry = std::make_unique<Entry>();
}
const auto raw = entry.get();
raw->changes.events() | rpl::on_next([=] {
consumer.put_next_copy(raw->state);
}, lifetime);
const auto now = crl::now();
if (raw->state.subscribedTill < 0
|| raw->state.subscribedTill >= now) {
consumer.put_next_copy(raw->state);
} else if (raw->state.subscribedTill >= 0) {
request(giftId);
}
return lifetime;
};
}
void GiftAuctions::apply(const MTPDupdateStarGiftAuctionState &data) {
if (const auto entry = find(data.vgift_id().v)) {
const auto was = myStateKey(entry->state);
apply(entry, data.vstate());
entry->changes.fire({});
if (was != myStateKey(entry->state)) {
_activeChanged.fire({});
}
} else {
requestActive();
}
}
void GiftAuctions::apply(const MTPDupdateStarGiftAuctionUserState &data) {
if (const auto entry = find(data.vgift_id().v)) {
const auto was = myStateKey(entry->state);
apply(entry, data.vuser_state());
entry->changes.fire({});
if (was != myStateKey(entry->state)) {
_activeChanged.fire({});
}
} else {
requestActive();
}
}
void GiftAuctions::requestAcquired(
uint64 giftId,
Fn<void(std::vector<Data::GiftAcquired>)> done) {
Expects(done != nullptr);
_session->api().request(MTPpayments_GetStarGiftAuctionAcquiredGifts(
MTP_long(giftId)
)).done([=](const MTPpayments_StarGiftAuctionAcquiredGifts &result) {
const auto &data = result.data();
const auto owner = &_session->data();
owner->processUsers(data.vusers());
owner->processChats(data.vchats());
const auto &list = data.vgifts().v;
auto gifts = std::vector<Data::GiftAcquired>();
gifts.reserve(list.size());
for (const auto &gift : list) {
const auto &data = gift.data();
gifts.push_back({
.to = owner->peer(peerFromMTP(data.vpeer())),
.message = (data.vmessage()
? Api::ParseTextWithEntities(_session, *data.vmessage())
: TextWithEntities()),
.date = data.vdate().v,
.bidAmount = int64(data.vbid_amount().v),
.round = data.vround().v,
.number = data.vgift_num().value_or_empty(),
.position = data.vpos().v,
.nameHidden = data.is_name_hidden(),
});
}
if (const auto entry = find(giftId)) {
const auto count = int(gifts.size());
if (entry->state.my.gotCount != count) {
entry->state.my.gotCount = count;
entry->changes.fire({});
}
}
done(std::move(gifts));
}).fail([=] {
done({});
}).send();
}
std::optional<Data::UniqueGiftAttributes> GiftAuctions::attributes(
uint64 giftId) const {
const auto i = _attributes.find(giftId);
return (i != end(_attributes) && i->second.waiters.empty())
? i->second.lists
: std::optional<Data::UniqueGiftAttributes>();
}
void GiftAuctions::requestAttributes(uint64 giftId, Fn<void()> ready) {
auto &entry = _attributes[giftId];
entry.waiters.push_back(std::move(ready));
if (entry.waiters.size() > 1) {
return;
}
_session->api().request(MTPpayments_GetStarGiftUpgradeAttributes(
MTP_long(giftId)
)).done([=](const MTPpayments_StarGiftUpgradeAttributes &result) {
const auto &attributes = result.data().vattributes().v;
auto &entry = _attributes[giftId];
auto &info = entry.lists;
info.models.reserve(attributes.size());
info.patterns.reserve(attributes.size());
info.backdrops.reserve(attributes.size());
for (const auto &attribute : attributes) {
attribute.match([&](const MTPDstarGiftAttributeModel &data) {
info.models.push_back(Api::FromTL(_session, data));
}, [&](const MTPDstarGiftAttributePattern &data) {
info.patterns.push_back(Api::FromTL(_session, data));
}, [&](const MTPDstarGiftAttributeBackdrop &data) {
info.backdrops.push_back(Api::FromTL(data));
}, [](const MTPDstarGiftAttributeOriginalDetails &data) {
});
}
for (const auto &ready : base::take(entry.waiters)) {
if (ready) ready();
}
}).fail([=] {
for (const auto &ready : base::take(_attributes[giftId].waiters)) {
if (ready) ready();
}
}).send();
}
rpl::producer<ActiveAuctions> GiftAuctions::active() const {
return _activeChanged.events_starting_with_copy(
rpl::empty
) | rpl::map([=] {
return collectActive();
});
}
rpl::producer<bool> GiftAuctions::hasActiveChanges() const {
const auto has = hasActive();
return _activeChanged.events(
) | rpl::map([=] {
return hasActive();
}) | rpl::combine_previous(
has
) | rpl::filter([=](bool previous, bool current) {
return previous != current;
}) | rpl::map([=](bool previous, bool current) {
return current;
});
}
bool GiftAuctions::hasActive() const {
for (const auto &[giftId, entry] : _map) {
if (myStateKey(entry->state)) {
return true;
}
}
return false;
}
void GiftAuctions::checkSubscriptions() {
const auto now = crl::now();
auto next = crl::time();
for (const auto &[giftId, entry] : _map) {
const auto raw = entry.get();
const auto till = raw->state.subscribedTill;
if (till <= 0 || !raw->changes.has_consumers()) {
continue;
} else if (till <= now) {
request(giftId);
} else {
const auto timeout = till - now;
if (!next || timeout < next) {
next = timeout;
}
}
}
if (next) {
_timer.callOnce(next);
}
}
auto GiftAuctions::myStateKey(const GiftAuctionState &state) const
-> MyStateKey {
if (!state.my.bid) {
return {};
}
auto min = 0;
for (const auto &level : state.bidLevels) {
if (level.position > state.gift->auctionGiftsPerRound) {
break;
} else if (!min || min > level.amount) {
min = level.amount;
}
}
return {
.bid = int(state.my.bid),
.position = MyAuctionPosition(state),
.version = state.version,
};
}
ActiveAuctions GiftAuctions::collectActive() const {
auto result = ActiveAuctions();
result.list.reserve(_map.size());
for (const auto &[giftId, entry] : _map) {
const auto raw = &entry->state;
if (raw->gift && raw->my.date) {
result.list.push_back(raw);
}
}
return result;
}
uint64 GiftAuctions::countActiveHash() const {
// The server hashes the auctions in a fixed order, so we have to sort
// them by (date, version) before hashing, just like the Android client
// does in GiftAuctionController::calculateUserAuctionsHash. Otherwise
// the server will never answer with starGiftActiveAuctionsNotModified.
auto list = collectActive().list;
ranges::sort(list, ranges::less(), [](const auto &active) {
return (uint64(uint32(active->my.date)) << 32)
| uint32(active->version);
});
auto result = Api::HashInit();
for (const auto &active : list) {
Api::HashUpdate(result, active->version);
Api::HashUpdate(result, active->my.date);
}
return Api::HashFinalize(result);
}
void GiftAuctions::requestActive() {
if (_activeRequestId) {
return;
}
_activeRequestId = _session->api().request(
MTPpayments_GetStarGiftActiveAuctions(MTP_long(countActiveHash()))
).done([=](const MTPpayments_StarGiftActiveAuctions &result) {
_activeRequestId = 0;
result.match([=](const MTPDpayments_starGiftActiveAuctions &data) {
const auto owner = &_session->data();
owner->processUsers(data.vusers());
owner->processChats(data.vchats());
auto giftsFound = base::flat_set<uint64>();
const auto &list = data.vauctions().v;
giftsFound.reserve(list.size());
for (const auto &auction : list) {
const auto &data = auction.data();
auto gift = Api::FromTL(_session, data.vgift());
if (!gift || !gift->id) {
LOG(("Api Error: Bad auction gift."));
continue;
}
const auto giftId = gift->id;
auto &entry = _map[giftId];
if (!entry) {
entry = std::make_unique<Entry>();
}
const auto raw = entry.get();
if (!raw->state.gift) {
raw->state.gift = std::move(gift);
}
apply(raw, data.vstate());
apply(raw, data.vuser_state());
giftsFound.emplace(giftId);
}
for (const auto &[giftId, entry] : _map) {
const auto my = &entry->state.my;
if (my->date && !giftsFound.contains(giftId)) {
my->to = nullptr;
my->minBidAmount = 0;
my->bid = 0;
my->date = 0;
my->returned = false;
giftsFound.emplace(giftId);
}
}
for (const auto &giftId : giftsFound) {
_map[giftId]->changes.fire({});
}
_activeChanged.fire({});
}, [](const MTPDpayments_starGiftActiveAuctionsNotModified &) {
});
}).send();
}
void GiftAuctions::request(uint64 giftId) {
auto it = _map.find(giftId);
if (it == _map.end()) {
return;
}
const auto raw = it->second.get();
if (raw->requested) {
return;
}
raw->requested = true;
_session->api().request(MTPpayments_GetStarGiftAuctionState(
MTP_inputStarGiftAuction(MTP_long(giftId)),
MTP_int(raw->state.version)
)).done([=](const MTPpayments_StarGiftAuctionState &result) {
auto it = _map.find(giftId);
if (it == _map.end()) {
return;
}
const auto raw = it->second.get();
raw->requested = false;
const auto &data = result.data();
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
raw->state.gift = Api::FromTL(_session, data.vgift());
if (!raw->state.gift) {
return;
}
applyStateResponse(raw, result);
}).fail([=] {
auto it = _map.find(giftId);
if (it != _map.end()) {
it->second->requested = false;
}
}).send();
}
GiftAuctions::Entry *GiftAuctions::find(uint64 giftId) const {
const auto it = _map.find(giftId);
return (it != _map.end()) ? it->second.get() : nullptr;
}
void GiftAuctions::apply(
not_null<Entry*> entry,
const MTPStarGiftAuctionState &state) {
apply(&entry->state, state);
}
void GiftAuctions::apply(
not_null<GiftAuctionState*> entry,
const MTPStarGiftAuctionState &state) {
Expects(entry->gift.has_value());
state.match([&](const MTPDstarGiftAuctionState &data) {
const auto version = data.vversion().v;
if (entry->version >= version) {
return;
}
const auto owner = &_session->data();
entry->startDate = data.vstart_date().v;
entry->endDate = data.vend_date().v;
entry->minBidAmount = data.vmin_bid_amount().v;
const auto &levels = data.vbid_levels().v;
entry->bidLevels.clear();
entry->bidLevels.reserve(levels.size());
for (const auto &level : levels) {
auto &bid = entry->bidLevels.emplace_back();
const auto &data = level.data();
bid.amount = data.vamount().v;
bid.position = data.vpos().v;
bid.date = data.vdate().v;
}
const auto &top = data.vtop_bidders().v;
entry->topBidders.clear();
entry->topBidders.reserve(top.size());
for (const auto &user : top) {
entry->topBidders.push_back(owner->user(UserId(user.v)));
}
entry->nextRoundAt = data.vnext_round_at().v;
entry->giftsLeft = data.vgifts_left().v;
entry->currentRound = data.vcurrent_round().v;
entry->totalRounds = data.vtotal_rounds().v;
const auto &rounds = data.vrounds().v;
entry->roundParameters.clear();
entry->roundParameters.reserve(rounds.size());
for (const auto &round : rounds) {
round.match([&](const MTPDstarGiftAuctionRound &data) {
entry->roundParameters.push_back({
.number = data.vnum().v,
.duration = data.vduration().v,
});
}, [&](const MTPDstarGiftAuctionRoundExtendable &data) {
entry->roundParameters.push_back({
.number = data.vnum().v,
.duration = data.vduration().v,
.extendTop = data.vextend_top().v,
.extendDuration = data.vextend_window().v,
});
});
}
entry->averagePrice = 0;
}, [&](const MTPDstarGiftAuctionStateFinished &data) {
entry->averagePrice = data.vaverage_price().v;
entry->startDate = data.vstart_date().v;
entry->endDate = data.vend_date().v;
entry->minBidAmount = 0;
entry->nextRoundAt
= entry->currentRound
= entry->totalRounds
= entry->giftsLeft
= entry->version
= 0;
}, [&](const MTPDstarGiftAuctionStateNotModified &data) {
});
}
void GiftAuctions::apply(
not_null<Entry*> entry,
const MTPStarGiftAuctionUserState &state) {
apply(&entry->state.my, state);
}
void GiftAuctions::apply(
not_null<StarGiftAuctionMyState*> entry,
const MTPStarGiftAuctionUserState &state) {
const auto &data = state.data();
entry->to = data.vbid_peer()
? _session->data().peer(peerFromMTP(*data.vbid_peer())).get()
: nullptr;
entry->minBidAmount = data.vmin_bid_amount().value_or(0);
entry->bid = data.vbid_amount().value_or(0);
entry->date = data.vbid_date().value_or(0);
entry->gotCount = data.vacquired_count().v;
entry->returned = data.is_returned();
}
int MyAuctionPosition(const GiftAuctionState &state) {
const auto &levels = state.bidLevels;
for (auto i = begin(levels), e = end(levels); i != e; ++i) {
if (i->amount < state.my.bid
|| (i->amount == state.my.bid && i->date >= state.my.date)) {
return i->position;
}
}
return (levels.empty() ? 0 : levels.back().position) + 1;
}
} // namespace Data