-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Expand file tree
/
Copy pathdata_peer.cpp
More file actions
2334 lines (2095 loc) · 61.1 KB
/
Copy pathdata_peer.cpp
File metadata and controls
2334 lines (2095 loc) · 61.1 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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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/data_peer.h"
#include "api/api_sensitive_content.h"
#include "data/data_user.h"
#include "data/data_chat.h"
#include "data/data_chat_participant_status.h"
#include "data/data_channel.h"
#include "data/data_changes.h"
#include "data/data_emoji_statuses.h"
#include "data/data_message_reaction_id.h"
#include "data/data_photo.h"
#include "data/data_folder.h"
#include "data/data_forum.h"
#include "data/data_forum_topic.h"
#include "data/data_saved_messages.h"
#include "data/data_session.h"
#include "data/data_file_origin.h"
#include "data/data_histories.h"
#include "data/data_cloud_themes.h"
#include "base/unixtime.h"
#include "base/crc32hash.h"
#include "lang/lang_keys.h"
#include "apiwrap.h"
#include "api/api_chat_participants.h"
#include "ui/boxes/confirm_box.h"
#include "main/main_session.h"
#include "main/main_session_settings.h"
#include "main/main_domain.h"
#include "main/main_app_config.h"
#include "mtproto/mtproto_config.h"
#include "core/application.h"
#include "core/click_handler_types.h"
#include "window/notifications_manager.h"
#include "window/window_session_controller.h"
#include "window/main_window.h" // Window::LogoNoMargin.
#include "ui/image/image.h"
#include "ui/chat/chat_style.h"
#include "ui/empty_userpic.h"
#include "ui/text/text_options.h"
#include "ui/painter.h"
#include "ui/unread_badge.h"
#include "ui/ui_utility.h"
#include "history/history.h"
#include "history/view/history_view_element.h"
#include "history/history_item.h"
#include "storage/file_download.h"
#include "storage/storage_account.h"
#include "storage/storage_facade.h"
#include "storage/storage_shared_media.h"
namespace {
constexpr auto kUpdateFullPeerTimeout = crl::time(5000); // Not more than once in 5 seconds.
constexpr auto kUserpicSize = 160;
using UpdateFlag = Data::PeerUpdate::Flag;
[[nodiscard]] const std::vector<QString> &IgnoredReasons(
not_null<Main::Session*> session) {
return session->appConfig().ignoredRestrictionReasons();
}
[[nodiscard]] int ParseRegistrationDate(const QString &text) {
// MM.YYYY
if (text.size() != 7 || text[2] != '.') {
return 0;
}
const auto month = text.mid(0, 2).toInt();
const auto year = text.mid(3, 4).toInt();
return (year > 2012 && year < 2100 && month > 0 && month <= 12)
? (year * 100) + month
: 0;
}
[[nodiscard]] int RegistrationYear(int date) {
const auto year = date / 100;
return (year > 2012 && year < 2100) ? year : 0;
}
[[nodiscard]] int RegistrationMonth(int date) {
const auto month = date % 100;
return (month > 0 && month <= 12) ? month : 0;
}
} // namespace
namespace Data {
uint8 DecideColorIndex(PeerId peerId) {
return Ui::DecideColorIndex(peerId.value & PeerId::kChatTypeMask);
}
PeerId FakePeerIdForJustName(const QString &name) {
constexpr auto kShift = (0xFEULL << 32);
const auto base = name.isEmpty()
? 777
: base::crc32(name.constData(), name.size() * sizeof(QChar));
return peerFromUser(kShift + std::abs(base));
}
bool UnavailableReason::sensitive() const {
return reason == u"sensitive"_q;
}
UnavailableReason UnavailableReason::Sensitive() {
return { u"sensitive"_q };
}
QString UnavailableReason::Compute(
not_null<Main::Session*> session,
const std::vector<UnavailableReason> &list) {
const auto &skip = IgnoredReasons(session);
auto &&filtered = ranges::views::all(
list
) | ranges::views::filter([&](const Data::UnavailableReason &reason) {
return !reason.sensitive()
&& !ranges::contains(skip, reason.reason);
});
const auto first = filtered.begin();
return (first != filtered.end()) ? first->text : QString();
}
bool UnavailableReason::IgnoreSensitiveMark(
not_null<Main::Session*> session) {
return ranges::contains(
IgnoredReasons(session),
UnavailableReason::Sensitive().reason);
}
// We should get a full restriction in "{full}: {reason}" format and we
// need to find an "-all" tag in {full}, otherwise ignore this restriction.
std::vector<UnavailableReason> UnavailableReason::Extract(
const MTPvector<MTPRestrictionReason> *list) {
if (!list) {
return {};
}
return ranges::views::all(
list->v
) | ranges::views::filter([](const MTPRestrictionReason &restriction) {
return restriction.match([&](const MTPDrestrictionReason &data) {
const auto platform = data.vplatform().v;
return false
#ifdef OS_MAC_STORE
|| (platform == "ios"_q)
#elif defined OS_WIN_STORE // OS_MAC_STORE
|| (platform == "ms"_q)
#endif // OS_MAC_STORE || OS_WIN_STORE
|| (platform == "all"_q);
});
}) | ranges::views::transform([](const MTPRestrictionReason &restriction) {
return restriction.match([&](const MTPDrestrictionReason &data) {
return UnavailableReason{ qs(data.vreason()), qs(data.vtext()) };
});
}) | ranges::to_vector;
}
bool ApplyBotMenuButton(
not_null<BotInfo*> info,
const MTPBotMenuButton *button) {
auto text = QString();
auto url = QString();
if (button) {
button->match([&](const MTPDbotMenuButton &data) {
text = qs(data.vtext());
url = qs(data.vurl());
}, [&](const auto &) {
});
}
const auto changed = (info->botMenuButtonText != text)
|| (info->botMenuButtonUrl != url);
info->botMenuButtonText = text;
info->botMenuButtonUrl = url;
return changed;
}
AllowedReactions Parse(
const MTPChatReactions &value,
int maxCount,
bool paidEnabled) {
return value.match([&](const MTPDchatReactionsNone &) {
return AllowedReactions{
.maxCount = maxCount,
.paidEnabled = paidEnabled,
};
}, [&](const MTPDchatReactionsAll &data) {
return AllowedReactions{
.maxCount = maxCount,
.type = (data.is_allow_custom()
? AllowedReactionsType::All
: AllowedReactionsType::Default),
.paidEnabled = paidEnabled,
};
}, [&](const MTPDchatReactionsSome &data) {
return AllowedReactions{
.some = ranges::views::all(
data.vreactions().v
) | ranges::views::transform(
ReactionFromMTP
) | ranges::to_vector,
.maxCount = maxCount,
.type = AllowedReactionsType::Some,
.paidEnabled = paidEnabled,
};
});
}
PeerData *PeerFromInputMTP(
not_null<Session*> owner,
const MTPInputPeer &input) {
return input.match([&](const MTPDinputPeerUser &data) {
const auto user = owner->user(data.vuser_id().v);
user->setAccessHash(data.vaccess_hash().v);
return (PeerData*)user;
}, [&](const MTPDinputPeerChat &data) {
return (PeerData*)owner->chat(data.vchat_id().v);
}, [&](const MTPDinputPeerChannel &data) {
const auto channel = owner->channel(data.vchannel_id().v);
channel->setAccessHash(data.vaccess_hash().v);
return (PeerData*)channel;
}, [&](const MTPDinputPeerSelf &data) {
return (PeerData*)owner->session().user();
}, [&](const auto &data) {
return (PeerData*)nullptr;
});
}
UserData *UserFromInputMTP(
not_null<Session*> owner,
const MTPInputUser &input) {
return input.match([&](const MTPDinputUser &data) {
const auto user = owner->user(data.vuser_id().v);
user->setAccessHash(data.vaccess_hash().v);
return user.get();
}, [&](const MTPDinputUserSelf &data) {
return owner->session().user().get();
}, [](const auto &data) {
return (UserData*)nullptr;
});
}
Ui::ColorCollectible ParseColorCollectible(
const MTPDpeerColorCollectible &data) {
return {
.collectibleId = data.vcollectible_id().v,
.giftEmojiId = data.vgift_emoji_id().v,
.backgroundEmojiId = data.vbackground_emoji_id().v,
.accentColor = Ui::ColorFromSerialized(data.vaccent_color()),
.strip = ranges::views::all(
data.vcolors().v
) | ranges::views::transform(
&Ui::ColorFromSerialized
) | ranges::to_vector,
.darkAccentColor = Ui::MaybeColorFromSerialized(
data.vdark_accent_color()).value_or(QColor(0, 0, 0, 0)),
.darkStrip = (data.vdark_colors()
? ranges::views::all(
data.vdark_colors()->v
) | ranges::views::transform(
&Ui::ColorFromSerialized
) | ranges::to_vector
: std::vector<QColor>()),
};
}
} // namespace Data
PeerClickHandler::PeerClickHandler(not_null<PeerData*> peer)
: _peer(peer) {
setProperty(kPeerLinkPeerIdProperty, peer->id.value);
}
void PeerClickHandler::onClick(ClickContext context) const {
if (context.button != Qt::LeftButton) {
return;
}
const auto my = context.other.value<ClickHandlerContext>();
const auto window = [&]() -> Window::SessionController* {
if (const auto controller = my.sessionWindow.get()) {
return controller;
}
const auto &windows = _peer->session().windows();
if (windows.empty()) {
_peer->session().domain().activate(&_peer->session().account());
if (windows.empty()) {
return nullptr;
}
}
return windows.front();
}();
if (window) {
window->showPeer(_peer);
}
}
PeerData::PeerData(not_null<Data::Session*> owner, PeerId id)
: id(id)
, _owner(owner)
, _colorIndex(Data::DecideColorIndex(id)) {
}
Data::Session &PeerData::owner() const {
return *_owner;
}
Main::Session &PeerData::session() const {
return _owner->session();
}
Main::Account &PeerData::account() const {
return session().account();
}
void PeerData::updateNameDelayed(
const QString &newName,
const QString &newNameOrPhone,
const QString &newUsername) {
if (_name == newName && _nameVersion > 1) {
if (isUser()) {
if (asUser()->nameOrPhone == newNameOrPhone
&& asUser()->editableUsername() == newUsername) {
return;
}
} else if (isChannel()) {
if (asChannel()->editableUsername() == newUsername) {
return;
}
} else if (isChat()) {
return;
}
}
_name = newName;
invalidateEmptyUserpic();
auto flags = UpdateFlag::None | UpdateFlag::None;
auto oldFirstLetters = base::flat_set<QChar>();
const auto nameUpdated = (_nameVersion++ > 1);
if (nameUpdated) {
oldFirstLetters = nameFirstLetters();
flags |= UpdateFlag::Name;
}
if (isUser()) {
if (asUser()->editableUsername() != newUsername) {
asUser()->setUsername(newUsername);
flags |= UpdateFlag::Username;
}
asUser()->setNameOrPhone(newNameOrPhone);
} else if (isChannel()) {
if (asChannel()->editableUsername() != newUsername) {
asChannel()->setUsername(newUsername);
if (asChannel()->username().isEmpty()) {
asChannel()->removeFlags(ChannelDataFlag::Username);
} else {
asChannel()->addFlags(ChannelDataFlag::Username);
}
flags |= UpdateFlag::Username;
}
}
fillNames();
if (nameUpdated) {
session().changes().nameUpdated(this, std::move(oldFirstLetters));
}
if (flags) {
session().changes().peerUpdated(this, flags);
}
}
not_null<Ui::EmptyUserpic*> PeerData::ensureEmptyUserpic() const {
if (!_userpicEmpty) {
const auto user = asUser();
_userpicEmpty = std::make_unique<Ui::EmptyUserpic>(
Ui::EmptyUserpic::UserpicColor(colorIndex()),
((user && user->isInaccessible())
? Ui::EmptyUserpic::InaccessibleName()
: name()));
}
return _userpicEmpty.get();
}
void PeerData::invalidateEmptyUserpic() {
_userpicEmpty = nullptr;
}
void PeerData::checkTrustedPayForMessage() {
if (!_checkedTrustedPayForMessage
&& !starsPerMessage()
&& session().local().peerTrustedPayForMessageRead()) {
_checkedTrustedPayForMessage = 1;
if (session().local().hasPeerTrustedPayForMessageEntry(id)) {
session().local().clearPeerTrustedPayForMessage(id);
}
}
}
ClickHandlerPtr PeerData::createOpenLink() {
return std::make_shared<PeerClickHandler>(this);
}
void PeerData::setUserpic(
PhotoId photoId,
const ImageLocation &location,
bool hasVideo) {
_userpicPhotoId = photoId;
_userpicHasVideo = hasVideo ? 1 : 0;
_userpic.set(&session(), ImageWithLocation{ .location = location });
}
void PeerData::setUserpicPhoto(const MTPPhoto &data) {
const auto photoId = data.match([&](const MTPDphoto &data) {
const auto photo = owner().processPhoto(data);
photo->peer = this;
return photo->id;
}, [](const MTPDphotoEmpty &data) {
return PhotoId(0);
});
if (_userpicPhotoId != photoId) {
_userpicPhotoId = photoId;
session().changes().peerUpdated(this, UpdateFlag::Photo);
}
}
QImage *PeerData::userpicCloudImage(Ui::PeerUserpicView &view) const {
if (!_userpic.isCurrentView(view.cloud)) {
if (!_userpic.empty()) {
view.cloud = _userpic.createView();
_userpic.load(&session(), userpicOrigin());
} else {
view.cloud = nullptr;
}
view.cached = QImage();
}
if (const auto image = view.cloud.get(); image && !image->isNull()) {
_userpicEmpty = nullptr;
return image;
} else if (isNotificationsUser()) {
static auto result = Window::LogoNoMargin().scaledToWidth(
kUserpicSize,
Qt::SmoothTransformation);
return &result;
}
return nullptr;
}
void PeerData::paintUserpic(
QPainter &p,
Ui::PeerUserpicView &view,
PaintUserpicContext context) const {
if (const auto broadcast = monoforumBroadcast()) {
if (context.shape == Ui::PeerUserpicShape::Auto) {
context.shape = Ui::PeerUserpicShape::Monoforum;
}
broadcast->paintUserpic(p, view, context);
return;
}
const auto size = context.size;
const auto cloud = userpicCloudImage(view);
const auto ratio = style::DevicePixelRatio();
if (context.shape == Ui::PeerUserpicShape::Auto) {
context.shape = userpicShape();
}
Ui::ValidateUserpicCache(
view,
cloud,
cloud ? nullptr : ensureEmptyUserpic().get(),
size * ratio,
context.shape);
p.drawImage(QRect(context.position, QSize(size, size)), view.cached);
}
void PeerData::loadUserpic() {
_userpic.load(&session(), userpicOrigin());
}
bool PeerData::hasUserpic() const {
return !_userpic.empty();
}
Ui::PeerUserpicView PeerData::activeUserpicView() {
return { .cloud = _userpic.empty() ? nullptr : _userpic.activeView() };
}
Ui::PeerUserpicView PeerData::createUserpicView() {
if (_userpic.empty()) {
return {};
}
auto result = _userpic.createView();
_userpic.load(&session(), userpicPhotoOrigin());
return { .cloud = result };
}
bool PeerData::useEmptyUserpic(Ui::PeerUserpicView &view) const {
return !userpicCloudImage(view);
}
InMemoryKey PeerData::userpicUniqueKey(Ui::PeerUserpicView &view) const {
if (const auto broadcast = monoforumBroadcast()) {
return broadcast->userpicUniqueKey(view);
}
return useEmptyUserpic(view)
? ensureEmptyUserpic()->uniqueKey()
: inMemoryKey(_userpic.location());
}
QImage PeerData::GenerateUserpicImage(
not_null<PeerData*> peer,
Ui::PeerUserpicView &view,
int size,
std::optional<int> radius) {
if (const auto userpic = peer->userpicCloudImage(view)) {
auto image = userpic->scaled(
{ size, size },
Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
const auto round = [&](int radius) {
return Images::Round(
std::move(image),
Images::CornersMask(radius / style::DevicePixelRatio()));
};
if (radius == 0) {
return image;
} else if (radius) {
return round(*radius);
} else if (peer->isForum()) {
return round(size * Ui::ForumUserpicRadiusMultiplier());
} else {
return Images::Circle(std::move(image));
}
}
auto result = QImage(
QSize(size, size),
QImage::Format_ARGB32_Premultiplied);
result.fill(Qt::transparent);
Painter p(&result);
if (radius == 0) {
peer->ensureEmptyUserpic()->paintSquare(p, 0, 0, size, size);
} else if (radius) {
const auto r = *radius;
peer->ensureEmptyUserpic()->paintRounded(p, 0, 0, size, size, r);
} else if (peer->isForum()) {
peer->ensureEmptyUserpic()->paintRounded(
p,
0,
0,
size,
size,
size * Ui::ForumUserpicRadiusMultiplier());
} else {
peer->ensureEmptyUserpic()->paintCircle(p, 0, 0, size, size);
}
p.end();
return result;
}
ImageLocation PeerData::userpicLocation() const {
return _userpic.location();
}
bool PeerData::userpicPhotoUnknown() const {
return (_userpicPhotoId == kUnknownPhotoId);
}
PhotoId PeerData::userpicPhotoId() const {
return userpicPhotoUnknown() ? 0 : _userpicPhotoId;
}
bool PeerData::userpicHasVideo() const {
return _userpicHasVideo != 0;
}
Data::FileOrigin PeerData::userpicOrigin() const {
return Data::FileOriginPeerPhoto(id);
}
Data::FileOrigin PeerData::userpicPhotoOrigin() const {
return (isUser() && userpicPhotoId())
? Data::FileOriginFullUser(peerToUser(id))
: Data::FileOrigin();
}
void PeerData::updateUserpic(
PhotoId photoId,
MTP::DcId dcId,
bool hasVideo) {
setUserpicChecked(
photoId,
ImageLocation(
{ StorageFileLocation(
dcId,
isSelf() ? peerToUser(id) : UserId(),
MTP_inputPeerPhotoFileLocation(
MTP_flags(0),
input(),
MTP_long(photoId))) },
kUserpicSize,
kUserpicSize),
hasVideo);
}
void PeerData::clearUserpic() {
setUserpicChecked(PhotoId(), ImageLocation(), false);
}
void PeerData::setUserpicChecked(
PhotoId photoId,
const ImageLocation &location,
bool hasVideo) {
if (_userpicPhotoId != photoId
|| _userpic.location() != location
|| _userpicHasVideo != (hasVideo ? 1 : 0)) {
const auto known = !userpicPhotoUnknown();
setUserpic(photoId, location, hasVideo);
session().changes().peerUpdated(this, UpdateFlag::Photo);
if (known && isPremium() && userpicPhotoUnknown()) {
updateFull();
}
}
}
auto PeerData::unavailableReasons() const
-> const std::vector<Data::UnavailableReason> & {
static const auto result = std::vector<Data::UnavailableReason>();
return result;
}
QString PeerData::computeUnavailableReason() const {
return Data::UnavailableReason::Compute(
&session(),
unavailableReasons());
}
bool PeerData::hasSensitiveContent() const {
return _sensitiveContent == 1;
}
void PeerData::setUnavailableReasonsList(
std::vector<Data::UnavailableReason> &&reasons) {
Unexpected("PeerData::setUnavailableReasonsList.");
}
void PeerData::setUnavailableReasons(
std::vector<Data::UnavailableReason> &&reasons) {
const auto i = ranges::find(
reasons,
true,
&Data::UnavailableReason::sensitive);
const auto sensitive = (i != end(reasons));
if (sensitive) {
reasons.erase(i);
}
auto changed = (sensitive != hasSensitiveContent());
if (changed) {
setHasSensitiveContent(sensitive);
}
if (reasons != unavailableReasons()) {
setUnavailableReasonsList(std::move(reasons));
changed = true;
}
if (changed) {
session().changes().peerUpdated(
this,
UpdateFlag::UnavailableReason);
}
}
void PeerData::setHasSensitiveContent(bool has) {
_sensitiveContent = has ? 1 : 0;
if (has) {
session().api().sensitiveContent().preload();
}
}
// This is duplicated in CanPinMessagesValue().
bool PeerData::canPinMessages() const {
if (const auto user = asUser()) {
return !user->amRestricted(ChatRestriction::PinMessages);
} else if (const auto chat = asChat()) {
return chat->amIn()
&& !chat->amRestricted(ChatRestriction::PinMessages);
} else if (const auto channel = asChannel()) {
return channel->isMegagroup()
? !channel->amRestricted(ChatRestriction::PinMessages)
: ((channel->amCreator()
|| channel->adminRights() & ChatAdminRight::EditMessages));
}
Unexpected("Peer type in PeerData::canPinMessages.");
}
bool PeerData::canCreatePolls(bool forbidInForums) const {
if (const auto user = asUser()) {
return user->isSelf()
|| (user->isBot()
&& !user->isSupport()
&& !user->isRepliesChat()
&& !user->isVerifyCodes());
} else if (isMonoforum()) {
return false;
}
return Data::CanSend(this, ChatRestriction::SendPolls, forbidInForums);
}
bool PeerData::canCreateTodoLists(bool forbidInForums) const {
if (isMonoforum() || isBroadcast()) {
return false;
}
return session().premium()
&& (Data::CanSend(this, ChatRestriction::SendPolls, forbidInForums)
|| isUser());
}
bool PeerData::canCreateTopics() const {
if (const auto bot = asBot()) {
return bot->isForum();
} else if (const auto channel = asChannel()) {
return channel->isForum()
&& !channel->amRestricted(ChatRestriction::CreateTopics);
}
return false;
}
bool PeerData::canManageTopics() const {
if (const auto bot = asBot()) {
return bot->isForum();
} else if (const auto channel = asChannel()) {
return channel->isForum()
&& (channel->amCreator()
|| (channel->adminRights() & ChatAdminRight::ManageTopics));
}
return false;
}
bool PeerData::canPostStories() const {
if (const auto channel = asChannel()) {
return channel->canPostStories();
}
return isSelf();
}
bool PeerData::canEditStories() const {
if (const auto channel = asChannel()) {
return channel->canEditStories();
}
return isSelf();
}
bool PeerData::canDeleteStories() const {
if (const auto channel = asChannel()) {
return channel->canDeleteStories();
}
return isSelf();
}
bool PeerData::canManageGifts() const {
if (const auto channel = asChannel()) {
return channel->canPostMessages();
}
return isSelf();
}
bool PeerData::canTransferGifts() const {
if (const auto channel = asChannel()) {
return channel->amCreator();
}
return isSelf();
}
bool PeerData::canEditMessagesIndefinitely() const {
if (const auto user = asUser()) {
return user->isSelf();
} else if (isChat()) {
return false;
} else if (const auto channel = asChannel()) {
return channel->isMegagroup()
? channel->canPinMessages()
: channel->canEditMessages();
}
Unexpected("Peer type in PeerData::canEditMessagesIndefinitely.");
}
bool PeerData::canExportChatHistory() const {
if (isRepliesChat() || isVerifyCodes() || !allowsForwarding()) {
return false;
} else if (const auto channel = asChannel()) {
if (!channel->amIn() && channel->invitePeekExpires()) {
return false;
}
}
for (const auto &block : _owner->history(id)->blocks) {
for (const auto &message : block->messages) {
if (!message->data()->isService()) {
return true;
}
}
}
if (const auto from = migrateFrom()) {
return from->canExportChatHistory();
}
return false;
}
bool PeerData::autoTranslation() const {
if (const auto channel = asChannel()) {
return channel->autoTranslation();
}
return false;
}
bool PeerData::setAbout(const QString &newAbout) {
if (_about == newAbout) {
return false;
}
_about = newAbout;
session().changes().peerUpdated(this, UpdateFlag::About);
return true;
}
void PeerData::checkFolder(FolderId folderId) {
const auto folder = folderId
? owner().folderLoaded(folderId)
: nullptr;
if (const auto history = owner().historyLoaded(this)) {
if (folder && history->folder() != folder) {
owner().histories().requestDialogEntry(history);
}
}
}
void PeerData::clearBusinessBot() {
if (const auto details = _barDetails.get()) {
if (details->requestChatDate
|| details->paysPerMessage
|| !details->phoneCountryCode.isEmpty()) {
details->businessBot = nullptr;
details->businessBotManageUrl = QString();
} else {
_barDetails = nullptr;
}
}
if (const auto settings = barSettings()) {
setBarSettings(*settings
& ~PeerBarSetting::BusinessBotPaused
& ~PeerBarSetting::BusinessBotCanReply
& ~PeerBarSetting::HasBusinessBot);
}
}
void PeerData::setTranslationDisabled(bool disabled) {
const auto flag = disabled
? TranslationFlag::Disabled
: TranslationFlag::Enabled;
if (_translationFlag != flag) {
_translationFlag = flag;
session().changes().peerUpdated(
this,
UpdateFlag::TranslationDisabled);
}
}
PeerData::TranslationFlag PeerData::translationFlag() const {
return _translationFlag;
}
void PeerData::saveTranslationDisabled(bool disabled) {
setTranslationDisabled(disabled);
using Flag = MTPmessages_TogglePeerTranslations::Flag;
session().api().request(MTPmessages_TogglePeerTranslations(
MTP_flags(disabled ? Flag::f_disabled : Flag()),
input()
)).send();
}
void PeerData::setBarSettings(const MTPPeerSettings &data) {
data.match([&](const MTPDpeerSettings &data) {
const auto wasPaysPerMessage = paysPerMessage();
if (!data.vbusiness_bot_id()
&& !data.vrequest_chat_title()
&& !data.vcharge_paid_message_stars()
&& !data.vphone_country()
&& !data.vregistration_month()
&& !data.vname_change_date()
&& !data.vphoto_change_date()) {
_barDetails = nullptr;
} else if (!_barDetails) {
_barDetails = std::make_unique<PeerBarDetails>();
}
if (_barDetails) {
_barDetails->phoneCountryCode
= qs(data.vphone_country().value_or_empty());
_barDetails->registrationDate = ParseRegistrationDate(
data.vregistration_month().value_or_empty());
_barDetails->nameChangeDate
= data.vname_change_date().value_or_empty();
_barDetails->photoChangeDate
= data.vphoto_change_date().value_or_empty();
_barDetails->requestChatTitle
= qs(data.vrequest_chat_title().value_or_empty());
_barDetails->requestChatDate
= data.vrequest_chat_date().value_or_empty();
_barDetails->businessBot = data.vbusiness_bot_id()
? _owner->user(data.vbusiness_bot_id()->v).get()
: nullptr;
_barDetails->businessBotManageUrl
= qs(data.vbusiness_bot_manage_url().value_or_empty());
_barDetails->paysPerMessage
= data.vcharge_paid_message_stars().value_or_empty();
}
using Flag = PeerBarSetting;
setBarSettings((data.is_add_contact() ? Flag::AddContact : Flag())
| (data.is_autoarchived() ? Flag::AutoArchived : Flag())
| (data.is_block_contact() ? Flag::BlockContact : Flag())
//| (data.is_invite_members() ? Flag::InviteMembers : Flag())
| (data.is_need_contacts_exception()
? Flag::NeedContactsException
: Flag())
//| (data.is_report_geo() ? Flag::ReportGeo : Flag())
| (data.is_report_spam() ? Flag::ReportSpam : Flag())
| (data.is_share_contact() ? Flag::ShareContact : Flag())
| (data.vrequest_chat_title() ? Flag::RequestChat : Flag())
| (data.vbusiness_bot_id() ? Flag::HasBusinessBot : Flag())
| (data.is_request_chat_broadcast()
? Flag::RequestChatIsBroadcast
: Flag())
| (data.is_business_bot_paused()
? Flag::BusinessBotPaused
: Flag())
| (data.is_business_bot_can_reply()
? Flag::BusinessBotCanReply
: Flag()));
if (wasPaysPerMessage != paysPerMessage()) {
session().changes().peerUpdated(
this,
UpdateFlag::PaysPerMessage);
}
});
}
void PeerData::setBarSettings(PeerBarSettings which) {
const auto was = hideLinks();
_barSettings.set(which);
if (was && !hideLinks()) {
if (const auto history = owner().historyLoaded(this)) {
crl::on_main(&history->session(), [=] {
history->refreshHiddenLinksItems();
});
}
if (const auto from = migrateFrom()) {
if (const auto history = owner().historyLoaded(from)) {
crl::on_main(&history->session(), [=] {
history->refreshHiddenLinksItems();
});
}
}
}
}
int PeerData::paysPerMessage() const {
return _barDetails ? _barDetails->paysPerMessage : 0;
}
void PeerData::clearPaysPerMessage() {
if (const auto details = _barDetails.get()) {
if (details->paysPerMessage) {
if (details->businessBot
|| details->requestChatDate
|| !details->phoneCountryCode.isEmpty()) {
details->paysPerMessage = 0;
} else {
_barDetails = nullptr;
}
session().changes().peerUpdated(
this,
UpdateFlag::PaysPerMessage);
}
}
}
bool PeerData::hideLinks() const {
//if (!isUser()) {
// return false;
//}
if (const auto to = migrateTo()) {
return to->hideLinks();
}
const auto settings = barSettings();
return !settings || (*settings & PeerBarSetting::ReportSpam);
}
QString PeerData::requestChatTitle() const {
return _barDetails ? _barDetails->requestChatTitle : QString();
}