forked from telegramdesktop/tdesktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.cpp
2878 lines (2591 loc) · 91.9 KB
/
app.cpp
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 version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "stdafx.h"
#include "app.h"
#ifdef OS_MAC_OLD
#include <libexif/exif-data.h>
#endif // OS_MAC_OLD
#include "styles/style_overview.h"
#include "styles/style_mediaview.h"
#include "styles/style_stickers.h"
#include "styles/style_history.h"
#include "styles/style_boxes.h"
#include "lang.h"
#include "data/data_abstract_structure.h"
#include "history/history_service_layout.h"
#include "history/history_location_manager.h"
#include "history/history_media_types.h"
#include "media/media_audio.h"
#include "inline_bots/inline_bot_layout_item.h"
#include "application.h"
#include "fileuploader.h"
#include "mainwidget.h"
#include "localstorage.h"
#include "apiwrap.h"
#include "numbers.h"
#include "observer_peer.h"
#include "window/window_theme.h"
#include "window/notifications_manager.h"
#include "platform/platform_notifications_manager.h"
namespace {
App::LaunchState _launchState = App::Launched;
UserData *self = nullptr;
using PeersData = QHash<PeerId, PeerData*>;
PeersData peersData;
using MutedPeers = QMap<PeerData*, bool>;
MutedPeers mutedPeers;
using UpdatedPeers = QMap<PeerData*, bool>;
UpdatedPeers updatedPeers;
PhotosData photosData;
DocumentsData documentsData;
using LocationsData = QHash<LocationCoords, LocationData*>;
LocationsData locationsData;
using WebPagesData = QHash<WebPageId, WebPageData*>;
WebPagesData webPagesData;
using GamesData = QHash<GameId, GameData*>;
GamesData gamesData;
PhotoItems photoItems;
DocumentItems documentItems;
WebPageItems webPageItems;
GameItems gameItems;
SharedContactItems sharedContactItems;
GifItems gifItems;
using DependentItemsSet = OrderedSet<HistoryItem*>;
using DependentItems = QMap<HistoryItem*, DependentItemsSet>;
DependentItems dependentItems;
Histories histories;
using MsgsData = QHash<MsgId, HistoryItem*>;
MsgsData msgsData;
using ChannelMsgsData = QMap<ChannelId, MsgsData>;
ChannelMsgsData channelMsgsData;
using RandomData = QMap<uint64, FullMsgId>;
RandomData randomData;
using SentData = QMap<uint64, QPair<PeerId, QString>>;
SentData sentData;
HistoryItem *hoveredItem = nullptr,
*pressedItem = nullptr,
*hoveredLinkItem = nullptr,
*pressedLinkItem = nullptr,
*contextItem = nullptr,
*mousedItem = nullptr;
QPixmap *emoji = nullptr, *emojiLarge = nullptr;
style::font monofont;
struct CornersPixmaps {
CornersPixmaps() {
memset(p, 0, sizeof(p));
}
QPixmap *p[4];
};
CornersPixmaps corners[RoundCornersCount];
using CornersMap = QMap<uint32, CornersPixmaps>;
CornersMap cornersMap;
QImage *cornersMaskLarge[4] = { nullptr }, *cornersMaskSmall[4] = { nullptr };
using EmojiMap = QMap<uint64, QPixmap>;
EmojiMap mainEmojiMap;
QMap<int32, EmojiMap> otherEmojiMap;
int32 serviceImageCacheSize = 0;
using LastPhotosList = QLinkedList<PhotoData*>;
LastPhotosList lastPhotos;
using LastPhotosMap = QHash<PhotoData*, LastPhotosList::iterator>;
LastPhotosMap lastPhotosMap;
}
namespace App {
QString formatPhone(QString phone) {
if (phone.isEmpty()) return QString();
if (phone.at(0) == '0') return phone;
QString number = phone;
for (const QChar *ch = phone.constData(), *e = ch + phone.size(); ch != e; ++ch) {
if (ch->unicode() < '0' || ch->unicode() > '9') {
number = phone.replace(QRegularExpression(qsl("[^\\d]")), QString());
}
}
QVector<int> groups = phoneNumberParse(number);
if (groups.isEmpty()) return '+' + number;
QString result;
result.reserve(number.size() + groups.size() + 1);
result.append('+');
int32 sum = 0;
for (int32 i = 0, l = groups.size(); i < l; ++i) {
result.append(number.midRef(sum, groups.at(i)));
sum += groups.at(i);
if (sum < number.size()) result.append(' ');
}
if (sum < number.size()) result.append(number.midRef(sum));
return result;
}
AppClass *app() {
return AppClass::app();
}
MainWindow *wnd() {
return AppClass::wnd();
}
MainWidget *main() {
if (auto w = wnd()) {
return w->mainWidget();
}
return nullptr;
}
bool passcoded() {
if (auto w = wnd()) {
return w->passcodeWidget();
}
return false;
}
FileUploader *uploader() {
return app() ? app()->uploader() : 0;
}
ApiWrap *api() {
return main() ? main()->api() : 0;
}
namespace {
bool loggedOut() {
if (Global::LocalPasscode()) {
Global::SetLocalPasscode(false);
Global::RefLocalPasscodeChanged().notify();
}
if (audioPlayer()) {
audioPlayer()->stopAndClear();
}
if (auto w = wnd()) {
w->tempDirDelete(Local::ClearManagerAll);
w->notifyClearFast();
w->setupIntro();
}
MTP::setAuthedId(0);
Local::reset();
Window::Theme::Background()->reset();
cSetOtherOnline(0);
histories().clear();
globalNotifyAllPtr = UnknownNotifySettings;
globalNotifyUsersPtr = UnknownNotifySettings;
globalNotifyChatsPtr = UnknownNotifySettings;
if (App::uploader()) App::uploader()->clear();
clearStorageImages();
if (auto w = wnd()) {
w->updateConnectingStatus();
}
return true;
}
} // namespace
void logOut() {
if (MTP::started()) {
MTP::logoutKeys(rpcDone(&loggedOut), rpcFail(&loggedOut));
} else {
loggedOut();
MTP::start();
}
}
TimeId onlineForSort(UserData *user, TimeId now) {
if (isServiceUser(user->id) || user->botInfo) {
return -1;
}
TimeId online = user->onlineTill;
if (online <= 0) {
switch (online) {
case 0:
case -1: return online;
case -2: {
QDate yesterday(date(now).date());
return int32(QDateTime(yesterday.addDays(-3)).toTime_t()) + (unixtime() - myunixtime());
} break;
case -3: {
QDate weekago(date(now).date());
return int32(QDateTime(weekago.addDays(-7)).toTime_t()) + (unixtime() - myunixtime());
} break;
case -4: {
QDate monthago(date(now).date());
return int32(QDateTime(monthago.addDays(-30)).toTime_t()) + (unixtime() - myunixtime());
} break;
}
return -online;
}
return online;
}
int32 onlineWillChangeIn(UserData *user, TimeId now) {
if (isServiceUser(user->id) || user->botInfo) {
return 86400;
}
return onlineWillChangeIn(user->onlineTill, now);
}
int32 onlineWillChangeIn(TimeId online, TimeId now) {
if (online <= 0) {
if (-online > now) return -online - now;
return 86400;
}
if (online > now) {
return online - now;
}
int32 minutes = (now - online) / 60;
if (minutes < 60) {
return (minutes + 1) * 60 - (now - online);
}
int32 hours = (now - online) / 3600;
if (hours < 12) {
return (hours + 1) * 3600 - (now - online);
}
QDateTime dNow(date(now)), dTomorrow(dNow.date().addDays(1));
return dNow.secsTo(dTomorrow);
}
QString onlineText(UserData *user, TimeId now, bool precise) {
if (isNotificationsUser(user->id)) {
return lang(lng_status_service_notifications);
} else if (user->botInfo) {
return lang(lng_status_bot);
} else if (isServiceUser(user->id)) {
return lang(lng_status_support);
}
return onlineText(user->onlineTill, now, precise);
}
QString onlineText(TimeId online, TimeId now, bool precise) {
if (online <= 0) {
switch (online) {
case 0: return lang(lng_status_offline);
case -1: return lang(lng_status_invisible);
case -2: return lang(lng_status_recently);
case -3: return lang(lng_status_last_week);
case -4: return lang(lng_status_last_month);
}
return (-online > now) ? lang(lng_status_online) : lang(lng_status_recently);
}
if (online > now) {
return lang(lng_status_online);
}
QString when;
if (precise) {
QDateTime dOnline(date(online)), dNow(date(now));
if (dOnline.date() == dNow.date()) {
return lng_status_lastseen_today(lt_time, dOnline.time().toString(cTimeFormat()));
} else if (dOnline.date().addDays(1) == dNow.date()) {
return lng_status_lastseen_yesterday(lt_time, dOnline.time().toString(cTimeFormat()));
}
return lng_status_lastseen_date_time(lt_date, dOnline.date().toString(qsl("dd.MM.yy")), lt_time, dOnline.time().toString(cTimeFormat()));
}
int32 minutes = (now - online) / 60;
if (!minutes) {
return lang(lng_status_lastseen_now);
} else if (minutes < 60) {
return lng_status_lastseen_minutes(lt_count, minutes);
}
int32 hours = (now - online) / 3600;
if (hours < 12) {
return lng_status_lastseen_hours(lt_count, hours);
}
QDateTime dOnline(date(online)), dNow(date(now));
if (dOnline.date() == dNow.date()) {
return lng_status_lastseen_today(lt_time, dOnline.time().toString(cTimeFormat()));
} else if (dOnline.date().addDays(1) == dNow.date()) {
return lng_status_lastseen_yesterday(lt_time, dOnline.time().toString(cTimeFormat()));
}
return lng_status_lastseen_date(lt_date, dOnline.date().toString(qsl("dd.MM.yy")));
}
namespace {
// we should get a full restriction in "{fulltype}: {reason}" format and we
// need to find a "-all" tag in {fulltype}, otherwise ignore this restriction
QString extractRestrictionReason(const QString &fullRestriction) {
int fullTypeEnd = fullRestriction.indexOf(':');
if (fullTypeEnd <= 0) {
return QString();
}
// {fulltype} is in "{type}-{tag}-{tag}-{tag}" format
// if we find "all" tag we return the restriction string
auto typeTags = fullRestriction.mid(0, fullTypeEnd).split('-').mid(1);
#ifndef OS_MAC_STORE
auto restrictionApplies = typeTags.contains(qsl("all"));
#else // OS_MAC_STORE
auto restrictionApplies = typeTags.contains(qsl("all")) || typeTags.contains(qsl("ios"));
#endif // OS_MAC_STORE
if (restrictionApplies) {
return fullRestriction.midRef(fullTypeEnd + 1).trimmed().toString();
}
return QString();
}
}
bool onlineColorUse(UserData *user, TimeId now) {
if (isServiceUser(user->id) || user->botInfo) {
return false;
}
return onlineColorUse(user->onlineTill, now);
}
bool onlineColorUse(TimeId online, TimeId now) {
if (online <= 0) {
switch (online) {
case 0:
case -1:
case -2:
case -3:
case -4: return false;
}
return (-online > now);
}
return (online > now);
}
UserData *feedUser(const MTPUser &user) {
UserData *data = nullptr;
bool wasContact = false, minimal = false;
const MTPUserStatus *status = 0, emptyStatus = MTP_userStatusEmpty();
Notify::PeerUpdate update;
using UpdateFlag = Notify::PeerUpdate::Flag;
switch (user.type()) {
case mtpc_userEmpty: {
auto &d = user.c_userEmpty();
auto peer = peerFromUser(d.vid.v);
data = App::user(peer);
auto canShareThisContact = data->canShareThisContactFast();
wasContact = data->isContact();
data->input = MTP_inputPeerUser(d.vid, MTP_long(0));
data->inputUser = MTP_inputUser(d.vid, MTP_long(0));
data->setName(lang(lng_deleted), QString(), QString(), QString());
data->setPhoto(MTP_userProfilePhotoEmpty());
data->access = UserNoAccess;
data->flags = 0;
data->setBotInfoVersion(-1);
status = &emptyStatus;
data->contact = -1;
if (canShareThisContact != data->canShareThisContactFast()) update.flags |= UpdateFlag::UserCanShareContact;
if (wasContact != data->isContact()) update.flags |= UpdateFlag::UserIsContact;
} break;
case mtpc_user: {
auto &d = user.c_user();
minimal = d.is_min();
auto peer = peerFromUser(d.vid.v);
data = App::user(peer);
auto canShareThisContact = data->canShareThisContactFast();
wasContact = data->isContact();
if (!minimal) {
data->flags = d.vflags.v;
if (d.is_self()) {
data->input = MTP_inputPeerSelf();
data->inputUser = MTP_inputUserSelf();
} else if (!d.has_access_hash()) {
data->input = MTP_inputPeerUser(d.vid, MTP_long((data->access == UserNoAccess) ? 0 : data->access));
data->inputUser = MTP_inputUser(d.vid, MTP_long((data->access == UserNoAccess) ? 0 : data->access));
} else {
data->input = MTP_inputPeerUser(d.vid, d.vaccess_hash);
data->inputUser = MTP_inputUser(d.vid, d.vaccess_hash);
}
if (d.is_restricted()) {
data->setRestrictionReason(extractRestrictionReason(qs(d.vrestriction_reason)));
} else {
data->setRestrictionReason(QString());
}
}
if (d.is_deleted()) {
if (!data->phone().isEmpty()) {
data->setPhone(QString());
update.flags |= UpdateFlag::UserPhoneChanged;
}
data->setName(lang(lng_deleted), QString(), QString(), QString());
data->setPhoto(MTP_userProfilePhotoEmpty());
data->access = UserNoAccess;
status = &emptyStatus;
} else {
// apply first_name and last_name from minimal user only if we don't have
// local values for first name and last name already, otherwise skip
bool noLocalName = data->firstName.isEmpty() && data->lastName.isEmpty();
QString fname = (!minimal || noLocalName) ? (d.has_first_name() ? textOneLine(qs(d.vfirst_name)) : QString()) : data->firstName;
QString lname = (!minimal || noLocalName) ? (d.has_last_name() ? textOneLine(qs(d.vlast_name)) : QString()) : data->lastName;
QString phone = minimal ? data->phone() : (d.has_phone() ? qs(d.vphone) : QString());
QString uname = minimal ? data->username : (d.has_username() ? textOneLine(qs(d.vusername)) : QString());
bool phoneChanged = (data->phone() != phone);
if (phoneChanged) {
data->setPhone(phone);
update.flags |= UpdateFlag::UserPhoneChanged;
}
bool nameChanged = (data->firstName != fname) || (data->lastName != lname);
bool showPhone = !isServiceUser(data->id) && !d.is_self() && !d.is_contact() && !d.is_mutual_contact();
bool showPhoneChanged = !isServiceUser(data->id) && !d.is_self() && ((showPhone && data->contact) || (!showPhone && !data->contact));
if (minimal) {
showPhoneChanged = false;
showPhone = !isServiceUser(data->id) && (data->id != peerFromUser(MTP::authedId())) && !data->contact;
}
// see also Local::readPeer
QString pname = (showPhoneChanged || phoneChanged || nameChanged) ? ((showPhone && !phone.isEmpty()) ? formatPhone(phone) : QString()) : data->nameOrPhone;
if (!minimal && d.is_self() && uname != data->username) {
SignalHandlers::setCrashAnnotation("Username", uname);
}
data->setName(fname, lname, pname, uname);
if (d.has_photo()) {
data->setPhoto(d.vphoto);
} else {
data->setPhoto(MTP_userProfilePhotoEmpty());
}
if (d.has_access_hash()) data->access = d.vaccess_hash.v;
status = d.has_status() ? &d.vstatus : &emptyStatus;
}
if (!minimal) {
if (d.has_bot_info_version()) {
data->setBotInfoVersion(d.vbot_info_version.v);
data->botInfo->readsAllHistory = d.is_bot_chat_history();
if (data->botInfo->cantJoinGroups != d.is_bot_nochats()) {
data->botInfo->cantJoinGroups = d.is_bot_nochats();
update.flags |= UpdateFlag::BotCanAddToGroups;
}
data->botInfo->inlinePlaceholder = d.has_bot_inline_placeholder() ? '_' + qs(d.vbot_inline_placeholder) : QString();
} else {
data->setBotInfoVersion(-1);
}
data->contact = (d.is_contact() || d.is_mutual_contact()) ? 1 : (data->phone().isEmpty() ? -1 : 0);
if (data->contact == 1 && cReportSpamStatuses().value(data->id, dbiprsHidden) != dbiprsHidden) {
cRefReportSpamStatuses().insert(data->id, dbiprsHidden);
Local::writeReportSpamStatuses();
}
if (d.is_self() && ::self != data) {
::self = data;
Global::RefSelfChanged().notify();
}
}
if (canShareThisContact != data->canShareThisContactFast()) update.flags |= UpdateFlag::UserCanShareContact;
if (wasContact != data->isContact()) update.flags |= UpdateFlag::UserIsContact;
} break;
}
if (!data) {
return nullptr;
}
if (minimal) {
if (data->loadedStatus == PeerData::NotLoaded) {
data->loadedStatus = PeerData::MinimalLoaded;
}
} else if (data->loadedStatus != PeerData::FullLoaded) {
data->loadedStatus = PeerData::FullLoaded;
}
auto oldOnlineTill = data->onlineTill;
if (status && !minimal) switch (status->type()) {
case mtpc_userStatusEmpty: data->onlineTill = 0; break;
case mtpc_userStatusRecently:
if (data->onlineTill > -10) { // don't modify pseudo-online
data->onlineTill = -2;
}
break;
case mtpc_userStatusLastWeek: data->onlineTill = -3; break;
case mtpc_userStatusLastMonth: data->onlineTill = -4; break;
case mtpc_userStatusOffline: data->onlineTill = status->c_userStatusOffline().vwas_online.v; break;
case mtpc_userStatusOnline: data->onlineTill = status->c_userStatusOnline().vexpires.v; break;
}
if (oldOnlineTill != data->onlineTill) {
update.flags |= UpdateFlag::UserOnlineChanged;
}
if (data->contact < 0 && !data->phone().isEmpty() && peerToUser(data->id) != MTP::authedId()) {
data->contact = 0;
}
if (App::main()) {
if ((data->contact > 0 && !wasContact) || (wasContact && data->contact < 1)) {
Notify::userIsContactChanged(data);
}
markPeerUpdated(data);
if (update.flags) {
update.peer = data;
Notify::peerUpdatedDelayed(update);
}
}
return data;
}
UserData *feedUsers(const MTPVector<MTPUser> &users) {
UserData *result = nullptr;
for_const (auto &user, users.c_vector().v) {
if (auto feededUser = feedUser(user)) {
result = feededUser;
}
}
return result;
}
PeerData *feedChat(const MTPChat &chat) {
PeerData *data = nullptr;
bool minimal = false;
Notify::PeerUpdate update;
using UpdateFlag = Notify::PeerUpdate::Flag;
switch (chat.type()) {
case mtpc_chat: {
auto &d(chat.c_chat());
data = App::chat(peerFromChat(d.vid.v));
auto cdata = data->asChat();
auto canEdit = cdata->canEdit();
if (cdata->version < d.vversion.v) {
cdata->version = d.vversion.v;
cdata->invalidateParticipants();
}
data->input = MTP_inputPeerChat(d.vid);
cdata->setName(qs(d.vtitle));
cdata->setPhoto(d.vphoto);
cdata->date = d.vdate.v;
if (d.has_migrated_to() && d.vmigrated_to.type() == mtpc_inputChannel) {
const auto &c(d.vmigrated_to.c_inputChannel());
ChannelData *channel = App::channel(peerFromChannel(c.vchannel_id));
if (!channel->mgInfo) {
channel->flags |= MTPDchannel::Flag::f_megagroup;
channel->flagsUpdated();
}
if (!channel->access) {
channel->input = MTP_inputPeerChannel(c.vchannel_id, c.vaccess_hash);
channel->inputChannel = d.vmigrated_to;
channel->access = d.vmigrated_to.c_inputChannel().vaccess_hash.v;
}
bool updatedTo = (cdata->migrateToPtr != channel), updatedFrom = (channel->mgInfo->migrateFromPtr != cdata);
if (updatedTo) {
cdata->migrateToPtr = channel;
}
if (updatedFrom) {
channel->mgInfo->migrateFromPtr = cdata;
if (History *h = App::historyLoaded(cdata->id)) {
if (History *hto = App::historyLoaded(channel->id)) {
if (!h->isEmpty()) {
h->clear(true);
}
if (hto->inChatList(Dialogs::Mode::All) && h->inChatList(Dialogs::Mode::All)) {
App::removeDialog(h);
}
}
}
Notify::migrateUpdated(channel);
update.flags |= UpdateFlag::MigrationChanged;
}
if (updatedTo) {
Notify::migrateUpdated(cdata);
update.flags |= UpdateFlag::MigrationChanged;
}
}
if (!(cdata->flags & MTPDchat::Flag::f_admins_enabled) && (d.vflags.v & MTPDchat::Flag::f_admins_enabled)) {
cdata->invalidateParticipants();
}
cdata->flags = d.vflags.v;
cdata->count = d.vparticipants_count.v;
cdata->isForbidden = false;
if (canEdit != cdata->canEdit()) {
update.flags |= UpdateFlag::ChatCanEdit;
}
} break;
case mtpc_chatForbidden: {
auto &d(chat.c_chatForbidden());
data = App::chat(peerFromChat(d.vid.v));
auto cdata = data->asChat();
auto canEdit = cdata->canEdit();
data->input = MTP_inputPeerChat(d.vid);
cdata->setName(qs(d.vtitle));
cdata->setPhoto(MTP_chatPhotoEmpty());
cdata->date = 0;
cdata->count = -1;
cdata->invalidateParticipants();
cdata->flags = 0;
cdata->isForbidden = true;
if (canEdit != cdata->canEdit()) {
update.flags |= UpdateFlag::ChatCanEdit;
}
} break;
case mtpc_channel: {
auto &d(chat.c_channel());
auto peerId = peerFromChannel(d.vid.v);
minimal = d.is_min();
if (minimal) {
data = App::channelLoaded(peerId);
if (!data) {
return nullptr; // minimal is not loaded, need to make getDifference
}
} else {
data = App::channel(peerId);
data->input = MTP_inputPeerChannel(d.vid, d.has_access_hash() ? d.vaccess_hash : MTP_long(0));
}
auto cdata = data->asChannel();
auto wasInChannel = cdata->amIn();
auto canEditPhoto = cdata->canEditPhoto();
auto canViewAdmins = cdata->canViewAdmins();
auto canViewMembers = cdata->canViewMembers();
auto canAddMembers = cdata->canAddMembers();
auto wasEditor = cdata->amEditor();
if (minimal) {
auto mask = MTPDchannel::Flag::f_broadcast | MTPDchannel::Flag::f_verified | MTPDchannel::Flag::f_megagroup | MTPDchannel::Flag::f_democracy;
cdata->flags = (cdata->flags & ~mask) | (d.vflags.v & mask);
} else {
cdata->inputChannel = MTP_inputChannel(d.vid, d.vaccess_hash);
cdata->access = d.vaccess_hash.v;
cdata->date = d.vdate.v;
if (cdata->version < d.vversion.v) {
cdata->version = d.vversion.v;
}
if (d.is_restricted()) {
cdata->setRestrictionReason(extractRestrictionReason(qs(d.vrestriction_reason)));
} else {
cdata->setRestrictionReason(QString());
}
cdata->flags = d.vflags.v;
}
cdata->flagsUpdated();
QString uname = d.has_username() ? textOneLine(qs(d.vusername)) : QString();
cdata->setName(qs(d.vtitle), uname);
cdata->isForbidden = false;
cdata->setPhoto(d.vphoto);
if (wasInChannel != cdata->amIn()) update.flags |= UpdateFlag::ChannelAmIn;
if (canEditPhoto != cdata->canEditPhoto()) update.flags |= UpdateFlag::ChannelCanEditPhoto;
if (canViewAdmins != cdata->canViewAdmins()) update.flags |= UpdateFlag::ChannelCanViewAdmins;
if (canViewMembers != cdata->canViewMembers()) update.flags |= UpdateFlag::ChannelCanViewMembers;
if (canAddMembers != cdata->canAddMembers()) update.flags |= UpdateFlag::ChannelCanAddMembers;
if (wasEditor != cdata->amEditor()) {
cdata->selfAdminUpdated();
update.flags |= (UpdateFlag::ChannelAmEditor | UpdateFlag::AdminsChanged);
}
} break;
case mtpc_channelForbidden: {
auto &d(chat.c_channelForbidden());
auto peerId = peerFromChannel(d.vid.v);
data = App::channel(peerId);
data->input = MTP_inputPeerChannel(d.vid, d.vaccess_hash);
auto cdata = data->asChannel();
auto wasInChannel = cdata->amIn();
auto canEditPhoto = cdata->canEditPhoto();
auto canViewAdmins = cdata->canViewAdmins();
auto canViewMembers = cdata->canViewMembers();
auto canAddMembers = cdata->canAddMembers();
auto wasEditor = cdata->amEditor();
cdata->inputChannel = MTP_inputChannel(d.vid, d.vaccess_hash);
auto mask = mtpCastFlags(MTPDchannelForbidden::Flag::f_broadcast | MTPDchannelForbidden::Flag::f_megagroup);
cdata->flags = (cdata->flags & ~mask) | (mtpCastFlags(d.vflags) & mask);
cdata->flagsUpdated();
cdata->setName(qs(d.vtitle), QString());
cdata->access = d.vaccess_hash.v;
cdata->setPhoto(MTP_chatPhotoEmpty());
cdata->date = 0;
cdata->setMembersCount(0);
cdata->isForbidden = true;
if (wasInChannel != cdata->amIn()) update.flags |= UpdateFlag::ChannelAmIn;
if (canEditPhoto != cdata->canEditPhoto()) update.flags |= UpdateFlag::ChannelCanEditPhoto;
if (canViewAdmins != cdata->canViewAdmins()) update.flags |= UpdateFlag::ChannelCanViewAdmins;
if (canViewMembers != cdata->canViewMembers()) update.flags |= UpdateFlag::ChannelCanViewMembers;
if (canAddMembers != cdata->canAddMembers()) update.flags |= UpdateFlag::ChannelCanAddMembers;
if (wasEditor != cdata->amEditor()) {
cdata->selfAdminUpdated();
update.flags |= (UpdateFlag::ChannelAmEditor | UpdateFlag::AdminsChanged);
}
} break;
}
if (!data) {
return nullptr;
}
if (minimal) {
if (data->loadedStatus == PeerData::NotLoaded) {
data->loadedStatus = PeerData::MinimalLoaded;
}
} else if (data->loadedStatus != PeerData::FullLoaded) {
data->loadedStatus = PeerData::FullLoaded;
}
if (App::main()) {
markPeerUpdated(data);
if (update.flags) {
update.peer = data;
Notify::peerUpdatedDelayed(update);
}
}
return data;
}
PeerData *feedChats(const MTPVector<MTPChat> &chats) {
PeerData *result = nullptr;
for_const (auto &chat, chats.c_vector().v) {
if (auto feededChat = feedChat(chat)) {
result = feededChat;
}
}
return result;
}
void feedParticipants(const MTPChatParticipants &p, bool requestBotInfos, bool emitPeerUpdated) {
ChatData *chat = 0;
switch (p.type()) {
case mtpc_chatParticipantsForbidden: {
const auto &d(p.c_chatParticipantsForbidden());
chat = App::chat(d.vchat_id.v);
chat->count = -1;
chat->invalidateParticipants();
} break;
case mtpc_chatParticipants: {
const auto &d(p.c_chatParticipants());
chat = App::chat(d.vchat_id.v);
auto canEdit = chat->canEdit();
if (!requestBotInfos || chat->version <= d.vversion.v) { // !requestBotInfos is true on getFullChat result
chat->version = d.vversion.v;
const auto &v(d.vparticipants.c_vector().v);
chat->count = v.size();
int32 pversion = chat->participants.isEmpty() ? 1 : (chat->participants.begin().value() + 1);
chat->invitedByMe = ChatData::InvitedByMe();
chat->admins = ChatData::Admins();
chat->flags &= ~MTPDchat::Flag::f_admin;
for (QVector<MTPChatParticipant>::const_iterator i = v.cbegin(), e = v.cend(); i != e; ++i) {
int32 uid = 0, inviter = 0;
switch (i->type()) {
case mtpc_chatParticipantCreator: {
const auto &p(i->c_chatParticipantCreator());
uid = p.vuser_id.v;
chat->creator = uid;
} break;
case mtpc_chatParticipantAdmin: {
const auto &p(i->c_chatParticipantAdmin());
uid = p.vuser_id.v;
inviter = p.vinviter_id.v;
} break;
case mtpc_chatParticipant: {
const auto &p(i->c_chatParticipant());
uid = p.vuser_id.v;
inviter = p.vinviter_id.v;
} break;
}
if (!uid) continue;
UserData *user = App::userLoaded(uid);
if (user) {
chat->participants[user] = pversion;
if (inviter == MTP::authedId()) {
chat->invitedByMe.insert(user);
}
if (i->type() == mtpc_chatParticipantAdmin) {
chat->admins.insert(user);
if (user->isSelf()) {
chat->flags |= MTPDchat::Flag::f_admin;
}
}
} else {
chat->invalidateParticipants();
break;
}
}
if (!chat->participants.isEmpty()) {
History *h = App::historyLoaded(chat->id);
bool found = !h || !h->lastKeyboardFrom;
int32 botStatus = -1;
for (ChatData::Participants::iterator i = chat->participants.begin(), e = chat->participants.end(); i != e;) {
if (i.value() < pversion) {
i = chat->participants.erase(i);
} else {
if (i.key()->botInfo) {
botStatus = 2;// (botStatus > 0/* || !i.key()->botInfo->readsAllHistory*/) ? 2 : 1;
if (requestBotInfos && !i.key()->botInfo->inited && App::api()) App::api()->requestFullPeer(i.key());
}
if (!found && i.key()->id == h->lastKeyboardFrom) {
found = true;
}
++i;
}
}
chat->botStatus = botStatus;
if (!found) {
h->clearLastKeyboard();
}
}
}
if (canEdit != chat->canEdit()) {
Notify::peerUpdatedDelayed(chat, Notify::PeerUpdate::Flag::ChatCanEdit);
}
} break;
}
Notify::peerUpdatedDelayed(chat, Notify::PeerUpdate::Flag::MembersChanged | Notify::PeerUpdate::Flag::AdminsChanged);
if (chat && App::main()) {
if (emitPeerUpdated) {
App::main()->peerUpdated(chat);
} else {
markPeerUpdated(chat);
}
}
}
void feedParticipantAdd(const MTPDupdateChatParticipantAdd &d, bool emitPeerUpdated) {
ChatData *chat = App::chat(d.vchat_id.v);
if (chat->version + 1 < d.vversion.v) {
chat->version = d.vversion.v;
chat->invalidateParticipants();
App::api()->requestPeer(chat);
if (App::main()) {
if (emitPeerUpdated) {
App::main()->peerUpdated(chat);
} else {
markPeerUpdated(chat);
}
}
} else if (chat->version <= d.vversion.v && chat->count >= 0) {
chat->version = d.vversion.v;
UserData *user = App::userLoaded(d.vuser_id.v);
if (user) {
if (chat->participants.isEmpty() && chat->count) {
chat->count++;
chat->botStatus = 0;
} else if (chat->participants.find(user) == chat->participants.end()) {
chat->participants[user] = (chat->participants.isEmpty() ? 1 : chat->participants.begin().value());
if (d.vinviter_id.v == MTP::authedId()) {
chat->invitedByMe.insert(user);
} else {
chat->invitedByMe.remove(user);
}
chat->count++;
if (user->botInfo) {
chat->botStatus = 2;// (chat->botStatus > 0/* || !user->botInfo->readsAllHistory*/) ? 2 : 1;
if (!user->botInfo->inited && App::api()) App::api()->requestFullPeer(user);
}
}
} else {
chat->invalidateParticipants();
chat->count++;
}
Notify::peerUpdatedDelayed(chat, Notify::PeerUpdate::Flag::MembersChanged);
if (App::main()) {
if (emitPeerUpdated) {
App::main()->peerUpdated(chat);
} else {
markPeerUpdated(chat);
}
}
}
}
void feedParticipantDelete(const MTPDupdateChatParticipantDelete &d, bool emitPeerUpdated) {
ChatData *chat = App::chat(d.vchat_id.v);
if (chat->version + 1 < d.vversion.v) {
chat->version = d.vversion.v;
chat->invalidateParticipants();
App::api()->requestPeer(chat);
if (App::main()) {
if (emitPeerUpdated) {
App::main()->peerUpdated(chat);
} else {
markPeerUpdated(chat);
}
}
} else if (chat->version <= d.vversion.v && chat->count > 0) {
chat->version = d.vversion.v;
auto canEdit = chat->canEdit();
UserData *user = App::userLoaded(d.vuser_id.v);
if (user) {
if (chat->participants.isEmpty()) {
if (chat->count > 0) {
chat->count--;
}
} else {
ChatData::Participants::iterator i = chat->participants.find(user);
if (i != chat->participants.end()) {
chat->participants.erase(i);
chat->count--;
chat->invitedByMe.remove(user);
chat->admins.remove(user);
if (user->isSelf()) {
chat->flags &= ~MTPDchat::Flag::f_admin;
}
History *h = App::historyLoaded(chat->id);
if (h && h->lastKeyboardFrom == user->id) {
h->clearLastKeyboard();
}
}
if (chat->botStatus > 0 && user->botInfo) {
int32 botStatus = -1;
for (ChatData::Participants::const_iterator j = chat->participants.cbegin(), e = chat->participants.cend(); j != e; ++j) {
if (j.key()->botInfo) {
if (true || botStatus > 0/* || !j.key()->botInfo->readsAllHistory*/) {
botStatus = 2;
break;
}
botStatus = 1;
}
}
chat->botStatus = botStatus;
}
}
} else {
chat->invalidateParticipants();